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