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