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