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