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