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