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 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "indvars"
35 
36 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
37 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
38 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
39 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
40 
41 namespace {
42   /// This is a utility for simplifying induction variables
43   /// based on ScalarEvolution. It is the primary instrument of the
44   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
45   /// other loop passes that preserve SCEV.
46   class SimplifyIndvar {
47     Loop             *L;
48     LoopInfo         *LI;
49     ScalarEvolution  *SE;
50     DominatorTree    *DT;
51 
52     SmallVectorImpl<WeakVH> &DeadInsts;
53 
54     bool Changed;
55 
56   public:
57     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
58                    LoopInfo *LI,SmallVectorImpl<WeakVH> &Dead)
59         : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
60       assert(LI && "IV simplification requires LoopInfo");
61     }
62 
63     bool hasChanged() const { return Changed; }
64 
65     /// Iteratively perform simplification on a worklist of users of the
66     /// specified induction variable. This is the top-level driver that applies
67     /// all simplifications to users of an IV.
68     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
69 
70     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
71 
72     bool eliminateIdentitySCEV(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     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
79 
80     Instruction *splitOverflowIntrinsic(Instruction *IVUser,
81                                         const DominatorTree *DT);
82   };
83 }
84 
85 /// Fold an IV operand into its use.  This removes increments of an
86 /// aligned IV when used by a instruction that ignores the low bits.
87 ///
88 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
89 ///
90 /// Return the operand of IVOperand for this induction variable if IVOperand can
91 /// be folded (in case more folding opportunities have been exposed).
92 /// Otherwise return null.
93 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
94   Value *IVSrc = nullptr;
95   unsigned OperIdx = 0;
96   const SCEV *FoldedExpr = nullptr;
97   switch (UseInst->getOpcode()) {
98   default:
99     return nullptr;
100   case Instruction::UDiv:
101   case Instruction::LShr:
102     // We're only interested in the case where we know something about
103     // the numerator and have a constant denominator.
104     if (IVOperand != UseInst->getOperand(OperIdx) ||
105         !isa<ConstantInt>(UseInst->getOperand(1)))
106       return nullptr;
107 
108     // Attempt to fold a binary operator with constant operand.
109     // e.g. ((I + 1) >> 2) => I >> 2
110     if (!isa<BinaryOperator>(IVOperand)
111         || !isa<ConstantInt>(IVOperand->getOperand(1)))
112       return nullptr;
113 
114     IVSrc = IVOperand->getOperand(0);
115     // IVSrc must be the (SCEVable) IV, since the other operand is const.
116     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
117 
118     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
119     if (UseInst->getOpcode() == Instruction::LShr) {
120       // Get a constant for the divisor. See createSCEV.
121       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
122       if (D->getValue().uge(BitWidth))
123         return nullptr;
124 
125       D = ConstantInt::get(UseInst->getContext(),
126                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
127     }
128     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
129   }
130   // We have something that might fold it's operand. Compare SCEVs.
131   if (!SE->isSCEVable(UseInst->getType()))
132     return nullptr;
133 
134   // Bypass the operand if SCEV can prove it has no effect.
135   if (SE->getSCEV(UseInst) != FoldedExpr)
136     return nullptr;
137 
138   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
139         << " -> " << *UseInst << '\n');
140 
141   UseInst->setOperand(OperIdx, IVSrc);
142   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
143 
144   ++NumElimOperand;
145   Changed = true;
146   if (IVOperand->use_empty())
147     DeadInsts.emplace_back(IVOperand);
148   return IVSrc;
149 }
150 
151 /// SimplifyIVUsers helper for eliminating useless
152 /// comparisons against an induction variable.
153 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
154   unsigned IVOperIdx = 0;
155   ICmpInst::Predicate Pred = ICmp->getPredicate();
156   if (IVOperand != ICmp->getOperand(0)) {
157     // Swapped
158     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
159     IVOperIdx = 1;
160     Pred = ICmpInst::getSwappedPredicate(Pred);
161   }
162 
163   // Get the SCEVs for the ICmp operands.
164   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
165   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
166 
167   // Simplify unnecessary loops away.
168   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
169   S = SE->getSCEVAtScope(S, ICmpLoop);
170   X = SE->getSCEVAtScope(X, ICmpLoop);
171 
172   ICmpInst::Predicate InvariantPredicate;
173   const SCEV *InvariantLHS, *InvariantRHS;
174 
175   // If the condition is always true or always false, replace it with
176   // a constant value.
177   if (SE->isKnownPredicate(Pred, S, X)) {
178     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
179     DeadInsts.emplace_back(ICmp);
180     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
181   } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
182     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
183     DeadInsts.emplace_back(ICmp);
184     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
185   } else if (isa<PHINode>(IVOperand) &&
186              SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
187                                           InvariantLHS, InvariantRHS)) {
188 
189     // Rewrite the comparison to a loop invariant comparison if it can be done
190     // cheaply, where cheaply means "we don't need to emit any new
191     // instructions".
192 
193     Value *NewLHS = nullptr, *NewRHS = nullptr;
194 
195     if (S == InvariantLHS || X == InvariantLHS)
196       NewLHS =
197           ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
198 
199     if (S == InvariantRHS || X == InvariantRHS)
200       NewRHS =
201           ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
202 
203     auto *PN = cast<PHINode>(IVOperand);
204     for (unsigned i = 0, e = PN->getNumIncomingValues();
205          i != e && (!NewLHS || !NewRHS);
206          ++i) {
207 
208       // If this is a value incoming from the backedge, then it cannot be a loop
209       // invariant value (since we know that IVOperand is an induction variable).
210       if (L->contains(PN->getIncomingBlock(i)))
211         continue;
212 
213       // NB! This following assert does not fundamentally have to be true, but
214       // it is true today given how SCEV analyzes induction variables.
215       // Specifically, today SCEV will *not* recognize %iv as an induction
216       // variable in the following case:
217       //
218       // define void @f(i32 %k) {
219       // entry:
220       //   br i1 undef, label %r, label %l
221       //
222       // l:
223       //   %k.inc.l = add i32 %k, 1
224       //   br label %loop
225       //
226       // r:
227       //   %k.inc.r = add i32 %k, 1
228       //   br label %loop
229       //
230       // loop:
231       //   %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
232       //   %iv.inc = add i32 %iv, 1
233       //   br label %loop
234       // }
235       //
236       // but if it starts to, at some point, then the assertion below will have
237       // to be changed to a runtime check.
238 
239       Value *Incoming = PN->getIncomingValue(i);
240 
241 #ifndef NDEBUG
242       if (auto *I = dyn_cast<Instruction>(Incoming))
243         assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
244 #endif
245 
246       const SCEV *IncomingS = SE->getSCEV(Incoming);
247 
248       if (!NewLHS && IncomingS == InvariantLHS)
249         NewLHS = Incoming;
250       if (!NewRHS && IncomingS == InvariantRHS)
251         NewRHS = Incoming;
252     }
253 
254     if (!NewLHS || !NewRHS)
255       // We could not find an existing value to replace either LHS or RHS.
256       // Generating new instructions has subtler tradeoffs, so avoid doing that
257       // for now.
258       return;
259 
260     DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
261     ICmp->setPredicate(InvariantPredicate);
262     ICmp->setOperand(0, NewLHS);
263     ICmp->setOperand(1, NewRHS);
264   } else
265     return;
266 
267   ++NumElimCmp;
268   Changed = true;
269 }
270 
271 /// SimplifyIVUsers helper for eliminating useless
272 /// remainder operations operating on an induction variable.
273 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
274                                       Value *IVOperand,
275                                       bool IsSigned) {
276   // We're only interested in the case where we know something about
277   // the numerator.
278   if (IVOperand != Rem->getOperand(0))
279     return;
280 
281   // Get the SCEVs for the ICmp operands.
282   const SCEV *S = SE->getSCEV(Rem->getOperand(0));
283   const SCEV *X = SE->getSCEV(Rem->getOperand(1));
284 
285   // Simplify unnecessary loops away.
286   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
287   S = SE->getSCEVAtScope(S, ICmpLoop);
288   X = SE->getSCEVAtScope(X, ICmpLoop);
289 
290   // i % n  -->  i  if i is in [0,n).
291   if ((!IsSigned || SE->isKnownNonNegative(S)) &&
292       SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
293                            S, X))
294     Rem->replaceAllUsesWith(Rem->getOperand(0));
295   else {
296     // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
297     const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->getType()));
298     if (IsSigned && !SE->isKnownNonNegative(LessOne))
299       return;
300 
301     if (!SE->isKnownPredicate(IsSigned ?
302                               ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
303                               LessOne, X))
304       return;
305 
306     ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
307                                   Rem->getOperand(0), Rem->getOperand(1));
308     SelectInst *Sel =
309       SelectInst::Create(ICmp,
310                          ConstantInt::get(Rem->getType(), 0),
311                          Rem->getOperand(0), "tmp", Rem);
312     Rem->replaceAllUsesWith(Sel);
313   }
314 
315   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
316   ++NumElimRem;
317   Changed = true;
318   DeadInsts.emplace_back(Rem);
319 }
320 
321 /// Eliminate an operation that consumes a simple IV and has no observable
322 /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
323 /// but UseInst may not be.
324 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
325                                      Instruction *IVOperand) {
326   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
327     eliminateIVComparison(ICmp, IVOperand);
328     return true;
329   }
330   if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
331     bool IsSigned = Rem->getOpcode() == Instruction::SRem;
332     if (IsSigned || Rem->getOpcode() == Instruction::URem) {
333       eliminateIVRemainder(Rem, IVOperand, IsSigned);
334       return true;
335     }
336   }
337 
338   if (eliminateIdentitySCEV(UseInst, IVOperand))
339     return true;
340 
341   return false;
342 }
343 
344 /// Eliminate any operation that SCEV can prove is an identity function.
345 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
346                                            Instruction *IVOperand) {
347   if (!SE->isSCEVable(UseInst->getType()) ||
348       (UseInst->getType() != IVOperand->getType()) ||
349       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
350     return false;
351 
352   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
353   // dominator tree, even if X is an operand to Y.  For instance, in
354   //
355   //     %iv = phi i32 {0,+,1}
356   //     br %cond, label %left, label %merge
357   //
358   //   left:
359   //     %X = add i32 %iv, 0
360   //     br label %merge
361   //
362   //   merge:
363   //     %M = phi (%X, %iv)
364   //
365   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
366   // %M.replaceAllUsesWith(%X) would be incorrect.
367 
368   if (isa<PHINode>(UseInst))
369     // If UseInst is not a PHI node then we know that IVOperand dominates
370     // UseInst directly from the legality of SSA.
371     if (!DT || !DT->dominates(IVOperand, UseInst))
372       return false;
373 
374   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
375     return false;
376 
377   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
378 
379   UseInst->replaceAllUsesWith(IVOperand);
380   ++NumElimIdentity;
381   Changed = true;
382   DeadInsts.emplace_back(UseInst);
383   return true;
384 }
385 
386 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
387 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
388 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
389                                                     Value *IVOperand) {
390 
391   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
392   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
393     return false;
394 
395   const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
396                                                SCEV::NoWrapFlags);
397 
398   switch (BO->getOpcode()) {
399   default:
400     return false;
401 
402   case Instruction::Add:
403     GetExprForBO = &ScalarEvolution::getAddExpr;
404     break;
405 
406   case Instruction::Sub:
407     GetExprForBO = &ScalarEvolution::getMinusSCEV;
408     break;
409 
410   case Instruction::Mul:
411     GetExprForBO = &ScalarEvolution::getMulExpr;
412     break;
413   }
414 
415   unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
416   Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
417   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
418   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
419 
420   bool Changed = false;
421 
422   if (!BO->hasNoUnsignedWrap()) {
423     const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
424     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
425       SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
426       SCEV::FlagAnyWrap);
427     if (ExtendAfterOp == OpAfterExtend) {
428       BO->setHasNoUnsignedWrap();
429       SE->forgetValue(BO);
430       Changed = true;
431     }
432   }
433 
434   if (!BO->hasNoSignedWrap()) {
435     const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
436     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
437       SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
438       SCEV::FlagAnyWrap);
439     if (ExtendAfterOp == OpAfterExtend) {
440       BO->setHasNoSignedWrap();
441       SE->forgetValue(BO);
442       Changed = true;
443     }
444   }
445 
446   return Changed;
447 }
448 
449 /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
450 /// analysis and optimization.
451 ///
452 /// \return A new value representing the non-overflowing add if possible,
453 /// otherwise return the original value.
454 Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
455                                                     const DominatorTree *DT) {
456   IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
457   if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
458     return IVUser;
459 
460   // Find a branch guarded by the overflow check.
461   BranchInst *Branch = nullptr;
462   Instruction *AddVal = nullptr;
463   for (User *U : II->users()) {
464     if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
465       if (ExtractInst->getNumIndices() != 1)
466         continue;
467       if (ExtractInst->getIndices()[0] == 0)
468         AddVal = ExtractInst;
469       else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
470         Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
471     }
472   }
473   if (!AddVal || !Branch)
474     return IVUser;
475 
476   BasicBlock *ContinueBB = Branch->getSuccessor(1);
477   if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
478     return IVUser;
479 
480   // Check if all users of the add are provably NSW.
481   bool AllNSW = true;
482   for (Use &U : AddVal->uses()) {
483     if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
484       BasicBlock *UseBB = UseInst->getParent();
485       if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
486         UseBB = PHI->getIncomingBlock(U);
487       if (!DT->dominates(ContinueBB, UseBB)) {
488         AllNSW = false;
489         break;
490       }
491     }
492   }
493   if (!AllNSW)
494     return IVUser;
495 
496   // Go for it...
497   IRBuilder<> Builder(IVUser);
498   Instruction *AddInst = dyn_cast<Instruction>(
499     Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
500 
501   // The caller expects the new add to have the same form as the intrinsic. The
502   // IV operand position must be the same.
503   assert((AddInst->getOpcode() == Instruction::Add &&
504           AddInst->getOperand(0) == II->getOperand(0)) &&
505          "Bad add instruction created from overflow intrinsic.");
506 
507   AddVal->replaceAllUsesWith(AddInst);
508   DeadInsts.emplace_back(AddVal);
509   return AddInst;
510 }
511 
512 /// Add all uses of Def to the current IV's worklist.
513 static void pushIVUsers(
514   Instruction *Def,
515   SmallPtrSet<Instruction*,16> &Simplified,
516   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
517 
518   for (User *U : Def->users()) {
519     Instruction *UI = cast<Instruction>(U);
520 
521     // Avoid infinite or exponential worklist processing.
522     // Also ensure unique worklist users.
523     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
524     // self edges first.
525     if (UI != Def && Simplified.insert(UI).second)
526       SimpleIVUsers.push_back(std::make_pair(UI, Def));
527   }
528 }
529 
530 /// Return true if this instruction generates a simple SCEV
531 /// expression in terms of that IV.
532 ///
533 /// This is similar to IVUsers' isInteresting() but processes each instruction
534 /// non-recursively when the operand is already known to be a simpleIVUser.
535 ///
536 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
537   if (!SE->isSCEVable(I->getType()))
538     return false;
539 
540   // Get the symbolic expression for this instruction.
541   const SCEV *S = SE->getSCEV(I);
542 
543   // Only consider affine recurrences.
544   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
545   if (AR && AR->getLoop() == L)
546     return true;
547 
548   return false;
549 }
550 
551 /// Iteratively perform simplification on a worklist of users
552 /// of the specified induction variable. Each successive simplification may push
553 /// more users which may themselves be candidates for simplification.
554 ///
555 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
556 /// instructions in-place during analysis. Rather than rewriting induction
557 /// variables bottom-up from their users, it transforms a chain of IVUsers
558 /// top-down, updating the IR only when it encounters a clear optimization
559 /// opportunity.
560 ///
561 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
562 ///
563 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
564   if (!SE->isSCEVable(CurrIV->getType()))
565     return;
566 
567   // Instructions processed by SimplifyIndvar for CurrIV.
568   SmallPtrSet<Instruction*,16> Simplified;
569 
570   // Use-def pairs if IV users waiting to be processed for CurrIV.
571   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
572 
573   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
574   // called multiple times for the same LoopPhi. This is the proper thing to
575   // do for loop header phis that use each other.
576   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
577 
578   while (!SimpleIVUsers.empty()) {
579     std::pair<Instruction*, Instruction*> UseOper =
580       SimpleIVUsers.pop_back_val();
581     Instruction *UseInst = UseOper.first;
582 
583     // Bypass back edges to avoid extra work.
584     if (UseInst == CurrIV) continue;
585 
586     if (V && V->shouldSplitOverflowInstrinsics()) {
587       UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
588       if (!UseInst)
589         continue;
590     }
591 
592     Instruction *IVOperand = UseOper.second;
593     for (unsigned N = 0; IVOperand; ++N) {
594       assert(N <= Simplified.size() && "runaway iteration");
595 
596       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
597       if (!NewOper)
598         break; // done folding
599       IVOperand = dyn_cast<Instruction>(NewOper);
600     }
601     if (!IVOperand)
602       continue;
603 
604     if (eliminateIVUser(UseOper.first, IVOperand)) {
605       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
606       continue;
607     }
608 
609     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
610       if (isa<OverflowingBinaryOperator>(BO) &&
611           strengthenOverflowingOperation(BO, IVOperand)) {
612         // re-queue uses of the now modified binary operator and fall
613         // through to the checks that remain.
614         pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
615       }
616     }
617 
618     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
619     if (V && Cast) {
620       V->visitCast(Cast);
621       continue;
622     }
623     if (isSimpleIVUser(UseOper.first, L, SE)) {
624       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
625     }
626   }
627 }
628 
629 namespace llvm {
630 
631 void IVVisitor::anchor() { }
632 
633 /// Simplify instructions that use this induction variable
634 /// by using ScalarEvolution to analyze the IV's recurrence.
635 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
636                        LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead,
637                        IVVisitor *V) {
638   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
639   SIV.simplifyUsers(CurrIV, V);
640   return SIV.hasChanged();
641 }
642 
643 /// Simplify users of induction variables within this
644 /// loop. This does not actually change or add IVs.
645 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
646                      LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead) {
647   bool Changed = false;
648   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
649     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
650   }
651   return Changed;
652 }
653 
654 } // namespace llvm
655