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