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