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