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