blob: c4c793285c986c9e0c50e7074de47caba4fb1ace [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
100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
104 // I - Change was made, I is still valid, I may be dead though
105 // otherwise - Change was made, replace I with returned instruction
106 //
107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner229907c2011-07-18 04:54:35 +0000109 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
Chris Lattner35522b72010-01-04 07:12:23 +0000110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitFSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitFMul(BinaryOperator &I);
114 Instruction *visitURem(BinaryOperator &I);
115 Instruction *visitSRem(BinaryOperator &I);
116 Instruction *visitFRem(BinaryOperator &I);
117 bool SimplifyDivRemOfSelect(BinaryOperator &I);
118 Instruction *commonRemTransforms(BinaryOperator &I);
119 Instruction *commonIRemTransforms(BinaryOperator &I);
120 Instruction *commonDivTransforms(BinaryOperator &I);
121 Instruction *commonIDivTransforms(BinaryOperator &I);
122 Instruction *visitUDiv(BinaryOperator &I);
123 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel2a559512011-01-29 17:50:27 +0000124 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000125 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
126 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000127 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000128 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
129 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000130 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
131 Value *A, Value *B, Value *C);
132 Instruction *visitOr (BinaryOperator &I);
133 Instruction *visitXor(BinaryOperator &I);
134 Instruction *visitShl(BinaryOperator &I);
135 Instruction *visitAShr(BinaryOperator &I);
136 Instruction *visitLShr(BinaryOperator &I);
137 Instruction *commonShiftTransforms(BinaryOperator &I);
138 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
139 Constant *RHSC);
140 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
141 GlobalVariable *GV, CmpInst &ICI,
142 ConstantInt *AndCst = 0);
143 Instruction *visitFCmpInst(FCmpInst &I);
144 Instruction *visitICmpInst(ICmpInst &I);
145 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
146 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
147 Instruction *LHS,
148 ConstantInt *RHS);
149 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
150 ConstantInt *DivRHS);
Chris Lattnerd369f572011-02-13 07:43:07 +0000151 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
152 ConstantInt *DivRHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000153 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
154 ICmpInst::Predicate Pred, Value *TheAdd);
155 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
156 ICmpInst::Predicate Cond, Instruction &I);
157 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
158 BinaryOperator &I);
159 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000160 Instruction *commonPointerCastTransforms(CastInst &CI);
161 Instruction *visitTrunc(TruncInst &CI);
162 Instruction *visitZExt(ZExtInst &CI);
163 Instruction *visitSExt(SExtInst &CI);
164 Instruction *visitFPTrunc(FPTruncInst &CI);
165 Instruction *visitFPExt(CastInst &CI);
166 Instruction *visitFPToUI(FPToUIInst &FI);
167 Instruction *visitFPToSI(FPToSIInst &FI);
168 Instruction *visitUIToFP(CastInst &CI);
169 Instruction *visitSIToFP(CastInst &CI);
170 Instruction *visitPtrToInt(PtrToIntInst &CI);
171 Instruction *visitIntToPtr(IntToPtrInst &CI);
172 Instruction *visitBitCast(BitCastInst &CI);
173 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
174 Instruction *FI);
175 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
176 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
177 Value *A, Value *B, Instruction &Outer,
178 SelectPatternFlavor SPF2, Value *C);
179 Instruction *visitSelectInst(SelectInst &SI);
180 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
181 Instruction *visitCallInst(CallInst &CI);
182 Instruction *visitInvokeInst(InvokeInst &II);
183
184 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
185 Instruction *visitPHINode(PHINode &PN);
186 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
187 Instruction *visitAllocaInst(AllocaInst &AI);
Duncan Sandsf162eac2010-05-27 19:09:06 +0000188 Instruction *visitMalloc(Instruction &FI);
Gabor Greif75f69432010-06-24 12:21:15 +0000189 Instruction *visitFree(CallInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000190 Instruction *visitLoadInst(LoadInst &LI);
191 Instruction *visitStoreInst(StoreInst &SI);
192 Instruction *visitBranchInst(BranchInst &BI);
193 Instruction *visitSwitchInst(SwitchInst &SI);
194 Instruction *visitInsertElementInst(InsertElementInst &IE);
195 Instruction *visitExtractElementInst(ExtractElementInst &EI);
196 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
197 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Duncan Sands5c055792011-09-30 13:12:16 +0000198 Instruction *visitLandingPadInst(LandingPadInst &LI);
Chris Lattner35522b72010-01-04 07:12:23 +0000199
200 // visitInstruction - Specify what to return for unhandled instructions...
201 Instruction *visitInstruction(Instruction &I) { return 0; }
202
203private:
Chris Lattner229907c2011-07-18 04:54:35 +0000204 bool ShouldChangeType(Type *From, Type *To) const;
Chris Lattner2188e402010-01-04 07:37:31 +0000205 Value *dyn_castNegVal(Value *V) const;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000206 Value *dyn_castFNegVal(Value *V) const;
Chris Lattner229907c2011-07-18 04:54:35 +0000207 Type *FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner2b295a02010-01-04 07:53:58 +0000208 SmallVectorImpl<Value*> &NewIndices);
209 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
210
Chris Lattner4e8137d2010-02-11 06:26:33 +0000211 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
212 /// results in any code being generated and is interesting to optimize out. If
213 /// the cast can be eliminated by some other simple transformation, we prefer
214 /// to do the simplification first.
215 bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000216 Type *Ty);
Chris Lattner2188e402010-01-04 07:37:31 +0000217
Chris Lattner35522b72010-01-04 07:12:23 +0000218 Instruction *visitCallSite(CallSite CS);
Eric Christophera7fb58f2010-03-06 10:50:38 +0000219 Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
Chris Lattner35522b72010-01-04 07:12:23 +0000220 bool transformConstExprCastCall(CallSite CS);
Duncan Sandsa0984362011-09-06 13:37:06 +0000221 Instruction *transformCallThroughTrampoline(CallSite CS,
222 IntrinsicInst *Tramp);
Chris Lattner35522b72010-01-04 07:12:23 +0000223 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
224 bool DoXform = true);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000225 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000226 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner2188e402010-01-04 07:37:31 +0000227 Value *EmitGEPOffset(User *GEP);
Chris Lattner35522b72010-01-04 07:12:23 +0000228
229public:
230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
238 Worklist.Add(New);
239 return New;
240 }
Eli Friedman6efb64e2011-05-19 01:20:42 +0000241
242 // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
243 // debug loc.
244 //
245 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
246 New->setDebugLoc(Old.getDebugLoc());
247 return InsertNewInstBefore(New, Old);
248 }
249
Chris Lattner35522b72010-01-04 07:12:23 +0000250 // ReplaceInstUsesWith - This method is to be used when an instruction is
251 // found to be dead, replacable with another preexisting expression. Here
252 // we add all uses of I to the worklist, replace all uses of I with the new
253 // value, then return I, so that the inst combiner will know that I was
254 // modified.
255 //
256 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
257 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
258
259 // If we are replacing the instruction with itself, this must be in a
260 // segment of unreachable code, so just clobber the instruction.
261 if (&I == V)
262 V = UndefValue::get(I.getType());
Frits van Bommeld14d9912011-03-27 23:32:31 +0000263
264 DEBUG(errs() << "IC: Replacing " << I << "\n"
265 " with " << *V << '\n');
266
Chris Lattner35522b72010-01-04 07:12:23 +0000267 I.replaceAllUsesWith(V);
268 return &I;
269 }
270
271 // EraseInstFromFunction - When dealing with an instruction that has side
272 // effects or produces a void value, we can't rely on DCE to delete the
273 // instruction. Instead, visit methods should return the value returned by
274 // this function.
275 Instruction *EraseInstFromFunction(Instruction &I) {
276 DEBUG(errs() << "IC: ERASE " << I << '\n');
277
278 assert(I.use_empty() && "Cannot erase instruction that is used!");
279 // Make sure that we reprocess all operands now that we reduced their
280 // use counts.
281 if (I.getNumOperands() < 8) {
282 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
283 if (Instruction *Op = dyn_cast<Instruction>(*i))
284 Worklist.Add(Op);
285 }
286 Worklist.Remove(&I);
287 I.eraseFromParent();
288 MadeIRChange = true;
289 return 0; // Don't do anything with FI
290 }
291
292 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
293 APInt &KnownOne, unsigned Depth = 0) const {
294 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
295 }
296
297 bool MaskedValueIsZero(Value *V, const APInt &Mask,
298 unsigned Depth = 0) const {
299 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
300 }
301 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
302 return llvm::ComputeNumSignBits(Op, TD, Depth);
303 }
304
305private:
306
Duncan Sands641baf12010-11-13 15:10:37 +0000307 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
308 /// operators which are associative or commutative.
309 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000310
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000311 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
312 /// which some other binary operation distributes over either by factorizing
313 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
314 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
315 /// a win). Returns the simplified value, or null if it didn't simplify.
316 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000317
Chris Lattner35522b72010-01-04 07:12:23 +0000318 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
319 /// based on the demanded bits.
320 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
321 APInt& KnownZero, APInt& KnownOne,
322 unsigned Depth);
323 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
324 APInt& KnownZero, APInt& KnownOne,
325 unsigned Depth=0);
326
327 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
328 /// SimplifyDemandedBits knows about. See if the instruction has any
329 /// properties that allow us to simplify its operands.
330 bool SimplifyDemandedInstructionBits(Instruction &Inst);
331
332 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
333 APInt& UndefElts, unsigned Depth = 0);
334
335 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
336 // which has a PHI node as operand #0, see if we can fold the instruction
337 // into the PHI (which is only possible if all operands to the PHI are
338 // constants).
339 //
Chris Lattnerea7131a2011-01-16 05:14:26 +0000340 Instruction *FoldOpIntoPhi(Instruction &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000341
342 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
343 // operator and they all are only used by the PHI, PHI together their
344 // inputs, and do the operation once, to the result of the PHI.
345 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
346 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
347 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
348 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
349
350
351 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
352 ConstantInt *AndRHS, BinaryOperator &TheAnd);
353
354 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
355 bool isSub, Instruction &I);
Chris Lattner067459c2010-03-05 08:46:26 +0000356 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
357 bool isSigned, bool Inside);
Chris Lattner35522b72010-01-04 07:12:23 +0000358 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
359 Instruction *MatchBSwap(BinaryOperator &I);
360 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
361 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
362 Instruction *SimplifyMemSet(MemSetInst *MI);
363
364
Chris Lattner229907c2011-07-18 04:54:35 +0000365 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
Chris Lattner35522b72010-01-04 07:12:23 +0000366};
367
368
369
370} // end namespace llvm.
371
372#endif