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