split instcombine of compares (visit[FI]Cmp) out to
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombine.h
1 //===- 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"
14 #include "llvm/Pass.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Support/IRBuilder.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/TargetFolder.h"
19
20 namespace llvm {
21   class CallSite;
22   class TargetData;
23   class DbgDeclareInst;
24   class MemIntrinsic;
25   class MemSetInst;
26   
27 /// SelectPatternFlavor - We can match a variety of different patterns for
28 /// select operations.
29 enum SelectPatternFlavor {
30   SPF_UNKNOWN = 0,
31   SPF_SMIN, SPF_UMIN,
32   SPF_SMAX, SPF_UMAX
33   //SPF_ABS - TODO.
34 };
35   
36 /// getComplexity:  Assign a complexity or rank value to LLVM Values...
37 ///   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
38 static inline unsigned getComplexity(Value *V) {
39   if (isa<Instruction>(V)) {
40     if (BinaryOperator::isNeg(V) ||
41         BinaryOperator::isFNeg(V) ||
42         BinaryOperator::isNot(V))
43       return 3;
44     return 4;
45   }
46   if (isa<Argument>(V)) return 3;
47   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
48 }
49
50   
51 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
52 /// just like the normal insertion helper, but also adds any new instructions
53 /// to the instcombine worklist.
54 class VISIBILITY_HIDDEN InstCombineIRInserter 
55     : public IRBuilderDefaultInserter<true> {
56   InstCombineWorklist &Worklist;
57 public:
58   InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
59   
60   void InsertHelper(Instruction *I, const Twine &Name,
61                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
62     IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
63     Worklist.Add(I);
64   }
65 };
66   
67 /// InstCombiner - The -instcombine pass.
68 class VISIBILITY_HIDDEN InstCombiner
69                              : public FunctionPass,
70                                public InstVisitor<InstCombiner, Instruction*> {
71   TargetData *TD;
72   bool MustPreserveLCSSA;
73   bool MadeIRChange;
74 public:
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
84   InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
85
86 public:
87   virtual bool runOnFunction(Function &F);
88   
89   bool DoOneIteration(Function &F, unsigned ItNum);
90
91   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
92                                  
93   TargetData *getTargetData() const { return TD; }
94
95   // Visitation implementation - Implement instruction combining for different
96   // instruction types.  The semantics are as follows:
97   // Return Value:
98   //    null        - No change was made
99   //     I          - Change was made, I is still valid, I may be dead though
100   //   otherwise    - Change was made, replace I with returned instruction
101   //
102   Instruction *visitAdd(BinaryOperator &I);
103   Instruction *visitFAdd(BinaryOperator &I);
104   Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
105   Instruction *visitSub(BinaryOperator &I);
106   Instruction *visitFSub(BinaryOperator &I);
107   Instruction *visitMul(BinaryOperator &I);
108   Instruction *visitFMul(BinaryOperator &I);
109   Instruction *visitURem(BinaryOperator &I);
110   Instruction *visitSRem(BinaryOperator &I);
111   Instruction *visitFRem(BinaryOperator &I);
112   bool SimplifyDivRemOfSelect(BinaryOperator &I);
113   Instruction *commonRemTransforms(BinaryOperator &I);
114   Instruction *commonIRemTransforms(BinaryOperator &I);
115   Instruction *commonDivTransforms(BinaryOperator &I);
116   Instruction *commonIDivTransforms(BinaryOperator &I);
117   Instruction *visitUDiv(BinaryOperator &I);
118   Instruction *visitSDiv(BinaryOperator &I);
119   Instruction *visitFDiv(BinaryOperator &I);
120   Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
121   Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
122   Instruction *visitAnd(BinaryOperator &I);
123   Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
124   Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
125   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
126                                    Value *A, Value *B, Value *C);
127   Instruction *visitOr (BinaryOperator &I);
128   Instruction *visitXor(BinaryOperator &I);
129   Instruction *visitShl(BinaryOperator &I);
130   Instruction *visitAShr(BinaryOperator &I);
131   Instruction *visitLShr(BinaryOperator &I);
132   Instruction *commonShiftTransforms(BinaryOperator &I);
133   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
134                                     Constant *RHSC);
135   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
136                                             GlobalVariable *GV, CmpInst &ICI,
137                                             ConstantInt *AndCst = 0);
138   Instruction *visitFCmpInst(FCmpInst &I);
139   Instruction *visitICmpInst(ICmpInst &I);
140   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
141   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
142                                               Instruction *LHS,
143                                               ConstantInt *RHS);
144   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
145                               ConstantInt *DivRHS);
146   Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
147                                 ICmpInst::Predicate Pred, Value *TheAdd);
148   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
149                            ICmpInst::Predicate Cond, Instruction &I);
150   Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
151                                    BinaryOperator &I);
152   Instruction *commonCastTransforms(CastInst &CI);
153   Instruction *commonIntCastTransforms(CastInst &CI);
154   Instruction *commonPointerCastTransforms(CastInst &CI);
155   Instruction *visitTrunc(TruncInst &CI);
156   Instruction *visitZExt(ZExtInst &CI);
157   Instruction *visitSExt(SExtInst &CI);
158   Instruction *visitFPTrunc(FPTruncInst &CI);
159   Instruction *visitFPExt(CastInst &CI);
160   Instruction *visitFPToUI(FPToUIInst &FI);
161   Instruction *visitFPToSI(FPToSIInst &FI);
162   Instruction *visitUIToFP(CastInst &CI);
163   Instruction *visitSIToFP(CastInst &CI);
164   Instruction *visitPtrToInt(PtrToIntInst &CI);
165   Instruction *visitIntToPtr(IntToPtrInst &CI);
166   Instruction *visitBitCast(BitCastInst &CI);
167   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
168                               Instruction *FI);
169   Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
170   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
171                             Value *A, Value *B, Instruction &Outer,
172                             SelectPatternFlavor SPF2, Value *C);
173   Instruction *visitSelectInst(SelectInst &SI);
174   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
175   Instruction *visitCallInst(CallInst &CI);
176   Instruction *visitInvokeInst(InvokeInst &II);
177
178   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
179   Instruction *visitPHINode(PHINode &PN);
180   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
181   Instruction *visitAllocaInst(AllocaInst &AI);
182   Instruction *visitFree(Instruction &FI);
183   Instruction *visitLoadInst(LoadInst &LI);
184   Instruction *visitStoreInst(StoreInst &SI);
185   Instruction *visitBranchInst(BranchInst &BI);
186   Instruction *visitSwitchInst(SwitchInst &SI);
187   Instruction *visitInsertElementInst(InsertElementInst &IE);
188   Instruction *visitExtractElementInst(ExtractElementInst &EI);
189   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
190   Instruction *visitExtractValueInst(ExtractValueInst &EV);
191
192   // visitInstruction - Specify what to return for unhandled instructions...
193   Instruction *visitInstruction(Instruction &I) { return 0; }
194
195 private:
196   Value *dyn_castNegVal(Value *V) const;
197
198   Instruction *visitCallSite(CallSite CS);
199   bool transformConstExprCastCall(CallSite CS);
200   Instruction *transformCallThroughTrampoline(CallSite CS);
201   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
202                                  bool DoXform = true);
203   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
204   DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
205   Value *EmitGEPOffset(User *GEP);
206
207 public:
208   // InsertNewInstBefore - insert an instruction New before instruction Old
209   // in the program.  Add the new instruction to the worklist.
210   //
211   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
212     assert(New && New->getParent() == 0 &&
213            "New instruction already inserted into a basic block!");
214     BasicBlock *BB = Old.getParent();
215     BB->getInstList().insert(&Old, New);  // Insert inst
216     Worklist.Add(New);
217     return New;
218   }
219       
220   // ReplaceInstUsesWith - This method is to be used when an instruction is
221   // found to be dead, replacable with another preexisting expression.  Here
222   // we add all uses of I to the worklist, replace all uses of I with the new
223   // value, then return I, so that the inst combiner will know that I was
224   // modified.
225   //
226   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
227     Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
228     
229     // If we are replacing the instruction with itself, this must be in a
230     // segment of unreachable code, so just clobber the instruction.
231     if (&I == V) 
232       V = UndefValue::get(I.getType());
233       
234     I.replaceAllUsesWith(V);
235     return &I;
236   }
237
238   // EraseInstFromFunction - When dealing with an instruction that has side
239   // effects or produces a void value, we can't rely on DCE to delete the
240   // instruction.  Instead, visit methods should return the value returned by
241   // this function.
242   Instruction *EraseInstFromFunction(Instruction &I) {
243     DEBUG(errs() << "IC: ERASE " << I << '\n');
244
245     assert(I.use_empty() && "Cannot erase instruction that is used!");
246     // Make sure that we reprocess all operands now that we reduced their
247     // use counts.
248     if (I.getNumOperands() < 8) {
249       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
250         if (Instruction *Op = dyn_cast<Instruction>(*i))
251           Worklist.Add(Op);
252     }
253     Worklist.Remove(&I);
254     I.eraseFromParent();
255     MadeIRChange = true;
256     return 0;  // Don't do anything with FI
257   }
258       
259   void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
260                          APInt &KnownOne, unsigned Depth = 0) const {
261     return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
262   }
263   
264   bool MaskedValueIsZero(Value *V, const APInt &Mask, 
265                          unsigned Depth = 0) const {
266     return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
267   }
268   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
269     return llvm::ComputeNumSignBits(Op, TD, Depth);
270   }
271
272 private:
273
274   /// SimplifyCommutative - This performs a few simplifications for 
275   /// commutative operators.
276   bool SimplifyCommutative(BinaryOperator &I);
277
278   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
279   /// based on the demanded bits.
280   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
281                                  APInt& KnownZero, APInt& KnownOne,
282                                  unsigned Depth);
283   bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
284                             APInt& KnownZero, APInt& KnownOne,
285                             unsigned Depth=0);
286       
287   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
288   /// SimplifyDemandedBits knows about.  See if the instruction has any
289   /// properties that allow us to simplify its operands.
290   bool SimplifyDemandedInstructionBits(Instruction &Inst);
291       
292   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
293                                     APInt& UndefElts, unsigned Depth = 0);
294     
295   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
296   // which has a PHI node as operand #0, see if we can fold the instruction
297   // into the PHI (which is only possible if all operands to the PHI are
298   // constants).
299   //
300   // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
301   // that would normally be unprofitable because they strongly encourage jump
302   // threading.
303   Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
304
305   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
306   // operator and they all are only used by the PHI, PHI together their
307   // inputs, and do the operation once, to the result of the PHI.
308   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
309   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
310   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
311   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
312
313   
314   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
315                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
316   
317   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
318                             bool isSub, Instruction &I);
319   Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
320                                bool isSigned, bool Inside, Instruction &IB);
321   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
322   Instruction *MatchBSwap(BinaryOperator &I);
323   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
324   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
325   Instruction *SimplifyMemSet(MemSetInst *MI);
326
327
328   Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
329
330   bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
331                                   unsigned CastOpc, int &NumCastsRemoved);
332   unsigned GetOrEnforceKnownAlignment(Value *V,
333                                       unsigned PrefAlign = 0);
334
335 };
336
337       
338   
339 } // end namespace llvm.
340
341 #endif