LLVM API Documentation

InstCombine.h
Go to the documentation of this file.
00001 //===- InstCombine.h - Main InstCombine pass definition ---------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
00011 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
00012 
00013 #include "InstCombineWorklist.h"
00014 #include "llvm/Analysis/AssumptionTracker.h"
00015 #include "llvm/Analysis/TargetFolder.h"
00016 #include "llvm/Analysis/ValueTracking.h"
00017 #include "llvm/IR/IRBuilder.h"
00018 #include "llvm/IR/InstVisitor.h"
00019 #include "llvm/IR/IntrinsicInst.h"
00020 #include "llvm/IR/Operator.h"
00021 #include "llvm/IR/PatternMatch.h"
00022 #include "llvm/Pass.h"
00023 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
00024 
00025 #define DEBUG_TYPE "instcombine"
00026 
00027 namespace llvm {
00028 class CallSite;
00029 class DataLayout;
00030 class DominatorTree;
00031 class TargetLibraryInfo;
00032 class DbgDeclareInst;
00033 class MemIntrinsic;
00034 class MemSetInst;
00035 
00036 /// SelectPatternFlavor - We can match a variety of different patterns for
00037 /// select operations.
00038 enum SelectPatternFlavor {
00039   SPF_UNKNOWN = 0,
00040   SPF_SMIN,
00041   SPF_UMIN,
00042   SPF_SMAX,
00043   SPF_UMAX,
00044   SPF_ABS,
00045   SPF_NABS
00046 };
00047 
00048 /// getComplexity:  Assign a complexity or rank value to LLVM Values...
00049 ///   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
00050 static inline unsigned getComplexity(Value *V) {
00051   if (isa<Instruction>(V)) {
00052     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
00053         BinaryOperator::isNot(V))
00054       return 3;
00055     return 4;
00056   }
00057   if (isa<Argument>(V))
00058     return 3;
00059   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
00060 }
00061 
00062 /// AddOne - Add one to a Constant
00063 static inline Constant *AddOne(Constant *C) {
00064   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
00065 }
00066 /// SubOne - Subtract one from a Constant
00067 static inline Constant *SubOne(Constant *C) {
00068   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
00069 }
00070 
00071 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
00072 /// just like the normal insertion helper, but also adds any new instructions
00073 /// to the instcombine worklist.
00074 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
00075     : public IRBuilderDefaultInserter<true> {
00076   InstCombineWorklist &Worklist;
00077   AssumptionTracker *AT;
00078 
00079 public:
00080   InstCombineIRInserter(InstCombineWorklist &WL, AssumptionTracker *AT)
00081     : Worklist(WL), AT(AT) {}
00082 
00083   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
00084                     BasicBlock::iterator InsertPt) const {
00085     IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
00086     Worklist.Add(I);
00087 
00088     using namespace llvm::PatternMatch;
00089     if (match(I, m_Intrinsic<Intrinsic::assume>()))
00090       AT->registerAssumption(cast<CallInst>(I));
00091   }
00092 };
00093 
00094 /// InstCombiner - The -instcombine pass.
00095 class LLVM_LIBRARY_VISIBILITY InstCombiner
00096     : public FunctionPass,
00097       public InstVisitor<InstCombiner, Instruction *> {
00098   AssumptionTracker *AT;
00099   const DataLayout *DL;
00100   TargetLibraryInfo *TLI;
00101   DominatorTree *DT; // not required
00102   bool MadeIRChange;
00103   LibCallSimplifier *Simplifier;
00104   bool MinimizeSize;
00105 
00106 public:
00107   /// Worklist - All of the instructions that need to be simplified.
00108   InstCombineWorklist Worklist;
00109 
00110   /// Builder - This is an IRBuilder that automatically inserts new
00111   /// instructions into the worklist when they are created.
00112   typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
00113   BuilderTy *Builder;
00114 
00115   static char ID; // Pass identification, replacement for typeid
00116   InstCombiner() : FunctionPass(ID), DL(nullptr), Builder(nullptr) {
00117     MinimizeSize = false;
00118     initializeInstCombinerPass(*PassRegistry::getPassRegistry());
00119   }
00120 
00121 public:
00122   bool runOnFunction(Function &F) override;
00123 
00124   bool DoOneIteration(Function &F, unsigned ItNum);
00125 
00126   void getAnalysisUsage(AnalysisUsage &AU) const override;
00127 
00128   AssumptionTracker *getAssumptionTracker() const { return AT; }
00129 
00130   const DataLayout *getDataLayout() const { return DL; }
00131   
00132   DominatorTree *getDominatorTree() const { return DT; }
00133 
00134   TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
00135 
00136   // Visitation implementation - Implement instruction combining for different
00137   // instruction types.  The semantics are as follows:
00138   // Return Value:
00139   //    null        - No change was made
00140   //     I          - Change was made, I is still valid, I may be dead though
00141   //   otherwise    - Change was made, replace I with returned instruction
00142   //
00143   Instruction *visitAdd(BinaryOperator &I);
00144   Instruction *visitFAdd(BinaryOperator &I);
00145   Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
00146   Instruction *visitSub(BinaryOperator &I);
00147   Instruction *visitFSub(BinaryOperator &I);
00148   Instruction *visitMul(BinaryOperator &I);
00149   Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
00150                        Instruction *InsertBefore);
00151   Instruction *visitFMul(BinaryOperator &I);
00152   Instruction *visitURem(BinaryOperator &I);
00153   Instruction *visitSRem(BinaryOperator &I);
00154   Instruction *visitFRem(BinaryOperator &I);
00155   bool SimplifyDivRemOfSelect(BinaryOperator &I);
00156   Instruction *commonRemTransforms(BinaryOperator &I);
00157   Instruction *commonIRemTransforms(BinaryOperator &I);
00158   Instruction *commonDivTransforms(BinaryOperator &I);
00159   Instruction *commonIDivTransforms(BinaryOperator &I);
00160   Instruction *visitUDiv(BinaryOperator &I);
00161   Instruction *visitSDiv(BinaryOperator &I);
00162   Instruction *visitFDiv(BinaryOperator &I);
00163   Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
00164   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
00165   Instruction *visitAnd(BinaryOperator &I);
00166   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
00167   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
00168   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
00169                                    Value *B, Value *C);
00170   Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
00171                                     Value *B, Value *C);
00172   Instruction *visitOr(BinaryOperator &I);
00173   Instruction *visitXor(BinaryOperator &I);
00174   Instruction *visitShl(BinaryOperator &I);
00175   Instruction *visitAShr(BinaryOperator &I);
00176   Instruction *visitLShr(BinaryOperator &I);
00177   Instruction *commonShiftTransforms(BinaryOperator &I);
00178   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
00179                                     Constant *RHSC);
00180   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
00181                                             GlobalVariable *GV, CmpInst &ICI,
00182                                             ConstantInt *AndCst = nullptr);
00183   Instruction *visitFCmpInst(FCmpInst &I);
00184   Instruction *visitICmpInst(ICmpInst &I);
00185   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
00186   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
00187                                               ConstantInt *RHS);
00188   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00189                               ConstantInt *DivRHS);
00190   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
00191                               ConstantInt *DivRHS);
00192   Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
00193                                  ConstantInt *CI1, ConstantInt *CI2);
00194   Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
00195                                  ConstantInt *CI1, ConstantInt *CI2);
00196   Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
00197                                 ICmpInst::Predicate Pred);
00198   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
00199                            ICmpInst::Predicate Cond, Instruction &I);
00200   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
00201                                    BinaryOperator &I);
00202   Instruction *commonCastTransforms(CastInst &CI);
00203   Instruction *commonPointerCastTransforms(CastInst &CI);
00204   Instruction *visitTrunc(TruncInst &CI);
00205   Instruction *visitZExt(ZExtInst &CI);
00206   Instruction *visitSExt(SExtInst &CI);
00207   Instruction *visitFPTrunc(FPTruncInst &CI);
00208   Instruction *visitFPExt(CastInst &CI);
00209   Instruction *visitFPToUI(FPToUIInst &FI);
00210   Instruction *visitFPToSI(FPToSIInst &FI);
00211   Instruction *visitUIToFP(CastInst &CI);
00212   Instruction *visitSIToFP(CastInst &CI);
00213   Instruction *visitPtrToInt(PtrToIntInst &CI);
00214   Instruction *visitIntToPtr(IntToPtrInst &CI);
00215   Instruction *visitBitCast(BitCastInst &CI);
00216   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
00217   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
00218   Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
00219   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
00220                             Value *A, Value *B, Instruction &Outer,
00221                             SelectPatternFlavor SPF2, Value *C);
00222   Instruction *visitSelectInst(SelectInst &SI);
00223   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
00224   Instruction *visitCallInst(CallInst &CI);
00225   Instruction *visitInvokeInst(InvokeInst &II);
00226 
00227   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
00228   Instruction *visitPHINode(PHINode &PN);
00229   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
00230   Instruction *visitAllocaInst(AllocaInst &AI);
00231   Instruction *visitAllocSite(Instruction &FI);
00232   Instruction *visitFree(CallInst &FI);
00233   Instruction *visitLoadInst(LoadInst &LI);
00234   Instruction *visitStoreInst(StoreInst &SI);
00235   Instruction *visitBranchInst(BranchInst &BI);
00236   Instruction *visitSwitchInst(SwitchInst &SI);
00237   Instruction *visitReturnInst(ReturnInst &RI);
00238   Instruction *visitInsertValueInst(InsertValueInst &IV);
00239   Instruction *visitInsertElementInst(InsertElementInst &IE);
00240   Instruction *visitExtractElementInst(ExtractElementInst &EI);
00241   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
00242   Instruction *visitExtractValueInst(ExtractValueInst &EV);
00243   Instruction *visitLandingPadInst(LandingPadInst &LI);
00244 
00245   // visitInstruction - Specify what to return for unhandled instructions...
00246   Instruction *visitInstruction(Instruction &I) { return nullptr; }
00247 
00248 private:
00249   bool ShouldChangeType(Type *From, Type *To) const;
00250   Value *dyn_castNegVal(Value *V) const;
00251   Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
00252   Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
00253                             SmallVectorImpl<Value *> &NewIndices);
00254   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
00255 
00256   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
00257   /// results in any code being generated and is interesting to optimize out. If
00258   /// the cast can be eliminated by some other simple transformation, we prefer
00259   /// to do the simplification first.
00260   bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
00261                           Type *Ty);
00262 
00263   Instruction *visitCallSite(CallSite CS);
00264   Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
00265   bool transformConstExprCastCall(CallSite CS);
00266   Instruction *transformCallThroughTrampoline(CallSite CS,
00267                                               IntrinsicInst *Tramp);
00268   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00269                                  bool DoXform = true);
00270   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
00271   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
00272   bool WillNotOverflowUnsignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
00273   bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
00274   bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
00275   Value *EmitGEPOffset(User *GEP);
00276   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
00277   Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
00278 
00279 public:
00280   // InsertNewInstBefore - insert an instruction New before instruction Old
00281   // in the program.  Add the new instruction to the worklist.
00282   //
00283   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
00284     assert(New && !New->getParent() &&
00285            "New instruction already inserted into a basic block!");
00286     BasicBlock *BB = Old.getParent();
00287     BB->getInstList().insert(&Old, New); // Insert inst
00288     Worklist.Add(New);
00289     return New;
00290   }
00291 
00292   // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
00293   // debug loc.
00294   //
00295   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
00296     New->setDebugLoc(Old.getDebugLoc());
00297     return InsertNewInstBefore(New, Old);
00298   }
00299 
00300   // ReplaceInstUsesWith - This method is to be used when an instruction is
00301   // found to be dead, replacable with another preexisting expression.  Here
00302   // we add all uses of I to the worklist, replace all uses of I with the new
00303   // value, then return I, so that the inst combiner will know that I was
00304   // modified.
00305   //
00306   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
00307     Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
00308 
00309     // If we are replacing the instruction with itself, this must be in a
00310     // segment of unreachable code, so just clobber the instruction.
00311     if (&I == V)
00312       V = UndefValue::get(I.getType());
00313 
00314     DEBUG(dbgs() << "IC: Replacing " << I << "\n"
00315                     "    with " << *V << '\n');
00316 
00317     I.replaceAllUsesWith(V);
00318     return &I;
00319   }
00320 
00321   // EraseInstFromFunction - When dealing with an instruction that has side
00322   // effects or produces a void value, we can't rely on DCE to delete the
00323   // instruction.  Instead, visit methods should return the value returned by
00324   // this function.
00325   Instruction *EraseInstFromFunction(Instruction &I) {
00326     DEBUG(dbgs() << "IC: ERASE " << I << '\n');
00327 
00328     assert(I.use_empty() && "Cannot erase instruction that is used!");
00329     // Make sure that we reprocess all operands now that we reduced their
00330     // use counts.
00331     if (I.getNumOperands() < 8) {
00332       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
00333         if (Instruction *Op = dyn_cast<Instruction>(*i))
00334           Worklist.Add(Op);
00335     }
00336     Worklist.Remove(&I);
00337     I.eraseFromParent();
00338     MadeIRChange = true;
00339     return nullptr; // Don't do anything with FI
00340   }
00341 
00342   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00343                         unsigned Depth = 0, Instruction *CxtI = nullptr) const {
00344     return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
00345                                   AT, CxtI, DT);
00346   }
00347 
00348   bool MaskedValueIsZero(Value *V, const APInt &Mask,
00349                          unsigned Depth = 0,
00350                          Instruction *CxtI = nullptr) const {
00351     return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AT, CxtI, DT);
00352   }
00353   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
00354                               Instruction *CxtI = nullptr) const {
00355     return llvm::ComputeNumSignBits(Op, DL, Depth, AT, CxtI, DT);
00356   }
00357 
00358 private:
00359   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00360   /// operators which are associative or commutative.
00361   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
00362 
00363   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00364   /// which some other binary operation distributes over either by factorizing
00365   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00366   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00367   /// a win).  Returns the simplified value, or null if it didn't simplify.
00368   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
00369 
00370   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
00371   /// based on the demanded bits.
00372   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
00373                                  APInt &KnownOne, unsigned Depth,
00374                                  Instruction *CxtI = nullptr);
00375   bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
00376                             APInt &KnownOne, unsigned Depth = 0);
00377   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
00378   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
00379   Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
00380                                     APInt DemandedMask, APInt &KnownZero,
00381                                     APInt &KnownOne);
00382 
00383   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00384   /// SimplifyDemandedBits knows about.  See if the instruction has any
00385   /// properties that allow us to simplify its operands.
00386   bool SimplifyDemandedInstructionBits(Instruction &Inst);
00387 
00388   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
00389                                     APInt &UndefElts, unsigned Depth = 0);
00390 
00391   Value *SimplifyVectorOp(BinaryOperator &Inst);
00392 
00393   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
00394   // which has a PHI node as operand #0, see if we can fold the instruction
00395   // into the PHI (which is only possible if all operands to the PHI are
00396   // constants).
00397   //
00398   Instruction *FoldOpIntoPhi(Instruction &I);
00399 
00400   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
00401   // operator and they all are only used by the PHI, PHI together their
00402   // inputs, and do the operation once, to the result of the PHI.
00403   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
00404   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
00405   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
00406   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
00407 
00408   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
00409                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
00410 
00411   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
00412                             bool isSub, Instruction &I);
00413   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
00414                          bool Inside);
00415   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
00416   Instruction *MatchBSwap(BinaryOperator &I);
00417   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
00418   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
00419   Instruction *SimplifyMemSet(MemSetInst *MI);
00420 
00421   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
00422 
00423   /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00424   /// the multiplication is known not to overflow then NoSignedWrap is set.
00425   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
00426 };
00427 
00428 } // end namespace llvm.
00429 
00430 #undef DEBUG_TYPE
00431 
00432 #endif