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