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