xref: /llvm-project/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp (revision 2cbba5633753552a984572c8b9a5997e5c96496d)
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
13 //
14 // If the trip count of a loop is computable, this pass also makes the following
15 // changes:
16 //   1. The exit condition for the loop is canonicalized to compare the
17 //      induction value against the exit value.  This turns loops like:
18 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19 //   2. Any use outside of the loop of an expression derived from the indvar
20 //      is changed to compute the derived value outside of the loop, eliminating
21 //      the dependence on the exit value of the induction variable.  If the only
22 //      purpose of the loop is to compute the exit value of some derived
23 //      expression, this transformation will make the loop dead.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/iterator_range.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ScalarEvolutionExpander.h"
43 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
44 #include "llvm/Analysis/TargetLibraryInfo.h"
45 #include "llvm/Analysis/TargetTransformInfo.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/IR/BasicBlock.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/ConstantRange.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InstrTypes.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/PassManager.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/IR/ValueHandle.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Scalar/LoopPassManager.h"
80 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
81 #include "llvm/Transforms/Utils/LoopUtils.h"
82 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
83 #include <cassert>
84 #include <cstdint>
85 #include <utility>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "indvars"
90 
91 STATISTIC(NumWidened     , "Number of indvars widened");
92 STATISTIC(NumReplaced    , "Number of exit values replaced");
93 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
94 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
95 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
96 
97 // Trip count verification can be enabled by default under NDEBUG if we
98 // implement a strong expression equivalence checker in SCEV. Until then, we
99 // use the verify-indvars flag, which may assert in some cases.
100 static cl::opt<bool> VerifyIndvars(
101   "verify-indvars", cl::Hidden,
102   cl::desc("Verify the ScalarEvolution result after running indvars"));
103 
104 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
105 
106 static cl::opt<ReplaceExitVal> ReplaceExitValue(
107     "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
108     cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
109     cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
110                clEnumValN(OnlyCheapRepl, "cheap",
111                           "only replace exit value when the cost is cheap"),
112                clEnumValN(AlwaysRepl, "always",
113                           "always replace exit value whenever possible")));
114 
115 static cl::opt<bool> UsePostIncrementRanges(
116   "indvars-post-increment-ranges", cl::Hidden,
117   cl::desc("Use post increment control-dependent ranges in IndVarSimplify"),
118   cl::init(true));
119 
120 static cl::opt<bool>
121 DisableLFTR("disable-lftr", cl::Hidden, cl::init(false),
122             cl::desc("Disable Linear Function Test Replace optimization"));
123 
124 namespace {
125 
126 struct RewritePhi;
127 
128 class IndVarSimplify {
129   LoopInfo *LI;
130   ScalarEvolution *SE;
131   DominatorTree *DT;
132   const DataLayout &DL;
133   TargetLibraryInfo *TLI;
134   const TargetTransformInfo *TTI;
135 
136   SmallVector<WeakTrackingVH, 16> DeadInsts;
137   bool Changed = false;
138 
139   bool isValidRewrite(Value *FromVal, Value *ToVal);
140 
141   void handleFloatingPointIV(Loop *L, PHINode *PH);
142   void rewriteNonIntegerIVs(Loop *L);
143 
144   void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
145 
146   bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
147   void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
148   void rewriteFirstIterationLoopExitValues(Loop *L);
149 
150   Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
151                                    PHINode *IndVar, SCEVExpander &Rewriter);
152 
153   void sinkUnusedInvariants(Loop *L);
154 
155 public:
156   IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
157                  const DataLayout &DL, TargetLibraryInfo *TLI,
158                  TargetTransformInfo *TTI)
159       : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
160 
161   bool run(Loop *L);
162 };
163 
164 } // end anonymous namespace
165 
166 /// Return true if the SCEV expansion generated by the rewriter can replace the
167 /// original value. SCEV guarantees that it produces the same value, but the way
168 /// it is produced may be illegal IR.  Ideally, this function will only be
169 /// called for verification.
170 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
171   // If an SCEV expression subsumed multiple pointers, its expansion could
172   // reassociate the GEP changing the base pointer. This is illegal because the
173   // final address produced by a GEP chain must be inbounds relative to its
174   // underlying object. Otherwise basic alias analysis, among other things,
175   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
176   // producing an expression involving multiple pointers. Until then, we must
177   // bail out here.
178   //
179   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
180   // because it understands lcssa phis while SCEV does not.
181   Value *FromPtr = FromVal;
182   Value *ToPtr = ToVal;
183   if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
184     FromPtr = GEP->getPointerOperand();
185   }
186   if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
187     ToPtr = GEP->getPointerOperand();
188   }
189   if (FromPtr != FromVal || ToPtr != ToVal) {
190     // Quickly check the common case
191     if (FromPtr == ToPtr)
192       return true;
193 
194     // SCEV may have rewritten an expression that produces the GEP's pointer
195     // operand. That's ok as long as the pointer operand has the same base
196     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
197     // base of a recurrence. This handles the case in which SCEV expansion
198     // converts a pointer type recurrence into a nonrecurrent pointer base
199     // indexed by an integer recurrence.
200 
201     // If the GEP base pointer is a vector of pointers, abort.
202     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
203       return false;
204 
205     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
206     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
207     if (FromBase == ToBase)
208       return true;
209 
210     LLVM_DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " << *FromBase
211                       << " != " << *ToBase << "\n");
212 
213     return false;
214   }
215   return true;
216 }
217 
218 /// Determine the insertion point for this user. By default, insert immediately
219 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
220 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
221 /// common dominator for the incoming blocks.
222 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
223                                           DominatorTree *DT, LoopInfo *LI) {
224   PHINode *PHI = dyn_cast<PHINode>(User);
225   if (!PHI)
226     return User;
227 
228   Instruction *InsertPt = nullptr;
229   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
230     if (PHI->getIncomingValue(i) != Def)
231       continue;
232 
233     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
234     if (!InsertPt) {
235       InsertPt = InsertBB->getTerminator();
236       continue;
237     }
238     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
239     InsertPt = InsertBB->getTerminator();
240   }
241   assert(InsertPt && "Missing phi operand");
242 
243   auto *DefI = dyn_cast<Instruction>(Def);
244   if (!DefI)
245     return InsertPt;
246 
247   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
248 
249   auto *L = LI->getLoopFor(DefI->getParent());
250   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
251 
252   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
253     if (LI->getLoopFor(DTN->getBlock()) == L)
254       return DTN->getBlock()->getTerminator();
255 
256   llvm_unreachable("DefI dominates InsertPt!");
257 }
258 
259 //===----------------------------------------------------------------------===//
260 // rewriteNonIntegerIVs and helpers. Prefer integer IVs.
261 //===----------------------------------------------------------------------===//
262 
263 /// Convert APF to an integer, if possible.
264 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
265   bool isExact = false;
266   // See if we can convert this to an int64_t
267   uint64_t UIntVal;
268   if (APF.convertToInteger(makeMutableArrayRef(UIntVal), 64, true,
269                            APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
270       !isExact)
271     return false;
272   IntVal = UIntVal;
273   return true;
274 }
275 
276 /// If the loop has floating induction variable then insert corresponding
277 /// integer induction variable if possible.
278 /// For example,
279 /// for(double i = 0; i < 10000; ++i)
280 ///   bar(i)
281 /// is converted into
282 /// for(int i = 0; i < 10000; ++i)
283 ///   bar((double)i);
284 void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
285   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
286   unsigned BackEdge     = IncomingEdge^1;
287 
288   // Check incoming value.
289   auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
290 
291   int64_t InitValue;
292   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
293     return;
294 
295   // Check IV increment. Reject this PN if increment operation is not
296   // an add or increment value can not be represented by an integer.
297   auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
298   if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
299 
300   // If this is not an add of the PHI with a constantfp, or if the constant fp
301   // is not an integer, bail out.
302   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
303   int64_t IncValue;
304   if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
305       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
306     return;
307 
308   // Check Incr uses. One user is PN and the other user is an exit condition
309   // used by the conditional terminator.
310   Value::user_iterator IncrUse = Incr->user_begin();
311   Instruction *U1 = cast<Instruction>(*IncrUse++);
312   if (IncrUse == Incr->user_end()) return;
313   Instruction *U2 = cast<Instruction>(*IncrUse++);
314   if (IncrUse != Incr->user_end()) return;
315 
316   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
317   // only used by a branch, we can't transform it.
318   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
319   if (!Compare)
320     Compare = dyn_cast<FCmpInst>(U2);
321   if (!Compare || !Compare->hasOneUse() ||
322       !isa<BranchInst>(Compare->user_back()))
323     return;
324 
325   BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
326 
327   // We need to verify that the branch actually controls the iteration count
328   // of the loop.  If not, the new IV can overflow and no one will notice.
329   // The branch block must be in the loop and one of the successors must be out
330   // of the loop.
331   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
332   if (!L->contains(TheBr->getParent()) ||
333       (L->contains(TheBr->getSuccessor(0)) &&
334        L->contains(TheBr->getSuccessor(1))))
335     return;
336 
337   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
338   // transform it.
339   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
340   int64_t ExitValue;
341   if (ExitValueVal == nullptr ||
342       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
343     return;
344 
345   // Find new predicate for integer comparison.
346   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
347   switch (Compare->getPredicate()) {
348   default: return;  // Unknown comparison.
349   case CmpInst::FCMP_OEQ:
350   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
351   case CmpInst::FCMP_ONE:
352   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
353   case CmpInst::FCMP_OGT:
354   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
355   case CmpInst::FCMP_OGE:
356   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
357   case CmpInst::FCMP_OLT:
358   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
359   case CmpInst::FCMP_OLE:
360   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
361   }
362 
363   // We convert the floating point induction variable to a signed i32 value if
364   // we can.  This is only safe if the comparison will not overflow in a way
365   // that won't be trapped by the integer equivalent operations.  Check for this
366   // now.
367   // TODO: We could use i64 if it is native and the range requires it.
368 
369   // The start/stride/exit values must all fit in signed i32.
370   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
371     return;
372 
373   // If not actually striding (add x, 0.0), avoid touching the code.
374   if (IncValue == 0)
375     return;
376 
377   // Positive and negative strides have different safety conditions.
378   if (IncValue > 0) {
379     // If we have a positive stride, we require the init to be less than the
380     // exit value.
381     if (InitValue >= ExitValue)
382       return;
383 
384     uint32_t Range = uint32_t(ExitValue-InitValue);
385     // Check for infinite loop, either:
386     // while (i <= Exit) or until (i > Exit)
387     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
388       if (++Range == 0) return;  // Range overflows.
389     }
390 
391     unsigned Leftover = Range % uint32_t(IncValue);
392 
393     // If this is an equality comparison, we require that the strided value
394     // exactly land on the exit value, otherwise the IV condition will wrap
395     // around and do things the fp IV wouldn't.
396     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
397         Leftover != 0)
398       return;
399 
400     // If the stride would wrap around the i32 before exiting, we can't
401     // transform the IV.
402     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
403       return;
404   } else {
405     // If we have a negative stride, we require the init to be greater than the
406     // exit value.
407     if (InitValue <= ExitValue)
408       return;
409 
410     uint32_t Range = uint32_t(InitValue-ExitValue);
411     // Check for infinite loop, either:
412     // while (i >= Exit) or until (i < Exit)
413     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
414       if (++Range == 0) return;  // Range overflows.
415     }
416 
417     unsigned Leftover = Range % uint32_t(-IncValue);
418 
419     // If this is an equality comparison, we require that the strided value
420     // exactly land on the exit value, otherwise the IV condition will wrap
421     // around and do things the fp IV wouldn't.
422     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
423         Leftover != 0)
424       return;
425 
426     // If the stride would wrap around the i32 before exiting, we can't
427     // transform the IV.
428     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
429       return;
430   }
431 
432   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
433 
434   // Insert new integer induction variable.
435   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
436   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
437                       PN->getIncomingBlock(IncomingEdge));
438 
439   Value *NewAdd =
440     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
441                               Incr->getName()+".int", Incr);
442   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
443 
444   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
445                                       ConstantInt::get(Int32Ty, ExitValue),
446                                       Compare->getName());
447 
448   // In the following deletions, PN may become dead and may be deleted.
449   // Use a WeakTrackingVH to observe whether this happens.
450   WeakTrackingVH WeakPH = PN;
451 
452   // Delete the old floating point exit comparison.  The branch starts using the
453   // new comparison.
454   NewCompare->takeName(Compare);
455   Compare->replaceAllUsesWith(NewCompare);
456   RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
457 
458   // Delete the old floating point increment.
459   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
460   RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
461 
462   // If the FP induction variable still has uses, this is because something else
463   // in the loop uses its value.  In order to canonicalize the induction
464   // variable, we chose to eliminate the IV and rewrite it in terms of an
465   // int->fp cast.
466   //
467   // We give preference to sitofp over uitofp because it is faster on most
468   // platforms.
469   if (WeakPH) {
470     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
471                                  &*PN->getParent()->getFirstInsertionPt());
472     PN->replaceAllUsesWith(Conv);
473     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
474   }
475   Changed = true;
476 }
477 
478 void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
479   // First step.  Check to see if there are any floating-point recurrences.
480   // If there are, change them into integer recurrences, permitting analysis by
481   // the SCEV routines.
482   BasicBlock *Header = L->getHeader();
483 
484   SmallVector<WeakTrackingVH, 8> PHIs;
485   for (PHINode &PN : Header->phis())
486     PHIs.push_back(&PN);
487 
488   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
489     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
490       handleFloatingPointIV(L, PN);
491 
492   // If the loop previously had floating-point IV, ScalarEvolution
493   // may not have been able to compute a trip count. Now that we've done some
494   // re-writing, the trip count may be computable.
495   if (Changed)
496     SE->forgetLoop(L);
497 }
498 
499 namespace {
500 
501 // Collect information about PHI nodes which can be transformed in
502 // rewriteLoopExitValues.
503 struct RewritePhi {
504   PHINode *PN;
505 
506   // Ith incoming value.
507   unsigned Ith;
508 
509   // Exit value after expansion.
510   Value *Val;
511 
512   // High Cost when expansion.
513   bool HighCost;
514 
515   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
516       : PN(P), Ith(I), Val(V), HighCost(H) {}
517 };
518 
519 } // end anonymous namespace
520 
521 //===----------------------------------------------------------------------===//
522 // rewriteLoopExitValues - Optimize IV users outside the loop.
523 // As a side effect, reduces the amount of IV processing within the loop.
524 //===----------------------------------------------------------------------===//
525 
526 /// Check to see if this loop has a computable loop-invariant execution count.
527 /// If so, this means that we can compute the final value of any expressions
528 /// that are recurrent in the loop, and substitute the exit values from the loop
529 /// into any instructions outside of the loop that use the final values of the
530 /// current expressions.
531 ///
532 /// This is mostly redundant with the regular IndVarSimplify activities that
533 /// happen later, except that it's more powerful in some cases, because it's
534 /// able to brute-force evaluate arbitrary instructions as long as they have
535 /// constant operands at the beginning of the loop.
536 void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
537   // Check a pre-condition.
538   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
539          "Indvars did not preserve LCSSA!");
540 
541   SmallVector<BasicBlock*, 8> ExitBlocks;
542   L->getUniqueExitBlocks(ExitBlocks);
543 
544   SmallVector<RewritePhi, 8> RewritePhiSet;
545   // Find all values that are computed inside the loop, but used outside of it.
546   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
547   // the exit blocks of the loop to find them.
548   for (BasicBlock *ExitBB : ExitBlocks) {
549     // If there are no PHI nodes in this exit block, then no values defined
550     // inside the loop are used on this path, skip it.
551     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
552     if (!PN) continue;
553 
554     unsigned NumPreds = PN->getNumIncomingValues();
555 
556     // Iterate over all of the PHI nodes.
557     BasicBlock::iterator BBI = ExitBB->begin();
558     while ((PN = dyn_cast<PHINode>(BBI++))) {
559       if (PN->use_empty())
560         continue; // dead use, don't replace it
561 
562       if (!SE->isSCEVable(PN->getType()))
563         continue;
564 
565       // It's necessary to tell ScalarEvolution about this explicitly so that
566       // it can walk the def-use list and forget all SCEVs, as it may not be
567       // watching the PHI itself. Once the new exit value is in place, there
568       // may not be a def-use connection between the loop and every instruction
569       // which got a SCEVAddRecExpr for that loop.
570       SE->forgetValue(PN);
571 
572       // Iterate over all of the values in all the PHI nodes.
573       for (unsigned i = 0; i != NumPreds; ++i) {
574         // If the value being merged in is not integer or is not defined
575         // in the loop, skip it.
576         Value *InVal = PN->getIncomingValue(i);
577         if (!isa<Instruction>(InVal))
578           continue;
579 
580         // If this pred is for a subloop, not L itself, skip it.
581         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
582           continue; // The Block is in a subloop, skip it.
583 
584         // Check that InVal is defined in the loop.
585         Instruction *Inst = cast<Instruction>(InVal);
586         if (!L->contains(Inst))
587           continue;
588 
589         // Okay, this instruction has a user outside of the current loop
590         // and varies predictably *inside* the loop.  Evaluate the value it
591         // contains when the loop exits, if possible.
592         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
593         if (!SE->isLoopInvariant(ExitValue, L) ||
594             !isSafeToExpand(ExitValue, *SE))
595           continue;
596 
597         // Computing the value outside of the loop brings no benefit if :
598         //  - it is definitely used inside the loop in a way which can not be
599         //    optimized away.
600         //  - no use outside of the loop can take advantage of hoisting the
601         //    computation out of the loop
602         if (ExitValue->getSCEVType()>=scMulExpr) {
603           unsigned NumHardInternalUses = 0;
604           unsigned NumSoftExternalUses = 0;
605           unsigned NumUses = 0;
606           for (auto IB = Inst->user_begin(), IE = Inst->user_end();
607                IB != IE && NumUses <= 6; ++IB) {
608             Instruction *UseInstr = cast<Instruction>(*IB);
609             unsigned Opc = UseInstr->getOpcode();
610             NumUses++;
611             if (L->contains(UseInstr)) {
612               if (Opc == Instruction::Call)
613                 NumHardInternalUses++;
614             } else {
615               if (Opc == Instruction::PHI) {
616                 // Do not count the Phi as a use. LCSSA may have inserted
617                 // plenty of trivial ones.
618                 NumUses--;
619                 for (auto PB = UseInstr->user_begin(),
620                           PE = UseInstr->user_end();
621                      PB != PE && NumUses <= 6; ++PB, ++NumUses) {
622                   unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
623                   if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
624                     NumSoftExternalUses++;
625                 }
626                 continue;
627               }
628               if (Opc != Instruction::Call && Opc != Instruction::Ret)
629                 NumSoftExternalUses++;
630             }
631           }
632           if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
633             continue;
634         }
635 
636         bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
637         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
638 
639         LLVM_DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
640                           << '\n'
641                           << "  LoopVal = " << *Inst << "\n");
642 
643         if (!isValidRewrite(Inst, ExitVal)) {
644           DeadInsts.push_back(ExitVal);
645           continue;
646         }
647 
648         // Collect all the candidate PHINodes to be rewritten.
649         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
650       }
651     }
652   }
653 
654   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
655 
656   // Transformation.
657   for (const RewritePhi &Phi : RewritePhiSet) {
658     PHINode *PN = Phi.PN;
659     Value *ExitVal = Phi.Val;
660 
661     // Only do the rewrite when the ExitValue can be expanded cheaply.
662     // If LoopCanBeDel is true, rewrite exit value aggressively.
663     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
664       DeadInsts.push_back(ExitVal);
665       continue;
666     }
667 
668     Changed = true;
669     ++NumReplaced;
670     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
671     PN->setIncomingValue(Phi.Ith, ExitVal);
672 
673     // If this instruction is dead now, delete it. Don't do it now to avoid
674     // invalidating iterators.
675     if (isInstructionTriviallyDead(Inst, TLI))
676       DeadInsts.push_back(Inst);
677 
678     // Replace PN with ExitVal if that is legal and does not break LCSSA.
679     if (PN->getNumIncomingValues() == 1 &&
680         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
681       PN->replaceAllUsesWith(ExitVal);
682       PN->eraseFromParent();
683     }
684   }
685 
686   // The insertion point instruction may have been deleted; clear it out
687   // so that the rewriter doesn't trip over it later.
688   Rewriter.clearInsertPoint();
689 }
690 
691 //===---------------------------------------------------------------------===//
692 // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
693 // they will exit at the first iteration.
694 //===---------------------------------------------------------------------===//
695 
696 /// Check to see if this loop has loop invariant conditions which lead to loop
697 /// exits. If so, we know that if the exit path is taken, it is at the first
698 /// loop iteration. This lets us predict exit values of PHI nodes that live in
699 /// loop header.
700 void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
701   // Verify the input to the pass is already in LCSSA form.
702   assert(L->isLCSSAForm(*DT));
703 
704   SmallVector<BasicBlock *, 8> ExitBlocks;
705   L->getUniqueExitBlocks(ExitBlocks);
706   auto *LoopHeader = L->getHeader();
707   assert(LoopHeader && "Invalid loop");
708 
709   for (auto *ExitBB : ExitBlocks) {
710     // If there are no more PHI nodes in this exit block, then no more
711     // values defined inside the loop are used on this path.
712     for (PHINode &PN : ExitBB->phis()) {
713       for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
714            IncomingValIdx != E; ++IncomingValIdx) {
715         auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
716 
717         // We currently only support loop exits from loop header. If the
718         // incoming block is not loop header, we need to recursively check
719         // all conditions starting from loop header are loop invariants.
720         // Additional support might be added in the future.
721         if (IncomingBB != LoopHeader)
722           continue;
723 
724         // Get condition that leads to the exit path.
725         auto *TermInst = IncomingBB->getTerminator();
726 
727         Value *Cond = nullptr;
728         if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
729           // Must be a conditional branch, otherwise the block
730           // should not be in the loop.
731           Cond = BI->getCondition();
732         } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
733           Cond = SI->getCondition();
734         else
735           continue;
736 
737         if (!L->isLoopInvariant(Cond))
738           continue;
739 
740         auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
741 
742         // Only deal with PHIs.
743         if (!ExitVal)
744           continue;
745 
746         // If ExitVal is a PHI on the loop header, then we know its
747         // value along this exit because the exit can only be taken
748         // on the first iteration.
749         auto *LoopPreheader = L->getLoopPreheader();
750         assert(LoopPreheader && "Invalid loop");
751         int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
752         if (PreheaderIdx != -1) {
753           assert(ExitVal->getParent() == LoopHeader &&
754                  "ExitVal must be in loop header");
755           PN.setIncomingValue(IncomingValIdx,
756                               ExitVal->getIncomingValue(PreheaderIdx));
757         }
758       }
759     }
760   }
761 }
762 
763 /// Check whether it is possible to delete the loop after rewriting exit
764 /// value. If it is possible, ignore ReplaceExitValue and do rewriting
765 /// aggressively.
766 bool IndVarSimplify::canLoopBeDeleted(
767     Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
768   BasicBlock *Preheader = L->getLoopPreheader();
769   // If there is no preheader, the loop will not be deleted.
770   if (!Preheader)
771     return false;
772 
773   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
774   // We obviate multiple ExitingBlocks case for simplicity.
775   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
776   // after exit value rewriting, we can enhance the logic here.
777   SmallVector<BasicBlock *, 4> ExitingBlocks;
778   L->getExitingBlocks(ExitingBlocks);
779   SmallVector<BasicBlock *, 8> ExitBlocks;
780   L->getUniqueExitBlocks(ExitBlocks);
781   if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
782     return false;
783 
784   BasicBlock *ExitBlock = ExitBlocks[0];
785   BasicBlock::iterator BI = ExitBlock->begin();
786   while (PHINode *P = dyn_cast<PHINode>(BI)) {
787     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
788 
789     // If the Incoming value of P is found in RewritePhiSet, we know it
790     // could be rewritten to use a loop invariant value in transformation
791     // phase later. Skip it in the loop invariant check below.
792     bool found = false;
793     for (const RewritePhi &Phi : RewritePhiSet) {
794       unsigned i = Phi.Ith;
795       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
796         found = true;
797         break;
798       }
799     }
800 
801     Instruction *I;
802     if (!found && (I = dyn_cast<Instruction>(Incoming)))
803       if (!L->hasLoopInvariantOperands(I))
804         return false;
805 
806     ++BI;
807   }
808 
809   for (auto *BB : L->blocks())
810     if (llvm::any_of(*BB, [](Instruction &I) {
811           return I.mayHaveSideEffects();
812         }))
813       return false;
814 
815   return true;
816 }
817 
818 //===----------------------------------------------------------------------===//
819 //  IV Widening - Extend the width of an IV to cover its widest uses.
820 //===----------------------------------------------------------------------===//
821 
822 namespace {
823 
824 // Collect information about induction variables that are used by sign/zero
825 // extend operations. This information is recorded by CollectExtend and provides
826 // the input to WidenIV.
827 struct WideIVInfo {
828   PHINode *NarrowIV = nullptr;
829 
830   // Widest integer type created [sz]ext
831   Type *WidestNativeType = nullptr;
832 
833   // Was a sext user seen before a zext?
834   bool IsSigned = false;
835 };
836 
837 } // end anonymous namespace
838 
839 /// Update information about the induction variable that is extended by this
840 /// sign or zero extend operation. This is used to determine the final width of
841 /// the IV before actually widening it.
842 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
843                         const TargetTransformInfo *TTI) {
844   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
845   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
846     return;
847 
848   Type *Ty = Cast->getType();
849   uint64_t Width = SE->getTypeSizeInBits(Ty);
850   if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
851     return;
852 
853   // Check that `Cast` actually extends the induction variable (we rely on this
854   // later).  This takes care of cases where `Cast` is extending a truncation of
855   // the narrow induction variable, and thus can end up being narrower than the
856   // "narrow" induction variable.
857   uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
858   if (NarrowIVWidth >= Width)
859     return;
860 
861   // Cast is either an sext or zext up to this point.
862   // We should not widen an indvar if arithmetics on the wider indvar are more
863   // expensive than those on the narrower indvar. We check only the cost of ADD
864   // because at least an ADD is required to increment the induction variable. We
865   // could compute more comprehensively the cost of all instructions on the
866   // induction variable when necessary.
867   if (TTI &&
868       TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
869           TTI->getArithmeticInstrCost(Instruction::Add,
870                                       Cast->getOperand(0)->getType())) {
871     return;
872   }
873 
874   if (!WI.WidestNativeType) {
875     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
876     WI.IsSigned = IsSigned;
877     return;
878   }
879 
880   // We extend the IV to satisfy the sign of its first user, arbitrarily.
881   if (WI.IsSigned != IsSigned)
882     return;
883 
884   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
885     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
886 }
887 
888 namespace {
889 
890 /// Record a link in the Narrow IV def-use chain along with the WideIV that
891 /// computes the same value as the Narrow IV def.  This avoids caching Use*
892 /// pointers.
893 struct NarrowIVDefUse {
894   Instruction *NarrowDef = nullptr;
895   Instruction *NarrowUse = nullptr;
896   Instruction *WideDef = nullptr;
897 
898   // True if the narrow def is never negative.  Tracking this information lets
899   // us use a sign extension instead of a zero extension or vice versa, when
900   // profitable and legal.
901   bool NeverNegative = false;
902 
903   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
904                  bool NeverNegative)
905       : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
906         NeverNegative(NeverNegative) {}
907 };
908 
909 /// The goal of this transform is to remove sign and zero extends without
910 /// creating any new induction variables. To do this, it creates a new phi of
911 /// the wider type and redirects all users, either removing extends or inserting
912 /// truncs whenever we stop propagating the type.
913 class WidenIV {
914   // Parameters
915   PHINode *OrigPhi;
916   Type *WideType;
917 
918   // Context
919   LoopInfo        *LI;
920   Loop            *L;
921   ScalarEvolution *SE;
922   DominatorTree   *DT;
923 
924   // Does the module have any calls to the llvm.experimental.guard intrinsic
925   // at all? If not we can avoid scanning instructions looking for guards.
926   bool HasGuards;
927 
928   // Result
929   PHINode *WidePhi = nullptr;
930   Instruction *WideInc = nullptr;
931   const SCEV *WideIncExpr = nullptr;
932   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
933 
934   SmallPtrSet<Instruction *,16> Widened;
935   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
936 
937   enum ExtendKind { ZeroExtended, SignExtended, Unknown };
938 
939   // A map tracking the kind of extension used to widen each narrow IV
940   // and narrow IV user.
941   // Key: pointer to a narrow IV or IV user.
942   // Value: the kind of extension used to widen this Instruction.
943   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
944 
945   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
946 
947   // A map with control-dependent ranges for post increment IV uses. The key is
948   // a pair of IV def and a use of this def denoting the context. The value is
949   // a ConstantRange representing possible values of the def at the given
950   // context.
951   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
952 
953   Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
954                                               Instruction *UseI) {
955     DefUserPair Key(Def, UseI);
956     auto It = PostIncRangeInfos.find(Key);
957     return It == PostIncRangeInfos.end()
958                ? Optional<ConstantRange>(None)
959                : Optional<ConstantRange>(It->second);
960   }
961 
962   void calculatePostIncRanges(PHINode *OrigPhi);
963   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
964 
965   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
966     DefUserPair Key(Def, UseI);
967     auto It = PostIncRangeInfos.find(Key);
968     if (It == PostIncRangeInfos.end())
969       PostIncRangeInfos.insert({Key, R});
970     else
971       It->second = R.intersectWith(It->second);
972   }
973 
974 public:
975   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
976           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
977           bool HasGuards)
978       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
979         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
980         HasGuards(HasGuards), DeadInsts(DI) {
981     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
982     ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
983   }
984 
985   PHINode *createWideIV(SCEVExpander &Rewriter);
986 
987 protected:
988   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
989                           Instruction *Use);
990 
991   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
992   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
993                                      const SCEVAddRecExpr *WideAR);
994   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
995 
996   ExtendKind getExtendKind(Instruction *I);
997 
998   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
999 
1000   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1001 
1002   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1003 
1004   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1005                               unsigned OpCode) const;
1006 
1007   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1008 
1009   bool widenLoopCompare(NarrowIVDefUse DU);
1010 
1011   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1012 };
1013 
1014 } // end anonymous namespace
1015 
1016 /// Perform a quick domtree based check for loop invariance assuming that V is
1017 /// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
1018 /// purpose.
1019 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
1020   Instruction *Inst = dyn_cast<Instruction>(V);
1021   if (!Inst)
1022     return true;
1023 
1024   return DT->properlyDominates(Inst->getParent(), L->getHeader());
1025 }
1026 
1027 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1028                                  bool IsSigned, Instruction *Use) {
1029   // Set the debug location and conservative insertion point.
1030   IRBuilder<> Builder(Use);
1031   // Hoist the insertion point into loop preheaders as far as possible.
1032   for (const Loop *L = LI->getLoopFor(Use->getParent());
1033        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
1034        L = L->getParentLoop())
1035     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1036 
1037   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1038                     Builder.CreateZExt(NarrowOper, WideType);
1039 }
1040 
1041 /// Instantiate a wide operation to replace a narrow operation. This only needs
1042 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1043 /// 0 for any operation we decide not to clone.
1044 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1045                                   const SCEVAddRecExpr *WideAR) {
1046   unsigned Opcode = DU.NarrowUse->getOpcode();
1047   switch (Opcode) {
1048   default:
1049     return nullptr;
1050   case Instruction::Add:
1051   case Instruction::Mul:
1052   case Instruction::UDiv:
1053   case Instruction::Sub:
1054     return cloneArithmeticIVUser(DU, WideAR);
1055 
1056   case Instruction::And:
1057   case Instruction::Or:
1058   case Instruction::Xor:
1059   case Instruction::Shl:
1060   case Instruction::LShr:
1061   case Instruction::AShr:
1062     return cloneBitwiseIVUser(DU);
1063   }
1064 }
1065 
1066 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1067   Instruction *NarrowUse = DU.NarrowUse;
1068   Instruction *NarrowDef = DU.NarrowDef;
1069   Instruction *WideDef = DU.WideDef;
1070 
1071   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1072 
1073   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1074   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1075   // invariant and will be folded or hoisted. If it actually comes from a
1076   // widened IV, it should be removed during a future call to widenIVUse.
1077   bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1078   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1079                    ? WideDef
1080                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1081                                       IsSigned, NarrowUse);
1082   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1083                    ? WideDef
1084                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1085                                       IsSigned, NarrowUse);
1086 
1087   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1088   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1089                                         NarrowBO->getName());
1090   IRBuilder<> Builder(NarrowUse);
1091   Builder.Insert(WideBO);
1092   WideBO->copyIRFlags(NarrowBO);
1093   return WideBO;
1094 }
1095 
1096 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1097                                             const SCEVAddRecExpr *WideAR) {
1098   Instruction *NarrowUse = DU.NarrowUse;
1099   Instruction *NarrowDef = DU.NarrowDef;
1100   Instruction *WideDef = DU.WideDef;
1101 
1102   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1103 
1104   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1105 
1106   // We're trying to find X such that
1107   //
1108   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1109   //
1110   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1111   // and check using SCEV if any of them are correct.
1112 
1113   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1114   // correct solution to X.
1115   auto GuessNonIVOperand = [&](bool SignExt) {
1116     const SCEV *WideLHS;
1117     const SCEV *WideRHS;
1118 
1119     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1120       if (SignExt)
1121         return SE->getSignExtendExpr(S, Ty);
1122       return SE->getZeroExtendExpr(S, Ty);
1123     };
1124 
1125     if (IVOpIdx == 0) {
1126       WideLHS = SE->getSCEV(WideDef);
1127       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1128       WideRHS = GetExtend(NarrowRHS, WideType);
1129     } else {
1130       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1131       WideLHS = GetExtend(NarrowLHS, WideType);
1132       WideRHS = SE->getSCEV(WideDef);
1133     }
1134 
1135     // WideUse is "WideDef `op.wide` X" as described in the comment.
1136     const SCEV *WideUse = nullptr;
1137 
1138     switch (NarrowUse->getOpcode()) {
1139     default:
1140       llvm_unreachable("No other possibility!");
1141 
1142     case Instruction::Add:
1143       WideUse = SE->getAddExpr(WideLHS, WideRHS);
1144       break;
1145 
1146     case Instruction::Mul:
1147       WideUse = SE->getMulExpr(WideLHS, WideRHS);
1148       break;
1149 
1150     case Instruction::UDiv:
1151       WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1152       break;
1153 
1154     case Instruction::Sub:
1155       WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1156       break;
1157     }
1158 
1159     return WideUse == WideAR;
1160   };
1161 
1162   bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1163   if (!GuessNonIVOperand(SignExtend)) {
1164     SignExtend = !SignExtend;
1165     if (!GuessNonIVOperand(SignExtend))
1166       return nullptr;
1167   }
1168 
1169   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1170                    ? WideDef
1171                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1172                                       SignExtend, NarrowUse);
1173   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1174                    ? WideDef
1175                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1176                                       SignExtend, NarrowUse);
1177 
1178   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1179   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1180                                         NarrowBO->getName());
1181 
1182   IRBuilder<> Builder(NarrowUse);
1183   Builder.Insert(WideBO);
1184   WideBO->copyIRFlags(NarrowBO);
1185   return WideBO;
1186 }
1187 
1188 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1189   auto It = ExtendKindMap.find(I);
1190   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1191   return It->second;
1192 }
1193 
1194 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1195                                      unsigned OpCode) const {
1196   if (OpCode == Instruction::Add)
1197     return SE->getAddExpr(LHS, RHS);
1198   if (OpCode == Instruction::Sub)
1199     return SE->getMinusSCEV(LHS, RHS);
1200   if (OpCode == Instruction::Mul)
1201     return SE->getMulExpr(LHS, RHS);
1202 
1203   llvm_unreachable("Unsupported opcode.");
1204 }
1205 
1206 /// No-wrap operations can transfer sign extension of their result to their
1207 /// operands. Generate the SCEV value for the widened operation without
1208 /// actually modifying the IR yet. If the expression after extending the
1209 /// operands is an AddRec for this loop, return the AddRec and the kind of
1210 /// extension used.
1211 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1212   // Handle the common case of add<nsw/nuw>
1213   const unsigned OpCode = DU.NarrowUse->getOpcode();
1214   // Only Add/Sub/Mul instructions supported yet.
1215   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1216       OpCode != Instruction::Mul)
1217     return {nullptr, Unknown};
1218 
1219   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1220   // if extending the other will lead to a recurrence.
1221   const unsigned ExtendOperIdx =
1222       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1223   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1224 
1225   const SCEV *ExtendOperExpr = nullptr;
1226   const OverflowingBinaryOperator *OBO =
1227     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1228   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1229   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1230     ExtendOperExpr = SE->getSignExtendExpr(
1231       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1232   else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1233     ExtendOperExpr = SE->getZeroExtendExpr(
1234       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1235   else
1236     return {nullptr, Unknown};
1237 
1238   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1239   // flags. This instruction may be guarded by control flow that the no-wrap
1240   // behavior depends on. Non-control-equivalent instructions can be mapped to
1241   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1242   // semantics to those operations.
1243   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1244   const SCEV *rhs = ExtendOperExpr;
1245 
1246   // Let's swap operands to the initial order for the case of non-commutative
1247   // operations, like SUB. See PR21014.
1248   if (ExtendOperIdx == 0)
1249     std::swap(lhs, rhs);
1250   const SCEVAddRecExpr *AddRec =
1251       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1252 
1253   if (!AddRec || AddRec->getLoop() != L)
1254     return {nullptr, Unknown};
1255 
1256   return {AddRec, ExtKind};
1257 }
1258 
1259 /// Is this instruction potentially interesting for further simplification after
1260 /// widening it's type? In other words, can the extend be safely hoisted out of
1261 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1262 /// so, return the extended recurrence and the kind of extension used. Otherwise
1263 /// return {nullptr, Unknown}.
1264 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1265   if (!SE->isSCEVable(DU.NarrowUse->getType()))
1266     return {nullptr, Unknown};
1267 
1268   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1269   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1270       SE->getTypeSizeInBits(WideType)) {
1271     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1272     // index. So don't follow this use.
1273     return {nullptr, Unknown};
1274   }
1275 
1276   const SCEV *WideExpr;
1277   ExtendKind ExtKind;
1278   if (DU.NeverNegative) {
1279     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1280     if (isa<SCEVAddRecExpr>(WideExpr))
1281       ExtKind = SignExtended;
1282     else {
1283       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1284       ExtKind = ZeroExtended;
1285     }
1286   } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1287     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1288     ExtKind = SignExtended;
1289   } else {
1290     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1291     ExtKind = ZeroExtended;
1292   }
1293   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1294   if (!AddRec || AddRec->getLoop() != L)
1295     return {nullptr, Unknown};
1296   return {AddRec, ExtKind};
1297 }
1298 
1299 /// This IV user cannot be widen. Replace this use of the original narrow IV
1300 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1301 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) {
1302   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1303                     << *DU.NarrowUse << "\n");
1304   IRBuilder<> Builder(
1305       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1306   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1307   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1308 }
1309 
1310 /// If the narrow use is a compare instruction, then widen the compare
1311 //  (and possibly the other operand).  The extend operation is hoisted into the
1312 // loop preheader as far as possible.
1313 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1314   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1315   if (!Cmp)
1316     return false;
1317 
1318   // We can legally widen the comparison in the following two cases:
1319   //
1320   //  - The signedness of the IV extension and comparison match
1321   //
1322   //  - The narrow IV is always positive (and thus its sign extension is equal
1323   //    to its zero extension).  For instance, let's say we're zero extending
1324   //    %narrow for the following use
1325   //
1326   //      icmp slt i32 %narrow, %val   ... (A)
1327   //
1328   //    and %narrow is always positive.  Then
1329   //
1330   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1331   //          == icmp slt i32 zext(%narrow), sext(%val)
1332   bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1333   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1334     return false;
1335 
1336   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1337   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1338   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1339   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1340 
1341   // Widen the compare instruction.
1342   IRBuilder<> Builder(
1343       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1344   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1345 
1346   // Widen the other operand of the compare, if necessary.
1347   if (CastWidth < IVWidth) {
1348     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1349     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1350   }
1351   return true;
1352 }
1353 
1354 /// Determine whether an individual user of the narrow IV can be widened. If so,
1355 /// return the wide clone of the user.
1356 Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1357   assert(ExtendKindMap.count(DU.NarrowDef) &&
1358          "Should already know the kind of extension used to widen NarrowDef");
1359 
1360   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1361   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1362     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1363       // For LCSSA phis, sink the truncate outside the loop.
1364       // After SimplifyCFG most loop exit targets have a single predecessor.
1365       // Otherwise fall back to a truncate within the loop.
1366       if (UsePhi->getNumOperands() != 1)
1367         truncateIVUse(DU, DT, LI);
1368       else {
1369         // Widening the PHI requires us to insert a trunc.  The logical place
1370         // for this trunc is in the same BB as the PHI.  This is not possible if
1371         // the BB is terminated by a catchswitch.
1372         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1373           return nullptr;
1374 
1375         PHINode *WidePhi =
1376           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1377                           UsePhi);
1378         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1379         IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1380         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1381         UsePhi->replaceAllUsesWith(Trunc);
1382         DeadInsts.emplace_back(UsePhi);
1383         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1384                           << *WidePhi << "\n");
1385       }
1386       return nullptr;
1387     }
1388   }
1389 
1390   // This narrow use can be widened by a sext if it's non-negative or its narrow
1391   // def was widended by a sext. Same for zext.
1392   auto canWidenBySExt = [&]() {
1393     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1394   };
1395   auto canWidenByZExt = [&]() {
1396     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1397   };
1398 
1399   // Our raison d'etre! Eliminate sign and zero extension.
1400   if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1401       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1402     Value *NewDef = DU.WideDef;
1403     if (DU.NarrowUse->getType() != WideType) {
1404       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1405       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1406       if (CastWidth < IVWidth) {
1407         // The cast isn't as wide as the IV, so insert a Trunc.
1408         IRBuilder<> Builder(DU.NarrowUse);
1409         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1410       }
1411       else {
1412         // A wider extend was hidden behind a narrower one. This may induce
1413         // another round of IV widening in which the intermediate IV becomes
1414         // dead. It should be very rare.
1415         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1416                           << " not wide enough to subsume " << *DU.NarrowUse
1417                           << "\n");
1418         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1419         NewDef = DU.NarrowUse;
1420       }
1421     }
1422     if (NewDef != DU.NarrowUse) {
1423       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1424                         << " replaced by " << *DU.WideDef << "\n");
1425       ++NumElimExt;
1426       DU.NarrowUse->replaceAllUsesWith(NewDef);
1427       DeadInsts.emplace_back(DU.NarrowUse);
1428     }
1429     // Now that the extend is gone, we want to expose it's uses for potential
1430     // further simplification. We don't need to directly inform SimplifyIVUsers
1431     // of the new users, because their parent IV will be processed later as a
1432     // new loop phi. If we preserved IVUsers analysis, we would also want to
1433     // push the uses of WideDef here.
1434 
1435     // No further widening is needed. The deceased [sz]ext had done it for us.
1436     return nullptr;
1437   }
1438 
1439   // Does this user itself evaluate to a recurrence after widening?
1440   WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1441   if (!WideAddRec.first)
1442     WideAddRec = getWideRecurrence(DU);
1443 
1444   assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1445   if (!WideAddRec.first) {
1446     // If use is a loop condition, try to promote the condition instead of
1447     // truncating the IV first.
1448     if (widenLoopCompare(DU))
1449       return nullptr;
1450 
1451     // This user does not evaluate to a recurrence after widening, so don't
1452     // follow it. Instead insert a Trunc to kill off the original use,
1453     // eventually isolating the original narrow IV so it can be removed.
1454     truncateIVUse(DU, DT, LI);
1455     return nullptr;
1456   }
1457   // Assume block terminators cannot evaluate to a recurrence. We can't to
1458   // insert a Trunc after a terminator if there happens to be a critical edge.
1459   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1460          "SCEV is not expected to evaluate a block terminator");
1461 
1462   // Reuse the IV increment that SCEVExpander created as long as it dominates
1463   // NarrowUse.
1464   Instruction *WideUse = nullptr;
1465   if (WideAddRec.first == WideIncExpr &&
1466       Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1467     WideUse = WideInc;
1468   else {
1469     WideUse = cloneIVUser(DU, WideAddRec.first);
1470     if (!WideUse)
1471       return nullptr;
1472   }
1473   // Evaluation of WideAddRec ensured that the narrow expression could be
1474   // extended outside the loop without overflow. This suggests that the wide use
1475   // evaluates to the same expression as the extended narrow use, but doesn't
1476   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1477   // where it fails, we simply throw away the newly created wide use.
1478   if (WideAddRec.first != SE->getSCEV(WideUse)) {
1479     LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1480                       << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1481                       << "\n");
1482     DeadInsts.emplace_back(WideUse);
1483     return nullptr;
1484   }
1485 
1486   ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1487   // Returning WideUse pushes it on the worklist.
1488   return WideUse;
1489 }
1490 
1491 /// Add eligible users of NarrowDef to NarrowIVUsers.
1492 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1493   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1494   bool NonNegativeDef =
1495       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1496                            SE->getConstant(NarrowSCEV->getType(), 0));
1497   for (User *U : NarrowDef->users()) {
1498     Instruction *NarrowUser = cast<Instruction>(U);
1499 
1500     // Handle data flow merges and bizarre phi cycles.
1501     if (!Widened.insert(NarrowUser).second)
1502       continue;
1503 
1504     bool NonNegativeUse = false;
1505     if (!NonNegativeDef) {
1506       // We might have a control-dependent range information for this context.
1507       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1508         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1509     }
1510 
1511     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1512                                NonNegativeDef || NonNegativeUse);
1513   }
1514 }
1515 
1516 /// Process a single induction variable. First use the SCEVExpander to create a
1517 /// wide induction variable that evaluates to the same recurrence as the
1518 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1519 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1520 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1521 ///
1522 /// It would be simpler to delete uses as they are processed, but we must avoid
1523 /// invalidating SCEV expressions.
1524 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1525   // Is this phi an induction variable?
1526   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1527   if (!AddRec)
1528     return nullptr;
1529 
1530   // Widen the induction variable expression.
1531   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1532                                ? SE->getSignExtendExpr(AddRec, WideType)
1533                                : SE->getZeroExtendExpr(AddRec, WideType);
1534 
1535   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1536          "Expect the new IV expression to preserve its type");
1537 
1538   // Can the IV be extended outside the loop without overflow?
1539   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1540   if (!AddRec || AddRec->getLoop() != L)
1541     return nullptr;
1542 
1543   // An AddRec must have loop-invariant operands. Since this AddRec is
1544   // materialized by a loop header phi, the expression cannot have any post-loop
1545   // operands, so they must dominate the loop header.
1546   assert(
1547       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1548       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1549       "Loop header phi recurrence inputs do not dominate the loop");
1550 
1551   // Iterate over IV uses (including transitive ones) looking for IV increments
1552   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1553   // the increment calculate control-dependent range information basing on
1554   // dominating conditions inside of the loop (e.g. a range check inside of the
1555   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1556   //
1557   // Control-dependent range information is later used to prove that a narrow
1558   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1559   // this on demand because when pushNarrowIVUsers needs this information some
1560   // of the dominating conditions might be already widened.
1561   if (UsePostIncrementRanges)
1562     calculatePostIncRanges(OrigPhi);
1563 
1564   // The rewriter provides a value for the desired IV expression. This may
1565   // either find an existing phi or materialize a new one. Either way, we
1566   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1567   // of the phi-SCC dominates the loop entry.
1568   Instruction *InsertPt = &L->getHeader()->front();
1569   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1570 
1571   // Remembering the WideIV increment generated by SCEVExpander allows
1572   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1573   // employ a general reuse mechanism because the call above is the only call to
1574   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1575   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1576     WideInc =
1577       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1578     WideIncExpr = SE->getSCEV(WideInc);
1579     // Propagate the debug location associated with the original loop increment
1580     // to the new (widened) increment.
1581     auto *OrigInc =
1582       cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1583     WideInc->setDebugLoc(OrigInc->getDebugLoc());
1584   }
1585 
1586   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1587   ++NumWidened;
1588 
1589   // Traverse the def-use chain using a worklist starting at the original IV.
1590   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1591 
1592   Widened.insert(OrigPhi);
1593   pushNarrowIVUsers(OrigPhi, WidePhi);
1594 
1595   while (!NarrowIVUsers.empty()) {
1596     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1597 
1598     // Process a def-use edge. This may replace the use, so don't hold a
1599     // use_iterator across it.
1600     Instruction *WideUse = widenIVUse(DU, Rewriter);
1601 
1602     // Follow all def-use edges from the previous narrow use.
1603     if (WideUse)
1604       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1605 
1606     // widenIVUse may have removed the def-use edge.
1607     if (DU.NarrowDef->use_empty())
1608       DeadInsts.emplace_back(DU.NarrowDef);
1609   }
1610 
1611   // Attach any debug information to the new PHI. Since OrigPhi and WidePHI
1612   // evaluate the same recurrence, we can just copy the debug info over.
1613   SmallVector<DbgValueInst *, 1> DbgValues;
1614   llvm::findDbgValues(DbgValues, OrigPhi);
1615   auto *MDPhi = MetadataAsValue::get(WidePhi->getContext(),
1616                                      ValueAsMetadata::get(WidePhi));
1617   for (auto &DbgValue : DbgValues)
1618     DbgValue->setOperand(0, MDPhi);
1619   return WidePhi;
1620 }
1621 
1622 /// Calculates control-dependent range for the given def at the given context
1623 /// by looking at dominating conditions inside of the loop
1624 void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1625                                     Instruction *NarrowUser) {
1626   using namespace llvm::PatternMatch;
1627 
1628   Value *NarrowDefLHS;
1629   const APInt *NarrowDefRHS;
1630   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1631                                  m_APInt(NarrowDefRHS))) ||
1632       !NarrowDefRHS->isNonNegative())
1633     return;
1634 
1635   auto UpdateRangeFromCondition = [&] (Value *Condition,
1636                                        bool TrueDest) {
1637     CmpInst::Predicate Pred;
1638     Value *CmpRHS;
1639     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
1640                                  m_Value(CmpRHS))))
1641       return;
1642 
1643     CmpInst::Predicate P =
1644             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
1645 
1646     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1647     auto CmpConstrainedLHSRange =
1648             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
1649     auto NarrowDefRange =
1650             CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1651 
1652     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1653   };
1654 
1655   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
1656     if (!HasGuards)
1657       return;
1658 
1659     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
1660                                      Ctx->getParent()->rend())) {
1661       Value *C = nullptr;
1662       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
1663         UpdateRangeFromCondition(C, /*TrueDest=*/true);
1664     }
1665   };
1666 
1667   UpdateRangeFromGuards(NarrowUser);
1668 
1669   BasicBlock *NarrowUserBB = NarrowUser->getParent();
1670   // If NarrowUserBB is statically unreachable asking dominator queries may
1671   // yield surprising results. (e.g. the block may not have a dom tree node)
1672   if (!DT->isReachableFromEntry(NarrowUserBB))
1673     return;
1674 
1675   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1676        L->contains(DTB->getBlock());
1677        DTB = DTB->getIDom()) {
1678     auto *BB = DTB->getBlock();
1679     auto *TI = BB->getTerminator();
1680     UpdateRangeFromGuards(TI);
1681 
1682     auto *BI = dyn_cast<BranchInst>(TI);
1683     if (!BI || !BI->isConditional())
1684       continue;
1685 
1686     auto *TrueSuccessor = BI->getSuccessor(0);
1687     auto *FalseSuccessor = BI->getSuccessor(1);
1688 
1689     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
1690       return BBE.isSingleEdge() &&
1691              DT->dominates(BBE, NarrowUser->getParent());
1692     };
1693 
1694     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
1695       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
1696 
1697     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
1698       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
1699   }
1700 }
1701 
1702 /// Calculates PostIncRangeInfos map for the given IV
1703 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
1704   SmallPtrSet<Instruction *, 16> Visited;
1705   SmallVector<Instruction *, 6> Worklist;
1706   Worklist.push_back(OrigPhi);
1707   Visited.insert(OrigPhi);
1708 
1709   while (!Worklist.empty()) {
1710     Instruction *NarrowDef = Worklist.pop_back_val();
1711 
1712     for (Use &U : NarrowDef->uses()) {
1713       auto *NarrowUser = cast<Instruction>(U.getUser());
1714 
1715       // Don't go looking outside the current loop.
1716       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
1717       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
1718         continue;
1719 
1720       if (!Visited.insert(NarrowUser).second)
1721         continue;
1722 
1723       Worklist.push_back(NarrowUser);
1724 
1725       calculatePostIncRange(NarrowDef, NarrowUser);
1726     }
1727   }
1728 }
1729 
1730 //===----------------------------------------------------------------------===//
1731 //  Live IV Reduction - Minimize IVs live across the loop.
1732 //===----------------------------------------------------------------------===//
1733 
1734 //===----------------------------------------------------------------------===//
1735 //  Simplification of IV users based on SCEV evaluation.
1736 //===----------------------------------------------------------------------===//
1737 
1738 namespace {
1739 
1740 class IndVarSimplifyVisitor : public IVVisitor {
1741   ScalarEvolution *SE;
1742   const TargetTransformInfo *TTI;
1743   PHINode *IVPhi;
1744 
1745 public:
1746   WideIVInfo WI;
1747 
1748   IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1749                         const TargetTransformInfo *TTI,
1750                         const DominatorTree *DTree)
1751     : SE(SCEV), TTI(TTI), IVPhi(IV) {
1752     DT = DTree;
1753     WI.NarrowIV = IVPhi;
1754   }
1755 
1756   // Implement the interface used by simplifyUsersOfIV.
1757   void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1758 };
1759 
1760 } // end anonymous namespace
1761 
1762 /// Iteratively perform simplification on a worklist of IV users. Each
1763 /// successive simplification may push more users which may themselves be
1764 /// candidates for simplification.
1765 ///
1766 /// Sign/Zero extend elimination is interleaved with IV simplification.
1767 void IndVarSimplify::simplifyAndExtend(Loop *L,
1768                                        SCEVExpander &Rewriter,
1769                                        LoopInfo *LI) {
1770   SmallVector<WideIVInfo, 8> WideIVs;
1771 
1772   auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction(
1773           Intrinsic::getName(Intrinsic::experimental_guard));
1774   bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1775 
1776   SmallVector<PHINode*, 8> LoopPhis;
1777   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1778     LoopPhis.push_back(cast<PHINode>(I));
1779   }
1780   // Each round of simplification iterates through the SimplifyIVUsers worklist
1781   // for all current phis, then determines whether any IVs can be
1782   // widened. Widening adds new phis to LoopPhis, inducing another round of
1783   // simplification on the wide IVs.
1784   while (!LoopPhis.empty()) {
1785     // Evaluate as many IV expressions as possible before widening any IVs. This
1786     // forces SCEV to set no-wrap flags before evaluating sign/zero
1787     // extension. The first time SCEV attempts to normalize sign/zero extension,
1788     // the result becomes final. So for the most predictable results, we delay
1789     // evaluation of sign/zero extend evaluation until needed, and avoid running
1790     // other SCEV based analysis prior to simplifyAndExtend.
1791     do {
1792       PHINode *CurrIV = LoopPhis.pop_back_val();
1793 
1794       // Information about sign/zero extensions of CurrIV.
1795       IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1796 
1797       Changed |=
1798           simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, Rewriter, &Visitor);
1799 
1800       if (Visitor.WI.WidestNativeType) {
1801         WideIVs.push_back(Visitor.WI);
1802       }
1803     } while(!LoopPhis.empty());
1804 
1805     for (; !WideIVs.empty(); WideIVs.pop_back()) {
1806       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts, HasGuards);
1807       if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1808         Changed = true;
1809         LoopPhis.push_back(WidePhi);
1810       }
1811     }
1812   }
1813 }
1814 
1815 //===----------------------------------------------------------------------===//
1816 //  linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1817 //===----------------------------------------------------------------------===//
1818 
1819 /// Return true if this loop's backedge taken count expression can be safely and
1820 /// cheaply expanded into an instruction sequence that can be used by
1821 /// linearFunctionTestReplace.
1822 ///
1823 /// TODO: This fails for pointer-type loop counters with greater than one byte
1824 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
1825 /// we could skip this check in the case that the LFTR loop counter (chosen by
1826 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
1827 /// the loop test to an inequality test by checking the target data's alignment
1828 /// of element types (given that the initial pointer value originates from or is
1829 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1830 /// However, we don't yet have a strong motivation for converting loop tests
1831 /// into inequality tests.
1832 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
1833                                         SCEVExpander &Rewriter) {
1834   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1835   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1836       BackedgeTakenCount->isZero())
1837     return false;
1838 
1839   if (!L->getExitingBlock())
1840     return false;
1841 
1842   // Can't rewrite non-branch yet.
1843   if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
1844     return false;
1845 
1846   if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
1847     return false;
1848 
1849   return true;
1850 }
1851 
1852 /// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
1853 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1854   Instruction *IncI = dyn_cast<Instruction>(IncV);
1855   if (!IncI)
1856     return nullptr;
1857 
1858   switch (IncI->getOpcode()) {
1859   case Instruction::Add:
1860   case Instruction::Sub:
1861     break;
1862   case Instruction::GetElementPtr:
1863     // An IV counter must preserve its type.
1864     if (IncI->getNumOperands() == 2)
1865       break;
1866     LLVM_FALLTHROUGH;
1867   default:
1868     return nullptr;
1869   }
1870 
1871   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1872   if (Phi && Phi->getParent() == L->getHeader()) {
1873     if (isLoopInvariant(IncI->getOperand(1), L, DT))
1874       return Phi;
1875     return nullptr;
1876   }
1877   if (IncI->getOpcode() == Instruction::GetElementPtr)
1878     return nullptr;
1879 
1880   // Allow add/sub to be commuted.
1881   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1882   if (Phi && Phi->getParent() == L->getHeader()) {
1883     if (isLoopInvariant(IncI->getOperand(0), L, DT))
1884       return Phi;
1885   }
1886   return nullptr;
1887 }
1888 
1889 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
1890 static ICmpInst *getLoopTest(Loop *L) {
1891   assert(L->getExitingBlock() && "expected loop exit");
1892 
1893   BasicBlock *LatchBlock = L->getLoopLatch();
1894   // Don't bother with LFTR if the loop is not properly simplified.
1895   if (!LatchBlock)
1896     return nullptr;
1897 
1898   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1899   assert(BI && "expected exit branch");
1900 
1901   return dyn_cast<ICmpInst>(BI->getCondition());
1902 }
1903 
1904 /// linearFunctionTestReplace policy. Return true unless we can show that the
1905 /// current exit test is already sufficiently canonical.
1906 static bool needsLFTR(Loop *L, DominatorTree *DT) {
1907   // Do LFTR to simplify the exit condition to an ICMP.
1908   ICmpInst *Cond = getLoopTest(L);
1909   if (!Cond)
1910     return true;
1911 
1912   // Do LFTR to simplify the exit ICMP to EQ/NE
1913   ICmpInst::Predicate Pred = Cond->getPredicate();
1914   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1915     return true;
1916 
1917   // Look for a loop invariant RHS
1918   Value *LHS = Cond->getOperand(0);
1919   Value *RHS = Cond->getOperand(1);
1920   if (!isLoopInvariant(RHS, L, DT)) {
1921     if (!isLoopInvariant(LHS, L, DT))
1922       return true;
1923     std::swap(LHS, RHS);
1924   }
1925   // Look for a simple IV counter LHS
1926   PHINode *Phi = dyn_cast<PHINode>(LHS);
1927   if (!Phi)
1928     Phi = getLoopPhiForCounter(LHS, L, DT);
1929 
1930   if (!Phi)
1931     return true;
1932 
1933   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
1934   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
1935   if (Idx < 0)
1936     return true;
1937 
1938   // Do LFTR if the exit condition's IV is *not* a simple counter.
1939   Value *IncV = Phi->getIncomingValue(Idx);
1940   return Phi != getLoopPhiForCounter(IncV, L, DT);
1941 }
1942 
1943 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
1944 /// down to checking that all operands are constant and listing instructions
1945 /// that may hide undef.
1946 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
1947                                unsigned Depth) {
1948   if (isa<Constant>(V))
1949     return !isa<UndefValue>(V);
1950 
1951   if (Depth >= 6)
1952     return false;
1953 
1954   // Conservatively handle non-constant non-instructions. For example, Arguments
1955   // may be undef.
1956   Instruction *I = dyn_cast<Instruction>(V);
1957   if (!I)
1958     return false;
1959 
1960   // Load and return values may be undef.
1961   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
1962     return false;
1963 
1964   // Optimistically handle other instructions.
1965   for (Value *Op : I->operands()) {
1966     if (!Visited.insert(Op).second)
1967       continue;
1968     if (!hasConcreteDefImpl(Op, Visited, Depth+1))
1969       return false;
1970   }
1971   return true;
1972 }
1973 
1974 /// Return true if the given value is concrete. We must prove that undef can
1975 /// never reach it.
1976 ///
1977 /// TODO: If we decide that this is a good approach to checking for undef, we
1978 /// may factor it into a common location.
1979 static bool hasConcreteDef(Value *V) {
1980   SmallPtrSet<Value*, 8> Visited;
1981   Visited.insert(V);
1982   return hasConcreteDefImpl(V, Visited, 0);
1983 }
1984 
1985 /// Return true if this IV has any uses other than the (soon to be rewritten)
1986 /// loop exit test.
1987 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1988   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1989   Value *IncV = Phi->getIncomingValue(LatchIdx);
1990 
1991   for (User *U : Phi->users())
1992     if (U != Cond && U != IncV) return false;
1993 
1994   for (User *U : IncV->users())
1995     if (U != Cond && U != Phi) return false;
1996   return true;
1997 }
1998 
1999 /// Find an affine IV in canonical form.
2000 ///
2001 /// BECount may be an i8* pointer type. The pointer difference is already
2002 /// valid count without scaling the address stride, so it remains a pointer
2003 /// expression as far as SCEV is concerned.
2004 ///
2005 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
2006 ///
2007 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
2008 ///
2009 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
2010 /// This is difficult in general for SCEV because of potential overflow. But we
2011 /// could at least handle constant BECounts.
2012 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
2013                                 ScalarEvolution *SE, DominatorTree *DT) {
2014   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
2015 
2016   Value *Cond =
2017     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
2018 
2019   // Loop over all of the PHI nodes, looking for a simple counter.
2020   PHINode *BestPhi = nullptr;
2021   const SCEV *BestInit = nullptr;
2022   BasicBlock *LatchBlock = L->getLoopLatch();
2023   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
2024   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2025 
2026   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
2027     PHINode *Phi = cast<PHINode>(I);
2028     if (!SE->isSCEVable(Phi->getType()))
2029       continue;
2030 
2031     // Avoid comparing an integer IV against a pointer Limit.
2032     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
2033       continue;
2034 
2035     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
2036     if (!AR || AR->getLoop() != L || !AR->isAffine())
2037       continue;
2038 
2039     // AR may be a pointer type, while BECount is an integer type.
2040     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
2041     // AR may not be a narrower type, or we may never exit.
2042     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
2043     if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
2044       continue;
2045 
2046     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
2047     if (!Step || !Step->isOne())
2048       continue;
2049 
2050     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
2051     Value *IncV = Phi->getIncomingValue(LatchIdx);
2052     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
2053       continue;
2054 
2055     // Avoid reusing a potentially undef value to compute other values that may
2056     // have originally had a concrete definition.
2057     if (!hasConcreteDef(Phi)) {
2058       // We explicitly allow unknown phis as long as they are already used by
2059       // the loop test. In this case we assume that performing LFTR could not
2060       // increase the number of undef users.
2061       if (ICmpInst *Cond = getLoopTest(L)) {
2062         if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) &&
2063             Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
2064           continue;
2065         }
2066       }
2067     }
2068     const SCEV *Init = AR->getStart();
2069 
2070     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2071       // Don't force a live loop counter if another IV can be used.
2072       if (AlmostDeadIV(Phi, LatchBlock, Cond))
2073         continue;
2074 
2075       // Prefer to count-from-zero. This is a more "canonical" counter form. It
2076       // also prefers integer to pointer IVs.
2077       if (BestInit->isZero() != Init->isZero()) {
2078         if (BestInit->isZero())
2079           continue;
2080       }
2081       // If two IVs both count from zero or both count from nonzero then the
2082       // narrower is likely a dead phi that has been widened. Use the wider phi
2083       // to allow the other to be eliminated.
2084       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
2085         continue;
2086     }
2087     BestPhi = Phi;
2088     BestInit = Init;
2089   }
2090   return BestPhi;
2091 }
2092 
2093 /// Help linearFunctionTestReplace by generating a value that holds the RHS of
2094 /// the new loop test.
2095 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
2096                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
2097   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2098   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
2099   const SCEV *IVInit = AR->getStart();
2100 
2101   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
2102   // finds a valid pointer IV. Sign extend BECount in order to materialize a
2103   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
2104   // the existing GEPs whenever possible.
2105   if (IndVar->getType()->isPointerTy() && !IVCount->getType()->isPointerTy()) {
2106     // IVOffset will be the new GEP offset that is interpreted by GEP as a
2107     // signed value. IVCount on the other hand represents the loop trip count,
2108     // which is an unsigned value. FindLoopCounter only allows induction
2109     // variables that have a positive unit stride of one. This means we don't
2110     // have to handle the case of negative offsets (yet) and just need to zero
2111     // extend IVCount.
2112     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
2113     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
2114 
2115     // Expand the code for the iteration count.
2116     assert(SE->isLoopInvariant(IVOffset, L) &&
2117            "Computed iteration count is not loop invariant!");
2118     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2119     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
2120 
2121     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
2122     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
2123     // We could handle pointer IVs other than i8*, but we need to compensate for
2124     // gep index scaling. See canExpandBackedgeTakenCount comments.
2125     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
2126                              cast<PointerType>(GEPBase->getType())
2127                                  ->getElementType())->isOne() &&
2128            "unit stride pointer IV must be i8*");
2129 
2130     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2131     return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
2132   } else {
2133     // In any other case, convert both IVInit and IVCount to integers before
2134     // comparing. This may result in SCEV expansion of pointers, but in practice
2135     // SCEV will fold the pointer arithmetic away as such:
2136     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
2137     //
2138     // Valid Cases: (1) both integers is most common; (2) both may be pointers
2139     // for simple memset-style loops.
2140     //
2141     // IVInit integer and IVCount pointer would only occur if a canonical IV
2142     // were generated on top of case #2, which is not expected.
2143 
2144     const SCEV *IVLimit = nullptr;
2145     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
2146     // For non-zero Start, compute IVCount here.
2147     if (AR->getStart()->isZero())
2148       IVLimit = IVCount;
2149     else {
2150       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
2151       const SCEV *IVInit = AR->getStart();
2152 
2153       // For integer IVs, truncate the IV before computing IVInit + BECount.
2154       if (SE->getTypeSizeInBits(IVInit->getType())
2155           > SE->getTypeSizeInBits(IVCount->getType()))
2156         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
2157 
2158       IVLimit = SE->getAddExpr(IVInit, IVCount);
2159     }
2160     // Expand the code for the iteration count.
2161     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2162     IRBuilder<> Builder(BI);
2163     assert(SE->isLoopInvariant(IVLimit, L) &&
2164            "Computed iteration count is not loop invariant!");
2165     // Ensure that we generate the same type as IndVar, or a smaller integer
2166     // type. In the presence of null pointer values, we have an integer type
2167     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
2168     Type *LimitTy = IVCount->getType()->isPointerTy() ?
2169       IndVar->getType() : IVCount->getType();
2170     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
2171   }
2172 }
2173 
2174 /// This method rewrites the exit condition of the loop to be a canonical !=
2175 /// comparison against the incremented loop induction variable.  This pass is
2176 /// able to rewrite the exit tests of any loop where the SCEV analysis can
2177 /// determine a loop-invariant trip count of the loop, which is actually a much
2178 /// broader range than just linear tests.
2179 Value *IndVarSimplify::
2180 linearFunctionTestReplace(Loop *L,
2181                           const SCEV *BackedgeTakenCount,
2182                           PHINode *IndVar,
2183                           SCEVExpander &Rewriter) {
2184   assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
2185 
2186   // Initialize CmpIndVar and IVCount to their preincremented values.
2187   Value *CmpIndVar = IndVar;
2188   const SCEV *IVCount = BackedgeTakenCount;
2189 
2190   assert(L->getLoopLatch() && "Loop no longer in simplified form?");
2191 
2192   // If the exiting block is the same as the backedge block, we prefer to
2193   // compare against the post-incremented value, otherwise we must compare
2194   // against the preincremented value.
2195   if (L->getExitingBlock() == L->getLoopLatch()) {
2196     // Add one to the "backedge-taken" count to get the trip count.
2197     // This addition may overflow, which is valid as long as the comparison is
2198     // truncated to BackedgeTakenCount->getType().
2199     IVCount = SE->getAddExpr(BackedgeTakenCount,
2200                              SE->getOne(BackedgeTakenCount->getType()));
2201     // The BackedgeTaken expression contains the number of times that the
2202     // backedge branches to the loop header.  This is one less than the
2203     // number of times the loop executes, so use the incremented indvar.
2204     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
2205   }
2206 
2207   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
2208   assert(ExitCnt->getType()->isPointerTy() ==
2209              IndVar->getType()->isPointerTy() &&
2210          "genLoopLimit missed a cast");
2211 
2212   // Insert a new icmp_ne or icmp_eq instruction before the branch.
2213   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2214   ICmpInst::Predicate P;
2215   if (L->contains(BI->getSuccessor(0)))
2216     P = ICmpInst::ICMP_NE;
2217   else
2218     P = ICmpInst::ICMP_EQ;
2219 
2220   LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
2221                     << "      LHS:" << *CmpIndVar << '\n'
2222                     << "       op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")
2223                     << "\n"
2224                     << "      RHS:\t" << *ExitCnt << "\n"
2225                     << "  IVCount:\t" << *IVCount << "\n");
2226 
2227   IRBuilder<> Builder(BI);
2228 
2229   // The new loop exit condition should reuse the debug location of the
2230   // original loop exit condition.
2231   if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2232     Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
2233 
2234   // LFTR can ignore IV overflow and truncate to the width of
2235   // BECount. This avoids materializing the add(zext(add)) expression.
2236   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
2237   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
2238   if (CmpIndVarSize > ExitCntSize) {
2239     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2240     const SCEV *ARStart = AR->getStart();
2241     const SCEV *ARStep = AR->getStepRecurrence(*SE);
2242     // For constant IVCount, avoid truncation.
2243     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2244       const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2245       APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
2246       // Note that the post-inc value of BackedgeTakenCount may have overflowed
2247       // above such that IVCount is now zero.
2248       if (IVCount != BackedgeTakenCount && Count == 0) {
2249         Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
2250         ++Count;
2251       }
2252       else
2253         Count = Count.zext(CmpIndVarSize);
2254       APInt NewLimit;
2255       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2256         NewLimit = Start - Count;
2257       else
2258         NewLimit = Start + Count;
2259       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
2260 
2261       LLVM_DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
2262     } else {
2263       // We try to extend trip count first. If that doesn't work we truncate IV.
2264       // Zext(trunc(IV)) == IV implies equivalence of the following two:
2265       // Trunc(IV) == ExitCnt and IV == zext(ExitCnt). Similarly for sext. If
2266       // one of the two holds, extend the trip count, otherwise we truncate IV.
2267       bool Extended = false;
2268       const SCEV *IV = SE->getSCEV(CmpIndVar);
2269       const SCEV *ZExtTrunc =
2270            SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2271                                                      ExitCnt->getType()),
2272                                  CmpIndVar->getType());
2273 
2274       if (ZExtTrunc == IV) {
2275         Extended = true;
2276         ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
2277                                      "wide.trip.count");
2278       } else {
2279         const SCEV *SExtTrunc =
2280           SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2281                                                     ExitCnt->getType()),
2282                                 CmpIndVar->getType());
2283         if (SExtTrunc == IV) {
2284           Extended = true;
2285           ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
2286                                        "wide.trip.count");
2287         }
2288       }
2289 
2290       if (!Extended)
2291         CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
2292                                         "lftr.wideiv");
2293     }
2294   }
2295   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
2296   Value *OrigCond = BI->getCondition();
2297   // It's tempting to use replaceAllUsesWith here to fully replace the old
2298   // comparison, but that's not immediately safe, since users of the old
2299   // comparison may not be dominated by the new comparison. Instead, just
2300   // update the branch to use the new comparison; in the common case this
2301   // will make old comparison dead.
2302   BI->setCondition(Cond);
2303   DeadInsts.push_back(OrigCond);
2304 
2305   ++NumLFTR;
2306   Changed = true;
2307   return Cond;
2308 }
2309 
2310 //===----------------------------------------------------------------------===//
2311 //  sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
2312 //===----------------------------------------------------------------------===//
2313 
2314 /// If there's a single exit block, sink any loop-invariant values that
2315 /// were defined in the preheader but not used inside the loop into the
2316 /// exit block to reduce register pressure in the loop.
2317 void IndVarSimplify::sinkUnusedInvariants(Loop *L) {
2318   BasicBlock *ExitBlock = L->getExitBlock();
2319   if (!ExitBlock) return;
2320 
2321   BasicBlock *Preheader = L->getLoopPreheader();
2322   if (!Preheader) return;
2323 
2324   BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();
2325   BasicBlock::iterator I(Preheader->getTerminator());
2326   while (I != Preheader->begin()) {
2327     --I;
2328     // New instructions were inserted at the end of the preheader.
2329     if (isa<PHINode>(I))
2330       break;
2331 
2332     // Don't move instructions which might have side effects, since the side
2333     // effects need to complete before instructions inside the loop.  Also don't
2334     // move instructions which might read memory, since the loop may modify
2335     // memory. Note that it's okay if the instruction might have undefined
2336     // behavior: LoopSimplify guarantees that the preheader dominates the exit
2337     // block.
2338     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2339       continue;
2340 
2341     // Skip debug info intrinsics.
2342     if (isa<DbgInfoIntrinsic>(I))
2343       continue;
2344 
2345     // Skip eh pad instructions.
2346     if (I->isEHPad())
2347       continue;
2348 
2349     // Don't sink alloca: we never want to sink static alloca's out of the
2350     // entry block, and correctly sinking dynamic alloca's requires
2351     // checks for stacksave/stackrestore intrinsics.
2352     // FIXME: Refactor this check somehow?
2353     if (isa<AllocaInst>(I))
2354       continue;
2355 
2356     // Determine if there is a use in or before the loop (direct or
2357     // otherwise).
2358     bool UsedInLoop = false;
2359     for (Use &U : I->uses()) {
2360       Instruction *User = cast<Instruction>(U.getUser());
2361       BasicBlock *UseBB = User->getParent();
2362       if (PHINode *P = dyn_cast<PHINode>(User)) {
2363         unsigned i =
2364           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2365         UseBB = P->getIncomingBlock(i);
2366       }
2367       if (UseBB == Preheader || L->contains(UseBB)) {
2368         UsedInLoop = true;
2369         break;
2370       }
2371     }
2372 
2373     // If there is, the def must remain in the preheader.
2374     if (UsedInLoop)
2375       continue;
2376 
2377     // Otherwise, sink it to the exit block.
2378     Instruction *ToMove = &*I;
2379     bool Done = false;
2380 
2381     if (I != Preheader->begin()) {
2382       // Skip debug info intrinsics.
2383       do {
2384         --I;
2385       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2386 
2387       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2388         Done = true;
2389     } else {
2390       Done = true;
2391     }
2392 
2393     ToMove->moveBefore(*ExitBlock, InsertPt);
2394     if (Done) break;
2395     InsertPt = ToMove->getIterator();
2396   }
2397 }
2398 
2399 //===----------------------------------------------------------------------===//
2400 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
2401 //===----------------------------------------------------------------------===//
2402 
2403 bool IndVarSimplify::run(Loop *L) {
2404   // We need (and expect!) the incoming loop to be in LCSSA.
2405   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2406          "LCSSA required to run indvars!");
2407 
2408   // If LoopSimplify form is not available, stay out of trouble. Some notes:
2409   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
2410   //    canonicalization can be a pessimization without LSR to "clean up"
2411   //    afterwards.
2412   //  - We depend on having a preheader; in particular,
2413   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
2414   //    and we're in trouble if we can't find the induction variable even when
2415   //    we've manually inserted one.
2416   //  - LFTR relies on having a single backedge.
2417   if (!L->isLoopSimplifyForm())
2418     return false;
2419 
2420   // If there are any floating-point recurrences, attempt to
2421   // transform them to use integer recurrences.
2422   rewriteNonIntegerIVs(L);
2423 
2424   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2425 
2426   // Create a rewriter object which we'll use to transform the code with.
2427   SCEVExpander Rewriter(*SE, DL, "indvars");
2428 #ifndef NDEBUG
2429   Rewriter.setDebugType(DEBUG_TYPE);
2430 #endif
2431 
2432   // Eliminate redundant IV users.
2433   //
2434   // Simplification works best when run before other consumers of SCEV. We
2435   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2436   // other expressions involving loop IVs have been evaluated. This helps SCEV
2437   // set no-wrap flags before normalizing sign/zero extension.
2438   Rewriter.disableCanonicalMode();
2439   simplifyAndExtend(L, Rewriter, LI);
2440 
2441   // Check to see if this loop has a computable loop-invariant execution count.
2442   // If so, this means that we can compute the final value of any expressions
2443   // that are recurrent in the loop, and substitute the exit values from the
2444   // loop into any instructions outside of the loop that use the final values of
2445   // the current expressions.
2446   //
2447   if (ReplaceExitValue != NeverRepl &&
2448       !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2449     rewriteLoopExitValues(L, Rewriter);
2450 
2451   // Eliminate redundant IV cycles.
2452   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
2453 
2454   // If we have a trip count expression, rewrite the loop's exit condition
2455   // using it.  We can currently only handle loops with a single exit.
2456   if (!DisableLFTR && canExpandBackedgeTakenCount(L, SE, Rewriter) &&
2457       needsLFTR(L, DT)) {
2458     PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
2459     if (IndVar) {
2460       // Check preconditions for proper SCEVExpander operation. SCEV does not
2461       // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2462       // pass that uses the SCEVExpander must do it. This does not work well for
2463       // loop passes because SCEVExpander makes assumptions about all loops,
2464       // while LoopPassManager only forces the current loop to be simplified.
2465       //
2466       // FIXME: SCEV expansion has no way to bail out, so the caller must
2467       // explicitly check any assumptions made by SCEV. Brittle.
2468       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2469       if (!AR || AR->getLoop()->getLoopPreheader())
2470         (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2471                                         Rewriter);
2472     }
2473   }
2474   // Clear the rewriter cache, because values that are in the rewriter's cache
2475   // can be deleted in the loop below, causing the AssertingVH in the cache to
2476   // trigger.
2477   Rewriter.clear();
2478 
2479   // Now that we're done iterating through lists, clean up any instructions
2480   // which are now dead.
2481   while (!DeadInsts.empty())
2482     if (Instruction *Inst =
2483             dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2484       RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
2485 
2486   // The Rewriter may not be used from this point on.
2487 
2488   // Loop-invariant instructions in the preheader that aren't used in the
2489   // loop may be sunk below the loop to reduce register pressure.
2490   sinkUnusedInvariants(L);
2491 
2492   // rewriteFirstIterationLoopExitValues does not rely on the computation of
2493   // trip count and therefore can further simplify exit values in addition to
2494   // rewriteLoopExitValues.
2495   rewriteFirstIterationLoopExitValues(L);
2496 
2497   // Clean up dead instructions.
2498   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
2499 
2500   // Check a post-condition.
2501   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2502          "Indvars did not preserve LCSSA!");
2503 
2504   // Verify that LFTR, and any other change have not interfered with SCEV's
2505   // ability to compute trip count.
2506 #ifndef NDEBUG
2507   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2508     SE->forgetLoop(L);
2509     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2510     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2511         SE->getTypeSizeInBits(NewBECount->getType()))
2512       NewBECount = SE->getTruncateOrNoop(NewBECount,
2513                                          BackedgeTakenCount->getType());
2514     else
2515       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2516                                                  NewBECount->getType());
2517     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2518   }
2519 #endif
2520 
2521   return Changed;
2522 }
2523 
2524 PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
2525                                           LoopStandardAnalysisResults &AR,
2526                                           LPMUpdater &) {
2527   Function *F = L.getHeader()->getParent();
2528   const DataLayout &DL = F->getParent()->getDataLayout();
2529 
2530   IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI);
2531   if (!IVS.run(&L))
2532     return PreservedAnalyses::all();
2533 
2534   auto PA = getLoopPassPreservedAnalyses();
2535   PA.preserveSet<CFGAnalyses>();
2536   return PA;
2537 }
2538 
2539 namespace {
2540 
2541 struct IndVarSimplifyLegacyPass : public LoopPass {
2542   static char ID; // Pass identification, replacement for typeid
2543 
2544   IndVarSimplifyLegacyPass() : LoopPass(ID) {
2545     initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
2546   }
2547 
2548   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
2549     if (skipLoop(L))
2550       return false;
2551 
2552     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2553     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2554     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2555     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2556     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2557     auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2558     auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2559     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2560 
2561     IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2562     return IVS.run(L);
2563   }
2564 
2565   void getAnalysisUsage(AnalysisUsage &AU) const override {
2566     AU.setPreservesCFG();
2567     getLoopAnalysisUsage(AU);
2568   }
2569 };
2570 
2571 } // end anonymous namespace
2572 
2573 char IndVarSimplifyLegacyPass::ID = 0;
2574 
2575 INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars",
2576                       "Induction Variable Simplification", false, false)
2577 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2578 INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars",
2579                     "Induction Variable Simplification", false, false)
2580 
2581 Pass *llvm::createIndVarSimplifyPass() {
2582   return new IndVarSimplifyLegacyPass();
2583 }
2584