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