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