[InstCombine] Re-commit of r218721 (Optimize icmp-select-icmp sequence)
[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 *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
166   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
167   Instruction *visitAnd(BinaryOperator &I);
168   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
169   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
170   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
171                                    Value *B, Value *C);
172   Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
173                                     Value *B, Value *C);
174   Instruction *visitOr(BinaryOperator &I);
175   Instruction *visitXor(BinaryOperator &I);
176   Instruction *visitShl(BinaryOperator &I);
177   Instruction *visitAShr(BinaryOperator &I);
178   Instruction *visitLShr(BinaryOperator &I);
179   Instruction *commonShiftTransforms(BinaryOperator &I);
180   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
181                                     Constant *RHSC);
182   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
183                                             GlobalVariable *GV, CmpInst &ICI,
184                                             ConstantInt *AndCst = nullptr);
185   Instruction *visitFCmpInst(FCmpInst &I);
186   Instruction *visitICmpInst(ICmpInst &I);
187   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
188   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
189                                               ConstantInt *RHS);
190   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
191                               ConstantInt *DivRHS);
192   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
193                               ConstantInt *DivRHS);
194   Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
195                                  ConstantInt *CI1, ConstantInt *CI2);
196   Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
197                                  ConstantInt *CI1, ConstantInt *CI2);
198   Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
199                                 ICmpInst::Predicate Pred);
200   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
201                            ICmpInst::Predicate Cond, Instruction &I);
202   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
203                                    BinaryOperator &I);
204   Instruction *commonCastTransforms(CastInst &CI);
205   Instruction *commonPointerCastTransforms(CastInst &CI);
206   Instruction *visitTrunc(TruncInst &CI);
207   Instruction *visitZExt(ZExtInst &CI);
208   Instruction *visitSExt(SExtInst &CI);
209   Instruction *visitFPTrunc(FPTruncInst &CI);
210   Instruction *visitFPExt(CastInst &CI);
211   Instruction *visitFPToUI(FPToUIInst &FI);
212   Instruction *visitFPToSI(FPToSIInst &FI);
213   Instruction *visitUIToFP(CastInst &CI);
214   Instruction *visitSIToFP(CastInst &CI);
215   Instruction *visitPtrToInt(PtrToIntInst &CI);
216   Instruction *visitIntToPtr(IntToPtrInst &CI);
217   Instruction *visitBitCast(BitCastInst &CI);
218   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
219   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
220   Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
221   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
222                             Value *A, Value *B, Instruction &Outer,
223                             SelectPatternFlavor SPF2, Value *C);
224   Instruction *visitSelectInst(SelectInst &SI);
225   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
226   Instruction *visitCallInst(CallInst &CI);
227   Instruction *visitInvokeInst(InvokeInst &II);
228
229   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
230   Instruction *visitPHINode(PHINode &PN);
231   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232   Instruction *visitAllocaInst(AllocaInst &AI);
233   Instruction *visitAllocSite(Instruction &FI);
234   Instruction *visitFree(CallInst &FI);
235   Instruction *visitLoadInst(LoadInst &LI);
236   Instruction *visitStoreInst(StoreInst &SI);
237   Instruction *visitBranchInst(BranchInst &BI);
238   Instruction *visitSwitchInst(SwitchInst &SI);
239   Instruction *visitReturnInst(ReturnInst &RI);
240   Instruction *visitInsertValueInst(InsertValueInst &IV);
241   Instruction *visitInsertElementInst(InsertElementInst &IE);
242   Instruction *visitExtractElementInst(ExtractElementInst &EI);
243   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
244   Instruction *visitExtractValueInst(ExtractValueInst &EV);
245   Instruction *visitLandingPadInst(LandingPadInst &LI);
246
247   // visitInstruction - Specify what to return for unhandled instructions...
248   Instruction *visitInstruction(Instruction &I) { return nullptr; }
249
250   // True when DB dominates all uses of DI execpt UI.
251   // UI must be in the same block as DI.
252   // The routine checks that the DI parent and DB are different.
253   bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
254                         const BasicBlock *DB) const;
255
256   // Replace select with select operand SIOpd in SI-ICmp sequence when possible
257   bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
258                                  const unsigned SIOpd);
259
260 private:
261   bool ShouldChangeType(Type *From, Type *To) const;
262   Value *dyn_castNegVal(Value *V) const;
263   Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
264   Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
265                             SmallVectorImpl<Value *> &NewIndices);
266   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
267
268   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
269   /// results in any code being generated and is interesting to optimize out. If
270   /// the cast can be eliminated by some other simple transformation, we prefer
271   /// to do the simplification first.
272   bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
273                           Type *Ty);
274
275   Instruction *visitCallSite(CallSite CS);
276   Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
277   bool transformConstExprCastCall(CallSite CS);
278   Instruction *transformCallThroughTrampoline(CallSite CS,
279                                               IntrinsicInst *Tramp);
280   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
281                                  bool DoXform = true);
282   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
283   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
284   bool WillNotOverflowUnsignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
285   bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
286   bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
287   Value *EmitGEPOffset(User *GEP);
288   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
289   Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
290
291 public:
292   // InsertNewInstBefore - insert an instruction New before instruction Old
293   // in the program.  Add the new instruction to the worklist.
294   //
295   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
296     assert(New && !New->getParent() &&
297            "New instruction already inserted into a basic block!");
298     BasicBlock *BB = Old.getParent();
299     BB->getInstList().insert(&Old, New); // Insert inst
300     Worklist.Add(New);
301     return New;
302   }
303
304   // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
305   // debug loc.
306   //
307   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
308     New->setDebugLoc(Old.getDebugLoc());
309     return InsertNewInstBefore(New, Old);
310   }
311
312   // ReplaceInstUsesWith - This method is to be used when an instruction is
313   // found to be dead, replacable with another preexisting expression.  Here
314   // we add all uses of I to the worklist, replace all uses of I with the new
315   // value, then return I, so that the inst combiner will know that I was
316   // modified.
317   //
318   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
319     Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
320
321     // If we are replacing the instruction with itself, this must be in a
322     // segment of unreachable code, so just clobber the instruction.
323     if (&I == V)
324       V = UndefValue::get(I.getType());
325
326     DEBUG(dbgs() << "IC: Replacing " << I << "\n"
327                     "    with " << *V << '\n');
328
329     I.replaceAllUsesWith(V);
330     return &I;
331   }
332
333   // EraseInstFromFunction - When dealing with an instruction that has side
334   // effects or produces a void value, we can't rely on DCE to delete the
335   // instruction.  Instead, visit methods should return the value returned by
336   // this function.
337   Instruction *EraseInstFromFunction(Instruction &I) {
338     DEBUG(dbgs() << "IC: ERASE " << I << '\n');
339
340     assert(I.use_empty() && "Cannot erase instruction that is used!");
341     // Make sure that we reprocess all operands now that we reduced their
342     // use counts.
343     if (I.getNumOperands() < 8) {
344       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
345         if (Instruction *Op = dyn_cast<Instruction>(*i))
346           Worklist.Add(Op);
347     }
348     Worklist.Remove(&I);
349     I.eraseFromParent();
350     MadeIRChange = true;
351     return nullptr; // Don't do anything with FI
352   }
353
354   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
355                         unsigned Depth = 0, Instruction *CxtI = nullptr) const {
356     return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
357                                   AT, CxtI, DT);
358   }
359
360   bool MaskedValueIsZero(Value *V, const APInt &Mask,
361                          unsigned Depth = 0,
362                          Instruction *CxtI = nullptr) const {
363     return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AT, CxtI, DT);
364   }
365   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
366                               Instruction *CxtI = nullptr) const {
367     return llvm::ComputeNumSignBits(Op, DL, Depth, AT, CxtI, DT);
368   }
369
370 private:
371   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
372   /// operators which are associative or commutative.
373   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
374
375   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
376   /// which some other binary operation distributes over either by factorizing
377   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
378   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
379   /// a win).  Returns the simplified value, or null if it didn't simplify.
380   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
381
382   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
383   /// based on the demanded bits.
384   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
385                                  APInt &KnownOne, unsigned Depth,
386                                  Instruction *CxtI = nullptr);
387   bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
388                             APInt &KnownOne, unsigned Depth = 0);
389   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
390   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
391   Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
392                                     APInt DemandedMask, APInt &KnownZero,
393                                     APInt &KnownOne);
394
395   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396   /// SimplifyDemandedBits knows about.  See if the instruction has any
397   /// properties that allow us to simplify its operands.
398   bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
400   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401                                     APInt &UndefElts, unsigned Depth = 0);
402
403   Value *SimplifyVectorOp(BinaryOperator &Inst);
404
405   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
406   // which has a PHI node as operand #0, see if we can fold the instruction
407   // into the PHI (which is only possible if all operands to the PHI are
408   // constants).
409   //
410   Instruction *FoldOpIntoPhi(Instruction &I);
411
412   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413   // operator and they all are only used by the PHI, PHI together their
414   // inputs, and do the operation once, to the result of the PHI.
415   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
416   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
417   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
418   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
419
420   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
422
423   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
424                             bool isSub, Instruction &I);
425   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
426                          bool Inside);
427   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
428   Instruction *MatchBSwap(BinaryOperator &I);
429   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
430   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
431   Instruction *SimplifyMemSet(MemSetInst *MI);
432
433   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
434
435   /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
436   /// the multiplication is known not to overflow then NoSignedWrap is set.
437   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
438 };
439
440 } // end namespace llvm.
441
442 #undef DEBUG_TYPE
443
444 #endif