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 INSTCOMBINE_INSTCOMBINE_H
00011 #define 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 *visitOr(BinaryOperator &I);
00156   Instruction *visitXor(BinaryOperator &I);
00157   Instruction *visitShl(BinaryOperator &I);
00158   Instruction *visitAShr(BinaryOperator &I);
00159   Instruction *visitLShr(BinaryOperator &I);
00160   Instruction *commonShiftTransforms(BinaryOperator &I);
00161   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
00162                                     Constant *RHSC);
00163   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
00164                                             GlobalVariable *GV, CmpInst &ICI,
00165                                             ConstantInt *AndCst = nullptr);
00166   Instruction *visitFCmpInst(FCmpInst &I);
00167   Instruction *visitICmpInst(ICmpInst &I);
00168   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
00169   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
00170                                               ConstantInt *RHS);
00171   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00172                               ConstantInt *DivRHS);
00173   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
00174                               ConstantInt *DivRHS);
00175   Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
00176                                  ConstantInt *CI1, ConstantInt *CI2);
00177   Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
00178                                 ICmpInst::Predicate Pred);
00179   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
00180                            ICmpInst::Predicate Cond, Instruction &I);
00181   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
00182                                    BinaryOperator &I);
00183   Instruction *commonCastTransforms(CastInst &CI);
00184   Instruction *commonPointerCastTransforms(CastInst &CI);
00185   Instruction *visitTrunc(TruncInst &CI);
00186   Instruction *visitZExt(ZExtInst &CI);
00187   Instruction *visitSExt(SExtInst &CI);
00188   Instruction *visitFPTrunc(FPTruncInst &CI);
00189   Instruction *visitFPExt(CastInst &CI);
00190   Instruction *visitFPToUI(FPToUIInst &FI);
00191   Instruction *visitFPToSI(FPToSIInst &FI);
00192   Instruction *visitUIToFP(CastInst &CI);
00193   Instruction *visitSIToFP(CastInst &CI);
00194   Instruction *visitPtrToInt(PtrToIntInst &CI);
00195   Instruction *visitIntToPtr(IntToPtrInst &CI);
00196   Instruction *visitBitCast(BitCastInst &CI);
00197   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
00198   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
00199   Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
00200   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
00201                             Value *A, Value *B, Instruction &Outer,
00202                             SelectPatternFlavor SPF2, Value *C);
00203   Instruction *visitSelectInst(SelectInst &SI);
00204   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
00205   Instruction *visitCallInst(CallInst &CI);
00206   Instruction *visitInvokeInst(InvokeInst &II);
00207 
00208   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
00209   Instruction *visitPHINode(PHINode &PN);
00210   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
00211   Instruction *visitAllocaInst(AllocaInst &AI);
00212   Instruction *visitAllocSite(Instruction &FI);
00213   Instruction *visitFree(CallInst &FI);
00214   Instruction *visitLoadInst(LoadInst &LI);
00215   Instruction *visitStoreInst(StoreInst &SI);
00216   Instruction *visitBranchInst(BranchInst &BI);
00217   Instruction *visitSwitchInst(SwitchInst &SI);
00218   Instruction *visitInsertValueInst(InsertValueInst &IV);
00219   Instruction *visitInsertElementInst(InsertElementInst &IE);
00220   Instruction *visitExtractElementInst(ExtractElementInst &EI);
00221   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
00222   Instruction *visitExtractValueInst(ExtractValueInst &EV);
00223   Instruction *visitLandingPadInst(LandingPadInst &LI);
00224 
00225   // visitInstruction - Specify what to return for unhandled instructions...
00226   Instruction *visitInstruction(Instruction &I) { return nullptr; }
00227 
00228 private:
00229   bool ShouldChangeType(Type *From, Type *To) const;
00230   Value *dyn_castNegVal(Value *V) const;
00231   Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
00232   Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
00233                             SmallVectorImpl<Value *> &NewIndices);
00234   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
00235 
00236   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
00237   /// results in any code being generated and is interesting to optimize out. If
00238   /// the cast can be eliminated by some other simple transformation, we prefer
00239   /// to do the simplification first.
00240   bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
00241                           Type *Ty);
00242 
00243   Instruction *visitCallSite(CallSite CS);
00244   Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
00245   bool transformConstExprCastCall(CallSite CS);
00246   Instruction *transformCallThroughTrampoline(CallSite CS,
00247                                               IntrinsicInst *Tramp);
00248   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00249                                  bool DoXform = true);
00250   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
00251   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
00252   bool WillNotOverflowUnsignedAdd(Value *LHS, Value *RHS);
00253   Value *EmitGEPOffset(User *GEP);
00254   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
00255   Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
00256 
00257 public:
00258   // InsertNewInstBefore - insert an instruction New before instruction Old
00259   // in the program.  Add the new instruction to the worklist.
00260   //
00261   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
00262     assert(New && !New->getParent() &&
00263            "New instruction already inserted into a basic block!");
00264     BasicBlock *BB = Old.getParent();
00265     BB->getInstList().insert(&Old, New); // Insert inst
00266     Worklist.Add(New);
00267     return New;
00268   }
00269 
00270   // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
00271   // debug loc.
00272   //
00273   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
00274     New->setDebugLoc(Old.getDebugLoc());
00275     return InsertNewInstBefore(New, Old);
00276   }
00277 
00278   // ReplaceInstUsesWith - This method is to be used when an instruction is
00279   // found to be dead, replacable with another preexisting expression.  Here
00280   // we add all uses of I to the worklist, replace all uses of I with the new
00281   // value, then return I, so that the inst combiner will know that I was
00282   // modified.
00283   //
00284   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
00285     Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
00286 
00287     // If we are replacing the instruction with itself, this must be in a
00288     // segment of unreachable code, so just clobber the instruction.
00289     if (&I == V)
00290       V = UndefValue::get(I.getType());
00291 
00292     DEBUG(dbgs() << "IC: Replacing " << I << "\n"
00293                     "    with " << *V << '\n');
00294 
00295     I.replaceAllUsesWith(V);
00296     return &I;
00297   }
00298 
00299   // EraseInstFromFunction - When dealing with an instruction that has side
00300   // effects or produces a void value, we can't rely on DCE to delete the
00301   // instruction.  Instead, visit methods should return the value returned by
00302   // this function.
00303   Instruction *EraseInstFromFunction(Instruction &I) {
00304     DEBUG(dbgs() << "IC: ERASE " << I << '\n');
00305 
00306     assert(I.use_empty() && "Cannot erase instruction that is used!");
00307     // Make sure that we reprocess all operands now that we reduced their
00308     // use counts.
00309     if (I.getNumOperands() < 8) {
00310       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
00311         if (Instruction *Op = dyn_cast<Instruction>(*i))
00312           Worklist.Add(Op);
00313     }
00314     Worklist.Remove(&I);
00315     I.eraseFromParent();
00316     MadeIRChange = true;
00317     return nullptr; // Don't do anything with FI
00318   }
00319 
00320   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00321                         unsigned Depth = 0) const {
00322     return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth);
00323   }
00324 
00325   bool MaskedValueIsZero(Value *V, const APInt &Mask,
00326                          unsigned Depth = 0) const {
00327     return llvm::MaskedValueIsZero(V, Mask, DL, Depth);
00328   }
00329   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
00330     return llvm::ComputeNumSignBits(Op, DL, Depth);
00331   }
00332 
00333 private:
00334   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00335   /// operators which are associative or commutative.
00336   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
00337 
00338   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00339   /// which some other binary operation distributes over either by factorizing
00340   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00341   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00342   /// a win).  Returns the simplified value, or null if it didn't simplify.
00343   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
00344 
00345   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
00346   /// based on the demanded bits.
00347   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
00348                                  APInt &KnownOne, unsigned Depth);
00349   bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
00350                             APInt &KnownOne, unsigned Depth = 0);
00351   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
00352   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
00353   Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
00354                                     APInt DemandedMask, APInt &KnownZero,
00355                                     APInt &KnownOne);
00356 
00357   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00358   /// SimplifyDemandedBits knows about.  See if the instruction has any
00359   /// properties that allow us to simplify its operands.
00360   bool SimplifyDemandedInstructionBits(Instruction &Inst);
00361 
00362   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
00363                                     APInt &UndefElts, unsigned Depth = 0);
00364 
00365   Value *SimplifyVectorOp(BinaryOperator &Inst);
00366 
00367   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
00368   // which has a PHI node as operand #0, see if we can fold the instruction
00369   // into the PHI (which is only possible if all operands to the PHI are
00370   // constants).
00371   //
00372   Instruction *FoldOpIntoPhi(Instruction &I);
00373 
00374   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
00375   // operator and they all are only used by the PHI, PHI together their
00376   // inputs, and do the operation once, to the result of the PHI.
00377   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
00378   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
00379   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
00380   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
00381 
00382   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
00383                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
00384 
00385   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
00386                             bool isSub, Instruction &I);
00387   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
00388                          bool Inside);
00389   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
00390   Instruction *MatchBSwap(BinaryOperator &I);
00391   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
00392   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
00393   Instruction *SimplifyMemSet(MemSetInst *MI);
00394 
00395   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
00396 
00397   /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00398   /// the multiplication is known not to overflow then NoSignedWrap is set.
00399   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
00400 };
00401 
00402 } // end namespace llvm.
00403 
00404 #undef DEBUG_TYPE
00405 
00406 #endif