use different name for parameter to make it clear that we set DIDescriptor::GV
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
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 file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle.  These classes are reference counted, managed by the SCEVHandle
18 // class.  We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
20 //
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
26 //
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression.  These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
31 //
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
35 //
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
38 //
39 //===----------------------------------------------------------------------===//
40 //
41 // There are several good references for the techniques used in this analysis.
42 //
43 //  Chains of recurrences -- a method to expedite the evaluation
44 //  of closed-form functions
45 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 //
47 //  On computational properties of chains of recurrences
48 //  Eugene V. Zima
49 //
50 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 //  Robert A. van Engelen
52 //
53 //  Efficient Symbolic Analysis for Optimizing Compilers
54 //  Robert A. van Engelen
55 //
56 //  Using the chains of recurrences algebra for data dependence testing and
57 //  induction variable substitution
58 //  MS Thesis, Johnie Birch
59 //
60 //===----------------------------------------------------------------------===//
61
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
81 #include <ostream>
82 #include <algorithm>
83 #include <cmath>
84 using namespace llvm;
85
86 STATISTIC(NumArrayLenItCounts,
87           "Number of trip counts computed with array length");
88 STATISTIC(NumTripCountsComputed,
89           "Number of loops with predictable loop counts");
90 STATISTIC(NumTripCountsNotComputed,
91           "Number of loops without predictable loop counts");
92 STATISTIC(NumBruteForceTripCountsComputed,
93           "Number of loops with trip counts computed by force");
94
95 static cl::opt<unsigned>
96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97                         cl::desc("Maximum number of iterations SCEV will "
98                                  "symbolically execute a constant derived loop"),
99                         cl::init(100));
100
101 static RegisterPass<ScalarEvolution>
102 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
103 char ScalarEvolution::ID = 0;
104
105 //===----------------------------------------------------------------------===//
106 //                           SCEV class definitions
107 //===----------------------------------------------------------------------===//
108
109 //===----------------------------------------------------------------------===//
110 // Implementation of the SCEV class.
111 //
112 SCEV::~SCEV() {}
113 void SCEV::dump() const {
114   print(cerr);
115   cerr << '\n';
116 }
117
118 uint32_t SCEV::getBitWidth() const {
119   if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120     return ITy->getBitWidth();
121   return 0;
122 }
123
124 bool SCEV::isZero() const {
125   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126     return SC->getValue()->isZero();
127   return false;
128 }
129
130
131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132
133 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
135   return false;
136 }
137
138 const Type *SCEVCouldNotCompute::getType() const {
139   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140   return 0;
141 }
142
143 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145   return false;
146 }
147
148 SCEVHandle SCEVCouldNotCompute::
149 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
150                                   const SCEVHandle &Conc,
151                                   ScalarEvolution &SE) const {
152   return this;
153 }
154
155 void SCEVCouldNotCompute::print(std::ostream &OS) const {
156   OS << "***COULDNOTCOMPUTE***";
157 }
158
159 bool SCEVCouldNotCompute::classof(const SCEV *S) {
160   return S->getSCEVType() == scCouldNotCompute;
161 }
162
163
164 // SCEVConstants - Only allow the creation of one SCEVConstant for any
165 // particular value.  Don't use a SCEVHandle here, or else the object will
166 // never be deleted!
167 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
168
169
170 SCEVConstant::~SCEVConstant() {
171   SCEVConstants->erase(V);
172 }
173
174 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
175   SCEVConstant *&R = (*SCEVConstants)[V];
176   if (R == 0) R = new SCEVConstant(V);
177   return R;
178 }
179
180 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181   return getConstant(ConstantInt::get(Val));
182 }
183
184 const Type *SCEVConstant::getType() const { return V->getType(); }
185
186 void SCEVConstant::print(std::ostream &OS) const {
187   WriteAsOperand(OS, V, false);
188 }
189
190 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191 // particular input.  Don't use a SCEVHandle here, or else the object will
192 // never be deleted!
193 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 
194                      SCEVTruncateExpr*> > SCEVTruncates;
195
196 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197   : SCEV(scTruncate), Op(op), Ty(ty) {
198   assert(Op->getType()->isInteger() && Ty->isInteger() &&
199          "Cannot truncate non-integer value!");
200   assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201          && "This is not a truncating conversion!");
202 }
203
204 SCEVTruncateExpr::~SCEVTruncateExpr() {
205   SCEVTruncates->erase(std::make_pair(Op, Ty));
206 }
207
208 void SCEVTruncateExpr::print(std::ostream &OS) const {
209   OS << "(truncate " << *Op << " to " << *Ty << ")";
210 }
211
212 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213 // particular input.  Don't use a SCEVHandle here, or else the object will never
214 // be deleted!
215 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216                      SCEVZeroExtendExpr*> > SCEVZeroExtends;
217
218 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
219   : SCEV(scZeroExtend), Op(op), Ty(ty) {
220   assert(Op->getType()->isInteger() && Ty->isInteger() &&
221          "Cannot zero extend non-integer value!");
222   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223          && "This is not an extending conversion!");
224 }
225
226 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
227   SCEVZeroExtends->erase(std::make_pair(Op, Ty));
228 }
229
230 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231   OS << "(zeroextend " << *Op << " to " << *Ty << ")";
232 }
233
234 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235 // particular input.  Don't use a SCEVHandle here, or else the object will never
236 // be deleted!
237 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238                      SCEVSignExtendExpr*> > SCEVSignExtends;
239
240 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241   : SCEV(scSignExtend), Op(op), Ty(ty) {
242   assert(Op->getType()->isInteger() && Ty->isInteger() &&
243          "Cannot sign extend non-integer value!");
244   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245          && "This is not an extending conversion!");
246 }
247
248 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249   SCEVSignExtends->erase(std::make_pair(Op, Ty));
250 }
251
252 void SCEVSignExtendExpr::print(std::ostream &OS) const {
253   OS << "(signextend " << *Op << " to " << *Ty << ")";
254 }
255
256 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257 // particular input.  Don't use a SCEVHandle here, or else the object will never
258 // be deleted!
259 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260                      SCEVCommutativeExpr*> > SCEVCommExprs;
261
262 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
263   SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264                                       std::vector<SCEV*>(Operands.begin(),
265                                                          Operands.end())));
266 }
267
268 void SCEVCommutativeExpr::print(std::ostream &OS) const {
269   assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270   const char *OpStr = getOperationStr();
271   OS << "(" << *Operands[0];
272   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273     OS << OpStr << *Operands[i];
274   OS << ")";
275 }
276
277 SCEVHandle SCEVCommutativeExpr::
278 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
279                                   const SCEVHandle &Conc,
280                                   ScalarEvolution &SE) const {
281   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
282     SCEVHandle H =
283       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
284     if (H != getOperand(i)) {
285       std::vector<SCEVHandle> NewOps;
286       NewOps.reserve(getNumOperands());
287       for (unsigned j = 0; j != i; ++j)
288         NewOps.push_back(getOperand(j));
289       NewOps.push_back(H);
290       for (++i; i != e; ++i)
291         NewOps.push_back(getOperand(i)->
292                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
293
294       if (isa<SCEVAddExpr>(this))
295         return SE.getAddExpr(NewOps);
296       else if (isa<SCEVMulExpr>(this))
297         return SE.getMulExpr(NewOps);
298       else if (isa<SCEVSMaxExpr>(this))
299         return SE.getSMaxExpr(NewOps);
300       else if (isa<SCEVUMaxExpr>(this))
301         return SE.getUMaxExpr(NewOps);
302       else
303         assert(0 && "Unknown commutative expr!");
304     }
305   }
306   return this;
307 }
308
309
310 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
311 // input.  Don't use a SCEVHandle here, or else the object will never be
312 // deleted!
313 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 
314                      SCEVUDivExpr*> > SCEVUDivs;
315
316 SCEVUDivExpr::~SCEVUDivExpr() {
317   SCEVUDivs->erase(std::make_pair(LHS, RHS));
318 }
319
320 void SCEVUDivExpr::print(std::ostream &OS) const {
321   OS << "(" << *LHS << " /u " << *RHS << ")";
322 }
323
324 const Type *SCEVUDivExpr::getType() const {
325   return LHS->getType();
326 }
327
328
329 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
330 // input.  Don't use a SCEVHandle here, or else the object will never be
331 // deleted!
332 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 
333                      SCEVSDivExpr*> > SCEVSDivs;
334
335 SCEVSDivExpr::~SCEVSDivExpr() {
336   SCEVSDivs->erase(std::make_pair(LHS, RHS));
337 }
338
339 void SCEVSDivExpr::print(std::ostream &OS) const {
340   OS << "(" << *LHS << " /s " << *RHS << ")";
341 }
342
343 const Type *SCEVSDivExpr::getType() const {
344   return LHS->getType();
345 }
346
347
348 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
349 // particular input.  Don't use a SCEVHandle here, or else the object will never
350 // be deleted!
351 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
352                      SCEVAddRecExpr*> > SCEVAddRecExprs;
353
354 SCEVAddRecExpr::~SCEVAddRecExpr() {
355   SCEVAddRecExprs->erase(std::make_pair(L,
356                                         std::vector<SCEV*>(Operands.begin(),
357                                                            Operands.end())));
358 }
359
360 SCEVHandle SCEVAddRecExpr::
361 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
362                                   const SCEVHandle &Conc,
363                                   ScalarEvolution &SE) const {
364   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365     SCEVHandle H =
366       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
367     if (H != getOperand(i)) {
368       std::vector<SCEVHandle> NewOps;
369       NewOps.reserve(getNumOperands());
370       for (unsigned j = 0; j != i; ++j)
371         NewOps.push_back(getOperand(j));
372       NewOps.push_back(H);
373       for (++i; i != e; ++i)
374         NewOps.push_back(getOperand(i)->
375                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
376
377       return SE.getAddRecExpr(NewOps, L);
378     }
379   }
380   return this;
381 }
382
383
384 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
385   // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
386   // contain L and if the start is invariant.
387   return !QueryLoop->contains(L->getHeader()) &&
388          getOperand(0)->isLoopInvariant(QueryLoop);
389 }
390
391
392 void SCEVAddRecExpr::print(std::ostream &OS) const {
393   OS << "{" << *Operands[0];
394   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
395     OS << ",+," << *Operands[i];
396   OS << "}<" << L->getHeader()->getName() + ">";
397 }
398
399 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
400 // value.  Don't use a SCEVHandle here, or else the object will never be
401 // deleted!
402 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
403
404 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
405
406 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
407   // All non-instruction values are loop invariant.  All instructions are loop
408   // invariant if they are not contained in the specified loop.
409   if (Instruction *I = dyn_cast<Instruction>(V))
410     return !L->contains(I->getParent());
411   return true;
412 }
413
414 const Type *SCEVUnknown::getType() const {
415   return V->getType();
416 }
417
418 void SCEVUnknown::print(std::ostream &OS) const {
419   WriteAsOperand(OS, V, false);
420 }
421
422 //===----------------------------------------------------------------------===//
423 //                               SCEV Utilities
424 //===----------------------------------------------------------------------===//
425
426 namespace {
427   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
428   /// than the complexity of the RHS.  This comparator is used to canonicalize
429   /// expressions.
430   struct VISIBILITY_HIDDEN SCEVComplexityCompare {
431     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
432       return LHS->getSCEVType() < RHS->getSCEVType();
433     }
434   };
435 }
436
437 /// GroupByComplexity - Given a list of SCEV objects, order them by their
438 /// complexity, and group objects of the same complexity together by value.
439 /// When this routine is finished, we know that any duplicates in the vector are
440 /// consecutive and that complexity is monotonically increasing.
441 ///
442 /// Note that we go take special precautions to ensure that we get determinstic
443 /// results from this routine.  In other words, we don't want the results of
444 /// this to depend on where the addresses of various SCEV objects happened to
445 /// land in memory.
446 ///
447 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
448   if (Ops.size() < 2) return;  // Noop
449   if (Ops.size() == 2) {
450     // This is the common case, which also happens to be trivially simple.
451     // Special case it.
452     if (SCEVComplexityCompare()(Ops[1], Ops[0]))
453       std::swap(Ops[0], Ops[1]);
454     return;
455   }
456
457   // Do the rough sort by complexity.
458   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
459
460   // Now that we are sorted by complexity, group elements of the same
461   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
462   // be extremely short in practice.  Note that we take this approach because we
463   // do not want to depend on the addresses of the objects we are grouping.
464   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
465     SCEV *S = Ops[i];
466     unsigned Complexity = S->getSCEVType();
467
468     // If there are any objects of the same complexity and same value as this
469     // one, group them.
470     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
471       if (Ops[j] == S) { // Found a duplicate.
472         // Move it to immediately after i'th element.
473         std::swap(Ops[i+1], Ops[j]);
474         ++i;   // no need to rescan it.
475         if (i == e-2) return;  // Done!
476       }
477     }
478   }
479 }
480
481
482
483 //===----------------------------------------------------------------------===//
484 //                      Simple SCEV method implementations
485 //===----------------------------------------------------------------------===//
486
487 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
488 /// specified signed integer value and return a SCEV for the constant.
489 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
490   Constant *C;
491   if (Val == 0)
492     C = Constant::getNullValue(Ty);
493   else if (Ty->isFloatingPoint())
494     C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle : 
495                                 APFloat::IEEEdouble, Val));
496   else 
497     C = ConstantInt::get(Ty, Val);
498   return getUnknown(C);
499 }
500
501 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
502 ///
503 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
504   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
505     return getUnknown(ConstantExpr::getNeg(VC->getValue()));
506
507   return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
508 }
509
510 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
511 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
512   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
513     return getUnknown(ConstantExpr::getNot(VC->getValue()));
514
515   SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
516   return getMinusSCEV(AllOnes, V);
517 }
518
519 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
520 ///
521 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
522                                          const SCEVHandle &RHS) {
523   // X - Y --> X + -Y
524   return getAddExpr(LHS, getNegativeSCEV(RHS));
525 }
526
527
528 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
529 // Assume, K > 0.
530 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
531                                       ScalarEvolution &SE,
532                                       const IntegerType* ResultTy) {
533   // Handle the simplest case efficiently.
534   if (K == 1)
535     return SE.getTruncateOrZeroExtend(It, ResultTy);
536
537   // We are using the following formula for BC(It, K):
538   //
539   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
540   //
541   // Suppose, W is the bitwidth of the return value.  We must be prepared for
542   // overflow.  Hence, we must assure that the result of our computation is
543   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
544   // safe in modular arithmetic.
545   //
546   // However, this code doesn't use exactly that formula; the formula it uses
547   // is something like the following, where T is the number of factors of 2 in 
548   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
549   // exponentiation:
550   //
551   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
552   //
553   // This formula is trivially equivalent to the previous formula.  However,
554   // this formula can be implemented much more efficiently.  The trick is that
555   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
556   // arithmetic.  To do exact division in modular arithmetic, all we have
557   // to do is multiply by the inverse.  Therefore, this step can be done at
558   // width W.
559   // 
560   // The next issue is how to safely do the division by 2^T.  The way this
561   // is done is by doing the multiplication step at a width of at least W + T
562   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
563   // when we perform the division by 2^T (which is equivalent to a right shift
564   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
565   // truncated out after the division by 2^T.
566   //
567   // In comparison to just directly using the first formula, this technique
568   // is much more efficient; using the first formula requires W * K bits,
569   // but this formula less than W + K bits. Also, the first formula requires
570   // a division step, whereas this formula only requires multiplies and shifts.
571   //
572   // It doesn't matter whether the subtraction step is done in the calculation
573   // width or the input iteration count's width; if the subtraction overflows,
574   // the result must be zero anyway.  We prefer here to do it in the width of
575   // the induction variable because it helps a lot for certain cases; CodeGen
576   // isn't smart enough to ignore the overflow, which leads to much less
577   // efficient code if the width of the subtraction is wider than the native
578   // register width.
579   //
580   // (It's possible to not widen at all by pulling out factors of 2 before
581   // the multiplication; for example, K=2 can be calculated as
582   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
583   // extra arithmetic, so it's not an obvious win, and it gets
584   // much more complicated for K > 3.)
585
586   // Protection from insane SCEVs; this bound is conservative,
587   // but it probably doesn't matter.
588   if (K > 1000)
589     return new SCEVCouldNotCompute();
590
591   unsigned W = ResultTy->getBitWidth();
592
593   // Calculate K! / 2^T and T; we divide out the factors of two before
594   // multiplying for calculating K! / 2^T to avoid overflow.
595   // Other overflow doesn't matter because we only care about the bottom
596   // W bits of the result.
597   APInt OddFactorial(W, 1);
598   unsigned T = 1;
599   for (unsigned i = 3; i <= K; ++i) {
600     APInt Mult(W, i);
601     unsigned TwoFactors = Mult.countTrailingZeros();
602     T += TwoFactors;
603     Mult = Mult.lshr(TwoFactors);
604     OddFactorial *= Mult;
605   }
606
607   // We need at least W + T bits for the multiplication step
608   // FIXME: A temporary hack; we round up the bitwidths
609   // to the nearest power of 2 to be nice to the code generator.
610   unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
611   // FIXME: Temporary hack to avoid generating integers that are too wide.
612   // Although, it's not completely clear how to determine how much
613   // widening is safe; for example, on X86, we can't really widen
614   // beyond 64 because we need to be able to do multiplication
615   // that's CalculationBits wide, but on X86-64, we can safely widen up to
616   // 128 bits.
617   if (CalculationBits > 64)
618     return new SCEVCouldNotCompute();
619
620   // Calcuate 2^T, at width T+W.
621   APInt DivFactor = APInt(CalculationBits, 1).shl(T);
622
623   // Calculate the multiplicative inverse of K! / 2^T;
624   // this multiplication factor will perform the exact division by
625   // K! / 2^T.
626   APInt Mod = APInt::getSignedMinValue(W+1);
627   APInt MultiplyFactor = OddFactorial.zext(W+1);
628   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
629   MultiplyFactor = MultiplyFactor.trunc(W);
630
631   // Calculate the product, at width T+W
632   const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
633   SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
634   for (unsigned i = 1; i != K; ++i) {
635     SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
636     Dividend = SE.getMulExpr(Dividend,
637                              SE.getTruncateOrZeroExtend(S, CalculationTy));
638   }
639
640   // Divide by 2^T
641   SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
642
643   // Truncate the result, and divide by K! / 2^T.
644
645   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
646                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
647 }
648
649 /// evaluateAtIteration - Return the value of this chain of recurrences at
650 /// the specified iteration number.  We can evaluate this recurrence by
651 /// multiplying each element in the chain by the binomial coefficient
652 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
653 ///
654 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
655 ///
656 /// where BC(It, k) stands for binomial coefficient.
657 ///
658 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
659                                                ScalarEvolution &SE) const {
660   SCEVHandle Result = getStart();
661   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
662     // The computation is correct in the face of overflow provided that the
663     // multiplication is performed _after_ the evaluation of the binomial
664     // coefficient.
665     SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
666                                            cast<IntegerType>(getType()));
667     if (isa<SCEVCouldNotCompute>(Coeff))
668       return Coeff;
669
670     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
671   }
672   return Result;
673 }
674
675 //===----------------------------------------------------------------------===//
676 //                    SCEV Expression folder implementations
677 //===----------------------------------------------------------------------===//
678
679 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
680   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
681     return getUnknown(
682         ConstantExpr::getTrunc(SC->getValue(), Ty));
683
684   // If the input value is a chrec scev made out of constants, truncate
685   // all of the constants.
686   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
687     std::vector<SCEVHandle> Operands;
688     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
689       // FIXME: This should allow truncation of other expression types!
690       if (isa<SCEVConstant>(AddRec->getOperand(i)))
691         Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
692       else
693         break;
694     if (Operands.size() == AddRec->getNumOperands())
695       return getAddRecExpr(Operands, AddRec->getLoop());
696   }
697
698   SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
699   if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
700   return Result;
701 }
702
703 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
704   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
705     return getUnknown(
706         ConstantExpr::getZExt(SC->getValue(), Ty));
707
708   // FIXME: If the input value is a chrec scev, and we can prove that the value
709   // did not overflow the old, smaller, value, we can zero extend all of the
710   // operands (often constants).  This would allow analysis of something like
711   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
712
713   SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
714   if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
715   return Result;
716 }
717
718 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
719   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
720     return getUnknown(
721         ConstantExpr::getSExt(SC->getValue(), Ty));
722
723   // FIXME: If the input value is a chrec scev, and we can prove that the value
724   // did not overflow the old, smaller, value, we can sign extend all of the
725   // operands (often constants).  This would allow analysis of something like
726   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
727
728   SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
729   if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
730   return Result;
731 }
732
733 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
734 /// of the input value to the specified type.  If the type must be
735 /// extended, it is zero extended.
736 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
737                                                     const Type *Ty) {
738   const Type *SrcTy = V->getType();
739   assert(SrcTy->isInteger() && Ty->isInteger() &&
740          "Cannot truncate or zero extend with non-integer arguments!");
741   if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
742     return V;  // No conversion
743   if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
744     return getTruncateExpr(V, Ty);
745   return getZeroExtendExpr(V, Ty);
746 }
747
748 // get - Get a canonical add expression, or something simpler if possible.
749 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
750   assert(!Ops.empty() && "Cannot get empty add!");
751   if (Ops.size() == 1) return Ops[0];
752
753   // Sort by complexity, this groups all similar expression types together.
754   GroupByComplexity(Ops);
755
756   // If there are any constants, fold them together.
757   unsigned Idx = 0;
758   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
759     ++Idx;
760     assert(Idx < Ops.size());
761     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
762       // We found two constants, fold them together!
763       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 
764                                            RHSC->getValue()->getValue());
765       Ops[0] = getConstant(Fold);
766       Ops.erase(Ops.begin()+1);  // Erase the folded element
767       if (Ops.size() == 1) return Ops[0];
768       LHSC = cast<SCEVConstant>(Ops[0]);
769     }
770
771     // If we are left with a constant zero being added, strip it off.
772     if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
773       Ops.erase(Ops.begin());
774       --Idx;
775     }
776   }
777
778   if (Ops.size() == 1) return Ops[0];
779
780   // Okay, check to see if the same value occurs in the operand list twice.  If
781   // so, merge them together into an multiply expression.  Since we sorted the
782   // list, these values are required to be adjacent.
783   const Type *Ty = Ops[0]->getType();
784   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
785     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
786       // Found a match, merge the two values into a multiply, and add any
787       // remaining values to the result.
788       SCEVHandle Two = getIntegerSCEV(2, Ty);
789       SCEVHandle Mul = getMulExpr(Ops[i], Two);
790       if (Ops.size() == 2)
791         return Mul;
792       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
793       Ops.push_back(Mul);
794       return getAddExpr(Ops);
795     }
796
797   // Now we know the first non-constant operand.  Skip past any cast SCEVs.
798   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
799     ++Idx;
800
801   // If there are add operands they would be next.
802   if (Idx < Ops.size()) {
803     bool DeletedAdd = false;
804     while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
805       // If we have an add, expand the add operands onto the end of the operands
806       // list.
807       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
808       Ops.erase(Ops.begin()+Idx);
809       DeletedAdd = true;
810     }
811
812     // If we deleted at least one add, we added operands to the end of the list,
813     // and they are not necessarily sorted.  Recurse to resort and resimplify
814     // any operands we just aquired.
815     if (DeletedAdd)
816       return getAddExpr(Ops);
817   }
818
819   // Skip over the add expression until we get to a multiply.
820   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
821     ++Idx;
822
823   // If we are adding something to a multiply expression, make sure the
824   // something is not already an operand of the multiply.  If so, merge it into
825   // the multiply.
826   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
827     SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
828     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
829       SCEV *MulOpSCEV = Mul->getOperand(MulOp);
830       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
831         if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
832           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
833           SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
834           if (Mul->getNumOperands() != 2) {
835             // If the multiply has more than two operands, we must get the
836             // Y*Z term.
837             std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
838             MulOps.erase(MulOps.begin()+MulOp);
839             InnerMul = getMulExpr(MulOps);
840           }
841           SCEVHandle One = getIntegerSCEV(1, Ty);
842           SCEVHandle AddOne = getAddExpr(InnerMul, One);
843           SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
844           if (Ops.size() == 2) return OuterMul;
845           if (AddOp < Idx) {
846             Ops.erase(Ops.begin()+AddOp);
847             Ops.erase(Ops.begin()+Idx-1);
848           } else {
849             Ops.erase(Ops.begin()+Idx);
850             Ops.erase(Ops.begin()+AddOp-1);
851           }
852           Ops.push_back(OuterMul);
853           return getAddExpr(Ops);
854         }
855
856       // Check this multiply against other multiplies being added together.
857       for (unsigned OtherMulIdx = Idx+1;
858            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
859            ++OtherMulIdx) {
860         SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
861         // If MulOp occurs in OtherMul, we can fold the two multiplies
862         // together.
863         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
864              OMulOp != e; ++OMulOp)
865           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
866             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
867             SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
868             if (Mul->getNumOperands() != 2) {
869               std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
870               MulOps.erase(MulOps.begin()+MulOp);
871               InnerMul1 = getMulExpr(MulOps);
872             }
873             SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
874             if (OtherMul->getNumOperands() != 2) {
875               std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
876                                              OtherMul->op_end());
877               MulOps.erase(MulOps.begin()+OMulOp);
878               InnerMul2 = getMulExpr(MulOps);
879             }
880             SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
881             SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
882             if (Ops.size() == 2) return OuterMul;
883             Ops.erase(Ops.begin()+Idx);
884             Ops.erase(Ops.begin()+OtherMulIdx-1);
885             Ops.push_back(OuterMul);
886             return getAddExpr(Ops);
887           }
888       }
889     }
890   }
891
892   // If there are any add recurrences in the operands list, see if any other
893   // added values are loop invariant.  If so, we can fold them into the
894   // recurrence.
895   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
896     ++Idx;
897
898   // Scan over all recurrences, trying to fold loop invariants into them.
899   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
900     // Scan all of the other operands to this add and add them to the vector if
901     // they are loop invariant w.r.t. the recurrence.
902     std::vector<SCEVHandle> LIOps;
903     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
904     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
905       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
906         LIOps.push_back(Ops[i]);
907         Ops.erase(Ops.begin()+i);
908         --i; --e;
909       }
910
911     // If we found some loop invariants, fold them into the recurrence.
912     if (!LIOps.empty()) {
913       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
914       LIOps.push_back(AddRec->getStart());
915
916       std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
917       AddRecOps[0] = getAddExpr(LIOps);
918
919       SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
920       // If all of the other operands were loop invariant, we are done.
921       if (Ops.size() == 1) return NewRec;
922
923       // Otherwise, add the folded AddRec by the non-liv parts.
924       for (unsigned i = 0;; ++i)
925         if (Ops[i] == AddRec) {
926           Ops[i] = NewRec;
927           break;
928         }
929       return getAddExpr(Ops);
930     }
931
932     // Okay, if there weren't any loop invariants to be folded, check to see if
933     // there are multiple AddRec's with the same loop induction variable being
934     // added together.  If so, we can fold them.
935     for (unsigned OtherIdx = Idx+1;
936          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
937       if (OtherIdx != Idx) {
938         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
939         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
940           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
941           std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
942           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
943             if (i >= NewOps.size()) {
944               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
945                             OtherAddRec->op_end());
946               break;
947             }
948             NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
949           }
950           SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
951
952           if (Ops.size() == 2) return NewAddRec;
953
954           Ops.erase(Ops.begin()+Idx);
955           Ops.erase(Ops.begin()+OtherIdx-1);
956           Ops.push_back(NewAddRec);
957           return getAddExpr(Ops);
958         }
959       }
960
961     // Otherwise couldn't fold anything into this recurrence.  Move onto the
962     // next one.
963   }
964
965   // Okay, it looks like we really DO need an add expr.  Check to see if we
966   // already have one, otherwise create a new one.
967   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
968   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
969                                                                  SCEVOps)];
970   if (Result == 0) Result = new SCEVAddExpr(Ops);
971   return Result;
972 }
973
974
975 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
976   assert(!Ops.empty() && "Cannot get empty mul!");
977
978   // Sort by complexity, this groups all similar expression types together.
979   GroupByComplexity(Ops);
980
981   // If there are any constants, fold them together.
982   unsigned Idx = 0;
983   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
984
985     // C1*(C2+V) -> C1*C2 + C1*V
986     if (Ops.size() == 2)
987       if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
988         if (Add->getNumOperands() == 2 &&
989             isa<SCEVConstant>(Add->getOperand(0)))
990           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
991                             getMulExpr(LHSC, Add->getOperand(1)));
992
993
994     ++Idx;
995     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
996       // We found two constants, fold them together!
997       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 
998                                            RHSC->getValue()->getValue());
999       Ops[0] = getConstant(Fold);
1000       Ops.erase(Ops.begin()+1);  // Erase the folded element
1001       if (Ops.size() == 1) return Ops[0];
1002       LHSC = cast<SCEVConstant>(Ops[0]);
1003     }
1004
1005     // If we are left with a constant one being multiplied, strip it off.
1006     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1007       Ops.erase(Ops.begin());
1008       --Idx;
1009     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1010       // If we have a multiply of zero, it will always be zero.
1011       return Ops[0];
1012     }
1013   }
1014
1015   // Skip over the add expression until we get to a multiply.
1016   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1017     ++Idx;
1018
1019   if (Ops.size() == 1)
1020     return Ops[0];
1021
1022   // If there are mul operands inline them all into this expression.
1023   if (Idx < Ops.size()) {
1024     bool DeletedMul = false;
1025     while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1026       // If we have an mul, expand the mul operands onto the end of the operands
1027       // list.
1028       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1029       Ops.erase(Ops.begin()+Idx);
1030       DeletedMul = true;
1031     }
1032
1033     // If we deleted at least one mul, we added operands to the end of the list,
1034     // and they are not necessarily sorted.  Recurse to resort and resimplify
1035     // any operands we just aquired.
1036     if (DeletedMul)
1037       return getMulExpr(Ops);
1038   }
1039
1040   // If there are any add recurrences in the operands list, see if any other
1041   // added values are loop invariant.  If so, we can fold them into the
1042   // recurrence.
1043   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1044     ++Idx;
1045
1046   // Scan over all recurrences, trying to fold loop invariants into them.
1047   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1048     // Scan all of the other operands to this mul and add them to the vector if
1049     // they are loop invariant w.r.t. the recurrence.
1050     std::vector<SCEVHandle> LIOps;
1051     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1052     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1053       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1054         LIOps.push_back(Ops[i]);
1055         Ops.erase(Ops.begin()+i);
1056         --i; --e;
1057       }
1058
1059     // If we found some loop invariants, fold them into the recurrence.
1060     if (!LIOps.empty()) {
1061       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
1062       std::vector<SCEVHandle> NewOps;
1063       NewOps.reserve(AddRec->getNumOperands());
1064       if (LIOps.size() == 1) {
1065         SCEV *Scale = LIOps[0];
1066         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1067           NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1068       } else {
1069         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1070           std::vector<SCEVHandle> MulOps(LIOps);
1071           MulOps.push_back(AddRec->getOperand(i));
1072           NewOps.push_back(getMulExpr(MulOps));
1073         }
1074       }
1075
1076       SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1077
1078       // If all of the other operands were loop invariant, we are done.
1079       if (Ops.size() == 1) return NewRec;
1080
1081       // Otherwise, multiply the folded AddRec by the non-liv parts.
1082       for (unsigned i = 0;; ++i)
1083         if (Ops[i] == AddRec) {
1084           Ops[i] = NewRec;
1085           break;
1086         }
1087       return getMulExpr(Ops);
1088     }
1089
1090     // Okay, if there weren't any loop invariants to be folded, check to see if
1091     // there are multiple AddRec's with the same loop induction variable being
1092     // multiplied together.  If so, we can fold them.
1093     for (unsigned OtherIdx = Idx+1;
1094          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1095       if (OtherIdx != Idx) {
1096         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1097         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1098           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
1099           SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1100           SCEVHandle NewStart = getMulExpr(F->getStart(),
1101                                                  G->getStart());
1102           SCEVHandle B = F->getStepRecurrence(*this);
1103           SCEVHandle D = G->getStepRecurrence(*this);
1104           SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1105                                           getMulExpr(G, B),
1106                                           getMulExpr(B, D));
1107           SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1108                                                F->getLoop());
1109           if (Ops.size() == 2) return NewAddRec;
1110
1111           Ops.erase(Ops.begin()+Idx);
1112           Ops.erase(Ops.begin()+OtherIdx-1);
1113           Ops.push_back(NewAddRec);
1114           return getMulExpr(Ops);
1115         }
1116       }
1117
1118     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1119     // next one.
1120   }
1121
1122   // Okay, it looks like we really DO need an mul expr.  Check to see if we
1123   // already have one, otherwise create a new one.
1124   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1125   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1126                                                                  SCEVOps)];
1127   if (Result == 0)
1128     Result = new SCEVMulExpr(Ops);
1129   return Result;
1130 }
1131
1132 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1133   if (LHS == RHS)
1134     return getIntegerSCEV(1, LHS->getType());  // X udiv X --> 1
1135
1136   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1137     if (RHSC->getValue()->equalsInt(1))
1138       return LHS;                              // X udiv 1 --> X
1139
1140     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1141       Constant *LHSCV = LHSC->getValue();
1142       Constant *RHSCV = RHSC->getValue();
1143       return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1144     }
1145   }
1146
1147   SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1148   if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1149   return Result;
1150 }
1151
1152 SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1153   if (LHS == RHS)                            
1154     return getIntegerSCEV(1, LHS->getType());  // X sdiv X --> 1
1155
1156   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1157     if (RHSC->getValue()->equalsInt(1))
1158       return LHS;                              // X sdiv 1 --> X
1159
1160     if (RHSC->getValue()->isAllOnesValue())
1161       return getNegativeSCEV(LHS);             // X sdiv -1 --> -X
1162
1163     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1164       Constant *LHSCV = LHSC->getValue();
1165       Constant *RHSCV = RHSC->getValue();
1166       return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
1167     }
1168   }
1169
1170   SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1171   if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1172   return Result;
1173 }
1174
1175
1176 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1177 /// specified loop.  Simplify the expression as much as possible.
1178 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1179                                const SCEVHandle &Step, const Loop *L) {
1180   std::vector<SCEVHandle> Operands;
1181   Operands.push_back(Start);
1182   if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1183     if (StepChrec->getLoop() == L) {
1184       Operands.insert(Operands.end(), StepChrec->op_begin(),
1185                       StepChrec->op_end());
1186       return getAddRecExpr(Operands, L);
1187     }
1188
1189   Operands.push_back(Step);
1190   return getAddRecExpr(Operands, L);
1191 }
1192
1193 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1194 /// specified loop.  Simplify the expression as much as possible.
1195 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1196                                const Loop *L) {
1197   if (Operands.size() == 1) return Operands[0];
1198
1199   if (Operands.back()->isZero()) {
1200     Operands.pop_back();
1201     return getAddRecExpr(Operands, L);             // {X,+,0}  -->  X
1202   }
1203
1204   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1205   if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1206     const Loop* NestedLoop = NestedAR->getLoop();
1207     if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1208       std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1209                                              NestedAR->op_end());
1210       SCEVHandle NestedARHandle(NestedAR);
1211       Operands[0] = NestedAR->getStart();
1212       NestedOperands[0] = getAddRecExpr(Operands, L);
1213       return getAddRecExpr(NestedOperands, NestedLoop);
1214     }
1215   }
1216
1217   SCEVAddRecExpr *&Result =
1218     (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1219                                                             Operands.end()))];
1220   if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1221   return Result;
1222 }
1223
1224 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1225                                         const SCEVHandle &RHS) {
1226   std::vector<SCEVHandle> Ops;
1227   Ops.push_back(LHS);
1228   Ops.push_back(RHS);
1229   return getSMaxExpr(Ops);
1230 }
1231
1232 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1233   assert(!Ops.empty() && "Cannot get empty smax!");
1234   if (Ops.size() == 1) return Ops[0];
1235
1236   // Sort by complexity, this groups all similar expression types together.
1237   GroupByComplexity(Ops);
1238
1239   // If there are any constants, fold them together.
1240   unsigned Idx = 0;
1241   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1242     ++Idx;
1243     assert(Idx < Ops.size());
1244     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1245       // We found two constants, fold them together!
1246       ConstantInt *Fold = ConstantInt::get(
1247                               APIntOps::smax(LHSC->getValue()->getValue(),
1248                                              RHSC->getValue()->getValue()));
1249       Ops[0] = getConstant(Fold);
1250       Ops.erase(Ops.begin()+1);  // Erase the folded element
1251       if (Ops.size() == 1) return Ops[0];
1252       LHSC = cast<SCEVConstant>(Ops[0]);
1253     }
1254
1255     // If we are left with a constant -inf, strip it off.
1256     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1257       Ops.erase(Ops.begin());
1258       --Idx;
1259     }
1260   }
1261
1262   if (Ops.size() == 1) return Ops[0];
1263
1264   // Find the first SMax
1265   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1266     ++Idx;
1267
1268   // Check to see if one of the operands is an SMax. If so, expand its operands
1269   // onto our operand list, and recurse to simplify.
1270   if (Idx < Ops.size()) {
1271     bool DeletedSMax = false;
1272     while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1273       Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1274       Ops.erase(Ops.begin()+Idx);
1275       DeletedSMax = true;
1276     }
1277
1278     if (DeletedSMax)
1279       return getSMaxExpr(Ops);
1280   }
1281
1282   // Okay, check to see if the same value occurs in the operand list twice.  If
1283   // so, delete one.  Since we sorted the list, these values are required to
1284   // be adjacent.
1285   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1286     if (Ops[i] == Ops[i+1]) {      //  X smax Y smax Y  -->  X smax Y
1287       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1288       --i; --e;
1289     }
1290
1291   if (Ops.size() == 1) return Ops[0];
1292
1293   assert(!Ops.empty() && "Reduced smax down to nothing!");
1294
1295   // Okay, it looks like we really DO need an smax expr.  Check to see if we
1296   // already have one, otherwise create a new one.
1297   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1298   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1299                                                                  SCEVOps)];
1300   if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1301   return Result;
1302 }
1303
1304 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1305                                         const SCEVHandle &RHS) {
1306   std::vector<SCEVHandle> Ops;
1307   Ops.push_back(LHS);
1308   Ops.push_back(RHS);
1309   return getUMaxExpr(Ops);
1310 }
1311
1312 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1313   assert(!Ops.empty() && "Cannot get empty umax!");
1314   if (Ops.size() == 1) return Ops[0];
1315
1316   // Sort by complexity, this groups all similar expression types together.
1317   GroupByComplexity(Ops);
1318
1319   // If there are any constants, fold them together.
1320   unsigned Idx = 0;
1321   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1322     ++Idx;
1323     assert(Idx < Ops.size());
1324     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1325       // We found two constants, fold them together!
1326       ConstantInt *Fold = ConstantInt::get(
1327                               APIntOps::umax(LHSC->getValue()->getValue(),
1328                                              RHSC->getValue()->getValue()));
1329       Ops[0] = getConstant(Fold);
1330       Ops.erase(Ops.begin()+1);  // Erase the folded element
1331       if (Ops.size() == 1) return Ops[0];
1332       LHSC = cast<SCEVConstant>(Ops[0]);
1333     }
1334
1335     // If we are left with a constant zero, strip it off.
1336     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1337       Ops.erase(Ops.begin());
1338       --Idx;
1339     }
1340   }
1341
1342   if (Ops.size() == 1) return Ops[0];
1343
1344   // Find the first UMax
1345   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1346     ++Idx;
1347
1348   // Check to see if one of the operands is a UMax. If so, expand its operands
1349   // onto our operand list, and recurse to simplify.
1350   if (Idx < Ops.size()) {
1351     bool DeletedUMax = false;
1352     while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1353       Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1354       Ops.erase(Ops.begin()+Idx);
1355       DeletedUMax = true;
1356     }
1357
1358     if (DeletedUMax)
1359       return getUMaxExpr(Ops);
1360   }
1361
1362   // Okay, check to see if the same value occurs in the operand list twice.  If
1363   // so, delete one.  Since we sorted the list, these values are required to
1364   // be adjacent.
1365   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1366     if (Ops[i] == Ops[i+1]) {      //  X umax Y umax Y  -->  X umax Y
1367       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1368       --i; --e;
1369     }
1370
1371   if (Ops.size() == 1) return Ops[0];
1372
1373   assert(!Ops.empty() && "Reduced umax down to nothing!");
1374
1375   // Okay, it looks like we really DO need a umax expr.  Check to see if we
1376   // already have one, otherwise create a new one.
1377   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1378   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1379                                                                  SCEVOps)];
1380   if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1381   return Result;
1382 }
1383
1384 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1385   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1386     return getConstant(CI);
1387   SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1388   if (Result == 0) Result = new SCEVUnknown(V);
1389   return Result;
1390 }
1391
1392
1393 //===----------------------------------------------------------------------===//
1394 //             ScalarEvolutionsImpl Definition and Implementation
1395 //===----------------------------------------------------------------------===//
1396 //
1397 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1398 /// evolution code.
1399 ///
1400 namespace {
1401   struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1402     /// SE - A reference to the public ScalarEvolution object.
1403     ScalarEvolution &SE;
1404
1405     /// F - The function we are analyzing.
1406     ///
1407     Function &F;
1408
1409     /// LI - The loop information for the function we are currently analyzing.
1410     ///
1411     LoopInfo &LI;
1412
1413     /// UnknownValue - This SCEV is used to represent unknown trip counts and
1414     /// things.
1415     SCEVHandle UnknownValue;
1416
1417     /// Scalars - This is a cache of the scalars we have analyzed so far.
1418     ///
1419     std::map<Value*, SCEVHandle> Scalars;
1420
1421     /// IterationCounts - Cache the iteration count of the loops for this
1422     /// function as they are computed.
1423     std::map<const Loop*, SCEVHandle> IterationCounts;
1424
1425     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1426     /// the PHI instructions that we attempt to compute constant evolutions for.
1427     /// This allows us to avoid potentially expensive recomputation of these
1428     /// properties.  An instruction maps to null if we are unable to compute its
1429     /// exit value.
1430     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1431
1432   public:
1433     ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1434       : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1435
1436     /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1437     /// expression and create a new one.
1438     SCEVHandle getSCEV(Value *V);
1439
1440     /// hasSCEV - Return true if the SCEV for this value has already been
1441     /// computed.
1442     bool hasSCEV(Value *V) const {
1443       return Scalars.count(V);
1444     }
1445
1446     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1447     /// the specified value.
1448     void setSCEV(Value *V, const SCEVHandle &H) {
1449       bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1450       assert(isNew && "This entry already existed!");
1451       isNew = false;
1452     }
1453
1454
1455     /// getSCEVAtScope - Compute the value of the specified expression within
1456     /// the indicated loop (which may be null to indicate in no loop).  If the
1457     /// expression cannot be evaluated, return UnknownValue itself.
1458     SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1459
1460
1461     /// hasLoopInvariantIterationCount - Return true if the specified loop has
1462     /// an analyzable loop-invariant iteration count.
1463     bool hasLoopInvariantIterationCount(const Loop *L);
1464
1465     /// getIterationCount - If the specified loop has a predictable iteration
1466     /// count, return it.  Note that it is not valid to call this method on a
1467     /// loop without a loop-invariant iteration count.
1468     SCEVHandle getIterationCount(const Loop *L);
1469
1470     /// deleteValueFromRecords - This method should be called by the
1471     /// client before it removes a value from the program, to make sure
1472     /// that no dangling references are left around.
1473     void deleteValueFromRecords(Value *V);
1474
1475   private:
1476     /// createSCEV - We know that there is no SCEV for the specified value.
1477     /// Analyze the expression.
1478     SCEVHandle createSCEV(Value *V);
1479
1480     /// createNodeForPHI - Provide the special handling we need to analyze PHI
1481     /// SCEVs.
1482     SCEVHandle createNodeForPHI(PHINode *PN);
1483
1484     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1485     /// for the specified instruction and replaces any references to the
1486     /// symbolic value SymName with the specified value.  This is used during
1487     /// PHI resolution.
1488     void ReplaceSymbolicValueWithConcrete(Instruction *I,
1489                                           const SCEVHandle &SymName,
1490                                           const SCEVHandle &NewVal);
1491
1492     /// ComputeIterationCount - Compute the number of times the specified loop
1493     /// will iterate.
1494     SCEVHandle ComputeIterationCount(const Loop *L);
1495
1496     /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1497     /// 'icmp op load X, cst', try to see if we can compute the trip count.
1498     SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1499                                                         Constant *RHS,
1500                                                         const Loop *L,
1501                                                         ICmpInst::Predicate p);
1502
1503     /// ComputeIterationCountExhaustively - If the trip is known to execute a
1504     /// constant number of times (the condition evolves only from constants),
1505     /// try to evaluate a few iterations of the loop until we get the exit
1506     /// condition gets a value of ExitWhen (true or false).  If we cannot
1507     /// evaluate the trip count of the loop, return UnknownValue.
1508     SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1509                                                  bool ExitWhen);
1510
1511     /// HowFarToZero - Return the number of times a backedge comparing the
1512     /// specified value to zero will execute.  If not computable, return
1513     /// UnknownValue.
1514     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1515
1516     /// HowFarToNonZero - Return the number of times a backedge checking the
1517     /// specified value for nonzero will execute.  If not computable, return
1518     /// UnknownValue.
1519     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1520
1521     /// HowManyLessThans - Return the number of times a backedge containing the
1522     /// specified less-than comparison will execute.  If not computable, return
1523     /// UnknownValue. isSigned specifies whether the less-than is signed.
1524     SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1525                                 bool isSigned, bool trueWhenEqual);
1526
1527     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1528     /// (which may not be an immediate predecessor) which has exactly one
1529     /// successor from which BB is reachable, or null if no such block is
1530     /// found.
1531     BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1532
1533     /// executesAtLeastOnce - Test whether entry to the loop is protected by
1534     /// a conditional between LHS and RHS.
1535     bool executesAtLeastOnce(const Loop *L, bool isSigned, bool trueWhenEqual,
1536                              SCEV *LHS, SCEV *RHS);
1537
1538     /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
1539     /// due to wrapping.
1540     bool potentialInfiniteLoop(SCEV *Stride, SCEV *RHS, bool isSigned,
1541                                bool trueWhenEqual);
1542
1543     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1544     /// in the header of its containing loop, we know the loop executes a
1545     /// constant number of times, and the PHI node is just a recurrence
1546     /// involving constants, fold it.
1547     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1548                                                 const Loop *L);
1549   };
1550 }
1551
1552 //===----------------------------------------------------------------------===//
1553 //            Basic SCEV Analysis and PHI Idiom Recognition Code
1554 //
1555
1556 /// deleteValueFromRecords - This method should be called by the
1557 /// client before it removes an instruction from the program, to make sure
1558 /// that no dangling references are left around.
1559 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1560   SmallVector<Value *, 16> Worklist;
1561
1562   if (Scalars.erase(V)) {
1563     if (PHINode *PN = dyn_cast<PHINode>(V))
1564       ConstantEvolutionLoopExitValue.erase(PN);
1565     Worklist.push_back(V);
1566   }
1567
1568   while (!Worklist.empty()) {
1569     Value *VV = Worklist.back();
1570     Worklist.pop_back();
1571
1572     for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1573          UI != UE; ++UI) {
1574       Instruction *Inst = cast<Instruction>(*UI);
1575       if (Scalars.erase(Inst)) {
1576         if (PHINode *PN = dyn_cast<PHINode>(VV))
1577           ConstantEvolutionLoopExitValue.erase(PN);
1578         Worklist.push_back(Inst);
1579       }
1580     }
1581   }
1582 }
1583
1584
1585 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1586 /// expression and create a new one.
1587 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1588   assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1589
1590   std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1591   if (I != Scalars.end()) return I->second;
1592   SCEVHandle S = createSCEV(V);
1593   Scalars.insert(std::make_pair(V, S));
1594   return S;
1595 }
1596
1597 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1598 /// the specified instruction and replaces any references to the symbolic value
1599 /// SymName with the specified value.  This is used during PHI resolution.
1600 void ScalarEvolutionsImpl::
1601 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1602                                  const SCEVHandle &NewVal) {
1603   std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1604   if (SI == Scalars.end()) return;
1605
1606   SCEVHandle NV =
1607     SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1608   if (NV == SI->second) return;  // No change.
1609
1610   SI->second = NV;       // Update the scalars map!
1611
1612   // Any instruction values that use this instruction might also need to be
1613   // updated!
1614   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1615        UI != E; ++UI)
1616     ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1617 }
1618
1619 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1620 /// a loop header, making it a potential recurrence, or it doesn't.
1621 ///
1622 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1623   if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1624     if (const Loop *L = LI.getLoopFor(PN->getParent()))
1625       if (L->getHeader() == PN->getParent()) {
1626         // If it lives in the loop header, it has two incoming values, one
1627         // from outside the loop, and one from inside.
1628         unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1629         unsigned BackEdge     = IncomingEdge^1;
1630
1631         // While we are analyzing this PHI node, handle its value symbolically.
1632         SCEVHandle SymbolicName = SE.getUnknown(PN);
1633         assert(Scalars.find(PN) == Scalars.end() &&
1634                "PHI node already processed?");
1635         Scalars.insert(std::make_pair(PN, SymbolicName));
1636
1637         // Using this symbolic name for the PHI, analyze the value coming around
1638         // the back-edge.
1639         SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1640
1641         // NOTE: If BEValue is loop invariant, we know that the PHI node just
1642         // has a special value for the first iteration of the loop.
1643
1644         // If the value coming around the backedge is an add with the symbolic
1645         // value we just inserted, then we found a simple induction variable!
1646         if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1647           // If there is a single occurrence of the symbolic value, replace it
1648           // with a recurrence.
1649           unsigned FoundIndex = Add->getNumOperands();
1650           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1651             if (Add->getOperand(i) == SymbolicName)
1652               if (FoundIndex == e) {
1653                 FoundIndex = i;
1654                 break;
1655               }
1656
1657           if (FoundIndex != Add->getNumOperands()) {
1658             // Create an add with everything but the specified operand.
1659             std::vector<SCEVHandle> Ops;
1660             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1661               if (i != FoundIndex)
1662                 Ops.push_back(Add->getOperand(i));
1663             SCEVHandle Accum = SE.getAddExpr(Ops);
1664
1665             // This is not a valid addrec if the step amount is varying each
1666             // loop iteration, but is not itself an addrec in this loop.
1667             if (Accum->isLoopInvariant(L) ||
1668                 (isa<SCEVAddRecExpr>(Accum) &&
1669                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1670               SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1671               SCEVHandle PHISCEV  = SE.getAddRecExpr(StartVal, Accum, L);
1672
1673               // Okay, for the entire analysis of this edge we assumed the PHI
1674               // to be symbolic.  We now need to go back and update all of the
1675               // entries for the scalars that use the PHI (except for the PHI
1676               // itself) to use the new analyzed value instead of the "symbolic"
1677               // value.
1678               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1679               return PHISCEV;
1680             }
1681           }
1682         } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1683           // Otherwise, this could be a loop like this:
1684           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
1685           // In this case, j = {1,+,1}  and BEValue is j.
1686           // Because the other in-value of i (0) fits the evolution of BEValue
1687           // i really is an addrec evolution.
1688           if (AddRec->getLoop() == L && AddRec->isAffine()) {
1689             SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1690
1691             // If StartVal = j.start - j.stride, we can use StartVal as the
1692             // initial step of the addrec evolution.
1693             if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1694                                             AddRec->getOperand(1))) {
1695               SCEVHandle PHISCEV = 
1696                  SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1697
1698               // Okay, for the entire analysis of this edge we assumed the PHI
1699               // to be symbolic.  We now need to go back and update all of the
1700               // entries for the scalars that use the PHI (except for the PHI
1701               // itself) to use the new analyzed value instead of the "symbolic"
1702               // value.
1703               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1704               return PHISCEV;
1705             }
1706           }
1707         }
1708
1709         return SymbolicName;
1710       }
1711
1712   // If it's not a loop phi, we can't handle it yet.
1713   return SE.getUnknown(PN);
1714 }
1715
1716 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1717 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
1718 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
1719 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
1720 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1721   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1722     return C->getValue()->getValue().countTrailingZeros();
1723
1724   if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1725     return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1726
1727   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1728     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1729     return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1730   }
1731
1732   if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1733     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1734     return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1735   }
1736
1737   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1738     // The result is the min of all operands results.
1739     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1740     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1741       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1742     return MinOpRes;
1743   }
1744
1745   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1746     // The result is the sum of all operands results.
1747     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1748     uint32_t BitWidth = M->getBitWidth();
1749     for (unsigned i = 1, e = M->getNumOperands();
1750          SumOpRes != BitWidth && i != e; ++i)
1751       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1752                           BitWidth);
1753     return SumOpRes;
1754   }
1755
1756   if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1757     // The result is the min of all operands results.
1758     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1759     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1760       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1761     return MinOpRes;
1762   }
1763
1764   if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1765     // The result is the min of all operands results.
1766     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1767     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1768       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1769     return MinOpRes;
1770   }
1771
1772   if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1773     // The result is the min of all operands results.
1774     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1775     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1776       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1777     return MinOpRes;
1778   }
1779
1780   // SCEVUDivExpr, SCEVSDivExpr, SCEVUnknown
1781   return 0;
1782 }
1783
1784 /// createSCEV - We know that there is no SCEV for the specified value.
1785 /// Analyze the expression.
1786 ///
1787 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1788   if (!isa<IntegerType>(V->getType()))
1789     return SE.getUnknown(V);
1790     
1791   unsigned Opcode = Instruction::UserOp1;
1792   if (Instruction *I = dyn_cast<Instruction>(V))
1793     Opcode = I->getOpcode();
1794   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1795     Opcode = CE->getOpcode();
1796   else
1797     return SE.getUnknown(V);
1798
1799   User *U = cast<User>(V);
1800   switch (Opcode) {
1801   case Instruction::Add:
1802     return SE.getAddExpr(getSCEV(U->getOperand(0)),
1803                          getSCEV(U->getOperand(1)));
1804   case Instruction::Mul:
1805     return SE.getMulExpr(getSCEV(U->getOperand(0)),
1806                          getSCEV(U->getOperand(1)));
1807   case Instruction::UDiv:
1808     return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1809                           getSCEV(U->getOperand(1)));
1810   case Instruction::SDiv:
1811     return SE.getSDivExpr(getSCEV(U->getOperand(0)),
1812                           getSCEV(U->getOperand(1)));
1813   case Instruction::Sub:
1814     return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1815                            getSCEV(U->getOperand(1)));
1816   case Instruction::Or:
1817     // If the RHS of the Or is a constant, we may have something like:
1818     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
1819     // optimizations will transparently handle this case.
1820     //
1821     // In order for this transformation to be safe, the LHS must be of the
1822     // form X*(2^n) and the Or constant must be less than 2^n.
1823     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1824       SCEVHandle LHS = getSCEV(U->getOperand(0));
1825       const APInt &CIVal = CI->getValue();
1826       if (GetMinTrailingZeros(LHS) >=
1827           (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1828         return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1829     }
1830     break;
1831   case Instruction::Xor:
1832     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1833       // If the RHS of the xor is a signbit, then this is just an add.
1834       // Instcombine turns add of signbit into xor as a strength reduction step.
1835       if (CI->getValue().isSignBit())
1836         return SE.getAddExpr(getSCEV(U->getOperand(0)),
1837                              getSCEV(U->getOperand(1)));
1838
1839       // If the RHS of xor is -1, then this is a not operation.
1840       else if (CI->isAllOnesValue())
1841         return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1842     }
1843     break;
1844
1845   case Instruction::Shl:
1846     // Turn shift left of a constant amount into a multiply.
1847     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1848       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1849       Constant *X = ConstantInt::get(
1850         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1851       return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1852     }
1853     break;
1854
1855   case Instruction::LShr:
1856     // Turn logical shift right of a constant into an unsigned divide.
1857     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1858       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1859       Constant *X = ConstantInt::get(
1860         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1861       return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1862     }
1863     break;
1864
1865   case Instruction::Trunc:
1866     return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1867
1868   case Instruction::ZExt:
1869     return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1870
1871   case Instruction::SExt:
1872     return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1873
1874   case Instruction::BitCast:
1875     // BitCasts are no-op casts so we just eliminate the cast.
1876     if (U->getType()->isInteger() &&
1877         U->getOperand(0)->getType()->isInteger())
1878       return getSCEV(U->getOperand(0));
1879     break;
1880
1881   case Instruction::PHI:
1882     return createNodeForPHI(cast<PHINode>(U));
1883
1884   case Instruction::Select:
1885     // This could be a smax or umax that was lowered earlier.
1886     // Try to recover it.
1887     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1888       Value *LHS = ICI->getOperand(0);
1889       Value *RHS = ICI->getOperand(1);
1890       switch (ICI->getPredicate()) {
1891       case ICmpInst::ICMP_SLT:
1892       case ICmpInst::ICMP_SLE:
1893         std::swap(LHS, RHS);
1894         // fall through
1895       case ICmpInst::ICMP_SGT:
1896       case ICmpInst::ICMP_SGE:
1897         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1898           return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1899         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1900           // ~smax(~x, ~y) == smin(x, y).
1901           return SE.getNotSCEV(SE.getSMaxExpr(
1902                                    SE.getNotSCEV(getSCEV(LHS)),
1903                                    SE.getNotSCEV(getSCEV(RHS))));
1904         break;
1905       case ICmpInst::ICMP_ULT:
1906       case ICmpInst::ICMP_ULE:
1907         std::swap(LHS, RHS);
1908         // fall through
1909       case ICmpInst::ICMP_UGT:
1910       case ICmpInst::ICMP_UGE:
1911         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1912           return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1913         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1914           // ~umax(~x, ~y) == umin(x, y)
1915           return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1916                                               SE.getNotSCEV(getSCEV(RHS))));
1917         break;
1918       default:
1919         break;
1920       }
1921     }
1922
1923   default: // We cannot analyze this expression.
1924     break;
1925   }
1926
1927   return SE.getUnknown(V);
1928 }
1929
1930
1931
1932 //===----------------------------------------------------------------------===//
1933 //                   Iteration Count Computation Code
1934 //
1935
1936 /// getIterationCount - If the specified loop has a predictable iteration
1937 /// count, return it.  Note that it is not valid to call this method on a
1938 /// loop without a loop-invariant iteration count.
1939 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1940   std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1941   if (I == IterationCounts.end()) {
1942     SCEVHandle ItCount = ComputeIterationCount(L);
1943     I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1944     if (ItCount != UnknownValue) {
1945       assert(ItCount->isLoopInvariant(L) &&
1946              "Computed trip count isn't loop invariant for loop!");
1947       ++NumTripCountsComputed;
1948     } else if (isa<PHINode>(L->getHeader()->begin())) {
1949       // Only count loops that have phi nodes as not being computable.
1950       ++NumTripCountsNotComputed;
1951     }
1952   }
1953   return I->second;
1954 }
1955
1956 /// ComputeIterationCount - Compute the number of times the specified loop
1957 /// will iterate.
1958 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1959   // If the loop has a non-one exit block count, we can't analyze it.
1960   SmallVector<BasicBlock*, 8> ExitBlocks;
1961   L->getExitBlocks(ExitBlocks);
1962   if (ExitBlocks.size() != 1) return UnknownValue;
1963
1964   // Okay, there is one exit block.  Try to find the condition that causes the
1965   // loop to be exited.
1966   BasicBlock *ExitBlock = ExitBlocks[0];
1967
1968   BasicBlock *ExitingBlock = 0;
1969   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1970        PI != E; ++PI)
1971     if (L->contains(*PI)) {
1972       if (ExitingBlock == 0)
1973         ExitingBlock = *PI;
1974       else
1975         return UnknownValue;   // More than one block exiting!
1976     }
1977   assert(ExitingBlock && "No exits from loop, something is broken!");
1978
1979   // Okay, we've computed the exiting block.  See what condition causes us to
1980   // exit.
1981   //
1982   // FIXME: we should be able to handle switch instructions (with a single exit)
1983   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1984   if (ExitBr == 0) return UnknownValue;
1985   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1986   
1987   // At this point, we know we have a conditional branch that determines whether
1988   // the loop is exited.  However, we don't know if the branch is executed each
1989   // time through the loop.  If not, then the execution count of the branch will
1990   // not be equal to the trip count of the loop.
1991   //
1992   // Currently we check for this by checking to see if the Exit branch goes to
1993   // the loop header.  If so, we know it will always execute the same number of
1994   // times as the loop.  We also handle the case where the exit block *is* the
1995   // loop header.  This is common for un-rotated loops.  More extensive analysis
1996   // could be done to handle more cases here.
1997   if (ExitBr->getSuccessor(0) != L->getHeader() &&
1998       ExitBr->getSuccessor(1) != L->getHeader() &&
1999       ExitBr->getParent() != L->getHeader())
2000     return UnknownValue;
2001   
2002   ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2003
2004   // If it's not an integer comparison then compute it the hard way. 
2005   // Note that ICmpInst deals with pointer comparisons too so we must check
2006   // the type of the operand.
2007   if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2008     return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2009                                           ExitBr->getSuccessor(0) == ExitBlock);
2010
2011   // If the condition was exit on true, convert the condition to exit on false
2012   ICmpInst::Predicate Cond;
2013   if (ExitBr->getSuccessor(1) == ExitBlock)
2014     Cond = ExitCond->getPredicate();
2015   else
2016     Cond = ExitCond->getInversePredicate();
2017
2018   // Handle common loops like: for (X = "string"; *X; ++X)
2019   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2020     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2021       SCEVHandle ItCnt =
2022         ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2023       if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2024     }
2025
2026   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2027   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2028
2029   // Try to evaluate any dependencies out of the loop.
2030   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2031   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2032   Tmp = getSCEVAtScope(RHS, L);
2033   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2034
2035   // At this point, we would like to compute how many iterations of the 
2036   // loop the predicate will return true for these inputs.
2037   if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2038     // If there is a loop-invariant, force it into the RHS.
2039     std::swap(LHS, RHS);
2040     Cond = ICmpInst::getSwappedPredicate(Cond);
2041   }
2042
2043   // FIXME: think about handling pointer comparisons!  i.e.:
2044   // while (P != P+100) ++P;
2045
2046   // If we have a comparison of a chrec against a constant, try to use value
2047   // ranges to answer this query.
2048   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2049     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2050       if (AddRec->getLoop() == L) {
2051         // Form the comparison range using the constant of the correct type so
2052         // that the ConstantRange class knows to do a signed or unsigned
2053         // comparison.
2054         ConstantInt *CompVal = RHSC->getValue();
2055         const Type *RealTy = ExitCond->getOperand(0)->getType();
2056         CompVal = dyn_cast<ConstantInt>(
2057           ConstantExpr::getBitCast(CompVal, RealTy));
2058         if (CompVal) {
2059           // Form the constant range.
2060           ConstantRange CompRange(
2061               ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2062
2063           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2064           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2065         }
2066       }
2067
2068   switch (Cond) {
2069   case ICmpInst::ICMP_NE: {                     // while (X != Y)
2070     // Convert to: while (X-Y != 0)
2071     SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2072     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2073     break;
2074   }
2075   case ICmpInst::ICMP_EQ: {
2076     // Convert to: while (X-Y == 0)           // while (X == Y)
2077     SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2078     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2079     break;
2080   }
2081   case ICmpInst::ICMP_SLT: {
2082     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, false);
2083     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2084     break;
2085   }
2086   case ICmpInst::ICMP_SGT: {
2087     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2088                                      SE.getNotSCEV(RHS), L, true, false);
2089     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2090     break;
2091   }
2092   case ICmpInst::ICMP_ULT: {
2093     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, false);
2094     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2095     break;
2096   }
2097   case ICmpInst::ICMP_UGT: {
2098     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2099                                      SE.getNotSCEV(RHS), L, false, false);
2100     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2101     break;
2102   }
2103   case ICmpInst::ICMP_SLE: {
2104     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, true);
2105     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2106     break;
2107   }
2108   case ICmpInst::ICMP_SGE: {
2109     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2110                                      SE.getNotSCEV(RHS), L, true, true);
2111     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2112     break;
2113   }
2114   case ICmpInst::ICMP_ULE: {
2115     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, true);
2116     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2117     break;
2118   }
2119   case ICmpInst::ICMP_UGE: {
2120     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2121                                      SE.getNotSCEV(RHS), L, false, true);
2122     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2123     break;
2124   }
2125   default:
2126 #if 0
2127     cerr << "ComputeIterationCount ";
2128     if (ExitCond->getOperand(0)->getType()->isUnsigned())
2129       cerr << "[unsigned] ";
2130     cerr << *LHS << "   "
2131          << Instruction::getOpcodeName(Instruction::ICmp) 
2132          << "   " << *RHS << "\n";
2133 #endif
2134     break;
2135   }
2136   return ComputeIterationCountExhaustively(L, ExitCond,
2137                                        ExitBr->getSuccessor(0) == ExitBlock);
2138 }
2139
2140 static ConstantInt *
2141 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2142                                 ScalarEvolution &SE) {
2143   SCEVHandle InVal = SE.getConstant(C);
2144   SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2145   assert(isa<SCEVConstant>(Val) &&
2146          "Evaluation of SCEV at constant didn't fold correctly?");
2147   return cast<SCEVConstant>(Val)->getValue();
2148 }
2149
2150 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2151 /// and a GEP expression (missing the pointer index) indexing into it, return
2152 /// the addressed element of the initializer or null if the index expression is
2153 /// invalid.
2154 static Constant *
2155 GetAddressedElementFromGlobal(GlobalVariable *GV,
2156                               const std::vector<ConstantInt*> &Indices) {
2157   Constant *Init = GV->getInitializer();
2158   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2159     uint64_t Idx = Indices[i]->getZExtValue();
2160     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2161       assert(Idx < CS->getNumOperands() && "Bad struct index!");
2162       Init = cast<Constant>(CS->getOperand(Idx));
2163     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2164       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
2165       Init = cast<Constant>(CA->getOperand(Idx));
2166     } else if (isa<ConstantAggregateZero>(Init)) {
2167       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2168         assert(Idx < STy->getNumElements() && "Bad struct index!");
2169         Init = Constant::getNullValue(STy->getElementType(Idx));
2170       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2171         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
2172         Init = Constant::getNullValue(ATy->getElementType());
2173       } else {
2174         assert(0 && "Unknown constant aggregate type!");
2175       }
2176       return 0;
2177     } else {
2178       return 0; // Unknown initializer type
2179     }
2180   }
2181   return Init;
2182 }
2183
2184 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2185 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2186 SCEVHandle ScalarEvolutionsImpl::
2187 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2188                                          const Loop *L, 
2189                                          ICmpInst::Predicate predicate) {
2190   if (LI->isVolatile()) return UnknownValue;
2191
2192   // Check to see if the loaded pointer is a getelementptr of a global.
2193   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2194   if (!GEP) return UnknownValue;
2195
2196   // Make sure that it is really a constant global we are gepping, with an
2197   // initializer, and make sure the first IDX is really 0.
2198   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2199   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2200       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2201       !cast<Constant>(GEP->getOperand(1))->isNullValue())
2202     return UnknownValue;
2203
2204   // Okay, we allow one non-constant index into the GEP instruction.
2205   Value *VarIdx = 0;
2206   std::vector<ConstantInt*> Indexes;
2207   unsigned VarIdxNum = 0;
2208   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2209     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2210       Indexes.push_back(CI);
2211     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2212       if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
2213       VarIdx = GEP->getOperand(i);
2214       VarIdxNum = i-2;
2215       Indexes.push_back(0);
2216     }
2217
2218   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2219   // Check to see if X is a loop variant variable value now.
2220   SCEVHandle Idx = getSCEV(VarIdx);
2221   SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2222   if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2223
2224   // We can only recognize very limited forms of loop index expressions, in
2225   // particular, only affine AddRec's like {C1,+,C2}.
2226   SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2227   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2228       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2229       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2230     return UnknownValue;
2231
2232   unsigned MaxSteps = MaxBruteForceIterations;
2233   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2234     ConstantInt *ItCst =
2235       ConstantInt::get(IdxExpr->getType(), IterationNum);
2236     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2237
2238     // Form the GEP offset.
2239     Indexes[VarIdxNum] = Val;
2240
2241     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2242     if (Result == 0) break;  // Cannot compute!
2243
2244     // Evaluate the condition for this iteration.
2245     Result = ConstantExpr::getICmp(predicate, Result, RHS);
2246     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
2247     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2248 #if 0
2249       cerr << "\n***\n*** Computed loop count " << *ItCst
2250            << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2251            << "***\n";
2252 #endif
2253       ++NumArrayLenItCounts;
2254       return SE.getConstant(ItCst);   // Found terminating iteration!
2255     }
2256   }
2257   return UnknownValue;
2258 }
2259
2260
2261 /// CanConstantFold - Return true if we can constant fold an instruction of the
2262 /// specified type, assuming that all operands were constants.
2263 static bool CanConstantFold(const Instruction *I) {
2264   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2265       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2266     return true;
2267
2268   if (const CallInst *CI = dyn_cast<CallInst>(I))
2269     if (const Function *F = CI->getCalledFunction())
2270       return canConstantFoldCallTo(F);
2271   return false;
2272 }
2273
2274 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2275 /// in the loop that V is derived from.  We allow arbitrary operations along the
2276 /// way, but the operands of an operation must either be constants or a value
2277 /// derived from a constant PHI.  If this expression does not fit with these
2278 /// constraints, return null.
2279 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2280   // If this is not an instruction, or if this is an instruction outside of the
2281   // loop, it can't be derived from a loop PHI.
2282   Instruction *I = dyn_cast<Instruction>(V);
2283   if (I == 0 || !L->contains(I->getParent())) return 0;
2284
2285   if (PHINode *PN = dyn_cast<PHINode>(I)) {
2286     if (L->getHeader() == I->getParent())
2287       return PN;
2288     else
2289       // We don't currently keep track of the control flow needed to evaluate
2290       // PHIs, so we cannot handle PHIs inside of loops.
2291       return 0;
2292   }
2293
2294   // If we won't be able to constant fold this expression even if the operands
2295   // are constants, return early.
2296   if (!CanConstantFold(I)) return 0;
2297
2298   // Otherwise, we can evaluate this instruction if all of its operands are
2299   // constant or derived from a PHI node themselves.
2300   PHINode *PHI = 0;
2301   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2302     if (!(isa<Constant>(I->getOperand(Op)) ||
2303           isa<GlobalValue>(I->getOperand(Op)))) {
2304       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2305       if (P == 0) return 0;  // Not evolving from PHI
2306       if (PHI == 0)
2307         PHI = P;
2308       else if (PHI != P)
2309         return 0;  // Evolving from multiple different PHIs.
2310     }
2311
2312   // This is a expression evolving from a constant PHI!
2313   return PHI;
2314 }
2315
2316 /// EvaluateExpression - Given an expression that passes the
2317 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2318 /// in the loop has the value PHIVal.  If we can't fold this expression for some
2319 /// reason, return null.
2320 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2321   if (isa<PHINode>(V)) return PHIVal;
2322   if (Constant *C = dyn_cast<Constant>(V)) return C;
2323   Instruction *I = cast<Instruction>(V);
2324
2325   std::vector<Constant*> Operands;
2326   Operands.resize(I->getNumOperands());
2327
2328   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2329     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2330     if (Operands[i] == 0) return 0;
2331   }
2332
2333   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2334     return ConstantFoldCompareInstOperands(CI->getPredicate(),
2335                                            &Operands[0], Operands.size());
2336   else
2337     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2338                                     &Operands[0], Operands.size());
2339 }
2340
2341 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2342 /// in the header of its containing loop, we know the loop executes a
2343 /// constant number of times, and the PHI node is just a recurrence
2344 /// involving constants, fold it.
2345 Constant *ScalarEvolutionsImpl::
2346 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2347   std::map<PHINode*, Constant*>::iterator I =
2348     ConstantEvolutionLoopExitValue.find(PN);
2349   if (I != ConstantEvolutionLoopExitValue.end())
2350     return I->second;
2351
2352   if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2353     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
2354
2355   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2356
2357   // Since the loop is canonicalized, the PHI node must have two entries.  One
2358   // entry must be a constant (coming in from outside of the loop), and the
2359   // second must be derived from the same PHI.
2360   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2361   Constant *StartCST =
2362     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2363   if (StartCST == 0)
2364     return RetVal = 0;  // Must be a constant.
2365
2366   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2367   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2368   if (PN2 != PN)
2369     return RetVal = 0;  // Not derived from same PHI.
2370
2371   // Execute the loop symbolically to determine the exit value.
2372   if (Its.getActiveBits() >= 32)
2373     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2374
2375   unsigned NumIterations = Its.getZExtValue(); // must be in range
2376   unsigned IterationNum = 0;
2377   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2378     if (IterationNum == NumIterations)
2379       return RetVal = PHIVal;  // Got exit value!
2380
2381     // Compute the value of the PHI node for the next iteration.
2382     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2383     if (NextPHI == PHIVal)
2384       return RetVal = NextPHI;  // Stopped evolving!
2385     if (NextPHI == 0)
2386       return 0;        // Couldn't evaluate!
2387     PHIVal = NextPHI;
2388   }
2389 }
2390
2391 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2392 /// constant number of times (the condition evolves only from constants),
2393 /// try to evaluate a few iterations of the loop until we get the exit
2394 /// condition gets a value of ExitWhen (true or false).  If we cannot
2395 /// evaluate the trip count of the loop, return UnknownValue.
2396 SCEVHandle ScalarEvolutionsImpl::
2397 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2398   PHINode *PN = getConstantEvolvingPHI(Cond, L);
2399   if (PN == 0) return UnknownValue;
2400
2401   // Since the loop is canonicalized, the PHI node must have two entries.  One
2402   // entry must be a constant (coming in from outside of the loop), and the
2403   // second must be derived from the same PHI.
2404   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2405   Constant *StartCST =
2406     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2407   if (StartCST == 0) return UnknownValue;  // Must be a constant.
2408
2409   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2410   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2411   if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
2412
2413   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
2414   // the loop symbolically to determine when the condition gets a value of
2415   // "ExitWhen".
2416   unsigned IterationNum = 0;
2417   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
2418   for (Constant *PHIVal = StartCST;
2419        IterationNum != MaxIterations; ++IterationNum) {
2420     ConstantInt *CondVal =
2421       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2422
2423     // Couldn't symbolically evaluate.
2424     if (!CondVal) return UnknownValue;
2425
2426     if (CondVal->getValue() == uint64_t(ExitWhen)) {
2427       ConstantEvolutionLoopExitValue[PN] = PHIVal;
2428       ++NumBruteForceTripCountsComputed;
2429       return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2430     }
2431
2432     // Compute the value of the PHI node for the next iteration.
2433     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2434     if (NextPHI == 0 || NextPHI == PHIVal)
2435       return UnknownValue;  // Couldn't evaluate or not making progress...
2436     PHIVal = NextPHI;
2437   }
2438
2439   // Too many iterations were needed to evaluate.
2440   return UnknownValue;
2441 }
2442
2443 /// getSCEVAtScope - Compute the value of the specified expression within the
2444 /// indicated loop (which may be null to indicate in no loop).  If the
2445 /// expression cannot be evaluated, return UnknownValue.
2446 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2447   // FIXME: this should be turned into a virtual method on SCEV!
2448
2449   if (isa<SCEVConstant>(V)) return V;
2450
2451   // If this instruction is evolved from a constant-evolving PHI, compute the
2452   // exit value from the loop without using SCEVs.
2453   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2454     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2455       const Loop *LI = this->LI[I->getParent()];
2456       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
2457         if (PHINode *PN = dyn_cast<PHINode>(I))
2458           if (PN->getParent() == LI->getHeader()) {
2459             // Okay, there is no closed form solution for the PHI node.  Check
2460             // to see if the loop that contains it has a known iteration count.
2461             // If so, we may be able to force computation of the exit value.
2462             SCEVHandle IterationCount = getIterationCount(LI);
2463             if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2464               // Okay, we know how many times the containing loop executes.  If
2465               // this is a constant evolving PHI node, get the final value at
2466               // the specified iteration number.
2467               Constant *RV = getConstantEvolutionLoopExitValue(PN,
2468                                                     ICC->getValue()->getValue(),
2469                                                                LI);
2470               if (RV) return SE.getUnknown(RV);
2471             }
2472           }
2473
2474       // Okay, this is an expression that we cannot symbolically evaluate
2475       // into a SCEV.  Check to see if it's possible to symbolically evaluate
2476       // the arguments into constants, and if so, try to constant propagate the
2477       // result.  This is particularly useful for computing loop exit values.
2478       if (CanConstantFold(I)) {
2479         std::vector<Constant*> Operands;
2480         Operands.reserve(I->getNumOperands());
2481         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2482           Value *Op = I->getOperand(i);
2483           if (Constant *C = dyn_cast<Constant>(Op)) {
2484             Operands.push_back(C);
2485           } else {
2486             // If any of the operands is non-constant and if they are
2487             // non-integer, don't even try to analyze them with scev techniques.
2488             if (!isa<IntegerType>(Op->getType()))
2489               return V;
2490               
2491             SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2492             if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2493               Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 
2494                                                               Op->getType(), 
2495                                                               false));
2496             else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2497               if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2498                 Operands.push_back(ConstantExpr::getIntegerCast(C, 
2499                                                                 Op->getType(), 
2500                                                                 false));
2501               else
2502                 return V;
2503             } else {
2504               return V;
2505             }
2506           }
2507         }
2508         
2509         Constant *C;
2510         if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2511           C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2512                                               &Operands[0], Operands.size());
2513         else
2514           C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2515                                        &Operands[0], Operands.size());
2516         return SE.getUnknown(C);
2517       }
2518     }
2519
2520     // This is some other type of SCEVUnknown, just return it.
2521     return V;
2522   }
2523
2524   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2525     // Avoid performing the look-up in the common case where the specified
2526     // expression has no loop-variant portions.
2527     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2528       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2529       if (OpAtScope != Comm->getOperand(i)) {
2530         if (OpAtScope == UnknownValue) return UnknownValue;
2531         // Okay, at least one of these operands is loop variant but might be
2532         // foldable.  Build a new instance of the folded commutative expression.
2533         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2534         NewOps.push_back(OpAtScope);
2535
2536         for (++i; i != e; ++i) {
2537           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2538           if (OpAtScope == UnknownValue) return UnknownValue;
2539           NewOps.push_back(OpAtScope);
2540         }
2541         if (isa<SCEVAddExpr>(Comm))
2542           return SE.getAddExpr(NewOps);
2543         if (isa<SCEVMulExpr>(Comm))
2544           return SE.getMulExpr(NewOps);
2545         if (isa<SCEVSMaxExpr>(Comm))
2546           return SE.getSMaxExpr(NewOps);
2547         if (isa<SCEVUMaxExpr>(Comm))
2548           return SE.getUMaxExpr(NewOps);
2549         assert(0 && "Unknown commutative SCEV type!");
2550       }
2551     }
2552     // If we got here, all operands are loop invariant.
2553     return Comm;
2554   }
2555
2556   if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
2557     SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
2558     if (LHS == UnknownValue) return LHS;
2559     SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
2560     if (RHS == UnknownValue) return RHS;
2561     if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
2562       return UDiv;   // must be loop invariant
2563     return SE.getUDivExpr(LHS, RHS);
2564   }
2565
2566   if (SCEVSDivExpr *SDiv = dyn_cast<SCEVSDivExpr>(V)) {
2567     SCEVHandle LHS = getSCEVAtScope(SDiv->getLHS(), L);
2568     if (LHS == UnknownValue) return LHS;
2569     SCEVHandle RHS = getSCEVAtScope(SDiv->getRHS(), L);
2570     if (RHS == UnknownValue) return RHS;
2571     if (LHS == SDiv->getLHS() && RHS == SDiv->getRHS())
2572       return SDiv;   // must be loop invariant
2573     return SE.getSDivExpr(LHS, RHS);
2574   }
2575
2576   // If this is a loop recurrence for a loop that does not contain L, then we
2577   // are dealing with the final value computed by the loop.
2578   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2579     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2580       // To evaluate this recurrence, we need to know how many times the AddRec
2581       // loop iterates.  Compute this now.
2582       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2583       if (IterationCount == UnknownValue) return UnknownValue;
2584
2585       // Then, evaluate the AddRec.
2586       return AddRec->evaluateAtIteration(IterationCount, SE);
2587     }
2588     return UnknownValue;
2589   }
2590
2591   //assert(0 && "Unknown SCEV type!");
2592   return UnknownValue;
2593 }
2594
2595 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2596 /// following equation:
2597 ///
2598 ///     A * X = B (mod N)
2599 ///
2600 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2601 /// A and B isn't important.
2602 ///
2603 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2604 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2605                                                ScalarEvolution &SE) {
2606   uint32_t BW = A.getBitWidth();
2607   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2608   assert(A != 0 && "A must be non-zero.");
2609
2610   // 1. D = gcd(A, N)
2611   //
2612   // The gcd of A and N may have only one prime factor: 2. The number of
2613   // trailing zeros in A is its multiplicity
2614   uint32_t Mult2 = A.countTrailingZeros();
2615   // D = 2^Mult2
2616
2617   // 2. Check if B is divisible by D.
2618   //
2619   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2620   // is not less than multiplicity of this prime factor for D.
2621   if (B.countTrailingZeros() < Mult2)
2622     return new SCEVCouldNotCompute();
2623
2624   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2625   // modulo (N / D).
2626   //
2627   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
2628   // bit width during computations.
2629   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
2630   APInt Mod(BW + 1, 0);
2631   Mod.set(BW - Mult2);  // Mod = N / D
2632   APInt I = AD.multiplicativeInverse(Mod);
2633
2634   // 4. Compute the minimum unsigned root of the equation:
2635   // I * (B / D) mod (N / D)
2636   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2637
2638   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2639   // bits.
2640   return SE.getConstant(Result.trunc(BW));
2641 }
2642
2643 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2644 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2645 /// might be the same) or two SCEVCouldNotCompute objects.
2646 ///
2647 static std::pair<SCEVHandle,SCEVHandle>
2648 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2649   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2650   SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2651   SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2652   SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2653
2654   // We currently can only solve this if the coefficients are constants.
2655   if (!LC || !MC || !NC) {
2656     SCEV *CNC = new SCEVCouldNotCompute();
2657     return std::make_pair(CNC, CNC);
2658   }
2659
2660   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2661   const APInt &L = LC->getValue()->getValue();
2662   const APInt &M = MC->getValue()->getValue();
2663   const APInt &N = NC->getValue()->getValue();
2664   APInt Two(BitWidth, 2);
2665   APInt Four(BitWidth, 4);
2666
2667   { 
2668     using namespace APIntOps;
2669     const APInt& C = L;
2670     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2671     // The B coefficient is M-N/2
2672     APInt B(M);
2673     B -= sdiv(N,Two);
2674
2675     // The A coefficient is N/2
2676     APInt A(N.sdiv(Two));
2677
2678     // Compute the B^2-4ac term.
2679     APInt SqrtTerm(B);
2680     SqrtTerm *= B;
2681     SqrtTerm -= Four * (A * C);
2682
2683     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2684     // integer value or else APInt::sqrt() will assert.
2685     APInt SqrtVal(SqrtTerm.sqrt());
2686
2687     // Compute the two solutions for the quadratic formula. 
2688     // The divisions must be performed as signed divisions.
2689     APInt NegB(-B);
2690     APInt TwoA( A << 1 );
2691     if (TwoA.isMinValue()) {
2692       SCEV *CNC = new SCEVCouldNotCompute();
2693       return std::make_pair(CNC, CNC);
2694     }
2695
2696     ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2697     ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2698
2699     return std::make_pair(SE.getConstant(Solution1), 
2700                           SE.getConstant(Solution2));
2701     } // end APIntOps namespace
2702 }
2703
2704 /// HowFarToZero - Return the number of times a backedge comparing the specified
2705 /// value to zero will execute.  If not computable, return UnknownValue
2706 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2707   // If the value is a constant
2708   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2709     // If the value is already zero, the branch will execute zero times.
2710     if (C->getValue()->isZero()) return C;
2711     return UnknownValue;  // Otherwise it will loop infinitely.
2712   }
2713
2714   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2715   if (!AddRec || AddRec->getLoop() != L)
2716     return UnknownValue;
2717
2718   if (AddRec->isAffine()) {
2719     // If this is an affine expression, the execution count of this branch is
2720     // the minimum unsigned root of the following equation:
2721     //
2722     //     Start + Step*N = 0 (mod 2^BW)
2723     //
2724     // equivalent to:
2725     //
2726     //             Step*N = -Start (mod 2^BW)
2727     //
2728     // where BW is the common bit width of Start and Step.
2729
2730     // Get the initial value for the loop.
2731     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2732     if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2733
2734     SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2735
2736     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2737       // For now we handle only constant steps.
2738
2739       // First, handle unitary steps.
2740       if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
2741         return SE.getNegativeSCEV(Start);       //   N = -Start (as unsigned)
2742       if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
2743         return Start;                           //    N = Start (as unsigned)
2744
2745       // Then, try to solve the above equation provided that Start is constant.
2746       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2747         return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2748                                             -StartC->getValue()->getValue(),SE);
2749     }
2750   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2751     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2752     // the quadratic equation to solve it.
2753     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2754     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2755     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2756     if (R1) {
2757 #if 0
2758       cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2759            << "  sol#2: " << *R2 << "\n";
2760 #endif
2761       // Pick the smallest positive root value.
2762       if (ConstantInt *CB =
2763           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2764                                    R1->getValue(), R2->getValue()))) {
2765         if (CB->getZExtValue() == false)
2766           std::swap(R1, R2);   // R1 is the minimum root now.
2767
2768         // We can only use this value if the chrec ends up with an exact zero
2769         // value at this index.  When solving for "X*X != 5", for example, we
2770         // should not accept a root of 2.
2771         SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2772         if (Val->isZero())
2773           return R1;  // We found a quadratic root!
2774       }
2775     }
2776   }
2777
2778   return UnknownValue;
2779 }
2780
2781 /// HowFarToNonZero - Return the number of times a backedge checking the
2782 /// specified value for nonzero will execute.  If not computable, return
2783 /// UnknownValue
2784 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2785   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2786   // handle them yet except for the trivial case.  This could be expanded in the
2787   // future as needed.
2788
2789   // If the value is a constant, check to see if it is known to be non-zero
2790   // already.  If so, the backedge will execute zero times.
2791   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2792     if (!C->getValue()->isNullValue())
2793       return SE.getIntegerSCEV(0, C->getType());
2794     return UnknownValue;  // Otherwise it will loop infinitely.
2795   }
2796
2797   // We could implement others, but I really doubt anyone writes loops like
2798   // this, and if they did, they would already be constant folded.
2799   return UnknownValue;
2800 }
2801
2802 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2803 /// (which may not be an immediate predecessor) which has exactly one
2804 /// successor from which BB is reachable, or null if no such block is
2805 /// found.
2806 ///
2807 BasicBlock *
2808 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2809   // If the block has a unique predecessor, the predecessor must have
2810   // no other successors from which BB is reachable.
2811   if (BasicBlock *Pred = BB->getSinglePredecessor())
2812     return Pred;
2813
2814   // A loop's header is defined to be a block that dominates the loop.
2815   // If the loop has a preheader, it must be a block that has exactly
2816   // one successor that can reach BB. This is slightly more strict
2817   // than necessary, but works if critical edges are split.
2818   if (Loop *L = LI.getLoopFor(BB))
2819     return L->getLoopPreheader();
2820
2821   return 0;
2822 }
2823
2824 /// executesAtLeastOnce - Test whether entry to the loop is protected by
2825 /// a conditional between LHS and RHS.
2826 bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2827                                                bool trueWhenEqual,
2828                                                SCEV *LHS, SCEV *RHS) {
2829   BasicBlock *Preheader = L->getLoopPreheader();
2830   BasicBlock *PreheaderDest = L->getHeader();
2831
2832   // Starting at the preheader, climb up the predecessor chain, as long as
2833   // there are predecessors that can be found that have unique successors
2834   // leading to the original header.
2835   for (; Preheader;
2836        PreheaderDest = Preheader,
2837        Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2838
2839     BranchInst *LoopEntryPredicate =
2840       dyn_cast<BranchInst>(Preheader->getTerminator());
2841     if (!LoopEntryPredicate ||
2842         LoopEntryPredicate->isUnconditional())
2843       continue;
2844
2845     ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2846     if (!ICI) continue;
2847
2848     // Now that we found a conditional branch that dominates the loop, check to
2849     // see if it is the comparison we are looking for.
2850     Value *PreCondLHS = ICI->getOperand(0);
2851     Value *PreCondRHS = ICI->getOperand(1);
2852     ICmpInst::Predicate Cond;
2853     if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2854       Cond = ICI->getPredicate();
2855     else
2856       Cond = ICI->getInversePredicate();
2857
2858     switch (Cond) {
2859     case ICmpInst::ICMP_UGT:
2860       if (isSigned || trueWhenEqual) continue;
2861       std::swap(PreCondLHS, PreCondRHS);
2862       Cond = ICmpInst::ICMP_ULT;
2863       break;
2864     case ICmpInst::ICMP_SGT:
2865       if (!isSigned || trueWhenEqual) continue;
2866       std::swap(PreCondLHS, PreCondRHS);
2867       Cond = ICmpInst::ICMP_SLT;
2868       break;
2869     case ICmpInst::ICMP_ULT:
2870       if (isSigned || trueWhenEqual) continue;
2871       break;
2872     case ICmpInst::ICMP_SLT:
2873       if (!isSigned || trueWhenEqual) continue;
2874       break;
2875     case ICmpInst::ICMP_UGE:
2876       if (isSigned || !trueWhenEqual) continue;
2877       std::swap(PreCondLHS, PreCondRHS);
2878       Cond = ICmpInst::ICMP_ULE;
2879       break;
2880     case ICmpInst::ICMP_SGE:
2881       if (!isSigned || !trueWhenEqual) continue;
2882       std::swap(PreCondLHS, PreCondRHS);
2883       Cond = ICmpInst::ICMP_SLE;
2884       break;
2885     case ICmpInst::ICMP_ULE:
2886       if (isSigned || !trueWhenEqual) continue;
2887       break;
2888     case ICmpInst::ICMP_SLE:
2889       if (!isSigned || !trueWhenEqual) continue;
2890       break;
2891     default:
2892       continue;
2893     }
2894
2895     if (!PreCondLHS->getType()->isInteger()) continue;
2896
2897     SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2898     SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2899     if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2900         (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2901          RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2902       return true;
2903   }
2904
2905   return false;
2906 }
2907
2908 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
2909 /// due to wrapping around 2^n.
2910 bool ScalarEvolutionsImpl::potentialInfiniteLoop(SCEV *Stride, SCEV *RHS,
2911                                                  bool isSigned, bool trueWhenEqual) {
2912   // Return true when the distance from RHS to maxint > Stride.
2913
2914   SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride);
2915   if (!SC)
2916     return true;
2917
2918   if (SC->getValue()->isZero())
2919     return true;
2920   if (!trueWhenEqual && SC->getValue()->isOne())
2921     return false;
2922
2923   SCEVConstant *R = dyn_cast<SCEVConstant>(RHS);
2924   if (!R)
2925     return true;
2926
2927   // If negative, it wraps around every iteration, but we don't care about that.
2928   APInt S = SC->getValue()->getValue().abs();
2929
2930   uint32_t Width = R->getValue()->getBitWidth();
2931   APInt Dist = (isSigned ? APInt::getSignedMaxValue(Width)
2932                          : APInt::getMaxValue(Width))
2933                - R->getValue()->getValue();
2934
2935   // Because we're looking at distance, we perform an unsigned comparison,
2936   // regardless of the sign of the computation.
2937   if (trueWhenEqual)
2938     return !S.ult(Dist);
2939   else
2940     return !S.ule(Dist);
2941 }
2942
2943 /// HowManyLessThans - Return the number of times a backedge containing the
2944 /// specified less-than comparison will execute.  If not computable, return
2945 /// UnknownValue.
2946 SCEVHandle ScalarEvolutionsImpl::
2947 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
2948                  bool isSigned, bool trueWhenEqual) {
2949   // Only handle:  "ADDREC < LoopInvariant".
2950   if (!RHS->isLoopInvariant(L)) return UnknownValue;
2951
2952   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2953   if (!AddRec || AddRec->getLoop() != L)
2954     return UnknownValue;
2955
2956   if (AddRec->isAffine()) {
2957     SCEVHandle Stride = AddRec->getOperand(1);
2958     if (potentialInfiniteLoop(Stride, RHS, isSigned, trueWhenEqual))
2959       return UnknownValue;
2960
2961     // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
2962     // m.  So, we count the number of iterations in which {n,+,s} < m is true.
2963     // Note that we cannot simply return max(m-n,0)/s because it's not safe to
2964     // treat m-n as signed nor unsigned due to overflow possibility.
2965     //
2966     // Assuming that the loop will run at least once, we know that it will
2967     // run (m-n)/s times.
2968
2969     // First, we get the value of the LHS in the first iteration: n
2970     SCEVHandle Start = AddRec->getOperand(0);
2971
2972     SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2973
2974     // If the expression is less-than-or-equal to, we need to extend the
2975     // loop by one iteration.
2976     //
2977     // The loop won't actually run (m-n)/s times because the loop iterations
2978     // might not divide cleanly. For example, if you have {2,+,5} u< 10 the
2979     // division would equal one, but the loop runs twice putting the
2980     // induction variable at 12.
2981     SCEVHandle End = SE.getAddExpr(RHS, Stride);
2982     if (!trueWhenEqual)
2983       End = SE.getMinusSCEV(End, One);
2984
2985     if (!executesAtLeastOnce(L, isSigned, trueWhenEqual,
2986                              SE.getMinusSCEV(Start, One), RHS)) {
2987       // If not, we get the value of the LHS in the first iteration in which
2988       // the above condition doesn't hold.  This equals to max(m,n).
2989       End = isSigned ? SE.getSMaxExpr(End, Start)
2990                      : SE.getUMaxExpr(End, Start);
2991     }
2992
2993     // Finally, we subtract these two values to get the number of times the
2994     // backedge is executed: (max(m,n)-n)/s.
2995     //
2996     // Note that a trip count is always positive. Using SDiv here produces
2997     // wrong answers when Start < End.
2998     return SE.getUDivExpr(SE.getMinusSCEV(End, Start), Stride);
2999   }
3000
3001   return UnknownValue;
3002 }
3003
3004 /// getNumIterationsInRange - Return the number of iterations of this loop that
3005 /// produce values in the specified constant range.  Another way of looking at
3006 /// this is that it returns the first iteration number where the value is not in
3007 /// the condition, thus computing the exit count. If the iteration count can't
3008 /// be computed, an instance of SCEVCouldNotCompute is returned.
3009 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3010                                                    ScalarEvolution &SE) const {
3011   if (Range.isFullSet())  // Infinite loop.
3012     return new SCEVCouldNotCompute();
3013
3014   // If the start is a non-zero constant, shift the range to simplify things.
3015   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3016     if (!SC->getValue()->isZero()) {
3017       std::vector<SCEVHandle> Operands(op_begin(), op_end());
3018       Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3019       SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3020       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3021         return ShiftedAddRec->getNumIterationsInRange(
3022                            Range.subtract(SC->getValue()->getValue()), SE);
3023       // This is strange and shouldn't happen.
3024       return new SCEVCouldNotCompute();
3025     }
3026
3027   // The only time we can solve this is when we have all constant indices.
3028   // Otherwise, we cannot determine the overflow conditions.
3029   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3030     if (!isa<SCEVConstant>(getOperand(i)))
3031       return new SCEVCouldNotCompute();
3032
3033
3034   // Okay at this point we know that all elements of the chrec are constants and
3035   // that the start element is zero.
3036
3037   // First check to see if the range contains zero.  If not, the first
3038   // iteration exits.
3039   if (!Range.contains(APInt(getBitWidth(),0))) 
3040     return SE.getConstant(ConstantInt::get(getType(),0));
3041
3042   if (isAffine()) {
3043     // If this is an affine expression then we have this situation:
3044     //   Solve {0,+,A} in Range  ===  Ax in Range
3045
3046     // We know that zero is in the range.  If A is positive then we know that
3047     // the upper value of the range must be the first possible exit value.
3048     // If A is negative then the lower of the range is the last possible loop
3049     // value.  Also note that we already checked for a full range.
3050     APInt One(getBitWidth(),1);
3051     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3052     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3053
3054     // The exit value should be (End+A)/A.
3055     APInt ExitVal = (End + A).udiv(A);
3056     ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3057
3058     // Evaluate at the exit value.  If we really did fall out of the valid
3059     // range, then we computed our trip count, otherwise wrap around or other
3060     // things must have happened.
3061     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3062     if (Range.contains(Val->getValue()))
3063       return new SCEVCouldNotCompute();  // Something strange happened
3064
3065     // Ensure that the previous value is in the range.  This is a sanity check.
3066     assert(Range.contains(
3067            EvaluateConstantChrecAtConstant(this, 
3068            ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3069            "Linear scev computation is off in a bad way!");
3070     return SE.getConstant(ExitValue);
3071   } else if (isQuadratic()) {
3072     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3073     // quadratic equation to solve it.  To do this, we must frame our problem in
3074     // terms of figuring out when zero is crossed, instead of when
3075     // Range.getUpper() is crossed.
3076     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3077     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3078     SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3079
3080     // Next, solve the constructed addrec
3081     std::pair<SCEVHandle,SCEVHandle> Roots =
3082       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3083     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3084     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3085     if (R1) {
3086       // Pick the smallest positive root value.
3087       if (ConstantInt *CB =
3088           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
3089                                    R1->getValue(), R2->getValue()))) {
3090         if (CB->getZExtValue() == false)
3091           std::swap(R1, R2);   // R1 is the minimum root now.
3092
3093         // Make sure the root is not off by one.  The returned iteration should
3094         // not be in the range, but the previous one should be.  When solving
3095         // for "X*X < 5", for example, we should not return a root of 2.
3096         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3097                                                              R1->getValue(),
3098                                                              SE);
3099         if (Range.contains(R1Val->getValue())) {
3100           // The next iteration must be out of the range...
3101           ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3102
3103           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3104           if (!Range.contains(R1Val->getValue()))
3105             return SE.getConstant(NextVal);
3106           return new SCEVCouldNotCompute();  // Something strange happened
3107         }
3108
3109         // If R1 was not in the range, then it is a good return value.  Make
3110         // sure that R1-1 WAS in the range though, just in case.
3111         ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3112         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3113         if (Range.contains(R1Val->getValue()))
3114           return R1;
3115         return new SCEVCouldNotCompute();  // Something strange happened
3116       }
3117     }
3118   }
3119
3120   return new SCEVCouldNotCompute();
3121 }
3122
3123
3124
3125 //===----------------------------------------------------------------------===//
3126 //                   ScalarEvolution Class Implementation
3127 //===----------------------------------------------------------------------===//
3128
3129 bool ScalarEvolution::runOnFunction(Function &F) {
3130   Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
3131   return false;
3132 }
3133
3134 void ScalarEvolution::releaseMemory() {
3135   delete (ScalarEvolutionsImpl*)Impl;
3136   Impl = 0;
3137 }
3138
3139 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3140   AU.setPreservesAll();
3141   AU.addRequiredTransitive<LoopInfo>();
3142 }
3143
3144 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3145   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3146 }
3147
3148 /// hasSCEV - Return true if the SCEV for this value has already been
3149 /// computed.
3150 bool ScalarEvolution::hasSCEV(Value *V) const {
3151   return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3152 }
3153
3154
3155 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3156 /// the specified value.
3157 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3158   ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3159 }
3160
3161
3162 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3163   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3164 }
3165
3166 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3167   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3168 }
3169
3170 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3171   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3172 }
3173
3174 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3175   return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3176 }
3177
3178 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3179                           const Loop *L) {
3180   // Print all inner loops first
3181   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3182     PrintLoopInfo(OS, SE, *I);
3183
3184   OS << "Loop " << L->getHeader()->getName() << ": ";
3185
3186   SmallVector<BasicBlock*, 8> ExitBlocks;
3187   L->getExitBlocks(ExitBlocks);
3188   if (ExitBlocks.size() != 1)
3189     OS << "<multiple exits> ";
3190
3191   if (SE->hasLoopInvariantIterationCount(L)) {
3192     OS << *SE->getIterationCount(L) << " iterations! ";
3193   } else {
3194     OS << "Unpredictable iteration count. ";
3195   }
3196
3197   OS << "\n";
3198 }
3199
3200 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3201   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3202   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3203
3204   OS << "Classifying expressions for: " << F.getName() << "\n";
3205   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3206     if (I->getType()->isInteger()) {
3207       OS << *I;
3208       OS << "  -->  ";
3209       SCEVHandle SV = getSCEV(&*I);
3210       SV->print(OS);
3211       OS << "\t\t";
3212
3213       if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3214         OS << "Exits: ";
3215         SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3216         if (isa<SCEVCouldNotCompute>(ExitValue)) {
3217           OS << "<<Unknown>>";
3218         } else {
3219           OS << *ExitValue;
3220         }
3221       }
3222
3223
3224       OS << "\n";
3225     }
3226
3227   OS << "Determining loop execution counts for: " << F.getName() << "\n";
3228   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3229     PrintLoopInfo(OS, this, *I);
3230 }