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