1 //===- InstCombine.h - Main InstCombine pass definition ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
11 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
13 #include "InstCombineWorklist.h"
14 #include "llvm/Analysis/AssumptionCache.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/TargetFolder.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/InstVisitor.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/IR/PatternMatch.h"
24 #include "llvm/Pass.h"
26 #define DEBUG_TYPE "instcombine"
32 class TargetLibraryInfo;
37 /// \brief Specific patterns of select instructions we can match.
38 enum SelectPatternFlavor {
48 /// \brief Assign a complexity or rank value to LLVM Values.
50 /// This routine maps IR values to various complexity ranks:
53 /// 2 -> Other non-instructions
55 /// 3 -> Unary operations
56 /// 4 -> Other instructions
57 static inline unsigned getComplexity(Value *V) {
58 if (isa<Instruction>(V)) {
59 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
60 BinaryOperator::isNot(V))
66 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
69 /// \brief Add one to a Constant
70 static inline Constant *AddOne(Constant *C) {
71 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
73 /// \brief Subtract one from a Constant
74 static inline Constant *SubOne(Constant *C) {
75 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
78 /// \brief An IRBuilder inserter that adds new instructions to the instcombine
80 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
81 : public IRBuilderDefaultInserter<true> {
82 InstCombineWorklist &Worklist;
86 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
87 : Worklist(WL), AC(AC) {}
89 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
90 BasicBlock::iterator InsertPt) const {
91 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
94 using namespace llvm::PatternMatch;
95 if (match(I, m_Intrinsic<Intrinsic::assume>()))
96 AC->registerAssumption(cast<CallInst>(I));
100 /// \brief The core instruction combiner logic.
102 /// This class provides both the logic to recursively visit instructions and
103 /// combine them, as well as the pass infrastructure for running this as part
104 /// of the LLVM pass pipeline.
105 class LLVM_LIBRARY_VISIBILITY InstCombiner
106 : public InstVisitor<InstCombiner, Instruction *> {
108 const DataLayout *DL;
109 TargetLibraryInfo *TLI;
116 /// \brief A worklist of the instructions that need to be simplified.
117 InstCombineWorklist Worklist;
119 /// \brief An IRBuilder that automatically inserts new instructions into the
121 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
124 InstCombiner() : DL(nullptr), DT(nullptr), LI(nullptr), Builder(nullptr) {
125 MinimizeSize = false;
129 bool run(Function &F, AssumptionCache *AC, const DataLayout *DL,
130 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI);
132 bool DoOneIteration(Function &F, unsigned ItNum);
134 AssumptionCache *getAssumptionCache() const { return AC; }
136 const DataLayout *getDataLayout() const { return DL; }
138 DominatorTree *getDominatorTree() const { return DT; }
140 LoopInfo *getLoopInfo() const { return LI; }
142 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
144 // Visitation implementation - Implement instruction combining for different
145 // instruction types. The semantics are as follows:
147 // null - No change was made
148 // I - Change was made, I is still valid, I may be dead though
149 // otherwise - Change was made, replace I with returned instruction
151 Instruction *visitAdd(BinaryOperator &I);
152 Instruction *visitFAdd(BinaryOperator &I);
153 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
154 Instruction *visitSub(BinaryOperator &I);
155 Instruction *visitFSub(BinaryOperator &I);
156 Instruction *visitMul(BinaryOperator &I);
157 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
158 Instruction *InsertBefore);
159 Instruction *visitFMul(BinaryOperator &I);
160 Instruction *visitURem(BinaryOperator &I);
161 Instruction *visitSRem(BinaryOperator &I);
162 Instruction *visitFRem(BinaryOperator &I);
163 bool SimplifyDivRemOfSelect(BinaryOperator &I);
164 Instruction *commonRemTransforms(BinaryOperator &I);
165 Instruction *commonIRemTransforms(BinaryOperator &I);
166 Instruction *commonDivTransforms(BinaryOperator &I);
167 Instruction *commonIDivTransforms(BinaryOperator &I);
168 Instruction *visitUDiv(BinaryOperator &I);
169 Instruction *visitSDiv(BinaryOperator &I);
170 Instruction *visitFDiv(BinaryOperator &I);
171 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
172 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
173 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
174 Instruction *visitAnd(BinaryOperator &I);
175 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
176 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
177 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
179 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
181 Instruction *visitOr(BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
187 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
190 GlobalVariable *GV, CmpInst &ICI,
191 ConstantInt *AndCst = nullptr);
192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
199 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
200 ConstantInt *DivRHS);
201 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
202 ConstantInt *CI1, ConstantInt *CI2);
203 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
204 ConstantInt *CI1, ConstantInt *CI2);
205 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
206 ICmpInst::Predicate Pred);
207 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
208 ICmpInst::Predicate Cond, Instruction &I);
209 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
211 Instruction *commonCastTransforms(CastInst &CI);
212 Instruction *commonPointerCastTransforms(CastInst &CI);
213 Instruction *visitTrunc(TruncInst &CI);
214 Instruction *visitZExt(ZExtInst &CI);
215 Instruction *visitSExt(SExtInst &CI);
216 Instruction *visitFPTrunc(FPTruncInst &CI);
217 Instruction *visitFPExt(CastInst &CI);
218 Instruction *visitFPToUI(FPToUIInst &FI);
219 Instruction *visitFPToSI(FPToSIInst &FI);
220 Instruction *visitUIToFP(CastInst &CI);
221 Instruction *visitSIToFP(CastInst &CI);
222 Instruction *visitPtrToInt(PtrToIntInst &CI);
223 Instruction *visitIntToPtr(IntToPtrInst &CI);
224 Instruction *visitBitCast(BitCastInst &CI);
225 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
226 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
227 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
228 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
229 Value *A, Value *B, Instruction &Outer,
230 SelectPatternFlavor SPF2, Value *C);
231 Instruction *visitSelectInst(SelectInst &SI);
232 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
233 Instruction *visitCallInst(CallInst &CI);
234 Instruction *visitInvokeInst(InvokeInst &II);
236 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
237 Instruction *visitPHINode(PHINode &PN);
238 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
239 Instruction *visitAllocaInst(AllocaInst &AI);
240 Instruction *visitAllocSite(Instruction &FI);
241 Instruction *visitFree(CallInst &FI);
242 Instruction *visitLoadInst(LoadInst &LI);
243 Instruction *visitStoreInst(StoreInst &SI);
244 Instruction *visitBranchInst(BranchInst &BI);
245 Instruction *visitSwitchInst(SwitchInst &SI);
246 Instruction *visitReturnInst(ReturnInst &RI);
247 Instruction *visitInsertValueInst(InsertValueInst &IV);
248 Instruction *visitInsertElementInst(InsertElementInst &IE);
249 Instruction *visitExtractElementInst(ExtractElementInst &EI);
250 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
251 Instruction *visitExtractValueInst(ExtractValueInst &EV);
252 Instruction *visitLandingPadInst(LandingPadInst &LI);
254 // visitInstruction - Specify what to return for unhandled instructions...
255 Instruction *visitInstruction(Instruction &I) { return nullptr; }
257 // True when DB dominates all uses of DI execpt UI.
258 // UI must be in the same block as DI.
259 // The routine checks that the DI parent and DB are different.
260 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
261 const BasicBlock *DB) const;
263 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
264 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
265 const unsigned SIOpd);
268 bool ShouldChangeType(Type *From, Type *To) const;
269 Value *dyn_castNegVal(Value *V) const;
270 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
271 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
272 SmallVectorImpl<Value *> &NewIndices);
273 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
275 /// \brief Classify whether a cast is worth optimizing.
277 /// Returns true if the cast from "V to Ty" actually results in any code
278 /// being generated and is interesting to optimize out. If the cast can be
279 /// eliminated by some other simple transformation, we prefer to do the
280 /// simplification first.
281 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
284 Instruction *visitCallSite(CallSite CS);
285 Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
286 bool transformConstExprCastCall(CallSite CS);
287 Instruction *transformCallThroughTrampoline(CallSite CS,
288 IntrinsicInst *Tramp);
289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
291 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
292 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
293 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
294 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
295 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction *CxtI);
296 Value *EmitGEPOffset(User *GEP);
297 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
298 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
301 /// \brief Inserts an instruction \p New before instruction \p Old
303 /// Also adds the new instruction to the worklist and returns \p New so that
304 /// it is suitable for use as the return from the visitation patterns.
305 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
306 assert(New && !New->getParent() &&
307 "New instruction already inserted into a basic block!");
308 BasicBlock *BB = Old.getParent();
309 BB->getInstList().insert(&Old, New); // Insert inst
314 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
315 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
316 New->setDebugLoc(Old.getDebugLoc());
317 return InsertNewInstBefore(New, Old);
320 /// \brief A combiner-aware RAUW-like routine.
322 /// This method is to be used when an instruction is found to be dead,
323 /// replacable with another preexisting expression. Here we add all uses of
324 /// I to the worklist, replace all uses of I with the new value, then return
325 /// I, so that the inst combiner will know that I was modified.
326 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
327 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
329 // If we are replacing the instruction with itself, this must be in a
330 // segment of unreachable code, so just clobber the instruction.
332 V = UndefValue::get(I.getType());
334 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
335 << " with " << *V << '\n');
337 I.replaceAllUsesWith(V);
341 /// Creates a result tuple for an overflow intrinsic \p II with a given
342 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
343 /// \p Result's name is taken from \p II.
344 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
345 bool Overflow, bool ReUseName = true) {
347 Result->takeName(II);
348 Constant *V[] = {UndefValue::get(Result->getType()),
349 Overflow ? Builder->getTrue() : Builder->getFalse()};
350 StructType *ST = cast<StructType>(II->getType());
351 Constant *Struct = ConstantStruct::get(ST, V);
352 return InsertValueInst::Create(Struct, Result, 0);
355 /// \brief Combiner aware instruction erasure.
357 /// When dealing with an instruction that has side effects or produces a void
358 /// value, we can't rely on DCE to delete the instruction. Instead, visit
359 /// methods should return the value returned by this function.
360 Instruction *EraseInstFromFunction(Instruction &I) {
361 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
363 assert(I.use_empty() && "Cannot erase instruction that is used!");
364 // Make sure that we reprocess all operands now that we reduced their
366 if (I.getNumOperands() < 8) {
367 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
368 if (Instruction *Op = dyn_cast<Instruction>(*i))
374 return nullptr; // Don't do anything with FI
377 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
378 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
379 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
383 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
384 Instruction *CxtI = nullptr) const {
385 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
387 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
388 Instruction *CxtI = nullptr) const {
389 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
391 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
392 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
393 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
396 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
397 const Instruction *CxtI) {
398 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
400 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
401 const Instruction *CxtI) {
402 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
406 /// \brief Performs a few simplifications for operators which are associative
408 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
410 /// \brief Tries to simplify binary operations which some other binary
411 /// operation distributes over.
413 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
414 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
415 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
416 /// value, or null if it didn't simplify.
417 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
419 /// \brief Attempts to replace V with a simpler value based on the demanded
421 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
422 APInt &KnownOne, unsigned Depth,
423 Instruction *CxtI = nullptr);
424 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
425 APInt &KnownOne, unsigned Depth = 0);
426 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
427 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
428 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
429 APInt DemandedMask, APInt &KnownZero,
432 /// \brief Tries to simplify operands to an integer instruction based on its
434 bool SimplifyDemandedInstructionBits(Instruction &Inst);
436 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
437 APInt &UndefElts, unsigned Depth = 0);
439 Value *SimplifyVectorOp(BinaryOperator &Inst);
440 Value *SimplifyBSwap(BinaryOperator &Inst);
442 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
443 // which has a PHI node as operand #0, see if we can fold the instruction
444 // into the PHI (which is only possible if all operands to the PHI are
447 Instruction *FoldOpIntoPhi(Instruction &I);
449 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
451 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
452 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
453 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
454 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
456 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
457 ConstantInt *AndRHS, BinaryOperator &TheAnd);
459 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
460 bool isSub, Instruction &I);
461 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
463 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
464 Instruction *MatchBSwap(BinaryOperator &I);
465 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
466 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
467 Instruction *SimplifyMemSet(MemSetInst *MI);
469 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
471 /// \brief Returns a value X such that Val = X * Scale, or null if none.
473 /// If the multiplication is known not to overflow then NoSignedWrap is set.
474 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
477 } // end namespace llvm.