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