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