LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
SimplifyIndVar.cpp
Go to the documentation of this file.
1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
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 // This file implements induction variable simplification. It does
11 // not define any actual pass or policy, but provides a single function to
12 // simplify a loop's induction variables based on ScalarEvolution.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #define DEBUG_TYPE "indvars"
17 
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/IVUsers.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Instructions.h"
28 #include "llvm/Support/Debug.h"
30 
31 using namespace llvm;
32 
33 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
34 STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
35 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
36 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
37 
38 namespace {
39  /// SimplifyIndvar - This is a utility for simplifying induction variables
40  /// based on ScalarEvolution. It is the primary instrument of the
41  /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
42  /// other loop passes that preserve SCEV.
43  class SimplifyIndvar {
44  Loop *L;
45  LoopInfo *LI;
46  ScalarEvolution *SE;
47  const DataLayout *TD; // May be NULL
48 
49  SmallVectorImpl<WeakVH> &DeadInsts;
50 
51  bool Changed;
52 
53  public:
54  SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
55  SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
56  L(Loop),
57  LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
58  SE(SE),
59  TD(LPM->getAnalysisIfAvailable<DataLayout>()),
60  DeadInsts(Dead),
61  Changed(false) {
62  assert(LI && "IV simplification requires LoopInfo");
63  }
64 
65  bool hasChanged() const { return Changed; }
66 
67  /// Iteratively perform simplification on a worklist of users of the
68  /// specified induction variable. This is the top-level driver that applies
69  /// all simplicitions to users of an IV.
70  void simplifyUsers(PHINode *CurrIV, IVVisitor *V = NULL);
71 
72  Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
73 
74  bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
75  void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
76  void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
77  bool IsSigned);
78  };
79 }
80 
81 /// foldIVUser - Fold an IV operand into its use. This removes increments of an
82 /// aligned IV when used by a instruction that ignores the low bits.
83 ///
84 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
85 ///
86 /// Return the operand of IVOperand for this induction variable if IVOperand can
87 /// be folded (in case more folding opportunities have been exposed).
88 /// Otherwise return null.
89 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
90  Value *IVSrc = 0;
91  unsigned OperIdx = 0;
92  const SCEV *FoldedExpr = 0;
93  switch (UseInst->getOpcode()) {
94  default:
95  return 0;
96  case Instruction::UDiv:
97  case Instruction::LShr:
98  // We're only interested in the case where we know something about
99  // the numerator and have a constant denominator.
100  if (IVOperand != UseInst->getOperand(OperIdx) ||
101  !isa<ConstantInt>(UseInst->getOperand(1)))
102  return 0;
103 
104  // Attempt to fold a binary operator with constant operand.
105  // e.g. ((I + 1) >> 2) => I >> 2
106  if (!isa<BinaryOperator>(IVOperand)
107  || !isa<ConstantInt>(IVOperand->getOperand(1)))
108  return 0;
109 
110  IVSrc = IVOperand->getOperand(0);
111  // IVSrc must be the (SCEVable) IV, since the other operand is const.
112  assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
113 
114  ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
115  if (UseInst->getOpcode() == Instruction::LShr) {
116  // Get a constant for the divisor. See createSCEV.
117  uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
118  if (D->getValue().uge(BitWidth))
119  return 0;
120 
121  D = ConstantInt::get(UseInst->getContext(),
122  APInt::getOneBitSet(BitWidth, D->getZExtValue()));
123  }
124  FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
125  }
126  // We have something that might fold it's operand. Compare SCEVs.
127  if (!SE->isSCEVable(UseInst->getType()))
128  return 0;
129 
130  // Bypass the operand if SCEV can prove it has no effect.
131  if (SE->getSCEV(UseInst) != FoldedExpr)
132  return 0;
133 
134  DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
135  << " -> " << *UseInst << '\n');
136 
137  UseInst->setOperand(OperIdx, IVSrc);
138  assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
139 
140  ++NumElimOperand;
141  Changed = true;
142  if (IVOperand->use_empty())
143  DeadInsts.push_back(IVOperand);
144  return IVSrc;
145 }
146 
147 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
148 /// comparisons against an induction variable.
149 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
150  unsigned IVOperIdx = 0;
151  ICmpInst::Predicate Pred = ICmp->getPredicate();
152  if (IVOperand != ICmp->getOperand(0)) {
153  // Swapped
154  assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
155  IVOperIdx = 1;
156  Pred = ICmpInst::getSwappedPredicate(Pred);
157  }
158 
159  // Get the SCEVs for the ICmp operands.
160  const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
161  const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
162 
163  // Simplify unnecessary loops away.
164  const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
165  S = SE->getSCEVAtScope(S, ICmpLoop);
166  X = SE->getSCEVAtScope(X, ICmpLoop);
167 
168  // If the condition is always true or always false, replace it with
169  // a constant value.
170  if (SE->isKnownPredicate(Pred, S, X))
172  else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
174  else
175  return;
176 
177  DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
178  ++NumElimCmp;
179  Changed = true;
180  DeadInsts.push_back(ICmp);
181 }
182 
183 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
184 /// remainder operations operating on an induction variable.
185 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
186  Value *IVOperand,
187  bool IsSigned) {
188  // We're only interested in the case where we know something about
189  // the numerator.
190  if (IVOperand != Rem->getOperand(0))
191  return;
192 
193  // Get the SCEVs for the ICmp operands.
194  const SCEV *S = SE->getSCEV(Rem->getOperand(0));
195  const SCEV *X = SE->getSCEV(Rem->getOperand(1));
196 
197  // Simplify unnecessary loops away.
198  const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
199  S = SE->getSCEVAtScope(S, ICmpLoop);
200  X = SE->getSCEVAtScope(X, ICmpLoop);
201 
202  // i % n --> i if i is in [0,n).
203  if ((!IsSigned || SE->isKnownNonNegative(S)) &&
204  SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
205  S, X))
206  Rem->replaceAllUsesWith(Rem->getOperand(0));
207  else {
208  // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
209  const SCEV *LessOne =
210  SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
211  if (IsSigned && !SE->isKnownNonNegative(LessOne))
212  return;
213 
214  if (!SE->isKnownPredicate(IsSigned ?
215  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
216  LessOne, X))
217  return;
218 
219  ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
220  Rem->getOperand(0), Rem->getOperand(1));
221  SelectInst *Sel =
222  SelectInst::Create(ICmp,
223  ConstantInt::get(Rem->getType(), 0),
224  Rem->getOperand(0), "tmp", Rem);
225  Rem->replaceAllUsesWith(Sel);
226  }
227 
228  DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
229  ++NumElimRem;
230  Changed = true;
231  DeadInsts.push_back(Rem);
232 }
233 
234 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
235 /// no observable side-effect given the range of IV values.
236 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
237 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
238  Instruction *IVOperand) {
239  if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
240  eliminateIVComparison(ICmp, IVOperand);
241  return true;
242  }
243  if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
244  bool IsSigned = Rem->getOpcode() == Instruction::SRem;
245  if (IsSigned || Rem->getOpcode() == Instruction::URem) {
246  eliminateIVRemainder(Rem, IVOperand, IsSigned);
247  return true;
248  }
249  }
250 
251  // Eliminate any operation that SCEV can prove is an identity function.
252  if (!SE->isSCEVable(UseInst->getType()) ||
253  (UseInst->getType() != IVOperand->getType()) ||
254  (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
255  return false;
256 
257  DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
258 
259  UseInst->replaceAllUsesWith(IVOperand);
260  ++NumElimIdentity;
261  Changed = true;
262  DeadInsts.push_back(UseInst);
263  return true;
264 }
265 
266 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
267 ///
268 static void pushIVUsers(
269  Instruction *Def,
270  SmallPtrSet<Instruction*,16> &Simplified,
271  SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
272 
273  for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
274  UI != E; ++UI) {
275  Instruction *User = cast<Instruction>(*UI);
276 
277  // Avoid infinite or exponential worklist processing.
278  // Also ensure unique worklist users.
279  // If Def is a LoopPhi, it may not be in the Simplified set, so check for
280  // self edges first.
281  if (User != Def && Simplified.insert(User))
282  SimpleIVUsers.push_back(std::make_pair(User, Def));
283  }
284 }
285 
286 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
287 /// expression in terms of that IV.
288 ///
289 /// This is similar to IVUsers' isInteresting() but processes each instruction
290 /// non-recursively when the operand is already known to be a simpleIVUser.
291 ///
292 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
293  if (!SE->isSCEVable(I->getType()))
294  return false;
295 
296  // Get the symbolic expression for this instruction.
297  const SCEV *S = SE->getSCEV(I);
298 
299  // Only consider affine recurrences.
300  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
301  if (AR && AR->getLoop() == L)
302  return true;
303 
304  return false;
305 }
306 
307 /// simplifyUsers - Iteratively perform simplification on a worklist of users
308 /// of the specified induction variable. Each successive simplification may push
309 /// more users which may themselves be candidates for simplification.
310 ///
311 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
312 /// instructions in-place during analysis. Rather than rewriting induction
313 /// variables bottom-up from their users, it transforms a chain of IVUsers
314 /// top-down, updating the IR only when it encouters a clear optimization
315 /// opportunitiy.
316 ///
317 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
318 ///
319 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
320  if (!SE->isSCEVable(CurrIV->getType()))
321  return;
322 
323  // Instructions processed by SimplifyIndvar for CurrIV.
324  SmallPtrSet<Instruction*,16> Simplified;
325 
326  // Use-def pairs if IV users waiting to be processed for CurrIV.
328 
329  // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
330  // called multiple times for the same LoopPhi. This is the proper thing to
331  // do for loop header phis that use each other.
332  pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
333 
334  while (!SimpleIVUsers.empty()) {
335  std::pair<Instruction*, Instruction*> UseOper =
336  SimpleIVUsers.pop_back_val();
337  // Bypass back edges to avoid extra work.
338  if (UseOper.first == CurrIV) continue;
339 
340  Instruction *IVOperand = UseOper.second;
341  for (unsigned N = 0; IVOperand; ++N) {
342  assert(N <= Simplified.size() && "runaway iteration");
343 
344  Value *NewOper = foldIVUser(UseOper.first, IVOperand);
345  if (!NewOper)
346  break; // done folding
347  IVOperand = dyn_cast<Instruction>(NewOper);
348  }
349  if (!IVOperand)
350  continue;
351 
352  if (eliminateIVUser(UseOper.first, IVOperand)) {
353  pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
354  continue;
355  }
356  CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
357  if (V && Cast) {
358  V->visitCast(Cast);
359  continue;
360  }
361  if (isSimpleIVUser(UseOper.first, L, SE)) {
362  pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
363  }
364  }
365 }
366 
367 namespace llvm {
368 
369 void IVVisitor::anchor() { }
370 
371 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
372 /// by using ScalarEvolution to analyze the IV's recurrence.
375 {
376  LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
377  SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
378  SIV.simplifyUsers(CurrIV, V);
379  return SIV.hasChanged();
380 }
381 
382 /// simplifyLoopIVs - Simplify users of induction variables within this
383 /// loop. This does not actually change or add IVs.
386  bool Changed = false;
387  for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
388  Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
389  }
390  return Changed;
391 }
392 
393 } // namespace llvm
use_iterator use_end()
Definition: Value.h:152
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:445
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=0)
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
Predicate getInversePredicate() const
Return the inverse of the instruction's predicate.
Definition: InstrTypes.h:737
unsigned less than
Definition: InstrTypes.h:676
bool insert(PtrType Ptr)
Definition: SmallPtrSet.h:253
BlockT * getHeader() const
Definition: LoopInfo.h:95
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
static unsigned getBitWidth(Type *Ty, const DataLayout *TD)
Base class of casting instructions.
Definition: InstrTypes.h:387
const APInt & getValue() const
Return the constant's value.
Definition: Constants.h:105
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:430
#define false
Definition: ConvertUTF.c:64
uint64_t getZExtValue() const
Return the zero extended value.
Definition: Constants.h:116
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM, SmallVectorImpl< WeakVH > &Dead, IVVisitor *V=NULL)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
Loop * getLoopFor(const BasicBlock *BB) const
Definition: LoopInfo.h:618
void replaceAllUsesWith(Value *V)
Definition: Value.cpp:303
bool isSCEVable(Type *Ty) const
Type * getType() const
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM, SmallVectorImpl< WeakVH > &Dead)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:476
Represent an integer comparison operator.
Definition: Instructions.h:911
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1116
Value * getOperand(unsigned i) const
Definition: User.h:88
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:714
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:517
BinaryOps getOpcode() const
Definition: InstrTypes.h:326
AnalysisType & getAnalysis() const
Class for constant integers.
Definition: Constants.h:51
Type * getType() const
Definition: Value.h:111
signed less than
Definition: InstrTypes.h:680
unsigned size() const
Definition: SmallPtrSet.h:75
Predicate getSwappedPredicate() const
Return the predicate as if the operands were swapped.
Definition: InstrTypes.h:753
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
Definition: Constants.cpp:492
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:438
void setOperand(unsigned i, Value *Val)
Definition: User.h:92
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE)
STATISTIC(NumElimIdentity,"Number of IV identities eliminated")
use_iterator use_begin()
Definition: Value.h:150
virtual void visitCast(CastInst *Cast)=0
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
const Loop * getLoop() const
bool use_empty() const
Definition: Value.h:149
static void pushIVUsers(Instruction *Def, SmallPtrSet< Instruction *, 16 > &Simplified, SmallVectorImpl< std::pair< Instruction *, Instruction * > > &SimpleIVUsers)
LLVM Value Representation.
Definition: Value.h:66
const SCEV * getSCEV(Value *V)
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:83
#define DEBUG(X)
Definition: Debug.h:97
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