1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements induction variable simplification. It does
10 // not define any actual pass or policy, but provides a single function to
11 // simplify a loop's induction variables based on ScalarEvolution.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.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(NumFoldedUser, "Number of IV users folded into a constant");
38 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
39 STATISTIC(
40     NumSimplifiedSDiv,
41     "Number of IV signed division operations converted to unsigned division");
42 STATISTIC(
43     NumSimplifiedSRem,
44     "Number of IV signed remainder operations converted to unsigned remainder");
45 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
46 
47 namespace {
48   /// This is a utility for simplifying induction variables
49   /// based on ScalarEvolution. It is the primary instrument of the
50   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
51   /// other loop passes that preserve SCEV.
52   class SimplifyIndvar {
53     Loop             *L;
54     LoopInfo         *LI;
55     ScalarEvolution  *SE;
56     DominatorTree    *DT;
57     const TargetTransformInfo *TTI;
58     SCEVExpander     &Rewriter;
59     SmallVectorImpl<WeakTrackingVH> &DeadInsts;
60 
61     bool Changed;
62 
63   public:
64     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
65                    LoopInfo *LI, const TargetTransformInfo *TTI,
66                    SCEVExpander &Rewriter,
67                    SmallVectorImpl<WeakTrackingVH> &Dead)
68         : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
69           DeadInsts(Dead), Changed(false) {
70       assert(LI && "IV simplification requires LoopInfo");
71     }
72 
73     bool hasChanged() const { return Changed; }
74 
75     /// Iteratively perform simplification on a worklist of users of the
76     /// specified induction variable. This is the top-level driver that applies
77     /// all simplifications to users of an IV.
78     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
79 
80     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
81 
82     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
83     bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
84 
85     bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
86     bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
87     bool eliminateTrunc(TruncInst *TI);
88     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
89     bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
90     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
91     void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
92                              bool IsSigned);
93     void replaceRemWithNumerator(BinaryOperator *Rem);
94     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
95     void replaceSRemWithURem(BinaryOperator *Rem);
96     bool eliminateSDiv(BinaryOperator *SDiv);
97     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
98     bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
99   };
100 }
101 
102 /// Find a point in code which dominates all given instructions. We can safely
103 /// assume that, whatever fact we can prove at the found point, this fact is
104 /// also true for each of the given instructions.
105 static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions,
106                                         DominatorTree &DT) {
107   Instruction *CommonDom = nullptr;
108   for (auto *Insn : Instructions)
109     if (!CommonDom || DT.dominates(Insn, CommonDom))
110       CommonDom = Insn;
111     else if (!DT.dominates(CommonDom, Insn))
112       // If there is no dominance relation, use common dominator.
113       CommonDom =
114           DT.findNearestCommonDominator(CommonDom->getParent(),
115                                         Insn->getParent())->getTerminator();
116   assert(CommonDom && "Common dominator not found?");
117   return CommonDom;
118 }
119 
120 /// Fold an IV operand into its use.  This removes increments of an
121 /// aligned IV when used by a instruction that ignores the low bits.
122 ///
123 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
124 ///
125 /// Return the operand of IVOperand for this induction variable if IVOperand can
126 /// be folded (in case more folding opportunities have been exposed).
127 /// Otherwise return null.
128 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
129   Value *IVSrc = nullptr;
130   const unsigned OperIdx = 0;
131   const SCEV *FoldedExpr = nullptr;
132   bool MustDropExactFlag = false;
133   switch (UseInst->getOpcode()) {
134   default:
135     return nullptr;
136   case Instruction::UDiv:
137   case Instruction::LShr:
138     // We're only interested in the case where we know something about
139     // the numerator and have a constant denominator.
140     if (IVOperand != UseInst->getOperand(OperIdx) ||
141         !isa<ConstantInt>(UseInst->getOperand(1)))
142       return nullptr;
143 
144     // Attempt to fold a binary operator with constant operand.
145     // e.g. ((I + 1) >> 2) => I >> 2
146     if (!isa<BinaryOperator>(IVOperand)
147         || !isa<ConstantInt>(IVOperand->getOperand(1)))
148       return nullptr;
149 
150     IVSrc = IVOperand->getOperand(0);
151     // IVSrc must be the (SCEVable) IV, since the other operand is const.
152     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
153 
154     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
155     if (UseInst->getOpcode() == Instruction::LShr) {
156       // Get a constant for the divisor. See createSCEV.
157       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
158       if (D->getValue().uge(BitWidth))
159         return nullptr;
160 
161       D = ConstantInt::get(UseInst->getContext(),
162                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
163     }
164     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
165     // We might have 'exact' flag set at this point which will no longer be
166     // correct after we make the replacement.
167     if (UseInst->isExact() &&
168         SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
169       MustDropExactFlag = true;
170   }
171   // We have something that might fold it's operand. Compare SCEVs.
172   if (!SE->isSCEVable(UseInst->getType()))
173     return nullptr;
174 
175   // Bypass the operand if SCEV can prove it has no effect.
176   if (SE->getSCEV(UseInst) != FoldedExpr)
177     return nullptr;
178 
179   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
180                     << " -> " << *UseInst << '\n');
181 
182   UseInst->setOperand(OperIdx, IVSrc);
183   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
184 
185   if (MustDropExactFlag)
186     UseInst->dropPoisonGeneratingFlags();
187 
188   ++NumElimOperand;
189   Changed = true;
190   if (IVOperand->use_empty())
191     DeadInsts.emplace_back(IVOperand);
192   return IVSrc;
193 }
194 
195 bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
196                                                Value *IVOperand) {
197   unsigned IVOperIdx = 0;
198   ICmpInst::Predicate Pred = ICmp->getPredicate();
199   if (IVOperand != ICmp->getOperand(0)) {
200     // Swapped
201     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
202     IVOperIdx = 1;
203     Pred = ICmpInst::getSwappedPredicate(Pred);
204   }
205 
206   // Get the SCEVs for the ICmp operands (in the specific context of the
207   // current loop)
208   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
209   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
210   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
211 
212   auto *PN = dyn_cast<PHINode>(IVOperand);
213   if (!PN)
214     return false;
215   auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L);
216   if (!LIP)
217     return false;
218   ICmpInst::Predicate InvariantPredicate = LIP->Pred;
219   const SCEV *InvariantLHS = LIP->LHS;
220   const SCEV *InvariantRHS = LIP->RHS;
221 
222   // Rewrite the comparison to a loop invariant comparison if it can be done
223   // cheaply, where cheaply means "we don't need to emit any new
224   // instructions".
225 
226   SmallDenseMap<const SCEV*, Value*> CheapExpansions;
227   CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
228   CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
229 
230   // TODO: Support multiple entry loops?  (We currently bail out of these in
231   // the IndVarSimplify pass)
232   if (auto *BB = L->getLoopPredecessor()) {
233     const int Idx = PN->getBasicBlockIndex(BB);
234     if (Idx >= 0) {
235       Value *Incoming = PN->getIncomingValue(Idx);
236       const SCEV *IncomingS = SE->getSCEV(Incoming);
237       CheapExpansions[IncomingS] = Incoming;
238     }
239   }
240   Value *NewLHS = CheapExpansions[InvariantLHS];
241   Value *NewRHS = CheapExpansions[InvariantRHS];
242 
243   if (!NewLHS)
244     if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
245       NewLHS = ConstLHS->getValue();
246   if (!NewRHS)
247     if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
248       NewRHS = ConstRHS->getValue();
249 
250   if (!NewLHS || !NewRHS)
251     // We could not find an existing value to replace either LHS or RHS.
252     // Generating new instructions has subtler tradeoffs, so avoid doing that
253     // for now.
254     return false;
255 
256   LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
257   ICmp->setPredicate(InvariantPredicate);
258   ICmp->setOperand(0, NewLHS);
259   ICmp->setOperand(1, NewRHS);
260   return true;
261 }
262 
263 /// SimplifyIVUsers helper for eliminating useless
264 /// comparisons against an induction variable.
265 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
266   unsigned IVOperIdx = 0;
267   ICmpInst::Predicate Pred = ICmp->getPredicate();
268   ICmpInst::Predicate OriginalPred = Pred;
269   if (IVOperand != ICmp->getOperand(0)) {
270     // Swapped
271     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
272     IVOperIdx = 1;
273     Pred = ICmpInst::getSwappedPredicate(Pred);
274   }
275 
276   // Get the SCEVs for the ICmp operands (in the specific context of the
277   // current loop)
278   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
279   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
280   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
281 
282   // If the condition is always true or always false in the given context,
283   // replace it with a constant value.
284   SmallVector<Instruction *, 4> Users;
285   for (auto *U : ICmp->users())
286     Users.push_back(cast<Instruction>(U));
287   const Instruction *CtxI = findCommonDominator(Users, *DT);
288   if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
289     ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev));
290     DeadInsts.emplace_back(ICmp);
291     LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
292   } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
293     // fallthrough to end of function
294   } else if (ICmpInst::isSigned(OriginalPred) &&
295              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
296     // If we were unable to make anything above, all we can is to canonicalize
297     // the comparison hoping that it will open the doors for other
298     // optimizations. If we find out that we compare two non-negative values,
299     // we turn the instruction's predicate to its unsigned version. Note that
300     // we cannot rely on Pred here unless we check if we have swapped it.
301     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
302     LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
303                       << '\n');
304     ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
305   } else
306     return;
307 
308   ++NumElimCmp;
309   Changed = true;
310 }
311 
312 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
313   // Get the SCEVs for the ICmp operands.
314   auto *N = SE->getSCEV(SDiv->getOperand(0));
315   auto *D = SE->getSCEV(SDiv->getOperand(1));
316 
317   // Simplify unnecessary loops away.
318   const Loop *L = LI->getLoopFor(SDiv->getParent());
319   N = SE->getSCEVAtScope(N, L);
320   D = SE->getSCEVAtScope(D, L);
321 
322   // Replace sdiv by udiv if both of the operands are non-negative
323   if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
324     auto *UDiv = BinaryOperator::Create(
325         BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
326         SDiv->getName() + ".udiv", SDiv);
327     UDiv->setIsExact(SDiv->isExact());
328     SDiv->replaceAllUsesWith(UDiv);
329     LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
330     ++NumSimplifiedSDiv;
331     Changed = true;
332     DeadInsts.push_back(SDiv);
333     return true;
334   }
335 
336   return false;
337 }
338 
339 // i %s n -> i %u n if i >= 0 and n >= 0
340 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
341   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
342   auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
343                                       Rem->getName() + ".urem", Rem);
344   Rem->replaceAllUsesWith(URem);
345   LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
346   ++NumSimplifiedSRem;
347   Changed = true;
348   DeadInsts.emplace_back(Rem);
349 }
350 
351 // i % n  -->  i  if i is in [0,n).
352 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
353   Rem->replaceAllUsesWith(Rem->getOperand(0));
354   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
355   ++NumElimRem;
356   Changed = true;
357   DeadInsts.emplace_back(Rem);
358 }
359 
360 // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
361 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
362   auto *T = Rem->getType();
363   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
364   ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
365   SelectInst *Sel =
366       SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
367   Rem->replaceAllUsesWith(Sel);
368   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
369   ++NumElimRem;
370   Changed = true;
371   DeadInsts.emplace_back(Rem);
372 }
373 
374 /// SimplifyIVUsers helper for eliminating useless remainder operations
375 /// operating on an induction variable or replacing srem by urem.
376 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
377                                          bool IsSigned) {
378   auto *NValue = Rem->getOperand(0);
379   auto *DValue = Rem->getOperand(1);
380   // We're only interested in the case where we know something about
381   // the numerator, unless it is a srem, because we want to replace srem by urem
382   // in general.
383   bool UsedAsNumerator = IVOperand == NValue;
384   if (!UsedAsNumerator && !IsSigned)
385     return;
386 
387   const SCEV *N = SE->getSCEV(NValue);
388 
389   // Simplify unnecessary loops away.
390   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
391   N = SE->getSCEVAtScope(N, ICmpLoop);
392 
393   bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
394 
395   // Do not proceed if the Numerator may be negative
396   if (!IsNumeratorNonNegative)
397     return;
398 
399   const SCEV *D = SE->getSCEV(DValue);
400   D = SE->getSCEVAtScope(D, ICmpLoop);
401 
402   if (UsedAsNumerator) {
403     auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
404     if (SE->isKnownPredicate(LT, N, D)) {
405       replaceRemWithNumerator(Rem);
406       return;
407     }
408 
409     auto *T = Rem->getType();
410     const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
411     if (SE->isKnownPredicate(LT, NLessOne, D)) {
412       replaceRemWithNumeratorOrZero(Rem);
413       return;
414     }
415   }
416 
417   // Try to replace SRem with URem, if both N and D are known non-negative.
418   // Since we had already check N, we only need to check D now
419   if (!IsSigned || !SE->isKnownNonNegative(D))
420     return;
421 
422   replaceSRemWithURem(Rem);
423 }
424 
425 static bool willNotOverflow(ScalarEvolution *SE, Instruction::BinaryOps BinOp,
426                             bool Signed, const SCEV *LHS, const SCEV *RHS) {
427   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
428                                             SCEV::NoWrapFlags, unsigned);
429   switch (BinOp) {
430   default:
431     llvm_unreachable("Unsupported binary op");
432   case Instruction::Add:
433     Operation = &ScalarEvolution::getAddExpr;
434     break;
435   case Instruction::Sub:
436     Operation = &ScalarEvolution::getMinusSCEV;
437     break;
438   case Instruction::Mul:
439     Operation = &ScalarEvolution::getMulExpr;
440     break;
441   }
442 
443   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
444       Signed ? &ScalarEvolution::getSignExtendExpr
445              : &ScalarEvolution::getZeroExtendExpr;
446 
447   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
448   auto *NarrowTy = cast<IntegerType>(LHS->getType());
449   auto *WideTy =
450     IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
451 
452   const SCEV *A =
453       (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
454                        WideTy, 0);
455   const SCEV *B =
456       (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
457                        (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
458   return A == B;
459 }
460 
461 bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
462   const SCEV *LHS = SE->getSCEV(WO->getLHS());
463   const SCEV *RHS = SE->getSCEV(WO->getRHS());
464   if (!willNotOverflow(SE, WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
465     return false;
466 
467   // Proved no overflow, nuke the overflow check and, if possible, the overflow
468   // intrinsic as well.
469 
470   BinaryOperator *NewResult = BinaryOperator::Create(
471       WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO);
472 
473   if (WO->isSigned())
474     NewResult->setHasNoSignedWrap(true);
475   else
476     NewResult->setHasNoUnsignedWrap(true);
477 
478   SmallVector<ExtractValueInst *, 4> ToDelete;
479 
480   for (auto *U : WO->users()) {
481     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
482       if (EVI->getIndices()[0] == 1)
483         EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
484       else {
485         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
486         EVI->replaceAllUsesWith(NewResult);
487       }
488       ToDelete.push_back(EVI);
489     }
490   }
491 
492   for (auto *EVI : ToDelete)
493     EVI->eraseFromParent();
494 
495   if (WO->use_empty())
496     WO->eraseFromParent();
497 
498   Changed = true;
499   return true;
500 }
501 
502 bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
503   const SCEV *LHS = SE->getSCEV(SI->getLHS());
504   const SCEV *RHS = SE->getSCEV(SI->getRHS());
505   if (!willNotOverflow(SE, SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
506     return false;
507 
508   BinaryOperator *BO = BinaryOperator::Create(
509       SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
510   if (SI->isSigned())
511     BO->setHasNoSignedWrap();
512   else
513     BO->setHasNoUnsignedWrap();
514 
515   SI->replaceAllUsesWith(BO);
516   DeadInsts.emplace_back(SI);
517   Changed = true;
518   return true;
519 }
520 
521 bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
522   // It is always legal to replace
523   //   icmp <pred> i32 trunc(iv), n
524   // with
525   //   icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
526   // Or with
527   //   icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
528   // Or with either of these if pred is an equality predicate.
529   //
530   // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
531   // every comparison which uses trunc, it means that we can replace each of
532   // them with comparison of iv against sext/zext(n). We no longer need trunc
533   // after that.
534   //
535   // TODO: Should we do this if we can widen *some* comparisons, but not all
536   // of them? Sometimes it is enough to enable other optimizations, but the
537   // trunc instruction will stay in the loop.
538   Value *IV = TI->getOperand(0);
539   Type *IVTy = IV->getType();
540   const SCEV *IVSCEV = SE->getSCEV(IV);
541   const SCEV *TISCEV = SE->getSCEV(TI);
542 
543   // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
544   // get rid of trunc
545   bool DoesSExtCollapse = false;
546   bool DoesZExtCollapse = false;
547   if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
548     DoesSExtCollapse = true;
549   if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
550     DoesZExtCollapse = true;
551 
552   // If neither sext nor zext does collapse, it is not profitable to do any
553   // transform. Bail.
554   if (!DoesSExtCollapse && !DoesZExtCollapse)
555     return false;
556 
557   // Collect users of the trunc that look like comparisons against invariants.
558   // Bail if we find something different.
559   SmallVector<ICmpInst *, 4> ICmpUsers;
560   for (auto *U : TI->users()) {
561     // We don't care about users in unreachable blocks.
562     if (isa<Instruction>(U) &&
563         !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
564       continue;
565     ICmpInst *ICI = dyn_cast<ICmpInst>(U);
566     if (!ICI) return false;
567     assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
568     if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
569         !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
570       return false;
571     // If we cannot get rid of trunc, bail.
572     if (ICI->isSigned() && !DoesSExtCollapse)
573       return false;
574     if (ICI->isUnsigned() && !DoesZExtCollapse)
575       return false;
576     // For equality, either signed or unsigned works.
577     ICmpUsers.push_back(ICI);
578   }
579 
580   auto CanUseZExt = [&](ICmpInst *ICI) {
581     // Unsigned comparison can be widened as unsigned.
582     if (ICI->isUnsigned())
583       return true;
584     // Is it profitable to do zext?
585     if (!DoesZExtCollapse)
586       return false;
587     // For equality, we can safely zext both parts.
588     if (ICI->isEquality())
589       return true;
590     // Otherwise we can only use zext when comparing two non-negative or two
591     // negative values. But in practice, we will never pass DoesZExtCollapse
592     // check for a negative value, because zext(trunc(x)) is non-negative. So
593     // it only make sense to check for non-negativity here.
594     const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
595     const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
596     return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
597   };
598   // Replace all comparisons against trunc with comparisons against IV.
599   for (auto *ICI : ICmpUsers) {
600     bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
601     auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
602     Instruction *Ext = nullptr;
603     // For signed/unsigned predicate, replace the old comparison with comparison
604     // of immediate IV against sext/zext of the invariant argument. If we can
605     // use either sext or zext (i.e. we are dealing with equality predicate),
606     // then prefer zext as a more canonical form.
607     // TODO: If we see a signed comparison which can be turned into unsigned,
608     // we can do it here for canonicalization purposes.
609     ICmpInst::Predicate Pred = ICI->getPredicate();
610     if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
611     if (CanUseZExt(ICI)) {
612       assert(DoesZExtCollapse && "Unprofitable zext?");
613       Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
614       Pred = ICmpInst::getUnsignedPredicate(Pred);
615     } else {
616       assert(DoesSExtCollapse && "Unprofitable sext?");
617       Ext = new SExtInst(Op1, IVTy, "sext", ICI);
618       assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
619     }
620     bool Changed;
621     L->makeLoopInvariant(Ext, Changed);
622     (void)Changed;
623     ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext);
624     ICI->replaceAllUsesWith(NewICI);
625     DeadInsts.emplace_back(ICI);
626   }
627 
628   // Trunc no longer needed.
629   TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
630   DeadInsts.emplace_back(TI);
631   return true;
632 }
633 
634 /// Eliminate an operation that consumes a simple IV and has no observable
635 /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
636 /// but UseInst may not be.
637 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
638                                      Instruction *IVOperand) {
639   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
640     eliminateIVComparison(ICmp, IVOperand);
641     return true;
642   }
643   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
644     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
645     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
646       simplifyIVRemainder(Bin, IVOperand, IsSRem);
647       return true;
648     }
649 
650     if (Bin->getOpcode() == Instruction::SDiv)
651       return eliminateSDiv(Bin);
652   }
653 
654   if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
655     if (eliminateOverflowIntrinsic(WO))
656       return true;
657 
658   if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
659     if (eliminateSaturatingIntrinsic(SI))
660       return true;
661 
662   if (auto *TI = dyn_cast<TruncInst>(UseInst))
663     if (eliminateTrunc(TI))
664       return true;
665 
666   if (eliminateIdentitySCEV(UseInst, IVOperand))
667     return true;
668 
669   return false;
670 }
671 
672 static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
673   if (auto *BB = L->getLoopPreheader())
674     return BB->getTerminator();
675 
676   return Hint;
677 }
678 
679 /// Replace the UseInst with a loop invariant expression if it is safe.
680 bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
681   if (!SE->isSCEVable(I->getType()))
682     return false;
683 
684   // Get the symbolic expression for this instruction.
685   const SCEV *S = SE->getSCEV(I);
686 
687   if (!SE->isLoopInvariant(S, L))
688     return false;
689 
690   // Do not generate something ridiculous even if S is loop invariant.
691   if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
692     return false;
693 
694   auto *IP = GetLoopInvariantInsertPosition(L, I);
695 
696   if (!isSafeToExpandAt(S, IP, *SE)) {
697     LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
698                       << " with non-speculable loop invariant: " << *S << '\n');
699     return false;
700   }
701 
702   auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
703 
704   I->replaceAllUsesWith(Invariant);
705   LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
706                     << " with loop invariant: " << *S << '\n');
707   ++NumFoldedUser;
708   Changed = true;
709   DeadInsts.emplace_back(I);
710   return true;
711 }
712 
713 /// Eliminate any operation that SCEV can prove is an identity function.
714 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
715                                            Instruction *IVOperand) {
716   if (!SE->isSCEVable(UseInst->getType()) ||
717       (UseInst->getType() != IVOperand->getType()) ||
718       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
719     return false;
720 
721   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
722   // dominator tree, even if X is an operand to Y.  For instance, in
723   //
724   //     %iv = phi i32 {0,+,1}
725   //     br %cond, label %left, label %merge
726   //
727   //   left:
728   //     %X = add i32 %iv, 0
729   //     br label %merge
730   //
731   //   merge:
732   //     %M = phi (%X, %iv)
733   //
734   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
735   // %M.replaceAllUsesWith(%X) would be incorrect.
736 
737   if (isa<PHINode>(UseInst))
738     // If UseInst is not a PHI node then we know that IVOperand dominates
739     // UseInst directly from the legality of SSA.
740     if (!DT || !DT->dominates(IVOperand, UseInst))
741       return false;
742 
743   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
744     return false;
745 
746   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
747 
748   UseInst->replaceAllUsesWith(IVOperand);
749   ++NumElimIdentity;
750   Changed = true;
751   DeadInsts.emplace_back(UseInst);
752   return true;
753 }
754 
755 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
756 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
757 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
758                                                     Value *IVOperand) {
759   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
760   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
761     return false;
762 
763   if (BO->getOpcode() != Instruction::Add &&
764       BO->getOpcode() != Instruction::Sub &&
765       BO->getOpcode() != Instruction::Mul)
766     return false;
767 
768   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
769   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
770   bool Changed = false;
771 
772   if (!BO->hasNoUnsignedWrap() &&
773       willNotOverflow(SE, BO->getOpcode(), /* Signed */ false, LHS, RHS)) {
774     BO->setHasNoUnsignedWrap();
775     Changed = true;
776   }
777 
778   if (!BO->hasNoSignedWrap() &&
779       willNotOverflow(SE, BO->getOpcode(), /* Signed */ true, LHS, RHS)) {
780     BO->setHasNoSignedWrap();
781     Changed = true;
782   }
783 
784   // The willNotOverflow() check might infer additional nowrap flags on addrecs
785   // while performing zero/sign extensions. We could call forgetValue() here
786   // to make sure those flags also propagate to any other SCEV expressions
787   // based on the addrec. However, this can have pathological compile-time
788   // impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
789   return Changed;
790 }
791 
792 /// Annotate the Shr in (X << IVOperand) >> C as exact using the
793 /// information from the IV's range. Returns true if anything changed, false
794 /// otherwise.
795 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
796                                           Value *IVOperand) {
797   using namespace llvm::PatternMatch;
798 
799   if (BO->getOpcode() == Instruction::Shl) {
800     bool Changed = false;
801     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
802     for (auto *U : BO->users()) {
803       const APInt *C;
804       if (match(U,
805                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
806           match(U,
807                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
808         BinaryOperator *Shr = cast<BinaryOperator>(U);
809         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
810           Shr->setIsExact(true);
811           Changed = true;
812         }
813       }
814     }
815     return Changed;
816   }
817 
818   return false;
819 }
820 
821 /// Add all uses of Def to the current IV's worklist.
822 static void pushIVUsers(
823   Instruction *Def, Loop *L,
824   SmallPtrSet<Instruction*,16> &Simplified,
825   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
826 
827   for (User *U : Def->users()) {
828     Instruction *UI = cast<Instruction>(U);
829 
830     // Avoid infinite or exponential worklist processing.
831     // Also ensure unique worklist users.
832     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
833     // self edges first.
834     if (UI == Def)
835       continue;
836 
837     // Only change the current Loop, do not change the other parts (e.g. other
838     // Loops).
839     if (!L->contains(UI))
840       continue;
841 
842     // Do not push the same instruction more than once.
843     if (!Simplified.insert(UI).second)
844       continue;
845 
846     SimpleIVUsers.push_back(std::make_pair(UI, Def));
847   }
848 }
849 
850 /// Return true if this instruction generates a simple SCEV
851 /// expression in terms of that IV.
852 ///
853 /// This is similar to IVUsers' isInteresting() but processes each instruction
854 /// non-recursively when the operand is already known to be a simpleIVUser.
855 ///
856 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
857   if (!SE->isSCEVable(I->getType()))
858     return false;
859 
860   // Get the symbolic expression for this instruction.
861   const SCEV *S = SE->getSCEV(I);
862 
863   // Only consider affine recurrences.
864   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
865   if (AR && AR->getLoop() == L)
866     return true;
867 
868   return false;
869 }
870 
871 /// Iteratively perform simplification on a worklist of users
872 /// of the specified induction variable. Each successive simplification may push
873 /// more users which may themselves be candidates for simplification.
874 ///
875 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
876 /// instructions in-place during analysis. Rather than rewriting induction
877 /// variables bottom-up from their users, it transforms a chain of IVUsers
878 /// top-down, updating the IR only when it encounters a clear optimization
879 /// opportunity.
880 ///
881 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
882 ///
883 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
884   if (!SE->isSCEVable(CurrIV->getType()))
885     return;
886 
887   // Instructions processed by SimplifyIndvar for CurrIV.
888   SmallPtrSet<Instruction*,16> Simplified;
889 
890   // Use-def pairs if IV users waiting to be processed for CurrIV.
891   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
892 
893   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
894   // called multiple times for the same LoopPhi. This is the proper thing to
895   // do for loop header phis that use each other.
896   pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
897 
898   while (!SimpleIVUsers.empty()) {
899     std::pair<Instruction*, Instruction*> UseOper =
900       SimpleIVUsers.pop_back_val();
901     Instruction *UseInst = UseOper.first;
902 
903     // If a user of the IndVar is trivially dead, we prefer just to mark it dead
904     // rather than try to do some complex analysis or transformation (such as
905     // widening) basing on it.
906     // TODO: Propagate TLI and pass it here to handle more cases.
907     if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
908       DeadInsts.emplace_back(UseInst);
909       continue;
910     }
911 
912     // Bypass back edges to avoid extra work.
913     if (UseInst == CurrIV) continue;
914 
915     // Try to replace UseInst with a loop invariant before any other
916     // simplifications.
917     if (replaceIVUserWithLoopInvariant(UseInst))
918       continue;
919 
920     Instruction *IVOperand = UseOper.second;
921     for (unsigned N = 0; IVOperand; ++N) {
922       assert(N <= Simplified.size() && "runaway iteration");
923 
924       Value *NewOper = foldIVUser(UseInst, IVOperand);
925       if (!NewOper)
926         break; // done folding
927       IVOperand = dyn_cast<Instruction>(NewOper);
928     }
929     if (!IVOperand)
930       continue;
931 
932     if (eliminateIVUser(UseInst, IVOperand)) {
933       pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
934       continue;
935     }
936 
937     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
938       if ((isa<OverflowingBinaryOperator>(BO) &&
939            strengthenOverflowingOperation(BO, IVOperand)) ||
940           (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
941         // re-queue uses of the now modified binary operator and fall
942         // through to the checks that remain.
943         pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
944       }
945     }
946 
947     CastInst *Cast = dyn_cast<CastInst>(UseInst);
948     if (V && Cast) {
949       V->visitCast(Cast);
950       continue;
951     }
952     if (isSimpleIVUser(UseInst, L, SE)) {
953       pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
954     }
955   }
956 }
957 
958 namespace llvm {
959 
960 void IVVisitor::anchor() { }
961 
962 /// Simplify instructions that use this induction variable
963 /// by using ScalarEvolution to analyze the IV's recurrence.
964 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
965                        LoopInfo *LI, const TargetTransformInfo *TTI,
966                        SmallVectorImpl<WeakTrackingVH> &Dead,
967                        SCEVExpander &Rewriter, IVVisitor *V) {
968   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
969                      Rewriter, Dead);
970   SIV.simplifyUsers(CurrIV, V);
971   return SIV.hasChanged();
972 }
973 
974 /// Simplify users of induction variables within this
975 /// loop. This does not actually change or add IVs.
976 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
977                      LoopInfo *LI, const TargetTransformInfo *TTI,
978                      SmallVectorImpl<WeakTrackingVH> &Dead) {
979   SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
980 #ifndef NDEBUG
981   Rewriter.setDebugType(DEBUG_TYPE);
982 #endif
983   bool Changed = false;
984   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
985     Changed |=
986         simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
987   }
988   return Changed;
989 }
990 
991 } // namespace llvm
992 
993 //===----------------------------------------------------------------------===//
994 // Widen Induction Variables - Extend the width of an IV to cover its
995 // widest uses.
996 //===----------------------------------------------------------------------===//
997 
998 class WidenIV {
999   // Parameters
1000   PHINode *OrigPhi;
1001   Type *WideType;
1002 
1003   // Context
1004   LoopInfo        *LI;
1005   Loop            *L;
1006   ScalarEvolution *SE;
1007   DominatorTree   *DT;
1008 
1009   // Does the module have any calls to the llvm.experimental.guard intrinsic
1010   // at all? If not we can avoid scanning instructions looking for guards.
1011   bool HasGuards;
1012 
1013   bool UsePostIncrementRanges;
1014 
1015   // Statistics
1016   unsigned NumElimExt = 0;
1017   unsigned NumWidened = 0;
1018 
1019   // Result
1020   PHINode *WidePhi = nullptr;
1021   Instruction *WideInc = nullptr;
1022   const SCEV *WideIncExpr = nullptr;
1023   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1024 
1025   SmallPtrSet<Instruction *,16> Widened;
1026 
1027   enum ExtendKind { ZeroExtended, SignExtended, Unknown };
1028 
1029   // A map tracking the kind of extension used to widen each narrow IV
1030   // and narrow IV user.
1031   // Key: pointer to a narrow IV or IV user.
1032   // Value: the kind of extension used to widen this Instruction.
1033   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
1034 
1035   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1036 
1037   // A map with control-dependent ranges for post increment IV uses. The key is
1038   // a pair of IV def and a use of this def denoting the context. The value is
1039   // a ConstantRange representing possible values of the def at the given
1040   // context.
1041   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1042 
1043   Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
1044                                               Instruction *UseI) {
1045     DefUserPair Key(Def, UseI);
1046     auto It = PostIncRangeInfos.find(Key);
1047     return It == PostIncRangeInfos.end()
1048                ? Optional<ConstantRange>(None)
1049                : Optional<ConstantRange>(It->second);
1050   }
1051 
1052   void calculatePostIncRanges(PHINode *OrigPhi);
1053   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1054 
1055   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
1056     DefUserPair Key(Def, UseI);
1057     auto It = PostIncRangeInfos.find(Key);
1058     if (It == PostIncRangeInfos.end())
1059       PostIncRangeInfos.insert({Key, R});
1060     else
1061       It->second = R.intersectWith(It->second);
1062   }
1063 
1064 public:
1065   /// Record a link in the Narrow IV def-use chain along with the WideIV that
1066   /// computes the same value as the Narrow IV def.  This avoids caching Use*
1067   /// pointers.
1068   struct NarrowIVDefUse {
1069     Instruction *NarrowDef = nullptr;
1070     Instruction *NarrowUse = nullptr;
1071     Instruction *WideDef = nullptr;
1072 
1073     // True if the narrow def is never negative.  Tracking this information lets
1074     // us use a sign extension instead of a zero extension or vice versa, when
1075     // profitable and legal.
1076     bool NeverNegative = false;
1077 
1078     NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1079                    bool NeverNegative)
1080         : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1081           NeverNegative(NeverNegative) {}
1082   };
1083 
1084   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1085           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1086           bool HasGuards, bool UsePostIncrementRanges = true);
1087 
1088   PHINode *createWideIV(SCEVExpander &Rewriter);
1089 
1090   unsigned getNumElimExt() { return NumElimExt; };
1091   unsigned getNumWidened() { return NumWidened; };
1092 
1093 protected:
1094   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1095                           Instruction *Use);
1096 
1097   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1098   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1099                                      const SCEVAddRecExpr *WideAR);
1100   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1101 
1102   ExtendKind getExtendKind(Instruction *I);
1103 
1104   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1105 
1106   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1107 
1108   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1109 
1110   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1111                               unsigned OpCode) const;
1112 
1113   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1114 
1115   bool widenLoopCompare(NarrowIVDefUse DU);
1116   bool widenWithVariantUse(NarrowIVDefUse DU);
1117 
1118   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1119 
1120 private:
1121   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
1122 };
1123 
1124 
1125 /// Determine the insertion point for this user. By default, insert immediately
1126 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
1127 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
1128 /// common dominator for the incoming blocks. A nullptr can be returned if no
1129 /// viable location is found: it may happen if User is a PHI and Def only comes
1130 /// to this PHI from unreachable blocks.
1131 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
1132                                           DominatorTree *DT, LoopInfo *LI) {
1133   PHINode *PHI = dyn_cast<PHINode>(User);
1134   if (!PHI)
1135     return User;
1136 
1137   Instruction *InsertPt = nullptr;
1138   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
1139     if (PHI->getIncomingValue(i) != Def)
1140       continue;
1141 
1142     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
1143 
1144     if (!DT->isReachableFromEntry(InsertBB))
1145       continue;
1146 
1147     if (!InsertPt) {
1148       InsertPt = InsertBB->getTerminator();
1149       continue;
1150     }
1151     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
1152     InsertPt = InsertBB->getTerminator();
1153   }
1154 
1155   // If we have skipped all inputs, it means that Def only comes to Phi from
1156   // unreachable blocks.
1157   if (!InsertPt)
1158     return nullptr;
1159 
1160   auto *DefI = dyn_cast<Instruction>(Def);
1161   if (!DefI)
1162     return InsertPt;
1163 
1164   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
1165 
1166   auto *L = LI->getLoopFor(DefI->getParent());
1167   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
1168 
1169   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
1170     if (LI->getLoopFor(DTN->getBlock()) == L)
1171       return DTN->getBlock()->getTerminator();
1172 
1173   llvm_unreachable("DefI dominates InsertPt!");
1174 }
1175 
1176 WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1177           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1178           bool HasGuards, bool UsePostIncrementRanges)
1179       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1180         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
1181         HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1182         DeadInsts(DI) {
1183     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
1184     ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
1185 }
1186 
1187 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1188                                  bool IsSigned, Instruction *Use) {
1189   // Set the debug location and conservative insertion point.
1190   IRBuilder<> Builder(Use);
1191   // Hoist the insertion point into loop preheaders as far as possible.
1192   for (const Loop *L = LI->getLoopFor(Use->getParent());
1193        L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1194        L = L->getParentLoop())
1195     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1196 
1197   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1198                     Builder.CreateZExt(NarrowOper, WideType);
1199 }
1200 
1201 /// Instantiate a wide operation to replace a narrow operation. This only needs
1202 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1203 /// 0 for any operation we decide not to clone.
1204 Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1205                                   const SCEVAddRecExpr *WideAR) {
1206   unsigned Opcode = DU.NarrowUse->getOpcode();
1207   switch (Opcode) {
1208   default:
1209     return nullptr;
1210   case Instruction::Add:
1211   case Instruction::Mul:
1212   case Instruction::UDiv:
1213   case Instruction::Sub:
1214     return cloneArithmeticIVUser(DU, WideAR);
1215 
1216   case Instruction::And:
1217   case Instruction::Or:
1218   case Instruction::Xor:
1219   case Instruction::Shl:
1220   case Instruction::LShr:
1221   case Instruction::AShr:
1222     return cloneBitwiseIVUser(DU);
1223   }
1224 }
1225 
1226 Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1227   Instruction *NarrowUse = DU.NarrowUse;
1228   Instruction *NarrowDef = DU.NarrowDef;
1229   Instruction *WideDef = DU.WideDef;
1230 
1231   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1232 
1233   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1234   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1235   // invariant and will be folded or hoisted. If it actually comes from a
1236   // widened IV, it should be removed during a future call to widenIVUse.
1237   bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1238   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1239                    ? WideDef
1240                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1241                                       IsSigned, NarrowUse);
1242   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1243                    ? WideDef
1244                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1245                                       IsSigned, NarrowUse);
1246 
1247   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1248   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1249                                         NarrowBO->getName());
1250   IRBuilder<> Builder(NarrowUse);
1251   Builder.Insert(WideBO);
1252   WideBO->copyIRFlags(NarrowBO);
1253   return WideBO;
1254 }
1255 
1256 Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1257                                             const SCEVAddRecExpr *WideAR) {
1258   Instruction *NarrowUse = DU.NarrowUse;
1259   Instruction *NarrowDef = DU.NarrowDef;
1260   Instruction *WideDef = DU.WideDef;
1261 
1262   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1263 
1264   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1265 
1266   // We're trying to find X such that
1267   //
1268   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1269   //
1270   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1271   // and check using SCEV if any of them are correct.
1272 
1273   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1274   // correct solution to X.
1275   auto GuessNonIVOperand = [&](bool SignExt) {
1276     const SCEV *WideLHS;
1277     const SCEV *WideRHS;
1278 
1279     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1280       if (SignExt)
1281         return SE->getSignExtendExpr(S, Ty);
1282       return SE->getZeroExtendExpr(S, Ty);
1283     };
1284 
1285     if (IVOpIdx == 0) {
1286       WideLHS = SE->getSCEV(WideDef);
1287       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1288       WideRHS = GetExtend(NarrowRHS, WideType);
1289     } else {
1290       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1291       WideLHS = GetExtend(NarrowLHS, WideType);
1292       WideRHS = SE->getSCEV(WideDef);
1293     }
1294 
1295     // WideUse is "WideDef `op.wide` X" as described in the comment.
1296     const SCEV *WideUse =
1297       getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
1298 
1299     return WideUse == WideAR;
1300   };
1301 
1302   bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1303   if (!GuessNonIVOperand(SignExtend)) {
1304     SignExtend = !SignExtend;
1305     if (!GuessNonIVOperand(SignExtend))
1306       return nullptr;
1307   }
1308 
1309   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1310                    ? WideDef
1311                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1312                                       SignExtend, NarrowUse);
1313   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1314                    ? WideDef
1315                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1316                                       SignExtend, NarrowUse);
1317 
1318   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1319   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1320                                         NarrowBO->getName());
1321 
1322   IRBuilder<> Builder(NarrowUse);
1323   Builder.Insert(WideBO);
1324   WideBO->copyIRFlags(NarrowBO);
1325   return WideBO;
1326 }
1327 
1328 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1329   auto It = ExtendKindMap.find(I);
1330   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1331   return It->second;
1332 }
1333 
1334 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1335                                      unsigned OpCode) const {
1336   switch (OpCode) {
1337   case Instruction::Add:
1338     return SE->getAddExpr(LHS, RHS);
1339   case Instruction::Sub:
1340     return SE->getMinusSCEV(LHS, RHS);
1341   case Instruction::Mul:
1342     return SE->getMulExpr(LHS, RHS);
1343   case Instruction::UDiv:
1344     return SE->getUDivExpr(LHS, RHS);
1345   default:
1346     llvm_unreachable("Unsupported opcode.");
1347   };
1348 }
1349 
1350 /// No-wrap operations can transfer sign extension of their result to their
1351 /// operands. Generate the SCEV value for the widened operation without
1352 /// actually modifying the IR yet. If the expression after extending the
1353 /// operands is an AddRec for this loop, return the AddRec and the kind of
1354 /// extension used.
1355 WidenIV::WidenedRecTy
1356 WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1357   // Handle the common case of add<nsw/nuw>
1358   const unsigned OpCode = DU.NarrowUse->getOpcode();
1359   // Only Add/Sub/Mul instructions supported yet.
1360   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1361       OpCode != Instruction::Mul)
1362     return {nullptr, Unknown};
1363 
1364   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1365   // if extending the other will lead to a recurrence.
1366   const unsigned ExtendOperIdx =
1367       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1368   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1369 
1370   const SCEV *ExtendOperExpr = nullptr;
1371   const OverflowingBinaryOperator *OBO =
1372     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1373   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1374   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1375     ExtendOperExpr = SE->getSignExtendExpr(
1376       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1377   else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1378     ExtendOperExpr = SE->getZeroExtendExpr(
1379       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1380   else
1381     return {nullptr, Unknown};
1382 
1383   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1384   // flags. This instruction may be guarded by control flow that the no-wrap
1385   // behavior depends on. Non-control-equivalent instructions can be mapped to
1386   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1387   // semantics to those operations.
1388   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1389   const SCEV *rhs = ExtendOperExpr;
1390 
1391   // Let's swap operands to the initial order for the case of non-commutative
1392   // operations, like SUB. See PR21014.
1393   if (ExtendOperIdx == 0)
1394     std::swap(lhs, rhs);
1395   const SCEVAddRecExpr *AddRec =
1396       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1397 
1398   if (!AddRec || AddRec->getLoop() != L)
1399     return {nullptr, Unknown};
1400 
1401   return {AddRec, ExtKind};
1402 }
1403 
1404 /// Is this instruction potentially interesting for further simplification after
1405 /// widening it's type? In other words, can the extend be safely hoisted out of
1406 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1407 /// so, return the extended recurrence and the kind of extension used. Otherwise
1408 /// return {nullptr, Unknown}.
1409 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1410   if (!SE->isSCEVable(DU.NarrowUse->getType()))
1411     return {nullptr, Unknown};
1412 
1413   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1414   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1415       SE->getTypeSizeInBits(WideType)) {
1416     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1417     // index. So don't follow this use.
1418     return {nullptr, Unknown};
1419   }
1420 
1421   const SCEV *WideExpr;
1422   ExtendKind ExtKind;
1423   if (DU.NeverNegative) {
1424     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1425     if (isa<SCEVAddRecExpr>(WideExpr))
1426       ExtKind = SignExtended;
1427     else {
1428       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1429       ExtKind = ZeroExtended;
1430     }
1431   } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1432     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1433     ExtKind = SignExtended;
1434   } else {
1435     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1436     ExtKind = ZeroExtended;
1437   }
1438   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1439   if (!AddRec || AddRec->getLoop() != L)
1440     return {nullptr, Unknown};
1441   return {AddRec, ExtKind};
1442 }
1443 
1444 /// This IV user cannot be widened. Replace this use of the original narrow IV
1445 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1446 static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT,
1447                           LoopInfo *LI) {
1448   auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1449   if (!InsertPt)
1450     return;
1451   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1452                     << *DU.NarrowUse << "\n");
1453   IRBuilder<> Builder(InsertPt);
1454   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1455   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1456 }
1457 
1458 /// If the narrow use is a compare instruction, then widen the compare
1459 //  (and possibly the other operand).  The extend operation is hoisted into the
1460 // loop preheader as far as possible.
1461 bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1462   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1463   if (!Cmp)
1464     return false;
1465 
1466   // We can legally widen the comparison in the following two cases:
1467   //
1468   //  - The signedness of the IV extension and comparison match
1469   //
1470   //  - The narrow IV is always positive (and thus its sign extension is equal
1471   //    to its zero extension).  For instance, let's say we're zero extending
1472   //    %narrow for the following use
1473   //
1474   //      icmp slt i32 %narrow, %val   ... (A)
1475   //
1476   //    and %narrow is always positive.  Then
1477   //
1478   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1479   //          == icmp slt i32 zext(%narrow), sext(%val)
1480   bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1481   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1482     return false;
1483 
1484   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1485   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1486   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1487   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1488 
1489   // Widen the compare instruction.
1490   auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1491   if (!InsertPt)
1492     return false;
1493   IRBuilder<> Builder(InsertPt);
1494   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1495 
1496   // Widen the other operand of the compare, if necessary.
1497   if (CastWidth < IVWidth) {
1498     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1499     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1500   }
1501   return true;
1502 }
1503 
1504 // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
1505 // will not work when:
1506 //    1) SCEV traces back to an instruction inside the loop that SCEV can not
1507 // expand, eg. add %indvar, (load %addr)
1508 //    2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
1509 // While SCEV fails to avoid trunc, we can still try to use instruction
1510 // combining approach to prove trunc is not required. This can be further
1511 // extended with other instruction combining checks, but for now we handle the
1512 // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
1513 //
1514 // Src:
1515 //   %c = sub nsw %b, %indvar
1516 //   %d = sext %c to i64
1517 // Dst:
1518 //   %indvar.ext1 = sext %indvar to i64
1519 //   %m = sext %b to i64
1520 //   %d = sub nsw i64 %m, %indvar.ext1
1521 // Therefore, as long as the result of add/sub/mul is extended to wide type, no
1522 // trunc is required regardless of how %b is generated. This pattern is common
1523 // when calculating address in 64 bit architecture
1524 bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1525   Instruction *NarrowUse = DU.NarrowUse;
1526   Instruction *NarrowDef = DU.NarrowDef;
1527   Instruction *WideDef = DU.WideDef;
1528 
1529   // Handle the common case of add<nsw/nuw>
1530   const unsigned OpCode = NarrowUse->getOpcode();
1531   // Only Add/Sub/Mul instructions are supported.
1532   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1533       OpCode != Instruction::Mul)
1534     return false;
1535 
1536   // The operand that is not defined by NarrowDef of DU. Let's call it the
1537   // other operand.
1538   assert((NarrowUse->getOperand(0) == NarrowDef ||
1539           NarrowUse->getOperand(1) == NarrowDef) &&
1540          "bad DU");
1541 
1542   const OverflowingBinaryOperator *OBO =
1543     cast<OverflowingBinaryOperator>(NarrowUse);
1544   ExtendKind ExtKind = getExtendKind(NarrowDef);
1545   bool CanSignExtend = ExtKind == SignExtended && OBO->hasNoSignedWrap();
1546   bool CanZeroExtend = ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap();
1547   auto AnotherOpExtKind = ExtKind;
1548 
1549   // Check that all uses are either:
1550   // - narrow def (in case of we are widening the IV increment);
1551   // - single-input LCSSA Phis;
1552   // - comparison of the chosen type;
1553   // - extend of the chosen type (raison d'etre).
1554   SmallVector<Instruction *, 4> ExtUsers;
1555   SmallVector<PHINode *, 4> LCSSAPhiUsers;
1556   SmallVector<ICmpInst *, 4> ICmpUsers;
1557   for (Use &U : NarrowUse->uses()) {
1558     Instruction *User = cast<Instruction>(U.getUser());
1559     if (User == NarrowDef)
1560       continue;
1561     if (!L->contains(User)) {
1562       auto *LCSSAPhi = cast<PHINode>(User);
1563       // Make sure there is only 1 input, so that we don't have to split
1564       // critical edges.
1565       if (LCSSAPhi->getNumOperands() != 1)
1566         return false;
1567       LCSSAPhiUsers.push_back(LCSSAPhi);
1568       continue;
1569     }
1570     if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1571       auto Pred = ICmp->getPredicate();
1572       // We have 3 types of predicates: signed, unsigned and equality
1573       // predicates. For equality, it's legal to widen icmp for either sign and
1574       // zero extend. For sign extend, we can also do so for signed predicates,
1575       // likeweise for zero extend we can widen icmp for unsigned predicates.
1576       if (ExtKind == ZeroExtended && ICmpInst::isSigned(Pred))
1577         return false;
1578       if (ExtKind == SignExtended && ICmpInst::isUnsigned(Pred))
1579         return false;
1580       ICmpUsers.push_back(ICmp);
1581       continue;
1582     }
1583     if (ExtKind == SignExtended)
1584       User = dyn_cast<SExtInst>(User);
1585     else
1586       User = dyn_cast<ZExtInst>(User);
1587     if (!User || User->getType() != WideType)
1588       return false;
1589     ExtUsers.push_back(User);
1590   }
1591   if (ExtUsers.empty()) {
1592     DeadInsts.emplace_back(NarrowUse);
1593     return true;
1594   }
1595 
1596   // We'll prove some facts that should be true in the context of ext users. If
1597   // there is no users, we are done now. If there are some, pick their common
1598   // dominator as context.
1599   const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1600 
1601   if (!CanSignExtend && !CanZeroExtend) {
1602     // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1603     // will most likely not see it. Let's try to prove it.
1604     if (OpCode != Instruction::Add)
1605       return false;
1606     if (ExtKind != ZeroExtended)
1607       return false;
1608     const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1609     const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1610     // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1611     if (NarrowUse->getOperand(0) != NarrowDef)
1612       return false;
1613     if (!SE->isKnownNegative(RHS))
1614       return false;
1615     bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1616                                                SE->getNegativeSCEV(RHS), CtxI);
1617     if (!ProvedSubNUW)
1618       return false;
1619     // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1620     // neg(zext(neg(op))), which is basically sext(op).
1621     AnotherOpExtKind = SignExtended;
1622   }
1623 
1624   // Verifying that Defining operand is an AddRec
1625   const SCEV *Op1 = SE->getSCEV(WideDef);
1626   const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1627   if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1628     return false;
1629 
1630   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1631 
1632   // Generating a widening use instruction.
1633   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1634                    ? WideDef
1635                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1636                                       AnotherOpExtKind, NarrowUse);
1637   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1638                    ? WideDef
1639                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1640                                       AnotherOpExtKind, NarrowUse);
1641 
1642   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1643   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1644                                         NarrowBO->getName());
1645   IRBuilder<> Builder(NarrowUse);
1646   Builder.Insert(WideBO);
1647   WideBO->copyIRFlags(NarrowBO);
1648   ExtendKindMap[NarrowUse] = ExtKind;
1649 
1650   for (Instruction *User : ExtUsers) {
1651     assert(User->getType() == WideType && "Checked before!");
1652     LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1653                       << *WideBO << "\n");
1654     ++NumElimExt;
1655     User->replaceAllUsesWith(WideBO);
1656     DeadInsts.emplace_back(User);
1657   }
1658 
1659   for (PHINode *User : LCSSAPhiUsers) {
1660     assert(User->getNumOperands() == 1 && "Checked before!");
1661     Builder.SetInsertPoint(User);
1662     auto *WidePN =
1663         Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1664     BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1665     assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1666            "Not a LCSSA Phi?");
1667     WidePN->addIncoming(WideBO, LoopExitingBlock);
1668     Builder.SetInsertPoint(&*User->getParent()->getFirstInsertionPt());
1669     auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1670     User->replaceAllUsesWith(TruncPN);
1671     DeadInsts.emplace_back(User);
1672   }
1673 
1674   for (ICmpInst *User : ICmpUsers) {
1675     Builder.SetInsertPoint(User);
1676     auto ExtendedOp = [&](Value * V)->Value * {
1677       if (V == NarrowUse)
1678         return WideBO;
1679       if (ExtKind == ZeroExtended)
1680         return Builder.CreateZExt(V, WideBO->getType());
1681       else
1682         return Builder.CreateSExt(V, WideBO->getType());
1683     };
1684     auto Pred = User->getPredicate();
1685     auto *LHS = ExtendedOp(User->getOperand(0));
1686     auto *RHS = ExtendedOp(User->getOperand(1));
1687     auto *WideCmp =
1688         Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1689     User->replaceAllUsesWith(WideCmp);
1690     DeadInsts.emplace_back(User);
1691   }
1692 
1693   return true;
1694 }
1695 
1696 /// Determine whether an individual user of the narrow IV can be widened. If so,
1697 /// return the wide clone of the user.
1698 Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1699   assert(ExtendKindMap.count(DU.NarrowDef) &&
1700          "Should already know the kind of extension used to widen NarrowDef");
1701 
1702   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1703   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1704     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1705       // For LCSSA phis, sink the truncate outside the loop.
1706       // After SimplifyCFG most loop exit targets have a single predecessor.
1707       // Otherwise fall back to a truncate within the loop.
1708       if (UsePhi->getNumOperands() != 1)
1709         truncateIVUse(DU, DT, LI);
1710       else {
1711         // Widening the PHI requires us to insert a trunc.  The logical place
1712         // for this trunc is in the same BB as the PHI.  This is not possible if
1713         // the BB is terminated by a catchswitch.
1714         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1715           return nullptr;
1716 
1717         PHINode *WidePhi =
1718           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1719                           UsePhi);
1720         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1721         IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1722         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1723         UsePhi->replaceAllUsesWith(Trunc);
1724         DeadInsts.emplace_back(UsePhi);
1725         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1726                           << *WidePhi << "\n");
1727       }
1728       return nullptr;
1729     }
1730   }
1731 
1732   // This narrow use can be widened by a sext if it's non-negative or its narrow
1733   // def was widended by a sext. Same for zext.
1734   auto canWidenBySExt = [&]() {
1735     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1736   };
1737   auto canWidenByZExt = [&]() {
1738     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1739   };
1740 
1741   // Our raison d'etre! Eliminate sign and zero extension.
1742   if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1743       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1744     Value *NewDef = DU.WideDef;
1745     if (DU.NarrowUse->getType() != WideType) {
1746       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1747       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1748       if (CastWidth < IVWidth) {
1749         // The cast isn't as wide as the IV, so insert a Trunc.
1750         IRBuilder<> Builder(DU.NarrowUse);
1751         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1752       }
1753       else {
1754         // A wider extend was hidden behind a narrower one. This may induce
1755         // another round of IV widening in which the intermediate IV becomes
1756         // dead. It should be very rare.
1757         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1758                           << " not wide enough to subsume " << *DU.NarrowUse
1759                           << "\n");
1760         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1761         NewDef = DU.NarrowUse;
1762       }
1763     }
1764     if (NewDef != DU.NarrowUse) {
1765       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1766                         << " replaced by " << *DU.WideDef << "\n");
1767       ++NumElimExt;
1768       DU.NarrowUse->replaceAllUsesWith(NewDef);
1769       DeadInsts.emplace_back(DU.NarrowUse);
1770     }
1771     // Now that the extend is gone, we want to expose it's uses for potential
1772     // further simplification. We don't need to directly inform SimplifyIVUsers
1773     // of the new users, because their parent IV will be processed later as a
1774     // new loop phi. If we preserved IVUsers analysis, we would also want to
1775     // push the uses of WideDef here.
1776 
1777     // No further widening is needed. The deceased [sz]ext had done it for us.
1778     return nullptr;
1779   }
1780 
1781   // Does this user itself evaluate to a recurrence after widening?
1782   WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1783   if (!WideAddRec.first)
1784     WideAddRec = getWideRecurrence(DU);
1785 
1786   assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1787   if (!WideAddRec.first) {
1788     // If use is a loop condition, try to promote the condition instead of
1789     // truncating the IV first.
1790     if (widenLoopCompare(DU))
1791       return nullptr;
1792 
1793     // We are here about to generate a truncate instruction that may hurt
1794     // performance because the scalar evolution expression computed earlier
1795     // in WideAddRec.first does not indicate a polynomial induction expression.
1796     // In that case, look at the operands of the use instruction to determine
1797     // if we can still widen the use instead of truncating its operand.
1798     if (widenWithVariantUse(DU))
1799       return nullptr;
1800 
1801     // This user does not evaluate to a recurrence after widening, so don't
1802     // follow it. Instead insert a Trunc to kill off the original use,
1803     // eventually isolating the original narrow IV so it can be removed.
1804     truncateIVUse(DU, DT, LI);
1805     return nullptr;
1806   }
1807   // Assume block terminators cannot evaluate to a recurrence. We can't to
1808   // insert a Trunc after a terminator if there happens to be a critical edge.
1809   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1810          "SCEV is not expected to evaluate a block terminator");
1811 
1812   // Reuse the IV increment that SCEVExpander created as long as it dominates
1813   // NarrowUse.
1814   Instruction *WideUse = nullptr;
1815   if (WideAddRec.first == WideIncExpr &&
1816       Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1817     WideUse = WideInc;
1818   else {
1819     WideUse = cloneIVUser(DU, WideAddRec.first);
1820     if (!WideUse)
1821       return nullptr;
1822   }
1823   // Evaluation of WideAddRec ensured that the narrow expression could be
1824   // extended outside the loop without overflow. This suggests that the wide use
1825   // evaluates to the same expression as the extended narrow use, but doesn't
1826   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1827   // where it fails, we simply throw away the newly created wide use.
1828   if (WideAddRec.first != SE->getSCEV(WideUse)) {
1829     LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1830                       << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1831                       << "\n");
1832     DeadInsts.emplace_back(WideUse);
1833     return nullptr;
1834   }
1835 
1836   // if we reached this point then we are going to replace
1837   // DU.NarrowUse with WideUse. Reattach DbgValue then.
1838   replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
1839 
1840   ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1841   // Returning WideUse pushes it on the worklist.
1842   return WideUse;
1843 }
1844 
1845 /// Add eligible users of NarrowDef to NarrowIVUsers.
1846 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1847   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1848   bool NonNegativeDef =
1849       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1850                            SE->getZero(NarrowSCEV->getType()));
1851   for (User *U : NarrowDef->users()) {
1852     Instruction *NarrowUser = cast<Instruction>(U);
1853 
1854     // Handle data flow merges and bizarre phi cycles.
1855     if (!Widened.insert(NarrowUser).second)
1856       continue;
1857 
1858     bool NonNegativeUse = false;
1859     if (!NonNegativeDef) {
1860       // We might have a control-dependent range information for this context.
1861       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1862         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1863     }
1864 
1865     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1866                                NonNegativeDef || NonNegativeUse);
1867   }
1868 }
1869 
1870 /// Process a single induction variable. First use the SCEVExpander to create a
1871 /// wide induction variable that evaluates to the same recurrence as the
1872 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1873 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1874 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1875 ///
1876 /// It would be simpler to delete uses as they are processed, but we must avoid
1877 /// invalidating SCEV expressions.
1878 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1879   // Is this phi an induction variable?
1880   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1881   if (!AddRec)
1882     return nullptr;
1883 
1884   // Widen the induction variable expression.
1885   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1886                                ? SE->getSignExtendExpr(AddRec, WideType)
1887                                : SE->getZeroExtendExpr(AddRec, WideType);
1888 
1889   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1890          "Expect the new IV expression to preserve its type");
1891 
1892   // Can the IV be extended outside the loop without overflow?
1893   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1894   if (!AddRec || AddRec->getLoop() != L)
1895     return nullptr;
1896 
1897   // An AddRec must have loop-invariant operands. Since this AddRec is
1898   // materialized by a loop header phi, the expression cannot have any post-loop
1899   // operands, so they must dominate the loop header.
1900   assert(
1901       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1902       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1903       "Loop header phi recurrence inputs do not dominate the loop");
1904 
1905   // Iterate over IV uses (including transitive ones) looking for IV increments
1906   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1907   // the increment calculate control-dependent range information basing on
1908   // dominating conditions inside of the loop (e.g. a range check inside of the
1909   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1910   //
1911   // Control-dependent range information is later used to prove that a narrow
1912   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1913   // this on demand because when pushNarrowIVUsers needs this information some
1914   // of the dominating conditions might be already widened.
1915   if (UsePostIncrementRanges)
1916     calculatePostIncRanges(OrigPhi);
1917 
1918   // The rewriter provides a value for the desired IV expression. This may
1919   // either find an existing phi or materialize a new one. Either way, we
1920   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1921   // of the phi-SCC dominates the loop entry.
1922   Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
1923   Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
1924   // If the wide phi is not a phi node, for example a cast node, like bitcast,
1925   // inttoptr, ptrtoint, just skip for now.
1926   if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
1927     // if the cast node is an inserted instruction without any user, we should
1928     // remove it to make sure the pass don't touch the function as we can not
1929     // wide the phi.
1930     if (ExpandInst->hasNUses(0) &&
1931         Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
1932       DeadInsts.emplace_back(ExpandInst);
1933     return nullptr;
1934   }
1935 
1936   // Remembering the WideIV increment generated by SCEVExpander allows
1937   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1938   // employ a general reuse mechanism because the call above is the only call to
1939   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1940   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1941     WideInc =
1942       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1943     WideIncExpr = SE->getSCEV(WideInc);
1944     // Propagate the debug location associated with the original loop increment
1945     // to the new (widened) increment.
1946     auto *OrigInc =
1947       cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1948     WideInc->setDebugLoc(OrigInc->getDebugLoc());
1949   }
1950 
1951   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1952   ++NumWidened;
1953 
1954   // Traverse the def-use chain using a worklist starting at the original IV.
1955   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1956 
1957   Widened.insert(OrigPhi);
1958   pushNarrowIVUsers(OrigPhi, WidePhi);
1959 
1960   while (!NarrowIVUsers.empty()) {
1961     WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1962 
1963     // Process a def-use edge. This may replace the use, so don't hold a
1964     // use_iterator across it.
1965     Instruction *WideUse = widenIVUse(DU, Rewriter);
1966 
1967     // Follow all def-use edges from the previous narrow use.
1968     if (WideUse)
1969       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1970 
1971     // widenIVUse may have removed the def-use edge.
1972     if (DU.NarrowDef->use_empty())
1973       DeadInsts.emplace_back(DU.NarrowDef);
1974   }
1975 
1976   // Attach any debug information to the new PHI.
1977   replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
1978 
1979   return WidePhi;
1980 }
1981 
1982 /// Calculates control-dependent range for the given def at the given context
1983 /// by looking at dominating conditions inside of the loop
1984 void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1985                                     Instruction *NarrowUser) {
1986   using namespace llvm::PatternMatch;
1987 
1988   Value *NarrowDefLHS;
1989   const APInt *NarrowDefRHS;
1990   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1991                                  m_APInt(NarrowDefRHS))) ||
1992       !NarrowDefRHS->isNonNegative())
1993     return;
1994 
1995   auto UpdateRangeFromCondition = [&] (Value *Condition,
1996                                        bool TrueDest) {
1997     CmpInst::Predicate Pred;
1998     Value *CmpRHS;
1999     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
2000                                  m_Value(CmpRHS))))
2001       return;
2002 
2003     CmpInst::Predicate P =
2004             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
2005 
2006     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2007     auto CmpConstrainedLHSRange =
2008             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
2009     auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2010         *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap);
2011 
2012     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2013   };
2014 
2015   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2016     if (!HasGuards)
2017       return;
2018 
2019     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2020                                      Ctx->getParent()->rend())) {
2021       Value *C = nullptr;
2022       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
2023         UpdateRangeFromCondition(C, /*TrueDest=*/true);
2024     }
2025   };
2026 
2027   UpdateRangeFromGuards(NarrowUser);
2028 
2029   BasicBlock *NarrowUserBB = NarrowUser->getParent();
2030   // If NarrowUserBB is statically unreachable asking dominator queries may
2031   // yield surprising results. (e.g. the block may not have a dom tree node)
2032   if (!DT->isReachableFromEntry(NarrowUserBB))
2033     return;
2034 
2035   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2036        L->contains(DTB->getBlock());
2037        DTB = DTB->getIDom()) {
2038     auto *BB = DTB->getBlock();
2039     auto *TI = BB->getTerminator();
2040     UpdateRangeFromGuards(TI);
2041 
2042     auto *BI = dyn_cast<BranchInst>(TI);
2043     if (!BI || !BI->isConditional())
2044       continue;
2045 
2046     auto *TrueSuccessor = BI->getSuccessor(0);
2047     auto *FalseSuccessor = BI->getSuccessor(1);
2048 
2049     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
2050       return BBE.isSingleEdge() &&
2051              DT->dominates(BBE, NarrowUser->getParent());
2052     };
2053 
2054     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
2055       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2056 
2057     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
2058       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2059   }
2060 }
2061 
2062 /// Calculates PostIncRangeInfos map for the given IV
2063 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2064   SmallPtrSet<Instruction *, 16> Visited;
2065   SmallVector<Instruction *, 6> Worklist;
2066   Worklist.push_back(OrigPhi);
2067   Visited.insert(OrigPhi);
2068 
2069   while (!Worklist.empty()) {
2070     Instruction *NarrowDef = Worklist.pop_back_val();
2071 
2072     for (Use &U : NarrowDef->uses()) {
2073       auto *NarrowUser = cast<Instruction>(U.getUser());
2074 
2075       // Don't go looking outside the current loop.
2076       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2077       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2078         continue;
2079 
2080       if (!Visited.insert(NarrowUser).second)
2081         continue;
2082 
2083       Worklist.push_back(NarrowUser);
2084 
2085       calculatePostIncRange(NarrowDef, NarrowUser);
2086     }
2087   }
2088 }
2089 
2090 PHINode *llvm::createWideIV(const WideIVInfo &WI,
2091     LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2092     DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
2093     unsigned &NumElimExt, unsigned &NumWidened,
2094     bool HasGuards, bool UsePostIncrementRanges) {
2095   WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2096   PHINode *WidePHI = Widener.createWideIV(Rewriter);
2097   NumElimExt = Widener.getNumElimExt();
2098   NumWidened = Widener.getNumWidened();
2099   return WidePHI;
2100 }
2101