1 //===- InstCombineInternal.h - InstCombine pass internals -------*- 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 //===----------------------------------------------------------------------===//
11 /// This file provides internal interfaces used to implement the InstCombine.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetFolder.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/InstVisitor.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
31 #define DEBUG_TYPE "instcombine"
37 class TargetLibraryInfo;
42 /// \brief Specific patterns of select instructions we can match.
43 enum SelectPatternFlavor {
53 /// \brief Assign a complexity or rank value to LLVM Values.
55 /// This routine maps IR values to various complexity ranks:
58 /// 2 -> Other non-instructions
60 /// 3 -> Unary operations
61 /// 4 -> Other instructions
62 static inline unsigned getComplexity(Value *V) {
63 if (isa<Instruction>(V)) {
64 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
65 BinaryOperator::isNot(V))
71 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
74 /// \brief Add one to a Constant
75 static inline Constant *AddOne(Constant *C) {
76 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
78 /// \brief Subtract one from a Constant
79 static inline Constant *SubOne(Constant *C) {
80 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
83 /// \brief An IRBuilder inserter that adds new instructions to the instcombine
85 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
86 : public IRBuilderDefaultInserter<true> {
87 InstCombineWorklist &Worklist;
91 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
92 : Worklist(WL), AC(AC) {}
94 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
95 BasicBlock::iterator InsertPt) const {
96 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
99 using namespace llvm::PatternMatch;
100 if (match(I, m_Intrinsic<Intrinsic::assume>()))
101 AC->registerAssumption(cast<CallInst>(I));
105 /// \brief The core instruction combiner logic.
107 /// This class provides both the logic to recursively visit instructions and
108 /// combine them, as well as the pass infrastructure for running this as part
109 /// of the LLVM pass pipeline.
110 class LLVM_LIBRARY_VISIBILITY InstCombiner
111 : public InstVisitor<InstCombiner, Instruction *> {
112 // FIXME: These members shouldn't be public.
114 /// \brief A worklist of the instructions that need to be simplified.
115 InstCombineWorklist &Worklist;
117 /// \brief An IRBuilder that automatically inserts new instructions into the
119 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
123 // Mode in which we are running the combiner.
124 const bool MinimizeSize;
126 // Required analyses.
127 // FIXME: These can never be null and should be references.
129 TargetLibraryInfo *TLI;
132 // Optional analyses. When non-null, these can both be used to do better
133 // combining and will be updated to reflect any changes.
134 const DataLayout *DL;
140 InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
141 bool MinimizeSize, AssumptionCache *AC, TargetLibraryInfo *TLI,
142 DominatorTree *DT, const DataLayout *DL, LoopInfo *LI)
143 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
144 AC(AC), TLI(TLI), DT(DT), DL(DL), LI(LI), MadeIRChange(false) {}
146 /// \brief Run the combiner over the entire worklist until it is empty.
148 /// \returns true if the IR is changed.
151 AssumptionCache *getAssumptionCache() const { return AC; }
153 const DataLayout *getDataLayout() const { return DL; }
155 DominatorTree *getDominatorTree() const { return DT; }
157 LoopInfo *getLoopInfo() const { return LI; }
159 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitFAdd(BinaryOperator &I);
170 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
171 Instruction *visitSub(BinaryOperator &I);
172 Instruction *visitFSub(BinaryOperator &I);
173 Instruction *visitMul(BinaryOperator &I);
174 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
175 Instruction *InsertBefore);
176 Instruction *visitFMul(BinaryOperator &I);
177 Instruction *visitURem(BinaryOperator &I);
178 Instruction *visitSRem(BinaryOperator &I);
179 Instruction *visitFRem(BinaryOperator &I);
180 bool SimplifyDivRemOfSelect(BinaryOperator &I);
181 Instruction *commonRemTransforms(BinaryOperator &I);
182 Instruction *commonIRemTransforms(BinaryOperator &I);
183 Instruction *commonDivTransforms(BinaryOperator &I);
184 Instruction *commonIDivTransforms(BinaryOperator &I);
185 Instruction *visitUDiv(BinaryOperator &I);
186 Instruction *visitSDiv(BinaryOperator &I);
187 Instruction *visitFDiv(BinaryOperator &I);
188 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
189 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
190 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
191 Instruction *visitAnd(BinaryOperator &I);
192 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
193 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
196 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
198 Instruction *visitOr(BinaryOperator &I);
199 Instruction *visitXor(BinaryOperator &I);
200 Instruction *visitShl(BinaryOperator &I);
201 Instruction *visitAShr(BinaryOperator &I);
202 Instruction *visitLShr(BinaryOperator &I);
203 Instruction *commonShiftTransforms(BinaryOperator &I);
204 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
207 GlobalVariable *GV, CmpInst &ICI,
208 ConstantInt *AndCst = nullptr);
209 Instruction *visitFCmpInst(FCmpInst &I);
210 Instruction *visitICmpInst(ICmpInst &I);
211 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
212 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
214 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
215 ConstantInt *DivRHS);
216 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
217 ConstantInt *DivRHS);
218 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
219 ConstantInt *CI1, ConstantInt *CI2);
220 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
221 ConstantInt *CI1, ConstantInt *CI2);
222 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
223 ICmpInst::Predicate Pred);
224 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
225 ICmpInst::Predicate Cond, Instruction &I);
226 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
228 Instruction *commonCastTransforms(CastInst &CI);
229 Instruction *commonPointerCastTransforms(CastInst &CI);
230 Instruction *visitTrunc(TruncInst &CI);
231 Instruction *visitZExt(ZExtInst &CI);
232 Instruction *visitSExt(SExtInst &CI);
233 Instruction *visitFPTrunc(FPTruncInst &CI);
234 Instruction *visitFPExt(CastInst &CI);
235 Instruction *visitFPToUI(FPToUIInst &FI);
236 Instruction *visitFPToSI(FPToSIInst &FI);
237 Instruction *visitUIToFP(CastInst &CI);
238 Instruction *visitSIToFP(CastInst &CI);
239 Instruction *visitPtrToInt(PtrToIntInst &CI);
240 Instruction *visitIntToPtr(IntToPtrInst &CI);
241 Instruction *visitBitCast(BitCastInst &CI);
242 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
243 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
244 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
245 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
246 Value *A, Value *B, Instruction &Outer,
247 SelectPatternFlavor SPF2, Value *C);
248 Instruction *FoldItoFPtoI(Instruction &FI);
249 Instruction *visitSelectInst(SelectInst &SI);
250 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
251 Instruction *visitCallInst(CallInst &CI);
252 Instruction *visitInvokeInst(InvokeInst &II);
254 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
255 Instruction *visitPHINode(PHINode &PN);
256 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
257 Instruction *visitAllocaInst(AllocaInst &AI);
258 Instruction *visitAllocSite(Instruction &FI);
259 Instruction *visitFree(CallInst &FI);
260 Instruction *visitLoadInst(LoadInst &LI);
261 Instruction *visitStoreInst(StoreInst &SI);
262 Instruction *visitBranchInst(BranchInst &BI);
263 Instruction *visitSwitchInst(SwitchInst &SI);
264 Instruction *visitReturnInst(ReturnInst &RI);
265 Instruction *visitInsertValueInst(InsertValueInst &IV);
266 Instruction *visitInsertElementInst(InsertElementInst &IE);
267 Instruction *visitExtractElementInst(ExtractElementInst &EI);
268 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
269 Instruction *visitExtractValueInst(ExtractValueInst &EV);
270 Instruction *visitLandingPadInst(LandingPadInst &LI);
272 // visitInstruction - Specify what to return for unhandled instructions...
273 Instruction *visitInstruction(Instruction &I) { return nullptr; }
275 // True when DB dominates all uses of DI execpt UI.
276 // UI must be in the same block as DI.
277 // The routine checks that the DI parent and DB are different.
278 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
279 const BasicBlock *DB) const;
281 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
282 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
283 const unsigned SIOpd);
286 bool ShouldChangeType(Type *From, Type *To) const;
287 Value *dyn_castNegVal(Value *V) const;
288 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
289 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
290 SmallVectorImpl<Value *> &NewIndices);
291 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
293 /// \brief Classify whether a cast is worth optimizing.
295 /// Returns true if the cast from "V to Ty" actually results in any code
296 /// being generated and is interesting to optimize out. If the cast can be
297 /// eliminated by some other simple transformation, we prefer to do the
298 /// simplification first.
299 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
302 Instruction *visitCallSite(CallSite CS);
303 Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
304 bool transformConstExprCastCall(CallSite CS);
305 Instruction *transformCallThroughTrampoline(CallSite CS,
306 IntrinsicInst *Tramp);
307 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
308 bool DoXform = true);
309 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
310 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
311 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
312 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
313 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction *CxtI);
314 Value *EmitGEPOffset(User *GEP);
315 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
316 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
319 /// \brief Inserts an instruction \p New before instruction \p Old
321 /// Also adds the new instruction to the worklist and returns \p New so that
322 /// it is suitable for use as the return from the visitation patterns.
323 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
324 assert(New && !New->getParent() &&
325 "New instruction already inserted into a basic block!");
326 BasicBlock *BB = Old.getParent();
327 BB->getInstList().insert(&Old, New); // Insert inst
332 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
333 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
334 New->setDebugLoc(Old.getDebugLoc());
335 return InsertNewInstBefore(New, Old);
338 /// \brief A combiner-aware RAUW-like routine.
340 /// This method is to be used when an instruction is found to be dead,
341 /// replacable with another preexisting expression. Here we add all uses of
342 /// I to the worklist, replace all uses of I with the new value, then return
343 /// I, so that the inst combiner will know that I was modified.
344 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
345 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
347 // If we are replacing the instruction with itself, this must be in a
348 // segment of unreachable code, so just clobber the instruction.
350 V = UndefValue::get(I.getType());
352 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
353 << " with " << *V << '\n');
355 I.replaceAllUsesWith(V);
359 /// Creates a result tuple for an overflow intrinsic \p II with a given
360 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
361 /// \p Result's name is taken from \p II.
362 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
363 bool Overflow, bool ReUseName = true) {
365 Result->takeName(II);
366 Constant *V[] = {UndefValue::get(Result->getType()),
367 Overflow ? Builder->getTrue() : Builder->getFalse()};
368 StructType *ST = cast<StructType>(II->getType());
369 Constant *Struct = ConstantStruct::get(ST, V);
370 return InsertValueInst::Create(Struct, Result, 0);
373 /// \brief Combiner aware instruction erasure.
375 /// When dealing with an instruction that has side effects or produces a void
376 /// value, we can't rely on DCE to delete the instruction. Instead, visit
377 /// methods should return the value returned by this function.
378 Instruction *EraseInstFromFunction(Instruction &I) {
379 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
381 assert(I.use_empty() && "Cannot erase instruction that is used!");
382 // Make sure that we reprocess all operands now that we reduced their
384 if (I.getNumOperands() < 8) {
385 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
386 if (Instruction *Op = dyn_cast<Instruction>(*i))
392 return nullptr; // Don't do anything with FI
395 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
396 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
397 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
401 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
402 Instruction *CxtI = nullptr) const {
403 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
405 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
406 Instruction *CxtI = nullptr) const {
407 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
409 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
410 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
411 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
414 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
415 const Instruction *CxtI) {
416 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
418 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
419 const Instruction *CxtI) {
420 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
424 /// \brief Performs a few simplifications for operators which are associative
426 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
428 /// \brief Tries to simplify binary operations which some other binary
429 /// operation distributes over.
431 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
432 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
433 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
434 /// value, or null if it didn't simplify.
435 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
437 /// \brief Attempts to replace V with a simpler value based on the demanded
439 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
440 APInt &KnownOne, unsigned Depth,
441 Instruction *CxtI = nullptr);
442 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
443 APInt &KnownOne, unsigned Depth = 0);
444 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
445 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
446 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
447 APInt DemandedMask, APInt &KnownZero,
450 /// \brief Tries to simplify operands to an integer instruction based on its
452 bool SimplifyDemandedInstructionBits(Instruction &Inst);
454 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
455 APInt &UndefElts, unsigned Depth = 0);
457 Value *SimplifyVectorOp(BinaryOperator &Inst);
458 Value *SimplifyBSwap(BinaryOperator &Inst);
460 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
461 // which has a PHI node as operand #0, see if we can fold the instruction
462 // into the PHI (which is only possible if all operands to the PHI are
465 Instruction *FoldOpIntoPhi(Instruction &I);
467 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
469 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
470 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
471 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
472 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
474 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
475 ConstantInt *AndRHS, BinaryOperator &TheAnd);
477 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
478 bool isSub, Instruction &I);
479 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
481 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
482 Instruction *MatchBSwap(BinaryOperator &I);
483 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
484 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
485 Instruction *SimplifyMemSet(MemSetInst *MI);
487 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
489 /// \brief Returns a value X such that Val = X * Scale, or null if none.
491 /// If the multiplication is known not to overflow then NoSignedWrap is set.
492 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
495 } // end namespace llvm.