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