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