blob: 9c70cf89e48c8a64310f4c71d3bc208aacf70fbe [file] [log] [blame]
Chris Lattnerac8f2fd2010-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"
Jay Foad562b84b2011-04-11 09:35:34 +000014#include "llvm/Operator.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000015#include "llvm/Pass.h"
16#include "llvm/Analysis/ValueTracking.h"
17#include "llvm/Support/IRBuilder.h"
18#include "llvm/Support/InstVisitor.h"
19#include "llvm/Support/TargetFolder.h"
20
21namespace llvm {
22 class CallSite;
23 class TargetData;
Chris Lattner43fd9012010-01-05 05:21:26 +000024 class DbgDeclareInst;
25 class MemIntrinsic;
26 class MemSetInst;
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000027
28/// SelectPatternFlavor - We can match a variety of different patterns for
29/// select operations.
30enum SelectPatternFlavor {
31 SPF_UNKNOWN = 0,
32 SPF_SMIN, SPF_UMIN,
33 SPF_SMAX, SPF_UMAX
34 //SPF_ABS - TODO.
35};
Chris Lattner02446fc2010-01-04 07:37:31 +000036
37/// getComplexity: Assign a complexity or rank value to LLVM Values...
38/// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
39static inline unsigned getComplexity(Value *V) {
40 if (isa<Instruction>(V)) {
41 if (BinaryOperator::isNeg(V) ||
42 BinaryOperator::isFNeg(V) ||
43 BinaryOperator::isNot(V))
44 return 3;
45 return 4;
46 }
47 if (isa<Argument>(V)) return 3;
48 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
49}
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000050
51
52/// InstCombineIRInserter - This is an IRBuilder insertion helper that works
53/// just like the normal insertion helper, but also adds any new instructions
54/// to the instcombine worklist.
Duncan Sands16d8f8b2010-05-11 20:16:09 +000055class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000056 : public IRBuilderDefaultInserter<true> {
57 InstCombineWorklist &Worklist;
58public:
59 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
60
61 void InsertHelper(Instruction *I, const Twine &Name,
62 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
63 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
64 Worklist.Add(I);
65 }
66};
67
68/// InstCombiner - The -instcombine pass.
Duncan Sands16d8f8b2010-05-11 20:16:09 +000069class LLVM_LIBRARY_VISIBILITY InstCombiner
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000070 : public FunctionPass,
71 public InstVisitor<InstCombiner, Instruction*> {
72 TargetData *TD;
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000073 bool MadeIRChange;
74public:
75 /// Worklist - All of the instructions that need to be simplified.
76 InstCombineWorklist Worklist;
77
78 /// Builder - This is an IRBuilder that automatically inserts new
79 /// instructions into the worklist when they are created.
80 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
81 BuilderTy *Builder;
82
83 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000084 InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
85 initializeInstCombinerPass(*PassRegistry::getPassRegistry());
86 }
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000087
88public:
89 virtual bool runOnFunction(Function &F);
90
91 bool DoOneIteration(Function &F, unsigned ItNum);
92
Chris Lattnere0b4b722010-01-04 07:17:19 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
94
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000095 TargetData *getTargetData() const { return TD; }
96
97 // Visitation implementation - Implement instruction combining for different
98 // instruction types. The semantics are as follows:
99 // Return Value:
100 // null - No change was made
101 // I - Change was made, I is still valid, I may be dead though
102 // otherwise - Change was made, replace I with returned instruction
103 //
104 Instruction *visitAdd(BinaryOperator &I);
105 Instruction *visitFAdd(BinaryOperator &I);
106 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
107 Instruction *visitSub(BinaryOperator &I);
108 Instruction *visitFSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitFMul(BinaryOperator &I);
111 Instruction *visitURem(BinaryOperator &I);
112 Instruction *visitSRem(BinaryOperator &I);
113 Instruction *visitFRem(BinaryOperator &I);
114 bool SimplifyDivRemOfSelect(BinaryOperator &I);
115 Instruction *commonRemTransforms(BinaryOperator &I);
116 Instruction *commonIRemTransforms(BinaryOperator &I);
117 Instruction *commonDivTransforms(BinaryOperator &I);
118 Instruction *commonIDivTransforms(BinaryOperator &I);
119 Instruction *visitUDiv(BinaryOperator &I);
120 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel31726c12011-01-29 17:50:27 +0000121 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000122 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
123 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000124 Instruction *visitAnd(BinaryOperator &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000125 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
126 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000127 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
128 Value *A, Value *B, Value *C);
129 Instruction *visitOr (BinaryOperator &I);
130 Instruction *visitXor(BinaryOperator &I);
131 Instruction *visitShl(BinaryOperator &I);
132 Instruction *visitAShr(BinaryOperator &I);
133 Instruction *visitLShr(BinaryOperator &I);
134 Instruction *commonShiftTransforms(BinaryOperator &I);
135 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
136 Constant *RHSC);
137 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
138 GlobalVariable *GV, CmpInst &ICI,
139 ConstantInt *AndCst = 0);
140 Instruction *visitFCmpInst(FCmpInst &I);
141 Instruction *visitICmpInst(ICmpInst &I);
142 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
143 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
144 Instruction *LHS,
145 ConstantInt *RHS);
146 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
147 ConstantInt *DivRHS);
Chris Lattner74542aa2011-02-13 07:43:07 +0000148 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
149 ConstantInt *DivRHS);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000150 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
151 ICmpInst::Predicate Pred, Value *TheAdd);
152 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
153 ICmpInst::Predicate Cond, Instruction &I);
154 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
155 BinaryOperator &I);
156 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000157 Instruction *commonPointerCastTransforms(CastInst &CI);
158 Instruction *visitTrunc(TruncInst &CI);
159 Instruction *visitZExt(ZExtInst &CI);
160 Instruction *visitSExt(SExtInst &CI);
161 Instruction *visitFPTrunc(FPTruncInst &CI);
162 Instruction *visitFPExt(CastInst &CI);
163 Instruction *visitFPToUI(FPToUIInst &FI);
164 Instruction *visitFPToSI(FPToSIInst &FI);
165 Instruction *visitUIToFP(CastInst &CI);
166 Instruction *visitSIToFP(CastInst &CI);
167 Instruction *visitPtrToInt(PtrToIntInst &CI);
168 Instruction *visitIntToPtr(IntToPtrInst &CI);
169 Instruction *visitBitCast(BitCastInst &CI);
170 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
171 Instruction *FI);
172 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
173 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
174 Value *A, Value *B, Instruction &Outer,
175 SelectPatternFlavor SPF2, Value *C);
176 Instruction *visitSelectInst(SelectInst &SI);
177 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
178 Instruction *visitCallInst(CallInst &CI);
179 Instruction *visitInvokeInst(InvokeInst &II);
180
181 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
182 Instruction *visitPHINode(PHINode &PN);
183 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
184 Instruction *visitAllocaInst(AllocaInst &AI);
Duncan Sands1d9b9732010-05-27 19:09:06 +0000185 Instruction *visitMalloc(Instruction &FI);
Gabor Greif91697372010-06-24 12:21:15 +0000186 Instruction *visitFree(CallInst &FI);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000187 Instruction *visitLoadInst(LoadInst &LI);
188 Instruction *visitStoreInst(StoreInst &SI);
189 Instruction *visitBranchInst(BranchInst &BI);
190 Instruction *visitSwitchInst(SwitchInst &SI);
191 Instruction *visitInsertElementInst(InsertElementInst &IE);
192 Instruction *visitExtractElementInst(ExtractElementInst &EI);
193 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
194 Instruction *visitExtractValueInst(ExtractValueInst &EV);
195
196 // visitInstruction - Specify what to return for unhandled instructions...
197 Instruction *visitInstruction(Instruction &I) { return 0; }
198
199private:
Chris Lattner80f43d32010-01-04 07:53:58 +0000200 bool ShouldChangeType(const Type *From, const Type *To) const;
Chris Lattner02446fc2010-01-04 07:37:31 +0000201 Value *dyn_castNegVal(Value *V) const;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000202 Value *dyn_castFNegVal(Value *V) const;
Chris Lattner80f43d32010-01-04 07:53:58 +0000203 const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
204 SmallVectorImpl<Value*> &NewIndices);
205 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
206
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000207 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
208 /// results in any code being generated and is interesting to optimize out. If
209 /// the cast can be eliminated by some other simple transformation, we prefer
210 /// to do the simplification first.
211 bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
212 const Type *Ty);
Chris Lattner02446fc2010-01-04 07:37:31 +0000213
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000214 Instruction *visitCallSite(CallSite CS);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000215 Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000216 bool transformConstExprCastCall(CallSite CS);
217 Instruction *transformCallThroughTrampoline(CallSite CS);
218 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
219 bool DoXform = true);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000220 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000221 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner02446fc2010-01-04 07:37:31 +0000222 Value *EmitGEPOffset(User *GEP);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000223
224public:
225 // InsertNewInstBefore - insert an instruction New before instruction Old
226 // in the program. Add the new instruction to the worklist.
227 //
228 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
229 assert(New && New->getParent() == 0 &&
230 "New instruction already inserted into a basic block!");
231 BasicBlock *BB = Old.getParent();
232 BB->getInstList().insert(&Old, New); // Insert inst
233 Worklist.Add(New);
234 return New;
235 }
236
237 // ReplaceInstUsesWith - This method is to be used when an instruction is
238 // found to be dead, replacable with another preexisting expression. Here
239 // we add all uses of I to the worklist, replace all uses of I with the new
240 // value, then return I, so that the inst combiner will know that I was
241 // modified.
242 //
243 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
244 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
245
246 // If we are replacing the instruction with itself, this must be in a
247 // segment of unreachable code, so just clobber the instruction.
248 if (&I == V)
249 V = UndefValue::get(I.getType());
Frits van Bommelf56762a2011-03-27 23:32:31 +0000250
251 DEBUG(errs() << "IC: Replacing " << I << "\n"
252 " with " << *V << '\n');
253
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000254 I.replaceAllUsesWith(V);
255 return &I;
256 }
257
258 // EraseInstFromFunction - When dealing with an instruction that has side
259 // effects or produces a void value, we can't rely on DCE to delete the
260 // instruction. Instead, visit methods should return the value returned by
261 // this function.
262 Instruction *EraseInstFromFunction(Instruction &I) {
263 DEBUG(errs() << "IC: ERASE " << I << '\n');
264
265 assert(I.use_empty() && "Cannot erase instruction that is used!");
266 // Make sure that we reprocess all operands now that we reduced their
267 // use counts.
268 if (I.getNumOperands() < 8) {
269 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
270 if (Instruction *Op = dyn_cast<Instruction>(*i))
271 Worklist.Add(Op);
272 }
273 Worklist.Remove(&I);
274 I.eraseFromParent();
275 MadeIRChange = true;
276 return 0; // Don't do anything with FI
277 }
278
279 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
280 APInt &KnownOne, unsigned Depth = 0) const {
281 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
282 }
283
284 bool MaskedValueIsZero(Value *V, const APInt &Mask,
285 unsigned Depth = 0) const {
286 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
287 }
288 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
289 return llvm::ComputeNumSignBits(Op, TD, Depth);
290 }
291
292private:
293
Duncan Sands096aa792010-11-13 15:10:37 +0000294 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
295 /// operators which are associative or commutative.
296 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000297
Duncan Sands37bf92b2010-12-22 13:36:08 +0000298 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
299 /// which some other binary operation distributes over either by factorizing
300 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
301 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
302 /// a win). Returns the simplified value, or null if it didn't simplify.
303 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sands5057f382010-11-23 14:23:47 +0000304
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000305 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
306 /// based on the demanded bits.
307 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
308 APInt& KnownZero, APInt& KnownOne,
309 unsigned Depth);
310 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
311 APInt& KnownZero, APInt& KnownOne,
312 unsigned Depth=0);
313
314 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
315 /// SimplifyDemandedBits knows about. See if the instruction has any
316 /// properties that allow us to simplify its operands.
317 bool SimplifyDemandedInstructionBits(Instruction &Inst);
318
319 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
320 APInt& UndefElts, unsigned Depth = 0);
321
322 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
323 // which has a PHI node as operand #0, see if we can fold the instruction
324 // into the PHI (which is only possible if all operands to the PHI are
325 // constants).
326 //
Chris Lattner9922ccf2011-01-16 05:14:26 +0000327 Instruction *FoldOpIntoPhi(Instruction &I);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000328
329 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
330 // operator and they all are only used by the PHI, PHI together their
331 // inputs, and do the operation once, to the result of the PHI.
332 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
333 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
334 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
335 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
336
337
338 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
339 ConstantInt *AndRHS, BinaryOperator &TheAnd);
340
341 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
342 bool isSub, Instruction &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000343 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
344 bool isSigned, bool Inside);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000345 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
346 Instruction *MatchBSwap(BinaryOperator &I);
347 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
348 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
349 Instruction *SimplifyMemSet(MemSetInst *MI);
350
351
352 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000353};
354
355
356
357} // end namespace llvm.
358
359#endif