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/AssumptionTracker.h"
15 #include "llvm/Analysis/TargetFolder.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/InstVisitor.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/Operator.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
26 #define DEBUG_TYPE "instcombine"
32 class TargetLibraryInfo;
37 /// SelectPatternFlavor - We can match a variety of different patterns for
38 /// select operations.
39 enum SelectPatternFlavor {
49 /// getComplexity: Assign a complexity or rank value to LLVM Values...
50 /// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
51 static inline unsigned getComplexity(Value *V) {
52 if (isa<Instruction>(V)) {
53 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
54 BinaryOperator::isNot(V))
60 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
63 /// AddOne - Add one to a Constant
64 static inline Constant *AddOne(Constant *C) {
65 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
67 /// SubOne - Subtract one from a Constant
68 static inline Constant *SubOne(Constant *C) {
69 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
72 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
73 /// just like the normal insertion helper, but also adds any new instructions
74 /// to the instcombine worklist.
75 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
76 : public IRBuilderDefaultInserter<true> {
77 InstCombineWorklist &Worklist;
78 AssumptionTracker *AT;
81 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionTracker *AT)
82 : Worklist(WL), AT(AT) {}
84 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
85 BasicBlock::iterator InsertPt) const {
86 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
89 using namespace llvm::PatternMatch;
90 if (match(I, m_Intrinsic<Intrinsic::assume>()))
91 AT->registerAssumption(cast<CallInst>(I));
95 /// InstCombiner - The -instcombine pass.
96 class LLVM_LIBRARY_VISIBILITY InstCombiner
97 : public FunctionPass,
98 public InstVisitor<InstCombiner, Instruction *> {
99 AssumptionTracker *AT;
100 const DataLayout *DL;
101 TargetLibraryInfo *TLI;
104 LibCallSimplifier *Simplifier;
108 /// Worklist - All of the instructions that need to be simplified.
109 InstCombineWorklist Worklist;
111 /// Builder - This is an IRBuilder that automatically inserts new
112 /// instructions into the worklist when they are created.
113 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
116 static char ID; // Pass identification, replacement for typeid
118 : FunctionPass(ID), DL(nullptr), DT(nullptr), Builder(nullptr) {
119 MinimizeSize = false;
120 initializeInstCombinerPass(*PassRegistry::getPassRegistry());
124 bool runOnFunction(Function &F) override;
126 bool DoOneIteration(Function &F, unsigned ItNum);
128 void getAnalysisUsage(AnalysisUsage &AU) const override;
130 AssumptionTracker *getAssumptionTracker() const { return AT; }
132 const DataLayout *getDataLayout() const { return DL; }
134 DominatorTree *getDominatorTree() const { return DT; }
136 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
138 // Visitation implementation - Implement instruction combining for different
139 // instruction types. The semantics are as follows:
141 // null - No change was made
142 // I - Change was made, I is still valid, I may be dead though
143 // otherwise - Change was made, replace I with returned instruction
145 Instruction *visitAdd(BinaryOperator &I);
146 Instruction *visitFAdd(BinaryOperator &I);
147 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
148 Instruction *visitSub(BinaryOperator &I);
149 Instruction *visitFSub(BinaryOperator &I);
150 Instruction *visitMul(BinaryOperator &I);
151 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
152 Instruction *InsertBefore);
153 Instruction *visitFMul(BinaryOperator &I);
154 Instruction *visitURem(BinaryOperator &I);
155 Instruction *visitSRem(BinaryOperator &I);
156 Instruction *visitFRem(BinaryOperator &I);
157 bool SimplifyDivRemOfSelect(BinaryOperator &I);
158 Instruction *commonRemTransforms(BinaryOperator &I);
159 Instruction *commonIRemTransforms(BinaryOperator &I);
160 Instruction *commonDivTransforms(BinaryOperator &I);
161 Instruction *commonIDivTransforms(BinaryOperator &I);
162 Instruction *visitUDiv(BinaryOperator &I);
163 Instruction *visitSDiv(BinaryOperator &I);
164 Instruction *visitFDiv(BinaryOperator &I);
165 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
166 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
167 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
168 Instruction *visitAnd(BinaryOperator &I);
169 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
170 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
171 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
173 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
175 Instruction *visitOr(BinaryOperator &I);
176 Instruction *visitXor(BinaryOperator &I);
177 Instruction *visitShl(BinaryOperator &I);
178 Instruction *visitAShr(BinaryOperator &I);
179 Instruction *visitLShr(BinaryOperator &I);
180 Instruction *commonShiftTransforms(BinaryOperator &I);
181 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
183 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
184 GlobalVariable *GV, CmpInst &ICI,
185 ConstantInt *AndCst = nullptr);
186 Instruction *visitFCmpInst(FCmpInst &I);
187 Instruction *visitICmpInst(ICmpInst &I);
188 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
189 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
191 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
192 ConstantInt *DivRHS);
193 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
195 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
196 ConstantInt *CI1, ConstantInt *CI2);
197 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
198 ConstantInt *CI1, ConstantInt *CI2);
199 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
200 ICmpInst::Predicate Pred);
201 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
203 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonPointerCastTransforms(CastInst &CI);
207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
210 Instruction *visitFPTrunc(FPTruncInst &CI);
211 Instruction *visitFPExt(CastInst &CI);
212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(PtrToIntInst &CI);
217 Instruction *visitIntToPtr(IntToPtrInst &CI);
218 Instruction *visitBitCast(BitCastInst &CI);
219 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
221 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
222 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
223 Value *A, Value *B, Instruction &Outer,
224 SelectPatternFlavor SPF2, Value *C);
225 Instruction *visitSelectInst(SelectInst &SI);
226 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
227 Instruction *visitCallInst(CallInst &CI);
228 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
231 Instruction *visitPHINode(PHINode &PN);
232 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
233 Instruction *visitAllocaInst(AllocaInst &AI);
234 Instruction *visitAllocSite(Instruction &FI);
235 Instruction *visitFree(CallInst &FI);
236 Instruction *visitLoadInst(LoadInst &LI);
237 Instruction *visitStoreInst(StoreInst &SI);
238 Instruction *visitBranchInst(BranchInst &BI);
239 Instruction *visitSwitchInst(SwitchInst &SI);
240 Instruction *visitReturnInst(ReturnInst &RI);
241 Instruction *visitInsertValueInst(InsertValueInst &IV);
242 Instruction *visitInsertElementInst(InsertElementInst &IE);
243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
246 Instruction *visitLandingPadInst(LandingPadInst &LI);
248 // visitInstruction - Specify what to return for unhandled instructions...
249 Instruction *visitInstruction(Instruction &I) { return nullptr; }
251 // True when DB dominates all uses of DI execpt UI.
252 // UI must be in the same block as DI.
253 // The routine checks that the DI parent and DB are different.
254 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
255 const BasicBlock *DB) const;
257 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
258 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
259 const unsigned SIOpd);
262 bool ShouldChangeType(Type *From, Type *To) const;
263 Value *dyn_castNegVal(Value *V) const;
264 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
265 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
266 SmallVectorImpl<Value *> &NewIndices);
267 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
269 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
270 /// results in any code being generated and is interesting to optimize out. If
271 /// the cast can be eliminated by some other simple transformation, we prefer
272 /// to do the simplification first.
273 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
276 Instruction *visitCallSite(CallSite CS);
277 Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
278 bool transformConstExprCastCall(CallSite CS);
279 Instruction *transformCallThroughTrampoline(CallSite CS,
280 IntrinsicInst *Tramp);
281 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
282 bool DoXform = true);
283 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
284 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
285 bool WillNotOverflowUnsignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
286 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
287 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
288 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction *CxtI);
289 Value *EmitGEPOffset(User *GEP);
290 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
291 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
294 // InsertNewInstBefore - insert an instruction New before instruction Old
295 // in the program. Add the new instruction to the worklist.
297 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
298 assert(New && !New->getParent() &&
299 "New instruction already inserted into a basic block!");
300 BasicBlock *BB = Old.getParent();
301 BB->getInstList().insert(&Old, New); // Insert inst
306 // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
309 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
310 New->setDebugLoc(Old.getDebugLoc());
311 return InsertNewInstBefore(New, Old);
314 // ReplaceInstUsesWith - This method is to be used when an instruction is
315 // found to be dead, replacable with another preexisting expression. Here
316 // we add all uses of I to the worklist, replace all uses of I with the new
317 // value, then return I, so that the inst combiner will know that I was
320 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
321 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
323 // If we are replacing the instruction with itself, this must be in a
324 // segment of unreachable code, so just clobber the instruction.
326 V = UndefValue::get(I.getType());
328 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
329 " with " << *V << '\n');
331 I.replaceAllUsesWith(V);
335 /// Creates a result tuple for an overflow intrinsic \p II with a given
336 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
337 /// \p Result's name is taken from \p II.
338 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
339 bool Overflow, bool ReUseName = true) {
341 Result->takeName(II);
342 Constant *V[] = { UndefValue::get(Result->getType()),
343 Overflow ? Builder->getTrue() : Builder->getFalse() };
344 StructType *ST = cast<StructType>(II->getType());
345 Constant *Struct = ConstantStruct::get(ST, V);
346 return InsertValueInst::Create(Struct, Result, 0);
349 // EraseInstFromFunction - When dealing with an instruction that has side
350 // effects or produces a void value, we can't rely on DCE to delete the
351 // instruction. Instead, visit methods should return the value returned by
353 Instruction *EraseInstFromFunction(Instruction &I) {
354 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
356 assert(I.use_empty() && "Cannot erase instruction that is used!");
357 // Make sure that we reprocess all operands now that we reduced their
359 if (I.getNumOperands() < 8) {
360 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
361 if (Instruction *Op = dyn_cast<Instruction>(*i))
367 return nullptr; // Don't do anything with FI
370 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
371 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
372 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
376 bool MaskedValueIsZero(Value *V, const APInt &Mask,
378 Instruction *CxtI = nullptr) const {
379 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AT, CxtI, DT);
381 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
382 Instruction *CxtI = nullptr) const {
383 return llvm::ComputeNumSignBits(Op, DL, Depth, AT, CxtI, DT);
385 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
386 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
387 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AT, CxtI,
392 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
393 /// operators which are associative or commutative.
394 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
396 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
397 /// which some other binary operation distributes over either by factorizing
398 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
399 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
400 /// a win). Returns the simplified value, or null if it didn't simplify.
401 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
403 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
404 /// based on the demanded bits.
405 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
406 APInt &KnownOne, unsigned Depth,
407 Instruction *CxtI = nullptr);
408 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
409 APInt &KnownOne, unsigned Depth = 0);
410 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
411 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
412 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
413 APInt DemandedMask, APInt &KnownZero,
416 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
417 /// SimplifyDemandedBits knows about. See if the instruction has any
418 /// properties that allow us to simplify its operands.
419 bool SimplifyDemandedInstructionBits(Instruction &Inst);
421 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
422 APInt &UndefElts, unsigned Depth = 0);
424 Value *SimplifyVectorOp(BinaryOperator &Inst);
425 Value *SimplifyBSwap(BinaryOperator &Inst);
427 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
428 // which has a PHI node as operand #0, see if we can fold the instruction
429 // into the PHI (which is only possible if all operands to the PHI are
432 Instruction *FoldOpIntoPhi(Instruction &I);
434 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
435 // operator and they all are only used by the PHI, PHI together their
436 // inputs, and do the operation once, to the result of the PHI.
437 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
438 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
439 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
440 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
442 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
443 ConstantInt *AndRHS, BinaryOperator &TheAnd);
445 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
446 bool isSub, Instruction &I);
447 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
449 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
450 Instruction *MatchBSwap(BinaryOperator &I);
451 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
452 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
453 Instruction *SimplifyMemSet(MemSetInst *MI);
455 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
457 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
458 /// the multiplication is known not to overflow then NoSignedWrap is set.
459 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
462 } // end namespace llvm.