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