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