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