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