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