LLVM API Documentation

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