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