Home | History | Annotate | Download | only in InstCombine
      1 //===- InstCombine.h - Main InstCombine pass definition -------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #ifndef INSTCOMBINE_INSTCOMBINE_H
     11 #define INSTCOMBINE_INSTCOMBINE_H
     12 
     13 #include "InstCombineWorklist.h"
     14 #include "llvm/IntrinsicInst.h"
     15 #include "llvm/Operator.h"
     16 #include "llvm/Pass.h"
     17 #include "llvm/Analysis/ValueTracking.h"
     18 #include "llvm/Support/IRBuilder.h"
     19 #include "llvm/Support/InstVisitor.h"
     20 #include "llvm/Support/TargetFolder.h"
     21 
     22 namespace llvm {
     23   class CallSite;
     24   class TargetData;
     25   class TargetLibraryInfo;
     26   class DbgDeclareInst;
     27   class MemIntrinsic;
     28   class MemSetInst;
     29 
     30 /// SelectPatternFlavor - We can match a variety of different patterns for
     31 /// select operations.
     32 enum SelectPatternFlavor {
     33   SPF_UNKNOWN = 0,
     34   SPF_SMIN, SPF_UMIN,
     35   SPF_SMAX, SPF_UMAX
     36   //SPF_ABS - TODO.
     37 };
     38 
     39 /// getComplexity:  Assign a complexity or rank value to LLVM Values...
     40 ///   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
     41 static inline unsigned getComplexity(Value *V) {
     42   if (isa<Instruction>(V)) {
     43     if (BinaryOperator::isNeg(V) ||
     44         BinaryOperator::isFNeg(V) ||
     45         BinaryOperator::isNot(V))
     46       return 3;
     47     return 4;
     48   }
     49   if (isa<Argument>(V)) return 3;
     50   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
     51 }
     52 
     53 
     54 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
     55 /// just like the normal insertion helper, but also adds any new instructions
     56 /// to the instcombine worklist.
     57 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
     58     : public IRBuilderDefaultInserter<true> {
     59   InstCombineWorklist &Worklist;
     60 public:
     61   InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
     62 
     63   void InsertHelper(Instruction *I, const Twine &Name,
     64                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
     65     IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
     66     Worklist.Add(I);
     67   }
     68 };
     69 
     70 /// InstCombiner - The -instcombine pass.
     71 class LLVM_LIBRARY_VISIBILITY InstCombiner
     72                              : public FunctionPass,
     73                                public InstVisitor<InstCombiner, Instruction*> {
     74   TargetData *TD;
     75   TargetLibraryInfo *TLI;
     76   bool MadeIRChange;
     77 public:
     78   /// Worklist - All of the instructions that need to be simplified.
     79   InstCombineWorklist Worklist;
     80 
     81   /// Builder - This is an IRBuilder that automatically inserts new
     82   /// instructions into the worklist when they are created.
     83   typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
     84   BuilderTy *Builder;
     85 
     86   static char ID; // Pass identification, replacement for typeid
     87   InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
     88     initializeInstCombinerPass(*PassRegistry::getPassRegistry());
     89   }
     90 
     91 public:
     92   virtual bool runOnFunction(Function &F);
     93 
     94   bool DoOneIteration(Function &F, unsigned ItNum);
     95 
     96   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
     97 
     98   TargetData *getTargetData() const { return TD; }
     99 
    100   TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
    101 
    102   // Visitation implementation - Implement instruction combining for different
    103   // instruction types.  The semantics are as follows:
    104   // Return Value:
    105   //    null        - No change was made
    106   //     I          - Change was made, I is still valid, I may be dead though
    107   //   otherwise    - Change was made, replace I with returned instruction
    108   //
    109   Instruction *visitAdd(BinaryOperator &I);
    110   Instruction *visitFAdd(BinaryOperator &I);
    111   Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
    112   Instruction *visitSub(BinaryOperator &I);
    113   Instruction *visitFSub(BinaryOperator &I);
    114   Instruction *visitMul(BinaryOperator &I);
    115   Instruction *visitFMul(BinaryOperator &I);
    116   Instruction *visitURem(BinaryOperator &I);
    117   Instruction *visitSRem(BinaryOperator &I);
    118   Instruction *visitFRem(BinaryOperator &I);
    119   bool SimplifyDivRemOfSelect(BinaryOperator &I);
    120   Instruction *commonRemTransforms(BinaryOperator &I);
    121   Instruction *commonIRemTransforms(BinaryOperator &I);
    122   Instruction *commonDivTransforms(BinaryOperator &I);
    123   Instruction *commonIDivTransforms(BinaryOperator &I);
    124   Instruction *visitUDiv(BinaryOperator &I);
    125   Instruction *visitSDiv(BinaryOperator &I);
    126   Instruction *visitFDiv(BinaryOperator &I);
    127   Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
    128   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
    129   Instruction *visitAnd(BinaryOperator &I);
    130   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
    131   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
    132   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
    133                                    Value *A, Value *B, Value *C);
    134   Instruction *visitOr (BinaryOperator &I);
    135   Instruction *visitXor(BinaryOperator &I);
    136   Instruction *visitShl(BinaryOperator &I);
    137   Instruction *visitAShr(BinaryOperator &I);
    138   Instruction *visitLShr(BinaryOperator &I);
    139   Instruction *commonShiftTransforms(BinaryOperator &I);
    140   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
    141                                     Constant *RHSC);
    142   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
    143                                             GlobalVariable *GV, CmpInst &ICI,
    144                                             ConstantInt *AndCst = 0);
    145   Instruction *visitFCmpInst(FCmpInst &I);
    146   Instruction *visitICmpInst(ICmpInst &I);
    147   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
    148   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
    149                                               Instruction *LHS,
    150                                               ConstantInt *RHS);
    151   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
    152                               ConstantInt *DivRHS);
    153   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
    154                               ConstantInt *DivRHS);
    155   Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
    156                                 ICmpInst::Predicate Pred, Value *TheAdd);
    157   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
    158                            ICmpInst::Predicate Cond, Instruction &I);
    159   Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
    160                                    BinaryOperator &I);
    161   Instruction *commonCastTransforms(CastInst &CI);
    162   Instruction *commonPointerCastTransforms(CastInst &CI);
    163   Instruction *visitTrunc(TruncInst &CI);
    164   Instruction *visitZExt(ZExtInst &CI);
    165   Instruction *visitSExt(SExtInst &CI);
    166   Instruction *visitFPTrunc(FPTruncInst &CI);
    167   Instruction *visitFPExt(CastInst &CI);
    168   Instruction *visitFPToUI(FPToUIInst &FI);
    169   Instruction *visitFPToSI(FPToSIInst &FI);
    170   Instruction *visitUIToFP(CastInst &CI);
    171   Instruction *visitSIToFP(CastInst &CI);
    172   Instruction *visitPtrToInt(PtrToIntInst &CI);
    173   Instruction *visitIntToPtr(IntToPtrInst &CI);
    174   Instruction *visitBitCast(BitCastInst &CI);
    175   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
    176                               Instruction *FI);
    177   Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
    178   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
    179                             Value *A, Value *B, Instruction &Outer,
    180                             SelectPatternFlavor SPF2, Value *C);
    181   Instruction *visitSelectInst(SelectInst &SI);
    182   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
    183   Instruction *visitCallInst(CallInst &CI);
    184   Instruction *visitInvokeInst(InvokeInst &II);
    185 
    186   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
    187   Instruction *visitPHINode(PHINode &PN);
    188   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
    189   Instruction *visitAllocaInst(AllocaInst &AI);
    190   Instruction *visitMalloc(Instruction &FI);
    191   Instruction *visitFree(CallInst &FI);
    192   Instruction *visitLoadInst(LoadInst &LI);
    193   Instruction *visitStoreInst(StoreInst &SI);
    194   Instruction *visitBranchInst(BranchInst &BI);
    195   Instruction *visitSwitchInst(SwitchInst &SI);
    196   Instruction *visitInsertElementInst(InsertElementInst &IE);
    197   Instruction *visitExtractElementInst(ExtractElementInst &EI);
    198   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
    199   Instruction *visitExtractValueInst(ExtractValueInst &EV);
    200   Instruction *visitLandingPadInst(LandingPadInst &LI);
    201 
    202   // visitInstruction - Specify what to return for unhandled instructions...
    203   Instruction *visitInstruction(Instruction &I) { return 0; }
    204 
    205 private:
    206   bool ShouldChangeType(Type *From, Type *To) const;
    207   Value *dyn_castNegVal(Value *V) const;
    208   Value *dyn_castFNegVal(Value *V) const;
    209   Type *FindElementAtOffset(Type *Ty, int64_t Offset,
    210                                   SmallVectorImpl<Value*> &NewIndices);
    211   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
    212 
    213   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
    214   /// results in any code being generated and is interesting to optimize out. If
    215   /// the cast can be eliminated by some other simple transformation, we prefer
    216   /// to do the simplification first.
    217   bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
    218                           Type *Ty);
    219 
    220   Instruction *visitCallSite(CallSite CS);
    221   Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
    222   bool transformConstExprCastCall(CallSite CS);
    223   Instruction *transformCallThroughTrampoline(CallSite CS,
    224                                               IntrinsicInst *Tramp);
    225   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
    226                                  bool DoXform = true);
    227   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
    228   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
    229   Value *EmitGEPOffset(User *GEP);
    230 
    231 public:
    232   // InsertNewInstBefore - insert an instruction New before instruction Old
    233   // in the program.  Add the new instruction to the worklist.
    234   //
    235   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
    236     assert(New && New->getParent() == 0 &&
    237            "New instruction already inserted into a basic block!");
    238     BasicBlock *BB = Old.getParent();
    239     BB->getInstList().insert(&Old, New);  // Insert inst
    240     Worklist.Add(New);
    241     return New;
    242   }
    243 
    244   // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
    245   // debug loc.
    246   //
    247   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
    248     New->setDebugLoc(Old.getDebugLoc());
    249     return InsertNewInstBefore(New, Old);
    250   }
    251 
    252   // ReplaceInstUsesWith - This method is to be used when an instruction is
    253   // found to be dead, replacable with another preexisting expression.  Here
    254   // we add all uses of I to the worklist, replace all uses of I with the new
    255   // value, then return I, so that the inst combiner will know that I was
    256   // modified.
    257   //
    258   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
    259     Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
    260 
    261     // If we are replacing the instruction with itself, this must be in a
    262     // segment of unreachable code, so just clobber the instruction.
    263     if (&I == V)
    264       V = UndefValue::get(I.getType());
    265 
    266     DEBUG(errs() << "IC: Replacing " << I << "\n"
    267                     "    with " << *V << '\n');
    268 
    269     I.replaceAllUsesWith(V);
    270     return &I;
    271   }
    272 
    273   // EraseInstFromFunction - When dealing with an instruction that has side
    274   // effects or produces a void value, we can't rely on DCE to delete the
    275   // instruction.  Instead, visit methods should return the value returned by
    276   // this function.
    277   Instruction *EraseInstFromFunction(Instruction &I) {
    278     DEBUG(errs() << "IC: ERASE " << I << '\n');
    279 
    280     assert(I.use_empty() && "Cannot erase instruction that is used!");
    281     // Make sure that we reprocess all operands now that we reduced their
    282     // use counts.
    283     if (I.getNumOperands() < 8) {
    284       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
    285         if (Instruction *Op = dyn_cast<Instruction>(*i))
    286           Worklist.Add(Op);
    287     }
    288     Worklist.Remove(&I);
    289     I.eraseFromParent();
    290     MadeIRChange = true;
    291     return 0;  // Don't do anything with FI
    292   }
    293 
    294   void ComputeMaskedBits(Value *V, APInt &KnownZero,
    295                          APInt &KnownOne, unsigned Depth = 0) const {
    296     return llvm::ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
    297   }
    298 
    299   bool MaskedValueIsZero(Value *V, const APInt &Mask,
    300                          unsigned Depth = 0) const {
    301     return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
    302   }
    303   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
    304     return llvm::ComputeNumSignBits(Op, TD, Depth);
    305   }
    306 
    307 private:
    308 
    309   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
    310   /// operators which are associative or commutative.
    311   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
    312 
    313   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
    314   /// which some other binary operation distributes over either by factorizing
    315   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
    316   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
    317   /// a win).  Returns the simplified value, or null if it didn't simplify.
    318   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
    319 
    320   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
    321   /// based on the demanded bits.
    322   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
    323                                  APInt& KnownZero, APInt& KnownOne,
    324                                  unsigned Depth);
    325   bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
    326                             APInt& KnownZero, APInt& KnownOne,
    327                             unsigned Depth=0);
    328 
    329   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
    330   /// SimplifyDemandedBits knows about.  See if the instruction has any
    331   /// properties that allow us to simplify its operands.
    332   bool SimplifyDemandedInstructionBits(Instruction &Inst);
    333 
    334   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
    335                                     APInt& UndefElts, unsigned Depth = 0);
    336 
    337   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
    338   // which has a PHI node as operand #0, see if we can fold the instruction
    339   // into the PHI (which is only possible if all operands to the PHI are
    340   // constants).
    341   //
    342   Instruction *FoldOpIntoPhi(Instruction &I);
    343 
    344   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
    345   // operator and they all are only used by the PHI, PHI together their
    346   // inputs, and do the operation once, to the result of the PHI.
    347   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
    348   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
    349   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
    350   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
    351 
    352 
    353   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
    354                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
    355 
    356   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
    357                             bool isSub, Instruction &I);
    358   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
    359                          bool isSigned, bool Inside);
    360   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
    361   Instruction *MatchBSwap(BinaryOperator &I);
    362   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
    363   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
    364   Instruction *SimplifyMemSet(MemSetInst *MI);
    365 
    366 
    367   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
    368 };
    369 
    370 
    371 
    372 } // end namespace llvm.
    373 
    374 #endif
    375