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