blob: 199df519ce07827f260934fe53c6459984f89744 [file] [log] [blame]
Chris Lattner35522b72010-01-04 07:12:23 +00001//===- InstCombine.h - Main InstCombine pass definition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef INSTCOMBINE_INSTCOMBINE_H
11#define INSTCOMBINE_INSTCOMBINE_H
12
13#include "InstCombineWorklist.h"
Duncan Sandsa0984362011-09-06 13:37:06 +000014#include "llvm/IntrinsicInst.h"
Jay Foad7c14a552011-04-11 09:35:34 +000015#include "llvm/Operator.h"
Chris Lattner35522b72010-01-04 07:12:23 +000016#include "llvm/Pass.h"
17#include "llvm/Analysis/ValueTracking.h"
18#include "llvm/Support/IRBuilder.h"
19#include "llvm/Support/InstVisitor.h"
20#include "llvm/Support/TargetFolder.h"
21
22namespace llvm {
23 class CallSite;
24 class TargetData;
Chad Rosiere6de63d2011-12-01 21:29:16 +000025 class TargetLibraryInfo;
Chris Lattner27acfcd2010-01-05 05:21:26 +000026 class DbgDeclareInst;
27 class MemIntrinsic;
28 class MemSetInst;
Chris Lattner35522b72010-01-04 07:12:23 +000029
30/// SelectPatternFlavor - We can match a variety of different patterns for
31/// select operations.
32enum SelectPatternFlavor {
33 SPF_UNKNOWN = 0,
34 SPF_SMIN, SPF_UMIN,
35 SPF_SMAX, SPF_UMAX
36 //SPF_ABS - TODO.
37};
Chris Lattner2188e402010-01-04 07:37:31 +000038
39/// getComplexity: Assign a complexity or rank value to LLVM Values...
40/// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
41static inline unsigned getComplexity(Value *V) {
42 if (isa<Instruction>(V)) {
43 if (BinaryOperator::isNeg(V) ||
44 BinaryOperator::isFNeg(V) ||
45 BinaryOperator::isNot(V))
46 return 3;
47 return 4;
48 }
49 if (isa<Argument>(V)) return 3;
50 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
51}
Chris Lattner35522b72010-01-04 07:12:23 +000052
53
54/// InstCombineIRInserter - This is an IRBuilder insertion helper that works
55/// just like the normal insertion helper, but also adds any new instructions
56/// to the instcombine worklist.
Duncan Sands6c5e4352010-05-11 20:16:09 +000057class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
Chris Lattner35522b72010-01-04 07:12:23 +000058 : public IRBuilderDefaultInserter<true> {
59 InstCombineWorklist &Worklist;
60public:
61 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
62
63 void InsertHelper(Instruction *I, const Twine &Name,
64 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
65 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
66 Worklist.Add(I);
67 }
68};
69
70/// InstCombiner - The -instcombine pass.
Duncan Sands6c5e4352010-05-11 20:16:09 +000071class LLVM_LIBRARY_VISIBILITY InstCombiner
Chris Lattner35522b72010-01-04 07:12:23 +000072 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
74 TargetData *TD;
Chad Rosiere6de63d2011-12-01 21:29:16 +000075 TargetLibraryInfo *TLI;
Chris Lattner35522b72010-01-04 07:12:23 +000076 bool MadeIRChange;
77public:
78 /// Worklist - All of the instructions that need to be simplified.
79 InstCombineWorklist Worklist;
80
81 /// Builder - This is an IRBuilder that automatically inserts new
82 /// instructions into the worklist when they are created.
83 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
84 BuilderTy *Builder;
85
86 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000087 InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
88 initializeInstCombinerPass(*PassRegistry::getPassRegistry());
89 }
Chris Lattner35522b72010-01-04 07:12:23 +000090
91public:
92 virtual bool runOnFunction(Function &F);
93
94 bool DoOneIteration(Function &F, unsigned ItNum);
95
Chris Lattner7e044912010-01-04 07:17:19 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Chad Rosiere6de63d2011-12-01 21:29:16 +000097
Chris Lattner35522b72010-01-04 07:12:23 +000098 TargetData *getTargetData() const { return TD; }
99
Chad Rosier43a33062011-12-02 01:26:24 +0000100 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
101
Chris Lattner35522b72010-01-04 07:12:23 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
106 // I - Change was made, I is still valid, I may be dead though
107 // otherwise - Change was made, replace I with returned instruction
108 //
109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner229907c2011-07-18 04:54:35 +0000111 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
Chris Lattner35522b72010-01-04 07:12:23 +0000112 Instruction *visitSub(BinaryOperator &I);
113 Instruction *visitFSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitFMul(BinaryOperator &I);
116 Instruction *visitURem(BinaryOperator &I);
117 Instruction *visitSRem(BinaryOperator &I);
118 Instruction *visitFRem(BinaryOperator &I);
119 bool SimplifyDivRemOfSelect(BinaryOperator &I);
120 Instruction *commonRemTransforms(BinaryOperator &I);
121 Instruction *commonIRemTransforms(BinaryOperator &I);
122 Instruction *commonDivTransforms(BinaryOperator &I);
123 Instruction *commonIDivTransforms(BinaryOperator &I);
124 Instruction *visitUDiv(BinaryOperator &I);
125 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel2a559512011-01-29 17:50:27 +0000126 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000127 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
128 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000129 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000130 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
131 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000132 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
133 Value *A, Value *B, Value *C);
134 Instruction *visitOr (BinaryOperator &I);
135 Instruction *visitXor(BinaryOperator &I);
136 Instruction *visitShl(BinaryOperator &I);
137 Instruction *visitAShr(BinaryOperator &I);
138 Instruction *visitLShr(BinaryOperator &I);
139 Instruction *commonShiftTransforms(BinaryOperator &I);
140 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
141 Constant *RHSC);
142 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
143 GlobalVariable *GV, CmpInst &ICI,
144 ConstantInt *AndCst = 0);
145 Instruction *visitFCmpInst(FCmpInst &I);
146 Instruction *visitICmpInst(ICmpInst &I);
147 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
148 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
149 Instruction *LHS,
150 ConstantInt *RHS);
151 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
152 ConstantInt *DivRHS);
Chris Lattnerd369f572011-02-13 07:43:07 +0000153 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
154 ConstantInt *DivRHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000155 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
156 ICmpInst::Predicate Pred, Value *TheAdd);
157 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
158 ICmpInst::Predicate Cond, Instruction &I);
159 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
160 BinaryOperator &I);
161 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000162 Instruction *commonPointerCastTransforms(CastInst &CI);
163 Instruction *visitTrunc(TruncInst &CI);
164 Instruction *visitZExt(ZExtInst &CI);
165 Instruction *visitSExt(SExtInst &CI);
166 Instruction *visitFPTrunc(FPTruncInst &CI);
167 Instruction *visitFPExt(CastInst &CI);
168 Instruction *visitFPToUI(FPToUIInst &FI);
169 Instruction *visitFPToSI(FPToSIInst &FI);
170 Instruction *visitUIToFP(CastInst &CI);
171 Instruction *visitSIToFP(CastInst &CI);
172 Instruction *visitPtrToInt(PtrToIntInst &CI);
173 Instruction *visitIntToPtr(IntToPtrInst &CI);
174 Instruction *visitBitCast(BitCastInst &CI);
175 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
176 Instruction *FI);
177 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
178 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
179 Value *A, Value *B, Instruction &Outer,
180 SelectPatternFlavor SPF2, Value *C);
181 Instruction *visitSelectInst(SelectInst &SI);
182 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
183 Instruction *visitCallInst(CallInst &CI);
184 Instruction *visitInvokeInst(InvokeInst &II);
185
186 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
187 Instruction *visitPHINode(PHINode &PN);
188 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
189 Instruction *visitAllocaInst(AllocaInst &AI);
Duncan Sandsf162eac2010-05-27 19:09:06 +0000190 Instruction *visitMalloc(Instruction &FI);
Gabor Greif75f69432010-06-24 12:21:15 +0000191 Instruction *visitFree(CallInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000192 Instruction *visitLoadInst(LoadInst &LI);
193 Instruction *visitStoreInst(StoreInst &SI);
194 Instruction *visitBranchInst(BranchInst &BI);
195 Instruction *visitSwitchInst(SwitchInst &SI);
196 Instruction *visitInsertElementInst(InsertElementInst &IE);
197 Instruction *visitExtractElementInst(ExtractElementInst &EI);
198 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
199 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Duncan Sands5c055792011-09-30 13:12:16 +0000200 Instruction *visitLandingPadInst(LandingPadInst &LI);
Chris Lattner35522b72010-01-04 07:12:23 +0000201
202 // visitInstruction - Specify what to return for unhandled instructions...
203 Instruction *visitInstruction(Instruction &I) { return 0; }
204
205private:
Chris Lattner229907c2011-07-18 04:54:35 +0000206 bool ShouldChangeType(Type *From, Type *To) const;
Chris Lattner2188e402010-01-04 07:37:31 +0000207 Value *dyn_castNegVal(Value *V) const;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000208 Value *dyn_castFNegVal(Value *V) const;
Chris Lattner229907c2011-07-18 04:54:35 +0000209 Type *FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner2b295a02010-01-04 07:53:58 +0000210 SmallVectorImpl<Value*> &NewIndices);
211 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
212
Chris Lattner4e8137d2010-02-11 06:26:33 +0000213 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
214 /// results in any code being generated and is interesting to optimize out. If
215 /// the cast can be eliminated by some other simple transformation, we prefer
216 /// to do the simplification first.
217 bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000218 Type *Ty);
Chris Lattner2188e402010-01-04 07:37:31 +0000219
Chris Lattner35522b72010-01-04 07:12:23 +0000220 Instruction *visitCallSite(CallSite CS);
Eric Christophera7fb58f2010-03-06 10:50:38 +0000221 Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
Chris Lattner35522b72010-01-04 07:12:23 +0000222 bool transformConstExprCastCall(CallSite CS);
Duncan Sandsa0984362011-09-06 13:37:06 +0000223 Instruction *transformCallThroughTrampoline(CallSite CS,
224 IntrinsicInst *Tramp);
Chris Lattner35522b72010-01-04 07:12:23 +0000225 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
226 bool DoXform = true);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000227 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000228 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000229 Value *EmitGEPOffset(User *GEP);
Chris Lattner35522b72010-01-04 07:12:23 +0000230
231public:
232 // InsertNewInstBefore - insert an instruction New before instruction Old
233 // in the program. Add the new instruction to the worklist.
234 //
235 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
236 assert(New && New->getParent() == 0 &&
237 "New instruction already inserted into a basic block!");
238 BasicBlock *BB = Old.getParent();
239 BB->getInstList().insert(&Old, New); // Insert inst
240 Worklist.Add(New);
241 return New;
242 }
Eli Friedman6efb64e2011-05-19 01:20:42 +0000243
244 // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
245 // debug loc.
246 //
247 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
248 New->setDebugLoc(Old.getDebugLoc());
249 return InsertNewInstBefore(New, Old);
250 }
251
Chris Lattner35522b72010-01-04 07:12:23 +0000252 // ReplaceInstUsesWith - This method is to be used when an instruction is
253 // found to be dead, replacable with another preexisting expression. Here
254 // we add all uses of I to the worklist, replace all uses of I with the new
255 // value, then return I, so that the inst combiner will know that I was
256 // modified.
257 //
258 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
259 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
260
261 // If we are replacing the instruction with itself, this must be in a
262 // segment of unreachable code, so just clobber the instruction.
263 if (&I == V)
264 V = UndefValue::get(I.getType());
Frits van Bommeld14d9912011-03-27 23:32:31 +0000265
266 DEBUG(errs() << "IC: Replacing " << I << "\n"
267 " with " << *V << '\n');
268
Chris Lattner35522b72010-01-04 07:12:23 +0000269 I.replaceAllUsesWith(V);
270 return &I;
271 }
272
273 // EraseInstFromFunction - When dealing with an instruction that has side
274 // effects or produces a void value, we can't rely on DCE to delete the
275 // instruction. Instead, visit methods should return the value returned by
276 // this function.
277 Instruction *EraseInstFromFunction(Instruction &I) {
278 DEBUG(errs() << "IC: ERASE " << I << '\n');
279
280 assert(I.use_empty() && "Cannot erase instruction that is used!");
281 // Make sure that we reprocess all operands now that we reduced their
282 // use counts.
283 if (I.getNumOperands() < 8) {
284 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
285 if (Instruction *Op = dyn_cast<Instruction>(*i))
286 Worklist.Add(Op);
287 }
288 Worklist.Remove(&I);
289 I.eraseFromParent();
290 MadeIRChange = true;
291 return 0; // Don't do anything with FI
292 }
293
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000294 void ComputeMaskedBits(Value *V, APInt &KnownZero,
Chris Lattner35522b72010-01-04 07:12:23 +0000295 APInt &KnownOne, unsigned Depth = 0) const {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000296 return llvm::ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
Chris Lattner35522b72010-01-04 07:12:23 +0000297 }
298
299 bool MaskedValueIsZero(Value *V, const APInt &Mask,
300 unsigned Depth = 0) const {
301 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
302 }
303 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
304 return llvm::ComputeNumSignBits(Op, TD, Depth);
305 }
306
307private:
308
Duncan Sands641baf12010-11-13 15:10:37 +0000309 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
310 /// operators which are associative or commutative.
311 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000312
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000313 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
314 /// which some other binary operation distributes over either by factorizing
315 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
316 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
317 /// a win). Returns the simplified value, or null if it didn't simplify.
318 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000319
Chris Lattner35522b72010-01-04 07:12:23 +0000320 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
321 /// based on the demanded bits.
322 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
323 APInt& KnownZero, APInt& KnownOne,
324 unsigned Depth);
325 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
326 APInt& KnownZero, APInt& KnownOne,
327 unsigned Depth=0);
328
329 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
330 /// SimplifyDemandedBits knows about. See if the instruction has any
331 /// properties that allow us to simplify its operands.
332 bool SimplifyDemandedInstructionBits(Instruction &Inst);
333
334 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
335 APInt& UndefElts, unsigned Depth = 0);
336
337 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
338 // which has a PHI node as operand #0, see if we can fold the instruction
339 // into the PHI (which is only possible if all operands to the PHI are
340 // constants).
341 //
Chris Lattnerea7131a2011-01-16 05:14:26 +0000342 Instruction *FoldOpIntoPhi(Instruction &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000343
344 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
345 // operator and they all are only used by the PHI, PHI together their
346 // inputs, and do the operation once, to the result of the PHI.
347 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
348 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
349 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
350 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
351
352
353 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
354 ConstantInt *AndRHS, BinaryOperator &TheAnd);
355
356 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
357 bool isSub, Instruction &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000358 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
359 bool isSigned, bool Inside);
Chris Lattner35522b72010-01-04 07:12:23 +0000360 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
361 Instruction *MatchBSwap(BinaryOperator &I);
362 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
363 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
364 Instruction *SimplifyMemSet(MemSetInst *MI);
365
366
Chris Lattner229907c2011-07-18 04:54:35 +0000367 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
Chris Lattner35522b72010-01-04 07:12:23 +0000368};
369
370
371
372} // end namespace llvm.
373
374#endif