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