1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
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.
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.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
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"
86 STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
98 static cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
104 static RegisterPass<ScalarEvolution>
105 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
106 char ScalarEvolution::ID = 0;
108 //===----------------------------------------------------------------------===//
109 // SCEV class definitions
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
113 // Implementation of the SCEV class.
116 void SCEV::dump() const {
120 uint32_t SCEV::getBitWidth() const {
121 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
122 return ITy->getBitWidth();
126 bool SCEV::isZero() const {
127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
128 return SC->getValue()->isZero();
133 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 SCEVHandle SCEVCouldNotCompute::
151 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
152 const SCEVHandle &Conc,
153 ScalarEvolution &SE) const {
157 void SCEVCouldNotCompute::print(std::ostream &OS) const {
158 OS << "***COULDNOTCOMPUTE***";
161 bool SCEVCouldNotCompute::classof(const SCEV *S) {
162 return S->getSCEVType() == scCouldNotCompute;
166 // SCEVConstants - Only allow the creation of one SCEVConstant for any
167 // particular value. Don't use a SCEVHandle here, or else the object will
169 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172 SCEVConstant::~SCEVConstant() {
173 SCEVConstants->erase(V);
176 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
177 SCEVConstant *&R = (*SCEVConstants)[V];
178 if (R == 0) R = new SCEVConstant(V);
182 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
183 return getConstant(ConstantInt::get(Val));
186 const Type *SCEVConstant::getType() const { return V->getType(); }
188 void SCEVConstant::print(std::ostream &OS) const {
189 WriteAsOperand(OS, V, false);
192 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
193 // particular input. Don't use a SCEVHandle here, or else the object will
195 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
196 SCEVTruncateExpr*> > SCEVTruncates;
198 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
199 : SCEV(scTruncate), Op(op), Ty(ty) {
200 assert(Op->getType()->isInteger() && Ty->isInteger() &&
201 "Cannot truncate non-integer value!");
202 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
203 && "This is not a truncating conversion!");
206 SCEVTruncateExpr::~SCEVTruncateExpr() {
207 SCEVTruncates->erase(std::make_pair(Op, Ty));
210 void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
214 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215 // particular input. Don't use a SCEVHandle here, or else the object will never
217 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> > SCEVZeroExtends;
220 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
221 : SCEV(scZeroExtend), Op(op), Ty(ty) {
222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
223 "Cannot zero extend non-integer value!");
224 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
225 && "This is not an extending conversion!");
228 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
229 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
232 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
233 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
236 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
237 // particular input. Don't use a SCEVHandle here, or else the object will never
239 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
240 SCEVSignExtendExpr*> > SCEVSignExtends;
242 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
243 : SCEV(scSignExtend), Op(op), Ty(ty) {
244 assert(Op->getType()->isInteger() && Ty->isInteger() &&
245 "Cannot sign extend non-integer value!");
246 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
247 && "This is not an extending conversion!");
250 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
251 SCEVSignExtends->erase(std::make_pair(Op, Ty));
254 void SCEVSignExtendExpr::print(std::ostream &OS) const {
255 OS << "(signextend " << *Op << " to " << *Ty << ")";
258 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
259 // particular input. Don't use a SCEVHandle here, or else the object will never
261 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
262 SCEVCommutativeExpr*> > SCEVCommExprs;
264 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
265 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
266 std::vector<SCEV*>(Operands.begin(),
270 void SCEVCommutativeExpr::print(std::ostream &OS) const {
271 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
272 const char *OpStr = getOperationStr();
273 OS << "(" << *Operands[0];
274 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
275 OS << OpStr << *Operands[i];
279 SCEVHandle SCEVCommutativeExpr::
280 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
281 const SCEVHandle &Conc,
282 ScalarEvolution &SE) const {
283 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
285 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
286 if (H != getOperand(i)) {
287 std::vector<SCEVHandle> NewOps;
288 NewOps.reserve(getNumOperands());
289 for (unsigned j = 0; j != i; ++j)
290 NewOps.push_back(getOperand(j));
292 for (++i; i != e; ++i)
293 NewOps.push_back(getOperand(i)->
294 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
296 if (isa<SCEVAddExpr>(this))
297 return SE.getAddExpr(NewOps);
298 else if (isa<SCEVMulExpr>(this))
299 return SE.getMulExpr(NewOps);
300 else if (isa<SCEVSMaxExpr>(this))
301 return SE.getSMaxExpr(NewOps);
302 else if (isa<SCEVUMaxExpr>(this))
303 return SE.getUMaxExpr(NewOps);
305 assert(0 && "Unknown commutative expr!");
312 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
313 // input. Don't use a SCEVHandle here, or else the object will never be
315 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
316 SCEVUDivExpr*> > SCEVUDivs;
318 SCEVUDivExpr::~SCEVUDivExpr() {
319 SCEVUDivs->erase(std::make_pair(LHS, RHS));
322 void SCEVUDivExpr::print(std::ostream &OS) const {
323 OS << "(" << *LHS << " /u " << *RHS << ")";
326 const Type *SCEVUDivExpr::getType() const {
327 return LHS->getType();
330 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
331 // particular input. Don't use a SCEVHandle here, or else the object will never
333 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
334 SCEVAddRecExpr*> > SCEVAddRecExprs;
336 SCEVAddRecExpr::~SCEVAddRecExpr() {
337 SCEVAddRecExprs->erase(std::make_pair(L,
338 std::vector<SCEV*>(Operands.begin(),
342 SCEVHandle SCEVAddRecExpr::
343 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
344 const SCEVHandle &Conc,
345 ScalarEvolution &SE) const {
346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
348 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
349 if (H != getOperand(i)) {
350 std::vector<SCEVHandle> NewOps;
351 NewOps.reserve(getNumOperands());
352 for (unsigned j = 0; j != i; ++j)
353 NewOps.push_back(getOperand(j));
355 for (++i; i != e; ++i)
356 NewOps.push_back(getOperand(i)->
357 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
359 return SE.getAddRecExpr(NewOps, L);
366 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
367 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
368 // contain L and if the start is invariant.
369 return !QueryLoop->contains(L->getHeader()) &&
370 getOperand(0)->isLoopInvariant(QueryLoop);
374 void SCEVAddRecExpr::print(std::ostream &OS) const {
375 OS << "{" << *Operands[0];
376 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
377 OS << ",+," << *Operands[i];
378 OS << "}<" << L->getHeader()->getName() + ">";
381 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
382 // value. Don't use a SCEVHandle here, or else the object will never be
384 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
386 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
388 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
389 // All non-instruction values are loop invariant. All instructions are loop
390 // invariant if they are not contained in the specified loop.
391 if (Instruction *I = dyn_cast<Instruction>(V))
392 return !L->contains(I->getParent());
396 const Type *SCEVUnknown::getType() const {
400 void SCEVUnknown::print(std::ostream &OS) const {
401 WriteAsOperand(OS, V, false);
404 //===----------------------------------------------------------------------===//
406 //===----------------------------------------------------------------------===//
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
412 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
413 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
414 return LHS->getSCEVType() < RHS->getSCEVType();
419 /// GroupByComplexity - Given a list of SCEV objects, order them by their
420 /// complexity, and group objects of the same complexity together by value.
421 /// When this routine is finished, we know that any duplicates in the vector are
422 /// consecutive and that complexity is monotonically increasing.
424 /// Note that we go take special precautions to ensure that we get determinstic
425 /// results from this routine. In other words, we don't want the results of
426 /// this to depend on where the addresses of various SCEV objects happened to
429 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
430 if (Ops.size() < 2) return; // Noop
431 if (Ops.size() == 2) {
432 // This is the common case, which also happens to be trivially simple.
434 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
435 std::swap(Ops[0], Ops[1]);
439 // Do the rough sort by complexity.
440 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
442 // Now that we are sorted by complexity, group elements of the same
443 // complexity. Note that this is, at worst, N^2, but the vector is likely to
444 // be extremely short in practice. Note that we take this approach because we
445 // do not want to depend on the addresses of the objects we are grouping.
446 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
448 unsigned Complexity = S->getSCEVType();
450 // If there are any objects of the same complexity and same value as this
452 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
453 if (Ops[j] == S) { // Found a duplicate.
454 // Move it to immediately after i'th element.
455 std::swap(Ops[i+1], Ops[j]);
456 ++i; // no need to rescan it.
457 if (i == e-2) return; // Done!
465 //===----------------------------------------------------------------------===//
466 // Simple SCEV method implementations
467 //===----------------------------------------------------------------------===//
469 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
470 /// specified signed integer value and return a SCEV for the constant.
471 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
474 C = Constant::getNullValue(Ty);
475 else if (Ty->isFloatingPoint())
476 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
477 APFloat::IEEEdouble, Val));
479 C = ConstantInt::get(Ty, Val);
480 return getUnknown(C);
483 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
485 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
486 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
487 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
489 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
492 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
493 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
494 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
495 return getUnknown(ConstantExpr::getNot(VC->getValue()));
497 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
498 return getMinusSCEV(AllOnes, V);
501 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
503 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
504 const SCEVHandle &RHS) {
506 return getAddExpr(LHS, getNegativeSCEV(RHS));
510 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
512 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
514 const IntegerType* ResultTy) {
515 // Handle the simplest case efficiently.
517 return SE.getTruncateOrZeroExtend(It, ResultTy);
519 // We are using the following formula for BC(It, K):
521 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
523 // Suppose, W is the bitwidth of the return value. We must be prepared for
524 // overflow. Hence, we must assure that the result of our computation is
525 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
526 // safe in modular arithmetic.
528 // However, this code doesn't use exactly that formula; the formula it uses
529 // is something like the following, where T is the number of factors of 2 in
530 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
533 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
535 // This formula is trivially equivalent to the previous formula. However,
536 // this formula can be implemented much more efficiently. The trick is that
537 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538 // arithmetic. To do exact division in modular arithmetic, all we have
539 // to do is multiply by the inverse. Therefore, this step can be done at
542 // The next issue is how to safely do the division by 2^T. The way this
543 // is done is by doing the multiplication step at a width of at least W + T
544 // bits. This way, the bottom W+T bits of the product are accurate. Then,
545 // when we perform the division by 2^T (which is equivalent to a right shift
546 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
547 // truncated out after the division by 2^T.
549 // In comparison to just directly using the first formula, this technique
550 // is much more efficient; using the first formula requires W * K bits,
551 // but this formula less than W + K bits. Also, the first formula requires
552 // a division step, whereas this formula only requires multiplies and shifts.
554 // It doesn't matter whether the subtraction step is done in the calculation
555 // width or the input iteration count's width; if the subtraction overflows,
556 // the result must be zero anyway. We prefer here to do it in the width of
557 // the induction variable because it helps a lot for certain cases; CodeGen
558 // isn't smart enough to ignore the overflow, which leads to much less
559 // efficient code if the width of the subtraction is wider than the native
562 // (It's possible to not widen at all by pulling out factors of 2 before
563 // the multiplication; for example, K=2 can be calculated as
564 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565 // extra arithmetic, so it's not an obvious win, and it gets
566 // much more complicated for K > 3.)
568 // Protection from insane SCEVs; this bound is conservative,
569 // but it probably doesn't matter.
571 return new SCEVCouldNotCompute();
573 unsigned W = ResultTy->getBitWidth();
575 // Calculate K! / 2^T and T; we divide out the factors of two before
576 // multiplying for calculating K! / 2^T to avoid overflow.
577 // Other overflow doesn't matter because we only care about the bottom
578 // W bits of the result.
579 APInt OddFactorial(W, 1);
581 for (unsigned i = 3; i <= K; ++i) {
583 unsigned TwoFactors = Mult.countTrailingZeros();
585 Mult = Mult.lshr(TwoFactors);
586 OddFactorial *= Mult;
589 // We need at least W + T bits for the multiplication step
590 // FIXME: A temporary hack; we round up the bitwidths
591 // to the nearest power of 2 to be nice to the code generator.
592 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
593 // FIXME: Temporary hack to avoid generating integers that are too wide.
594 // Although, it's not completely clear how to determine how much
595 // widening is safe; for example, on X86, we can't really widen
596 // beyond 64 because we need to be able to do multiplication
597 // that's CalculationBits wide, but on X86-64, we can safely widen up to
599 if (CalculationBits > 64)
600 return new SCEVCouldNotCompute();
602 // Calcuate 2^T, at width T+W.
603 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
605 // Calculate the multiplicative inverse of K! / 2^T;
606 // this multiplication factor will perform the exact division by
608 APInt Mod = APInt::getSignedMinValue(W+1);
609 APInt MultiplyFactor = OddFactorial.zext(W+1);
610 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
611 MultiplyFactor = MultiplyFactor.trunc(W);
613 // Calculate the product, at width T+W
614 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
615 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
616 for (unsigned i = 1; i != K; ++i) {
617 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
618 Dividend = SE.getMulExpr(Dividend,
619 SE.getTruncateOrZeroExtend(S, CalculationTy));
623 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
625 // Truncate the result, and divide by K! / 2^T.
627 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
628 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
631 /// evaluateAtIteration - Return the value of this chain of recurrences at
632 /// the specified iteration number. We can evaluate this recurrence by
633 /// multiplying each element in the chain by the binomial coefficient
634 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
636 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
638 /// where BC(It, k) stands for binomial coefficient.
640 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
641 ScalarEvolution &SE) const {
642 SCEVHandle Result = getStart();
643 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
644 // The computation is correct in the face of overflow provided that the
645 // multiplication is performed _after_ the evaluation of the binomial
648 SE.getMulExpr(getOperand(i),
649 BinomialCoefficient(It, i, SE,
650 cast<IntegerType>(getType())));
651 Result = SE.getAddExpr(Result, Val);
656 //===----------------------------------------------------------------------===//
657 // SCEV Expression folder implementations
658 //===----------------------------------------------------------------------===//
660 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
661 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
663 ConstantExpr::getTrunc(SC->getValue(), Ty));
665 // If the input value is a chrec scev made out of constants, truncate
666 // all of the constants.
667 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
668 std::vector<SCEVHandle> Operands;
669 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
670 // FIXME: This should allow truncation of other expression types!
671 if (isa<SCEVConstant>(AddRec->getOperand(i)))
672 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
675 if (Operands.size() == AddRec->getNumOperands())
676 return getAddRecExpr(Operands, AddRec->getLoop());
679 if (isa<SCEVCouldNotCompute>(Op))
680 return new SCEVCouldNotCompute();
682 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
683 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
687 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
688 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
690 ConstantExpr::getZExt(SC->getValue(), Ty));
692 // FIXME: If the input value is a chrec scev, and we can prove that the value
693 // did not overflow the old, smaller, value, we can zero extend all of the
694 // operands (often constants). This would allow analysis of something like
695 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
697 if (isa<SCEVCouldNotCompute>(Op))
698 return new SCEVCouldNotCompute();
700 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
701 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
705 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
706 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
708 ConstantExpr::getSExt(SC->getValue(), Ty));
710 // FIXME: If the input value is a chrec scev, and we can prove that the value
711 // did not overflow the old, smaller, value, we can sign extend all of the
712 // operands (often constants). This would allow analysis of something like
713 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
715 if (isa<SCEVCouldNotCompute>(Op))
716 return new SCEVCouldNotCompute();
718 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
719 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
723 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
724 /// of the input value to the specified type. If the type must be
725 /// extended, it is zero extended.
726 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
728 const Type *SrcTy = V->getType();
729 assert(SrcTy->isInteger() && Ty->isInteger() &&
730 "Cannot truncate or zero extend with non-integer arguments!");
731 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
732 return V; // No conversion
733 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
734 return getTruncateExpr(V, Ty);
735 return getZeroExtendExpr(V, Ty);
738 // get - Get a canonical add expression, or something simpler if possible.
739 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
740 assert(!Ops.empty() && "Cannot get empty add!");
741 if (Ops.size() == 1) return Ops[0];
743 // Sort by complexity, this groups all similar expression types together.
744 GroupByComplexity(Ops);
746 // Could not compute plus anything equals could not compute.
747 if (isa<SCEVCouldNotCompute>(Ops.back()))
748 return new SCEVCouldNotCompute();
750 // If there are any constants, fold them together.
752 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
754 assert(Idx < Ops.size());
755 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
756 // We found two constants, fold them together!
757 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
758 RHSC->getValue()->getValue());
759 Ops[0] = getConstant(Fold);
760 Ops.erase(Ops.begin()+1); // Erase the folded element
761 if (Ops.size() == 1) return Ops[0];
762 LHSC = cast<SCEVConstant>(Ops[0]);
765 // If we are left with a constant zero being added, strip it off.
766 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
767 Ops.erase(Ops.begin());
772 if (Ops.size() == 1) return Ops[0];
774 // Okay, check to see if the same value occurs in the operand list twice. If
775 // so, merge them together into an multiply expression. Since we sorted the
776 // list, these values are required to be adjacent.
777 const Type *Ty = Ops[0]->getType();
778 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
779 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
780 // Found a match, merge the two values into a multiply, and add any
781 // remaining values to the result.
782 SCEVHandle Two = getIntegerSCEV(2, Ty);
783 SCEVHandle Mul = getMulExpr(Ops[i], Two);
786 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
788 return getAddExpr(Ops);
791 // Now we know the first non-constant operand. Skip past any cast SCEVs.
792 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
795 // If there are add operands they would be next.
796 if (Idx < Ops.size()) {
797 bool DeletedAdd = false;
798 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
799 // If we have an add, expand the add operands onto the end of the operands
801 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
802 Ops.erase(Ops.begin()+Idx);
806 // If we deleted at least one add, we added operands to the end of the list,
807 // and they are not necessarily sorted. Recurse to resort and resimplify
808 // any operands we just aquired.
810 return getAddExpr(Ops);
813 // Skip over the add expression until we get to a multiply.
814 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
817 // If we are adding something to a multiply expression, make sure the
818 // something is not already an operand of the multiply. If so, merge it into
820 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
821 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
822 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
823 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
824 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
825 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
826 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
827 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
828 if (Mul->getNumOperands() != 2) {
829 // If the multiply has more than two operands, we must get the
831 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
832 MulOps.erase(MulOps.begin()+MulOp);
833 InnerMul = getMulExpr(MulOps);
835 SCEVHandle One = getIntegerSCEV(1, Ty);
836 SCEVHandle AddOne = getAddExpr(InnerMul, One);
837 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
838 if (Ops.size() == 2) return OuterMul;
840 Ops.erase(Ops.begin()+AddOp);
841 Ops.erase(Ops.begin()+Idx-1);
843 Ops.erase(Ops.begin()+Idx);
844 Ops.erase(Ops.begin()+AddOp-1);
846 Ops.push_back(OuterMul);
847 return getAddExpr(Ops);
850 // Check this multiply against other multiplies being added together.
851 for (unsigned OtherMulIdx = Idx+1;
852 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
854 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
855 // If MulOp occurs in OtherMul, we can fold the two multiplies
857 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
858 OMulOp != e; ++OMulOp)
859 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
860 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
861 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
862 if (Mul->getNumOperands() != 2) {
863 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
864 MulOps.erase(MulOps.begin()+MulOp);
865 InnerMul1 = getMulExpr(MulOps);
867 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
868 if (OtherMul->getNumOperands() != 2) {
869 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
871 MulOps.erase(MulOps.begin()+OMulOp);
872 InnerMul2 = getMulExpr(MulOps);
874 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
875 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
876 if (Ops.size() == 2) return OuterMul;
877 Ops.erase(Ops.begin()+Idx);
878 Ops.erase(Ops.begin()+OtherMulIdx-1);
879 Ops.push_back(OuterMul);
880 return getAddExpr(Ops);
886 // If there are any add recurrences in the operands list, see if any other
887 // added values are loop invariant. If so, we can fold them into the
889 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
892 // Scan over all recurrences, trying to fold loop invariants into them.
893 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
894 // Scan all of the other operands to this add and add them to the vector if
895 // they are loop invariant w.r.t. the recurrence.
896 std::vector<SCEVHandle> LIOps;
897 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
898 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
899 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
900 LIOps.push_back(Ops[i]);
901 Ops.erase(Ops.begin()+i);
905 // If we found some loop invariants, fold them into the recurrence.
906 if (!LIOps.empty()) {
907 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
908 LIOps.push_back(AddRec->getStart());
910 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
911 AddRecOps[0] = getAddExpr(LIOps);
913 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
914 // If all of the other operands were loop invariant, we are done.
915 if (Ops.size() == 1) return NewRec;
917 // Otherwise, add the folded AddRec by the non-liv parts.
918 for (unsigned i = 0;; ++i)
919 if (Ops[i] == AddRec) {
923 return getAddExpr(Ops);
926 // Okay, if there weren't any loop invariants to be folded, check to see if
927 // there are multiple AddRec's with the same loop induction variable being
928 // added together. If so, we can fold them.
929 for (unsigned OtherIdx = Idx+1;
930 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
931 if (OtherIdx != Idx) {
932 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
933 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
934 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
935 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
936 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
937 if (i >= NewOps.size()) {
938 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
939 OtherAddRec->op_end());
942 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
944 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
946 if (Ops.size() == 2) return NewAddRec;
948 Ops.erase(Ops.begin()+Idx);
949 Ops.erase(Ops.begin()+OtherIdx-1);
950 Ops.push_back(NewAddRec);
951 return getAddExpr(Ops);
955 // Otherwise couldn't fold anything into this recurrence. Move onto the
959 // Okay, it looks like we really DO need an add expr. Check to see if we
960 // already have one, otherwise create a new one.
961 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
962 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
964 if (Result == 0) Result = new SCEVAddExpr(Ops);
969 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
970 assert(!Ops.empty() && "Cannot get empty mul!");
972 // Sort by complexity, this groups all similar expression types together.
973 GroupByComplexity(Ops);
975 if (isa<SCEVCouldNotCompute>(Ops.back())) {
977 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
978 if (Ops[i]->getSCEVType() != scConstant)
981 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
982 if (SC->getValue()->isMinValue(false))
986 // Otherwise, we can't compute it.
987 return new SCEVCouldNotCompute();
990 // If there are any constants, fold them together.
992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
994 // C1*(C2+V) -> C1*C2 + C1*V
996 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
997 if (Add->getNumOperands() == 2 &&
998 isa<SCEVConstant>(Add->getOperand(0)))
999 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1000 getMulExpr(LHSC, Add->getOperand(1)));
1004 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1005 // We found two constants, fold them together!
1006 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1007 RHSC->getValue()->getValue());
1008 Ops[0] = getConstant(Fold);
1009 Ops.erase(Ops.begin()+1); // Erase the folded element
1010 if (Ops.size() == 1) return Ops[0];
1011 LHSC = cast<SCEVConstant>(Ops[0]);
1014 // If we are left with a constant one being multiplied, strip it off.
1015 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1016 Ops.erase(Ops.begin());
1018 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1019 // If we have a multiply of zero, it will always be zero.
1024 // Skip over the add expression until we get to a multiply.
1025 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1028 if (Ops.size() == 1)
1031 // If there are mul operands inline them all into this expression.
1032 if (Idx < Ops.size()) {
1033 bool DeletedMul = false;
1034 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1035 // If we have an mul, expand the mul operands onto the end of the operands
1037 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1038 Ops.erase(Ops.begin()+Idx);
1042 // If we deleted at least one mul, we added operands to the end of the list,
1043 // and they are not necessarily sorted. Recurse to resort and resimplify
1044 // any operands we just aquired.
1046 return getMulExpr(Ops);
1049 // If there are any add recurrences in the operands list, see if any other
1050 // added values are loop invariant. If so, we can fold them into the
1052 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1055 // Scan over all recurrences, trying to fold loop invariants into them.
1056 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1057 // Scan all of the other operands to this mul and add them to the vector if
1058 // they are loop invariant w.r.t. the recurrence.
1059 std::vector<SCEVHandle> LIOps;
1060 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1061 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1062 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1063 LIOps.push_back(Ops[i]);
1064 Ops.erase(Ops.begin()+i);
1068 // If we found some loop invariants, fold them into the recurrence.
1069 if (!LIOps.empty()) {
1070 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1071 std::vector<SCEVHandle> NewOps;
1072 NewOps.reserve(AddRec->getNumOperands());
1073 if (LIOps.size() == 1) {
1074 SCEV *Scale = LIOps[0];
1075 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1076 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1078 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1079 std::vector<SCEVHandle> MulOps(LIOps);
1080 MulOps.push_back(AddRec->getOperand(i));
1081 NewOps.push_back(getMulExpr(MulOps));
1085 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1087 // If all of the other operands were loop invariant, we are done.
1088 if (Ops.size() == 1) return NewRec;
1090 // Otherwise, multiply the folded AddRec by the non-liv parts.
1091 for (unsigned i = 0;; ++i)
1092 if (Ops[i] == AddRec) {
1096 return getMulExpr(Ops);
1099 // Okay, if there weren't any loop invariants to be folded, check to see if
1100 // there are multiple AddRec's with the same loop induction variable being
1101 // multiplied together. If so, we can fold them.
1102 for (unsigned OtherIdx = Idx+1;
1103 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1104 if (OtherIdx != Idx) {
1105 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1106 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1107 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1108 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1109 SCEVHandle NewStart = getMulExpr(F->getStart(),
1111 SCEVHandle B = F->getStepRecurrence(*this);
1112 SCEVHandle D = G->getStepRecurrence(*this);
1113 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1116 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1118 if (Ops.size() == 2) return NewAddRec;
1120 Ops.erase(Ops.begin()+Idx);
1121 Ops.erase(Ops.begin()+OtherIdx-1);
1122 Ops.push_back(NewAddRec);
1123 return getMulExpr(Ops);
1127 // Otherwise couldn't fold anything into this recurrence. Move onto the
1131 // Okay, it looks like we really DO need an mul expr. Check to see if we
1132 // already have one, otherwise create a new one.
1133 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1134 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1137 Result = new SCEVMulExpr(Ops);
1141 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1142 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1143 if (RHSC->getValue()->equalsInt(1))
1144 return LHS; // X udiv 1 --> x
1146 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1147 Constant *LHSCV = LHSC->getValue();
1148 Constant *RHSCV = RHSC->getValue();
1149 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1153 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1155 if (isa<SCEVCouldNotCompute>(LHS) || isa<SCEVCouldNotCompute>(RHS))
1156 return new SCEVCouldNotCompute();
1158 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1159 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1164 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1165 /// specified loop. Simplify the expression as much as possible.
1166 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1167 const SCEVHandle &Step, const Loop *L) {
1168 std::vector<SCEVHandle> Operands;
1169 Operands.push_back(Start);
1170 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1171 if (StepChrec->getLoop() == L) {
1172 Operands.insert(Operands.end(), StepChrec->op_begin(),
1173 StepChrec->op_end());
1174 return getAddRecExpr(Operands, L);
1177 Operands.push_back(Step);
1178 return getAddRecExpr(Operands, L);
1181 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1182 /// specified loop. Simplify the expression as much as possible.
1183 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1185 if (Operands.size() == 1) return Operands[0];
1187 if (Operands.back()->isZero()) {
1188 Operands.pop_back();
1189 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1192 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1193 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1194 const Loop* NestedLoop = NestedAR->getLoop();
1195 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1196 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1197 NestedAR->op_end());
1198 SCEVHandle NestedARHandle(NestedAR);
1199 Operands[0] = NestedAR->getStart();
1200 NestedOperands[0] = getAddRecExpr(Operands, L);
1201 return getAddRecExpr(NestedOperands, NestedLoop);
1205 // Refuse to build an AddRec out of SCEVCouldNotCompute.
1206 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1207 if (isa<SCEVCouldNotCompute>(Operands[i]))
1208 return new SCEVCouldNotCompute();
1211 SCEVAddRecExpr *&Result =
1212 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1214 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1218 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1219 const SCEVHandle &RHS) {
1220 std::vector<SCEVHandle> Ops;
1223 return getSMaxExpr(Ops);
1226 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1227 assert(!Ops.empty() && "Cannot get empty smax!");
1228 if (Ops.size() == 1) return Ops[0];
1230 // Sort by complexity, this groups all similar expression types together.
1231 GroupByComplexity(Ops);
1233 if (isa<SCEVCouldNotCompute>(Ops.back())) {
1234 // CNC smax +inf = +inf.
1235 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
1236 if (Ops[i]->getSCEVType() != scConstant)
1239 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
1240 if (SC->getValue()->isMaxValue(true))
1244 // Otherwise, we can't compute it.
1245 return new SCEVCouldNotCompute();
1248 // If there are any constants, fold them together.
1250 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1252 assert(Idx < Ops.size());
1253 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1254 // We found two constants, fold them together!
1255 ConstantInt *Fold = ConstantInt::get(
1256 APIntOps::smax(LHSC->getValue()->getValue(),
1257 RHSC->getValue()->getValue()));
1258 Ops[0] = getConstant(Fold);
1259 Ops.erase(Ops.begin()+1); // Erase the folded element
1260 if (Ops.size() == 1) return Ops[0];
1261 LHSC = cast<SCEVConstant>(Ops[0]);
1264 // If we are left with a constant -inf, strip it off.
1265 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1266 Ops.erase(Ops.begin());
1271 if (Ops.size() == 1) return Ops[0];
1273 // Find the first SMax
1274 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1277 // Check to see if one of the operands is an SMax. If so, expand its operands
1278 // onto our operand list, and recurse to simplify.
1279 if (Idx < Ops.size()) {
1280 bool DeletedSMax = false;
1281 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1282 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1283 Ops.erase(Ops.begin()+Idx);
1288 return getSMaxExpr(Ops);
1291 // Okay, check to see if the same value occurs in the operand list twice. If
1292 // so, delete one. Since we sorted the list, these values are required to
1294 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1295 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1296 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1300 if (Ops.size() == 1) return Ops[0];
1302 assert(!Ops.empty() && "Reduced smax down to nothing!");
1304 // Okay, it looks like we really DO need an smax expr. Check to see if we
1305 // already have one, otherwise create a new one.
1306 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1307 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1309 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1313 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1314 const SCEVHandle &RHS) {
1315 std::vector<SCEVHandle> Ops;
1318 return getUMaxExpr(Ops);
1321 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1322 assert(!Ops.empty() && "Cannot get empty umax!");
1323 if (Ops.size() == 1) return Ops[0];
1325 // Sort by complexity, this groups all similar expression types together.
1326 GroupByComplexity(Ops);
1328 if (isa<SCEVCouldNotCompute>(Ops[0])) {
1329 // CNC umax inf = inf.
1330 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
1331 if (Ops[i]->getSCEVType() != scConstant)
1334 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
1335 if (SC->getValue()->isMaxValue(false))
1339 // Otherwise, we can't compute it.
1340 return new SCEVCouldNotCompute();
1343 // If there are any constants, fold them together.
1345 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1347 assert(Idx < Ops.size());
1348 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1349 // We found two constants, fold them together!
1350 ConstantInt *Fold = ConstantInt::get(
1351 APIntOps::umax(LHSC->getValue()->getValue(),
1352 RHSC->getValue()->getValue()));
1353 Ops[0] = getConstant(Fold);
1354 Ops.erase(Ops.begin()+1); // Erase the folded element
1355 if (Ops.size() == 1) return Ops[0];
1356 LHSC = cast<SCEVConstant>(Ops[0]);
1359 // If we are left with a constant zero, strip it off.
1360 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1361 Ops.erase(Ops.begin());
1366 if (Ops.size() == 1) return Ops[0];
1368 // Find the first UMax
1369 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1372 // Check to see if one of the operands is a UMax. If so, expand its operands
1373 // onto our operand list, and recurse to simplify.
1374 if (Idx < Ops.size()) {
1375 bool DeletedUMax = false;
1376 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1377 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1378 Ops.erase(Ops.begin()+Idx);
1383 return getUMaxExpr(Ops);
1386 // Okay, check to see if the same value occurs in the operand list twice. If
1387 // so, delete one. Since we sorted the list, these values are required to
1389 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1390 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1391 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1395 if (Ops.size() == 1) return Ops[0];
1397 assert(!Ops.empty() && "Reduced umax down to nothing!");
1399 // Okay, it looks like we really DO need a umax expr. Check to see if we
1400 // already have one, otherwise create a new one.
1401 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1402 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1404 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1408 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1409 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1410 return getConstant(CI);
1411 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1412 if (Result == 0) Result = new SCEVUnknown(V);
1417 //===----------------------------------------------------------------------===//
1418 // ScalarEvolutionsImpl Definition and Implementation
1419 //===----------------------------------------------------------------------===//
1421 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1425 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1426 /// SE - A reference to the public ScalarEvolution object.
1427 ScalarEvolution &SE;
1429 /// F - The function we are analyzing.
1433 /// LI - The loop information for the function we are currently analyzing.
1437 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1439 SCEVHandle UnknownValue;
1441 /// Scalars - This is a cache of the scalars we have analyzed so far.
1443 std::map<Value*, SCEVHandle> Scalars;
1445 /// IterationCounts - Cache the iteration count of the loops for this
1446 /// function as they are computed.
1447 std::map<const Loop*, SCEVHandle> IterationCounts;
1449 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1450 /// the PHI instructions that we attempt to compute constant evolutions for.
1451 /// This allows us to avoid potentially expensive recomputation of these
1452 /// properties. An instruction maps to null if we are unable to compute its
1454 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1457 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1458 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1460 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1461 /// expression and create a new one.
1462 SCEVHandle getSCEV(Value *V);
1464 /// hasSCEV - Return true if the SCEV for this value has already been
1466 bool hasSCEV(Value *V) const {
1467 return Scalars.count(V);
1470 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1471 /// the specified value.
1472 void setSCEV(Value *V, const SCEVHandle &H) {
1473 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1474 assert(isNew && "This entry already existed!");
1478 /// getSCEVAtScope - Compute the value of the specified expression within
1479 /// the indicated loop (which may be null to indicate in no loop). If the
1480 /// expression cannot be evaluated, return UnknownValue itself.
1481 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1484 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1485 /// an analyzable loop-invariant iteration count.
1486 bool hasLoopInvariantIterationCount(const Loop *L);
1488 /// getIterationCount - If the specified loop has a predictable iteration
1489 /// count, return it. Note that it is not valid to call this method on a
1490 /// loop without a loop-invariant iteration count.
1491 SCEVHandle getIterationCount(const Loop *L);
1493 /// deleteValueFromRecords - This method should be called by the
1494 /// client before it removes a value from the program, to make sure
1495 /// that no dangling references are left around.
1496 void deleteValueFromRecords(Value *V);
1499 /// createSCEV - We know that there is no SCEV for the specified value.
1500 /// Analyze the expression.
1501 SCEVHandle createSCEV(Value *V);
1503 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1505 SCEVHandle createNodeForPHI(PHINode *PN);
1507 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1508 /// for the specified instruction and replaces any references to the
1509 /// symbolic value SymName with the specified value. This is used during
1511 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1512 const SCEVHandle &SymName,
1513 const SCEVHandle &NewVal);
1515 /// ComputeIterationCount - Compute the number of times the specified loop
1517 SCEVHandle ComputeIterationCount(const Loop *L);
1519 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1520 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1521 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1524 ICmpInst::Predicate p);
1526 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1527 /// constant number of times (the condition evolves only from constants),
1528 /// try to evaluate a few iterations of the loop until we get the exit
1529 /// condition gets a value of ExitWhen (true or false). If we cannot
1530 /// evaluate the trip count of the loop, return UnknownValue.
1531 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1534 /// HowFarToZero - Return the number of times a backedge comparing the
1535 /// specified value to zero will execute. If not computable, return
1537 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1539 /// HowFarToNonZero - Return the number of times a backedge checking the
1540 /// specified value for nonzero will execute. If not computable, return
1542 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1544 /// HowManyLessThans - Return the number of times a backedge containing the
1545 /// specified less-than comparison will execute. If not computable, return
1546 /// UnknownValue. isSigned specifies whether the less-than is signed.
1547 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1550 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1551 /// (which may not be an immediate predecessor) which has exactly one
1552 /// successor from which BB is reachable, or null if no such block is
1554 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1556 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1557 /// a conditional between LHS and RHS.
1558 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
1560 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1561 /// in the header of its containing loop, we know the loop executes a
1562 /// constant number of times, and the PHI node is just a recurrence
1563 /// involving constants, fold it.
1564 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1569 //===----------------------------------------------------------------------===//
1570 // Basic SCEV Analysis and PHI Idiom Recognition Code
1573 /// deleteValueFromRecords - This method should be called by the
1574 /// client before it removes an instruction from the program, to make sure
1575 /// that no dangling references are left around.
1576 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1577 SmallVector<Value *, 16> Worklist;
1579 if (Scalars.erase(V)) {
1580 if (PHINode *PN = dyn_cast<PHINode>(V))
1581 ConstantEvolutionLoopExitValue.erase(PN);
1582 Worklist.push_back(V);
1585 while (!Worklist.empty()) {
1586 Value *VV = Worklist.back();
1587 Worklist.pop_back();
1589 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1591 Instruction *Inst = cast<Instruction>(*UI);
1592 if (Scalars.erase(Inst)) {
1593 if (PHINode *PN = dyn_cast<PHINode>(VV))
1594 ConstantEvolutionLoopExitValue.erase(PN);
1595 Worklist.push_back(Inst);
1602 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1603 /// expression and create a new one.
1604 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1605 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1607 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1608 if (I != Scalars.end()) return I->second;
1609 SCEVHandle S = createSCEV(V);
1610 Scalars.insert(std::make_pair(V, S));
1614 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1615 /// the specified instruction and replaces any references to the symbolic value
1616 /// SymName with the specified value. This is used during PHI resolution.
1617 void ScalarEvolutionsImpl::
1618 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1619 const SCEVHandle &NewVal) {
1620 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1621 if (SI == Scalars.end()) return;
1624 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1625 if (NV == SI->second) return; // No change.
1627 SI->second = NV; // Update the scalars map!
1629 // Any instruction values that use this instruction might also need to be
1631 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1633 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1636 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1637 /// a loop header, making it a potential recurrence, or it doesn't.
1639 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1640 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1641 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1642 if (L->getHeader() == PN->getParent()) {
1643 // If it lives in the loop header, it has two incoming values, one
1644 // from outside the loop, and one from inside.
1645 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1646 unsigned BackEdge = IncomingEdge^1;
1648 // While we are analyzing this PHI node, handle its value symbolically.
1649 SCEVHandle SymbolicName = SE.getUnknown(PN);
1650 assert(Scalars.find(PN) == Scalars.end() &&
1651 "PHI node already processed?");
1652 Scalars.insert(std::make_pair(PN, SymbolicName));
1654 // Using this symbolic name for the PHI, analyze the value coming around
1656 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1658 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1659 // has a special value for the first iteration of the loop.
1661 // If the value coming around the backedge is an add with the symbolic
1662 // value we just inserted, then we found a simple induction variable!
1663 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1664 // If there is a single occurrence of the symbolic value, replace it
1665 // with a recurrence.
1666 unsigned FoundIndex = Add->getNumOperands();
1667 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1668 if (Add->getOperand(i) == SymbolicName)
1669 if (FoundIndex == e) {
1674 if (FoundIndex != Add->getNumOperands()) {
1675 // Create an add with everything but the specified operand.
1676 std::vector<SCEVHandle> Ops;
1677 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1678 if (i != FoundIndex)
1679 Ops.push_back(Add->getOperand(i));
1680 SCEVHandle Accum = SE.getAddExpr(Ops);
1682 // This is not a valid addrec if the step amount is varying each
1683 // loop iteration, but is not itself an addrec in this loop.
1684 if (Accum->isLoopInvariant(L) ||
1685 (isa<SCEVAddRecExpr>(Accum) &&
1686 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1687 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1688 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1690 // Okay, for the entire analysis of this edge we assumed the PHI
1691 // to be symbolic. We now need to go back and update all of the
1692 // entries for the scalars that use the PHI (except for the PHI
1693 // itself) to use the new analyzed value instead of the "symbolic"
1695 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1699 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1700 // Otherwise, this could be a loop like this:
1701 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1702 // In this case, j = {1,+,1} and BEValue is j.
1703 // Because the other in-value of i (0) fits the evolution of BEValue
1704 // i really is an addrec evolution.
1705 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1706 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1708 // If StartVal = j.start - j.stride, we can use StartVal as the
1709 // initial step of the addrec evolution.
1710 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1711 AddRec->getOperand(1))) {
1712 SCEVHandle PHISCEV =
1713 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1715 // Okay, for the entire analysis of this edge we assumed the PHI
1716 // to be symbolic. We now need to go back and update all of the
1717 // entries for the scalars that use the PHI (except for the PHI
1718 // itself) to use the new analyzed value instead of the "symbolic"
1720 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1726 return SymbolicName;
1729 // If it's not a loop phi, we can't handle it yet.
1730 return SE.getUnknown(PN);
1733 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1734 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1735 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1736 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1737 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1738 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1739 return C->getValue()->getValue().countTrailingZeros();
1741 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1742 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1744 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1745 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1746 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1749 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1750 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1751 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1754 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1755 // The result is the min of all operands results.
1756 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1757 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1758 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1762 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1763 // The result is the sum of all operands results.
1764 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1765 uint32_t BitWidth = M->getBitWidth();
1766 for (unsigned i = 1, e = M->getNumOperands();
1767 SumOpRes != BitWidth && i != e; ++i)
1768 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1773 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1774 // The result is the min of all operands results.
1775 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1776 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1777 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1781 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1782 // The result is the min of all operands results.
1783 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1784 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1785 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1789 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1790 // The result is the min of all operands results.
1791 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1792 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1793 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1797 // SCEVUDivExpr, SCEVUnknown
1801 /// createSCEV - We know that there is no SCEV for the specified value.
1802 /// Analyze the expression.
1804 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1805 if (!isa<IntegerType>(V->getType()))
1806 return SE.getUnknown(V);
1808 unsigned Opcode = Instruction::UserOp1;
1809 if (Instruction *I = dyn_cast<Instruction>(V))
1810 Opcode = I->getOpcode();
1811 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1812 Opcode = CE->getOpcode();
1814 return SE.getUnknown(V);
1816 User *U = cast<User>(V);
1818 case Instruction::Add:
1819 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1820 getSCEV(U->getOperand(1)));
1821 case Instruction::Mul:
1822 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1823 getSCEV(U->getOperand(1)));
1824 case Instruction::UDiv:
1825 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1826 getSCEV(U->getOperand(1)));
1827 case Instruction::Sub:
1828 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1829 getSCEV(U->getOperand(1)));
1830 case Instruction::Or:
1831 // If the RHS of the Or is a constant, we may have something like:
1832 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1833 // optimizations will transparently handle this case.
1835 // In order for this transformation to be safe, the LHS must be of the
1836 // form X*(2^n) and the Or constant must be less than 2^n.
1837 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1838 SCEVHandle LHS = getSCEV(U->getOperand(0));
1839 const APInt &CIVal = CI->getValue();
1840 if (GetMinTrailingZeros(LHS) >=
1841 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1842 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1845 case Instruction::Xor:
1846 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1847 // If the RHS of the xor is a signbit, then this is just an add.
1848 // Instcombine turns add of signbit into xor as a strength reduction step.
1849 if (CI->getValue().isSignBit())
1850 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1851 getSCEV(U->getOperand(1)));
1853 // If the RHS of xor is -1, then this is a not operation.
1854 else if (CI->isAllOnesValue())
1855 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1859 case Instruction::Shl:
1860 // Turn shift left of a constant amount into a multiply.
1861 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1862 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1863 Constant *X = ConstantInt::get(
1864 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1865 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1869 case Instruction::LShr:
1870 // Turn logical shift right of a constant into a unsigned divide.
1871 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1872 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1873 Constant *X = ConstantInt::get(
1874 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1875 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1879 case Instruction::Trunc:
1880 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1882 case Instruction::ZExt:
1883 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1885 case Instruction::SExt:
1886 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1888 case Instruction::BitCast:
1889 // BitCasts are no-op casts so we just eliminate the cast.
1890 if (U->getType()->isInteger() &&
1891 U->getOperand(0)->getType()->isInteger())
1892 return getSCEV(U->getOperand(0));
1895 case Instruction::PHI:
1896 return createNodeForPHI(cast<PHINode>(U));
1898 case Instruction::Select:
1899 // This could be a smax or umax that was lowered earlier.
1900 // Try to recover it.
1901 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1902 Value *LHS = ICI->getOperand(0);
1903 Value *RHS = ICI->getOperand(1);
1904 switch (ICI->getPredicate()) {
1905 case ICmpInst::ICMP_SLT:
1906 case ICmpInst::ICMP_SLE:
1907 std::swap(LHS, RHS);
1909 case ICmpInst::ICMP_SGT:
1910 case ICmpInst::ICMP_SGE:
1911 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1912 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1913 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1914 // ~smax(~x, ~y) == smin(x, y).
1915 return SE.getNotSCEV(SE.getSMaxExpr(
1916 SE.getNotSCEV(getSCEV(LHS)),
1917 SE.getNotSCEV(getSCEV(RHS))));
1919 case ICmpInst::ICMP_ULT:
1920 case ICmpInst::ICMP_ULE:
1921 std::swap(LHS, RHS);
1923 case ICmpInst::ICMP_UGT:
1924 case ICmpInst::ICMP_UGE:
1925 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1926 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1927 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1928 // ~umax(~x, ~y) == umin(x, y)
1929 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1930 SE.getNotSCEV(getSCEV(RHS))));
1937 default: // We cannot analyze this expression.
1941 return SE.getUnknown(V);
1946 //===----------------------------------------------------------------------===//
1947 // Iteration Count Computation Code
1950 /// getIterationCount - If the specified loop has a predictable iteration
1951 /// count, return it. Note that it is not valid to call this method on a
1952 /// loop without a loop-invariant iteration count.
1953 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1954 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1955 if (I == IterationCounts.end()) {
1956 SCEVHandle ItCount = ComputeIterationCount(L);
1957 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1958 if (ItCount != UnknownValue) {
1959 assert(ItCount->isLoopInvariant(L) &&
1960 "Computed trip count isn't loop invariant for loop!");
1961 ++NumTripCountsComputed;
1962 } else if (isa<PHINode>(L->getHeader()->begin())) {
1963 // Only count loops that have phi nodes as not being computable.
1964 ++NumTripCountsNotComputed;
1970 /// ComputeIterationCount - Compute the number of times the specified loop
1972 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1973 // If the loop has a non-one exit block count, we can't analyze it.
1974 SmallVector<BasicBlock*, 8> ExitBlocks;
1975 L->getExitBlocks(ExitBlocks);
1976 if (ExitBlocks.size() != 1) return UnknownValue;
1978 // Okay, there is one exit block. Try to find the condition that causes the
1979 // loop to be exited.
1980 BasicBlock *ExitBlock = ExitBlocks[0];
1982 BasicBlock *ExitingBlock = 0;
1983 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1985 if (L->contains(*PI)) {
1986 if (ExitingBlock == 0)
1989 return UnknownValue; // More than one block exiting!
1991 assert(ExitingBlock && "No exits from loop, something is broken!");
1993 // Okay, we've computed the exiting block. See what condition causes us to
1996 // FIXME: we should be able to handle switch instructions (with a single exit)
1997 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1998 if (ExitBr == 0) return UnknownValue;
1999 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2001 // At this point, we know we have a conditional branch that determines whether
2002 // the loop is exited. However, we don't know if the branch is executed each
2003 // time through the loop. If not, then the execution count of the branch will
2004 // not be equal to the trip count of the loop.
2006 // Currently we check for this by checking to see if the Exit branch goes to
2007 // the loop header. If so, we know it will always execute the same number of
2008 // times as the loop. We also handle the case where the exit block *is* the
2009 // loop header. This is common for un-rotated loops. More extensive analysis
2010 // could be done to handle more cases here.
2011 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2012 ExitBr->getSuccessor(1) != L->getHeader() &&
2013 ExitBr->getParent() != L->getHeader())
2014 return UnknownValue;
2016 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2018 // If it's not an integer comparison then compute it the hard way.
2019 // Note that ICmpInst deals with pointer comparisons too so we must check
2020 // the type of the operand.
2021 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2022 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2023 ExitBr->getSuccessor(0) == ExitBlock);
2025 // If the condition was exit on true, convert the condition to exit on false
2026 ICmpInst::Predicate Cond;
2027 if (ExitBr->getSuccessor(1) == ExitBlock)
2028 Cond = ExitCond->getPredicate();
2030 Cond = ExitCond->getInversePredicate();
2032 // Handle common loops like: for (X = "string"; *X; ++X)
2033 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2034 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2036 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2037 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2040 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2041 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2043 // Try to evaluate any dependencies out of the loop.
2044 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2045 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2046 Tmp = getSCEVAtScope(RHS, L);
2047 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2049 // At this point, we would like to compute how many iterations of the
2050 // loop the predicate will return true for these inputs.
2051 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2052 // If there is a loop-invariant, force it into the RHS.
2053 std::swap(LHS, RHS);
2054 Cond = ICmpInst::getSwappedPredicate(Cond);
2057 // FIXME: think about handling pointer comparisons! i.e.:
2058 // while (P != P+100) ++P;
2060 // If we have a comparison of a chrec against a constant, try to use value
2061 // ranges to answer this query.
2062 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2063 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2064 if (AddRec->getLoop() == L) {
2065 // Form the comparison range using the constant of the correct type so
2066 // that the ConstantRange class knows to do a signed or unsigned
2068 ConstantInt *CompVal = RHSC->getValue();
2069 const Type *RealTy = ExitCond->getOperand(0)->getType();
2070 CompVal = dyn_cast<ConstantInt>(
2071 ConstantExpr::getBitCast(CompVal, RealTy));
2073 // Form the constant range.
2074 ConstantRange CompRange(
2075 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2077 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2078 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2083 case ICmpInst::ICMP_NE: { // while (X != Y)
2084 // Convert to: while (X-Y != 0)
2085 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2086 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2089 case ICmpInst::ICMP_EQ: {
2090 // Convert to: while (X-Y == 0) // while (X == Y)
2091 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2092 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2095 case ICmpInst::ICMP_SLT: {
2096 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2097 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2100 case ICmpInst::ICMP_SGT: {
2101 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2102 SE.getNotSCEV(RHS), L, true);
2103 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2106 case ICmpInst::ICMP_ULT: {
2107 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2108 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2111 case ICmpInst::ICMP_UGT: {
2112 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2113 SE.getNotSCEV(RHS), L, false);
2114 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2119 cerr << "ComputeIterationCount ";
2120 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2121 cerr << "[unsigned] ";
2123 << Instruction::getOpcodeName(Instruction::ICmp)
2124 << " " << *RHS << "\n";
2128 return ComputeIterationCountExhaustively(L, ExitCond,
2129 ExitBr->getSuccessor(0) == ExitBlock);
2132 static ConstantInt *
2133 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2134 ScalarEvolution &SE) {
2135 SCEVHandle InVal = SE.getConstant(C);
2136 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2137 assert(isa<SCEVConstant>(Val) &&
2138 "Evaluation of SCEV at constant didn't fold correctly?");
2139 return cast<SCEVConstant>(Val)->getValue();
2142 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2143 /// and a GEP expression (missing the pointer index) indexing into it, return
2144 /// the addressed element of the initializer or null if the index expression is
2147 GetAddressedElementFromGlobal(GlobalVariable *GV,
2148 const std::vector<ConstantInt*> &Indices) {
2149 Constant *Init = GV->getInitializer();
2150 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2151 uint64_t Idx = Indices[i]->getZExtValue();
2152 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2153 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2154 Init = cast<Constant>(CS->getOperand(Idx));
2155 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2156 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2157 Init = cast<Constant>(CA->getOperand(Idx));
2158 } else if (isa<ConstantAggregateZero>(Init)) {
2159 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2160 assert(Idx < STy->getNumElements() && "Bad struct index!");
2161 Init = Constant::getNullValue(STy->getElementType(Idx));
2162 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2163 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2164 Init = Constant::getNullValue(ATy->getElementType());
2166 assert(0 && "Unknown constant aggregate type!");
2170 return 0; // Unknown initializer type
2176 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2177 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2178 SCEVHandle ScalarEvolutionsImpl::
2179 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2181 ICmpInst::Predicate predicate) {
2182 if (LI->isVolatile()) return UnknownValue;
2184 // Check to see if the loaded pointer is a getelementptr of a global.
2185 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2186 if (!GEP) return UnknownValue;
2188 // Make sure that it is really a constant global we are gepping, with an
2189 // initializer, and make sure the first IDX is really 0.
2190 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2191 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2192 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2193 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2194 return UnknownValue;
2196 // Okay, we allow one non-constant index into the GEP instruction.
2198 std::vector<ConstantInt*> Indexes;
2199 unsigned VarIdxNum = 0;
2200 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2201 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2202 Indexes.push_back(CI);
2203 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2204 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2205 VarIdx = GEP->getOperand(i);
2207 Indexes.push_back(0);
2210 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2211 // Check to see if X is a loop variant variable value now.
2212 SCEVHandle Idx = getSCEV(VarIdx);
2213 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2214 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2216 // We can only recognize very limited forms of loop index expressions, in
2217 // particular, only affine AddRec's like {C1,+,C2}.
2218 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2219 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2220 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2221 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2222 return UnknownValue;
2224 unsigned MaxSteps = MaxBruteForceIterations;
2225 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2226 ConstantInt *ItCst =
2227 ConstantInt::get(IdxExpr->getType(), IterationNum);
2228 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2230 // Form the GEP offset.
2231 Indexes[VarIdxNum] = Val;
2233 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2234 if (Result == 0) break; // Cannot compute!
2236 // Evaluate the condition for this iteration.
2237 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2238 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2239 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2241 cerr << "\n***\n*** Computed loop count " << *ItCst
2242 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2245 ++NumArrayLenItCounts;
2246 return SE.getConstant(ItCst); // Found terminating iteration!
2249 return UnknownValue;
2253 /// CanConstantFold - Return true if we can constant fold an instruction of the
2254 /// specified type, assuming that all operands were constants.
2255 static bool CanConstantFold(const Instruction *I) {
2256 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2257 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2260 if (const CallInst *CI = dyn_cast<CallInst>(I))
2261 if (const Function *F = CI->getCalledFunction())
2262 return canConstantFoldCallTo(F);
2266 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2267 /// in the loop that V is derived from. We allow arbitrary operations along the
2268 /// way, but the operands of an operation must either be constants or a value
2269 /// derived from a constant PHI. If this expression does not fit with these
2270 /// constraints, return null.
2271 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2272 // If this is not an instruction, or if this is an instruction outside of the
2273 // loop, it can't be derived from a loop PHI.
2274 Instruction *I = dyn_cast<Instruction>(V);
2275 if (I == 0 || !L->contains(I->getParent())) return 0;
2277 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2278 if (L->getHeader() == I->getParent())
2281 // We don't currently keep track of the control flow needed to evaluate
2282 // PHIs, so we cannot handle PHIs inside of loops.
2286 // If we won't be able to constant fold this expression even if the operands
2287 // are constants, return early.
2288 if (!CanConstantFold(I)) return 0;
2290 // Otherwise, we can evaluate this instruction if all of its operands are
2291 // constant or derived from a PHI node themselves.
2293 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2294 if (!(isa<Constant>(I->getOperand(Op)) ||
2295 isa<GlobalValue>(I->getOperand(Op)))) {
2296 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2297 if (P == 0) return 0; // Not evolving from PHI
2301 return 0; // Evolving from multiple different PHIs.
2304 // This is a expression evolving from a constant PHI!
2308 /// EvaluateExpression - Given an expression that passes the
2309 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2310 /// in the loop has the value PHIVal. If we can't fold this expression for some
2311 /// reason, return null.
2312 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2313 if (isa<PHINode>(V)) return PHIVal;
2314 if (Constant *C = dyn_cast<Constant>(V)) return C;
2315 Instruction *I = cast<Instruction>(V);
2317 std::vector<Constant*> Operands;
2318 Operands.resize(I->getNumOperands());
2320 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2321 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2322 if (Operands[i] == 0) return 0;
2325 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2326 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2327 &Operands[0], Operands.size());
2329 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2330 &Operands[0], Operands.size());
2333 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2334 /// in the header of its containing loop, we know the loop executes a
2335 /// constant number of times, and the PHI node is just a recurrence
2336 /// involving constants, fold it.
2337 Constant *ScalarEvolutionsImpl::
2338 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2339 std::map<PHINode*, Constant*>::iterator I =
2340 ConstantEvolutionLoopExitValue.find(PN);
2341 if (I != ConstantEvolutionLoopExitValue.end())
2344 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2345 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2347 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2349 // Since the loop is canonicalized, the PHI node must have two entries. One
2350 // entry must be a constant (coming in from outside of the loop), and the
2351 // second must be derived from the same PHI.
2352 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2353 Constant *StartCST =
2354 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2356 return RetVal = 0; // Must be a constant.
2358 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2359 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2361 return RetVal = 0; // Not derived from same PHI.
2363 // Execute the loop symbolically to determine the exit value.
2364 if (Its.getActiveBits() >= 32)
2365 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2367 unsigned NumIterations = Its.getZExtValue(); // must be in range
2368 unsigned IterationNum = 0;
2369 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2370 if (IterationNum == NumIterations)
2371 return RetVal = PHIVal; // Got exit value!
2373 // Compute the value of the PHI node for the next iteration.
2374 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2375 if (NextPHI == PHIVal)
2376 return RetVal = NextPHI; // Stopped evolving!
2378 return 0; // Couldn't evaluate!
2383 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2384 /// constant number of times (the condition evolves only from constants),
2385 /// try to evaluate a few iterations of the loop until we get the exit
2386 /// condition gets a value of ExitWhen (true or false). If we cannot
2387 /// evaluate the trip count of the loop, return UnknownValue.
2388 SCEVHandle ScalarEvolutionsImpl::
2389 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2390 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2391 if (PN == 0) return UnknownValue;
2393 // Since the loop is canonicalized, the PHI node must have two entries. One
2394 // entry must be a constant (coming in from outside of the loop), and the
2395 // second must be derived from the same PHI.
2396 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2397 Constant *StartCST =
2398 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2399 if (StartCST == 0) return UnknownValue; // Must be a constant.
2401 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2402 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2403 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2405 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2406 // the loop symbolically to determine when the condition gets a value of
2408 unsigned IterationNum = 0;
2409 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2410 for (Constant *PHIVal = StartCST;
2411 IterationNum != MaxIterations; ++IterationNum) {
2412 ConstantInt *CondVal =
2413 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2415 // Couldn't symbolically evaluate.
2416 if (!CondVal) return UnknownValue;
2418 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2419 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2420 ++NumBruteForceTripCountsComputed;
2421 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2424 // Compute the value of the PHI node for the next iteration.
2425 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2426 if (NextPHI == 0 || NextPHI == PHIVal)
2427 return UnknownValue; // Couldn't evaluate or not making progress...
2431 // Too many iterations were needed to evaluate.
2432 return UnknownValue;
2435 /// getSCEVAtScope - Compute the value of the specified expression within the
2436 /// indicated loop (which may be null to indicate in no loop). If the
2437 /// expression cannot be evaluated, return UnknownValue.
2438 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2439 // FIXME: this should be turned into a virtual method on SCEV!
2441 if (isa<SCEVConstant>(V)) return V;
2443 // If this instruction is evolved from a constant-evolving PHI, compute the
2444 // exit value from the loop without using SCEVs.
2445 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2446 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2447 const Loop *LI = this->LI[I->getParent()];
2448 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2449 if (PHINode *PN = dyn_cast<PHINode>(I))
2450 if (PN->getParent() == LI->getHeader()) {
2451 // Okay, there is no closed form solution for the PHI node. Check
2452 // to see if the loop that contains it has a known iteration count.
2453 // If so, we may be able to force computation of the exit value.
2454 SCEVHandle IterationCount = getIterationCount(LI);
2455 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2456 // Okay, we know how many times the containing loop executes. If
2457 // this is a constant evolving PHI node, get the final value at
2458 // the specified iteration number.
2459 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2460 ICC->getValue()->getValue(),
2462 if (RV) return SE.getUnknown(RV);
2466 // Okay, this is an expression that we cannot symbolically evaluate
2467 // into a SCEV. Check to see if it's possible to symbolically evaluate
2468 // the arguments into constants, and if so, try to constant propagate the
2469 // result. This is particularly useful for computing loop exit values.
2470 if (CanConstantFold(I)) {
2471 std::vector<Constant*> Operands;
2472 Operands.reserve(I->getNumOperands());
2473 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2474 Value *Op = I->getOperand(i);
2475 if (Constant *C = dyn_cast<Constant>(Op)) {
2476 Operands.push_back(C);
2478 // If any of the operands is non-constant and if they are
2479 // non-integer, don't even try to analyze them with scev techniques.
2480 if (!isa<IntegerType>(Op->getType()))
2483 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2484 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2485 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2488 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2489 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2490 Operands.push_back(ConstantExpr::getIntegerCast(C,
2502 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2503 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2504 &Operands[0], Operands.size());
2506 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2507 &Operands[0], Operands.size());
2508 return SE.getUnknown(C);
2512 // This is some other type of SCEVUnknown, just return it.
2516 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2517 // Avoid performing the look-up in the common case where the specified
2518 // expression has no loop-variant portions.
2519 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2520 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2521 if (OpAtScope != Comm->getOperand(i)) {
2522 if (OpAtScope == UnknownValue) return UnknownValue;
2523 // Okay, at least one of these operands is loop variant but might be
2524 // foldable. Build a new instance of the folded commutative expression.
2525 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2526 NewOps.push_back(OpAtScope);
2528 for (++i; i != e; ++i) {
2529 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2530 if (OpAtScope == UnknownValue) return UnknownValue;
2531 NewOps.push_back(OpAtScope);
2533 if (isa<SCEVAddExpr>(Comm))
2534 return SE.getAddExpr(NewOps);
2535 if (isa<SCEVMulExpr>(Comm))
2536 return SE.getMulExpr(NewOps);
2537 if (isa<SCEVSMaxExpr>(Comm))
2538 return SE.getSMaxExpr(NewOps);
2539 if (isa<SCEVUMaxExpr>(Comm))
2540 return SE.getUMaxExpr(NewOps);
2541 assert(0 && "Unknown commutative SCEV type!");
2544 // If we got here, all operands are loop invariant.
2548 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2549 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2550 if (LHS == UnknownValue) return LHS;
2551 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2552 if (RHS == UnknownValue) return RHS;
2553 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2554 return Div; // must be loop invariant
2555 return SE.getUDivExpr(LHS, RHS);
2558 // If this is a loop recurrence for a loop that does not contain L, then we
2559 // are dealing with the final value computed by the loop.
2560 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2561 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2562 // To evaluate this recurrence, we need to know how many times the AddRec
2563 // loop iterates. Compute this now.
2564 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2565 if (IterationCount == UnknownValue) return UnknownValue;
2567 // Then, evaluate the AddRec.
2568 return AddRec->evaluateAtIteration(IterationCount, SE);
2570 return UnknownValue;
2573 //assert(0 && "Unknown SCEV type!");
2574 return UnknownValue;
2577 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2578 /// following equation:
2580 /// A * X = B (mod N)
2582 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2583 /// A and B isn't important.
2585 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2586 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2587 ScalarEvolution &SE) {
2588 uint32_t BW = A.getBitWidth();
2589 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2590 assert(A != 0 && "A must be non-zero.");
2594 // The gcd of A and N may have only one prime factor: 2. The number of
2595 // trailing zeros in A is its multiplicity
2596 uint32_t Mult2 = A.countTrailingZeros();
2599 // 2. Check if B is divisible by D.
2601 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2602 // is not less than multiplicity of this prime factor for D.
2603 if (B.countTrailingZeros() < Mult2)
2604 return new SCEVCouldNotCompute();
2606 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2609 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2610 // bit width during computations.
2611 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2612 APInt Mod(BW + 1, 0);
2613 Mod.set(BW - Mult2); // Mod = N / D
2614 APInt I = AD.multiplicativeInverse(Mod);
2616 // 4. Compute the minimum unsigned root of the equation:
2617 // I * (B / D) mod (N / D)
2618 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2620 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2622 return SE.getConstant(Result.trunc(BW));
2625 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2626 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2627 /// might be the same) or two SCEVCouldNotCompute objects.
2629 static std::pair<SCEVHandle,SCEVHandle>
2630 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2631 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2632 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2633 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2634 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2636 // We currently can only solve this if the coefficients are constants.
2637 if (!LC || !MC || !NC) {
2638 SCEV *CNC = new SCEVCouldNotCompute();
2639 return std::make_pair(CNC, CNC);
2642 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2643 const APInt &L = LC->getValue()->getValue();
2644 const APInt &M = MC->getValue()->getValue();
2645 const APInt &N = NC->getValue()->getValue();
2646 APInt Two(BitWidth, 2);
2647 APInt Four(BitWidth, 4);
2650 using namespace APIntOps;
2652 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2653 // The B coefficient is M-N/2
2657 // The A coefficient is N/2
2658 APInt A(N.sdiv(Two));
2660 // Compute the B^2-4ac term.
2663 SqrtTerm -= Four * (A * C);
2665 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2666 // integer value or else APInt::sqrt() will assert.
2667 APInt SqrtVal(SqrtTerm.sqrt());
2669 // Compute the two solutions for the quadratic formula.
2670 // The divisions must be performed as signed divisions.
2672 APInt TwoA( A << 1 );
2673 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2674 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2676 return std::make_pair(SE.getConstant(Solution1),
2677 SE.getConstant(Solution2));
2678 } // end APIntOps namespace
2681 /// HowFarToZero - Return the number of times a backedge comparing the specified
2682 /// value to zero will execute. If not computable, return UnknownValue
2683 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2684 // If the value is a constant
2685 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2686 // If the value is already zero, the branch will execute zero times.
2687 if (C->getValue()->isZero()) return C;
2688 return UnknownValue; // Otherwise it will loop infinitely.
2691 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2692 if (!AddRec || AddRec->getLoop() != L)
2693 return UnknownValue;
2695 if (AddRec->isAffine()) {
2696 // If this is an affine expression, the execution count of this branch is
2697 // the minimum unsigned root of the following equation:
2699 // Start + Step*N = 0 (mod 2^BW)
2703 // Step*N = -Start (mod 2^BW)
2705 // where BW is the common bit width of Start and Step.
2707 // Get the initial value for the loop.
2708 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2709 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2711 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2713 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2714 // For now we handle only constant steps.
2716 // First, handle unitary steps.
2717 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2718 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2719 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2720 return Start; // N = Start (as unsigned)
2722 // Then, try to solve the above equation provided that Start is constant.
2723 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2724 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2725 -StartC->getValue()->getValue(),SE);
2727 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2728 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2729 // the quadratic equation to solve it.
2730 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2731 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2732 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2735 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2736 << " sol#2: " << *R2 << "\n";
2738 // Pick the smallest positive root value.
2739 if (ConstantInt *CB =
2740 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2741 R1->getValue(), R2->getValue()))) {
2742 if (CB->getZExtValue() == false)
2743 std::swap(R1, R2); // R1 is the minimum root now.
2745 // We can only use this value if the chrec ends up with an exact zero
2746 // value at this index. When solving for "X*X != 5", for example, we
2747 // should not accept a root of 2.
2748 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2750 return R1; // We found a quadratic root!
2755 return UnknownValue;
2758 /// HowFarToNonZero - Return the number of times a backedge checking the
2759 /// specified value for nonzero will execute. If not computable, return
2761 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2762 // Loops that look like: while (X == 0) are very strange indeed. We don't
2763 // handle them yet except for the trivial case. This could be expanded in the
2764 // future as needed.
2766 // If the value is a constant, check to see if it is known to be non-zero
2767 // already. If so, the backedge will execute zero times.
2768 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2769 if (!C->getValue()->isNullValue())
2770 return SE.getIntegerSCEV(0, C->getType());
2771 return UnknownValue; // Otherwise it will loop infinitely.
2774 // We could implement others, but I really doubt anyone writes loops like
2775 // this, and if they did, they would already be constant folded.
2776 return UnknownValue;
2779 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2780 /// (which may not be an immediate predecessor) which has exactly one
2781 /// successor from which BB is reachable, or null if no such block is
2785 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2786 // If the block has a unique predecessor, the predecessor must have
2787 // no other successors from which BB is reachable.
2788 if (BasicBlock *Pred = BB->getSinglePredecessor())
2791 // A loop's header is defined to be a block that dominates the loop.
2792 // If the loop has a preheader, it must be a block that has exactly
2793 // one successor that can reach BB. This is slightly more strict
2794 // than necessary, but works if critical edges are split.
2795 if (Loop *L = LI.getLoopFor(BB))
2796 return L->getLoopPreheader();
2801 /// executesAtLeastOnce - Test whether entry to the loop is protected by
2802 /// a conditional between LHS and RHS.
2803 bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2804 SCEV *LHS, SCEV *RHS) {
2805 BasicBlock *Preheader = L->getLoopPreheader();
2806 BasicBlock *PreheaderDest = L->getHeader();
2808 // Starting at the preheader, climb up the predecessor chain, as long as
2809 // there are predecessors that can be found that have unique successors
2810 // leading to the original header.
2812 PreheaderDest = Preheader,
2813 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2815 BranchInst *LoopEntryPredicate =
2816 dyn_cast<BranchInst>(Preheader->getTerminator());
2817 if (!LoopEntryPredicate ||
2818 LoopEntryPredicate->isUnconditional())
2821 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2824 // Now that we found a conditional branch that dominates the loop, check to
2825 // see if it is the comparison we are looking for.
2826 Value *PreCondLHS = ICI->getOperand(0);
2827 Value *PreCondRHS = ICI->getOperand(1);
2828 ICmpInst::Predicate Cond;
2829 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2830 Cond = ICI->getPredicate();
2832 Cond = ICI->getInversePredicate();
2835 case ICmpInst::ICMP_UGT:
2836 if (isSigned) continue;
2837 std::swap(PreCondLHS, PreCondRHS);
2838 Cond = ICmpInst::ICMP_ULT;
2840 case ICmpInst::ICMP_SGT:
2841 if (!isSigned) continue;
2842 std::swap(PreCondLHS, PreCondRHS);
2843 Cond = ICmpInst::ICMP_SLT;
2845 case ICmpInst::ICMP_ULT:
2846 if (isSigned) continue;
2848 case ICmpInst::ICMP_SLT:
2849 if (!isSigned) continue;
2855 if (!PreCondLHS->getType()->isInteger()) continue;
2857 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2858 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2859 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2860 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2861 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2868 /// HowManyLessThans - Return the number of times a backedge containing the
2869 /// specified less-than comparison will execute. If not computable, return
2871 SCEVHandle ScalarEvolutionsImpl::
2872 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2873 // Only handle: "ADDREC < LoopInvariant".
2874 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2876 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2877 if (!AddRec || AddRec->getLoop() != L)
2878 return UnknownValue;
2880 if (AddRec->isAffine()) {
2881 // FORNOW: We only support unit strides.
2882 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2883 if (AddRec->getOperand(1) != One)
2884 return UnknownValue;
2886 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2887 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2888 // Note that we cannot simply return max(m-n,0) because it's not safe to
2889 // treat m-n as signed nor unsigned due to overflow possibility.
2891 // First, we get the value of the LHS in the first iteration: n
2892 SCEVHandle Start = AddRec->getOperand(0);
2894 if (executesAtLeastOnce(L, isSigned,
2895 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2896 // Since we know that the condition is true in order to enter the loop,
2897 // we know that it will run exactly m-n times.
2898 return SE.getMinusSCEV(RHS, Start);
2900 // Then, we get the value of the LHS in the first iteration in which the
2901 // above condition doesn't hold. This equals to max(m,n).
2902 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2903 : SE.getUMaxExpr(RHS, Start);
2905 // Finally, we subtract these two values to get the number of times the
2906 // backedge is executed: max(m,n)-n.
2907 return SE.getMinusSCEV(End, Start);
2911 return UnknownValue;
2914 /// getNumIterationsInRange - Return the number of iterations of this loop that
2915 /// produce values in the specified constant range. Another way of looking at
2916 /// this is that it returns the first iteration number where the value is not in
2917 /// the condition, thus computing the exit count. If the iteration count can't
2918 /// be computed, an instance of SCEVCouldNotCompute is returned.
2919 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2920 ScalarEvolution &SE) const {
2921 if (Range.isFullSet()) // Infinite loop.
2922 return new SCEVCouldNotCompute();
2924 // If the start is a non-zero constant, shift the range to simplify things.
2925 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2926 if (!SC->getValue()->isZero()) {
2927 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2928 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2929 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2930 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2931 return ShiftedAddRec->getNumIterationsInRange(
2932 Range.subtract(SC->getValue()->getValue()), SE);
2933 // This is strange and shouldn't happen.
2934 return new SCEVCouldNotCompute();
2937 // The only time we can solve this is when we have all constant indices.
2938 // Otherwise, we cannot determine the overflow conditions.
2939 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2940 if (!isa<SCEVConstant>(getOperand(i)))
2941 return new SCEVCouldNotCompute();
2944 // Okay at this point we know that all elements of the chrec are constants and
2945 // that the start element is zero.
2947 // First check to see if the range contains zero. If not, the first
2949 if (!Range.contains(APInt(getBitWidth(),0)))
2950 return SE.getConstant(ConstantInt::get(getType(),0));
2953 // If this is an affine expression then we have this situation:
2954 // Solve {0,+,A} in Range === Ax in Range
2956 // We know that zero is in the range. If A is positive then we know that
2957 // the upper value of the range must be the first possible exit value.
2958 // If A is negative then the lower of the range is the last possible loop
2959 // value. Also note that we already checked for a full range.
2960 APInt One(getBitWidth(),1);
2961 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2962 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2964 // The exit value should be (End+A)/A.
2965 APInt ExitVal = (End + A).udiv(A);
2966 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2968 // Evaluate at the exit value. If we really did fall out of the valid
2969 // range, then we computed our trip count, otherwise wrap around or other
2970 // things must have happened.
2971 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2972 if (Range.contains(Val->getValue()))
2973 return new SCEVCouldNotCompute(); // Something strange happened
2975 // Ensure that the previous value is in the range. This is a sanity check.
2976 assert(Range.contains(
2977 EvaluateConstantChrecAtConstant(this,
2978 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2979 "Linear scev computation is off in a bad way!");
2980 return SE.getConstant(ExitValue);
2981 } else if (isQuadratic()) {
2982 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2983 // quadratic equation to solve it. To do this, we must frame our problem in
2984 // terms of figuring out when zero is crossed, instead of when
2985 // Range.getUpper() is crossed.
2986 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2987 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2988 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2990 // Next, solve the constructed addrec
2991 std::pair<SCEVHandle,SCEVHandle> Roots =
2992 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2993 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2994 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2996 // Pick the smallest positive root value.
2997 if (ConstantInt *CB =
2998 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2999 R1->getValue(), R2->getValue()))) {
3000 if (CB->getZExtValue() == false)
3001 std::swap(R1, R2); // R1 is the minimum root now.
3003 // Make sure the root is not off by one. The returned iteration should
3004 // not be in the range, but the previous one should be. When solving
3005 // for "X*X < 5", for example, we should not return a root of 2.
3006 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3009 if (Range.contains(R1Val->getValue())) {
3010 // The next iteration must be out of the range...
3011 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3013 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3014 if (!Range.contains(R1Val->getValue()))
3015 return SE.getConstant(NextVal);
3016 return new SCEVCouldNotCompute(); // Something strange happened
3019 // If R1 was not in the range, then it is a good return value. Make
3020 // sure that R1-1 WAS in the range though, just in case.
3021 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3022 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3023 if (Range.contains(R1Val->getValue()))
3025 return new SCEVCouldNotCompute(); // Something strange happened
3030 // Fallback, if this is a general polynomial, figure out the progression
3031 // through brute force: evaluate until we find an iteration that fails the
3032 // test. This is likely to be slow, but getting an accurate trip count is
3033 // incredibly important, we will be able to simplify the exit test a lot, and
3034 // we are almost guaranteed to get a trip count in this case.
3035 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
3036 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
3038 ++NumBruteForceEvaluations;
3039 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
3040 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
3041 return new SCEVCouldNotCompute();
3043 // Check to see if we found the value!
3044 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
3045 return SE.getConstant(TestVal);
3047 // Increment to test the next index.
3048 TestVal = ConstantInt::get(TestVal->getValue()+1);
3049 } while (TestVal != EndVal);
3051 return new SCEVCouldNotCompute();
3056 //===----------------------------------------------------------------------===//
3057 // ScalarEvolution Class Implementation
3058 //===----------------------------------------------------------------------===//
3060 bool ScalarEvolution::runOnFunction(Function &F) {
3061 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
3065 void ScalarEvolution::releaseMemory() {
3066 delete (ScalarEvolutionsImpl*)Impl;
3070 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3071 AU.setPreservesAll();
3072 AU.addRequiredTransitive<LoopInfo>();
3075 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3076 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3079 /// hasSCEV - Return true if the SCEV for this value has already been
3081 bool ScalarEvolution::hasSCEV(Value *V) const {
3082 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3086 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3087 /// the specified value.
3088 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3089 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3093 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3094 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3097 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3098 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3101 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3102 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3105 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3106 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3109 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3111 // Print all inner loops first
3112 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3113 PrintLoopInfo(OS, SE, *I);
3115 OS << "Loop " << L->getHeader()->getName() << ": ";
3117 SmallVector<BasicBlock*, 8> ExitBlocks;
3118 L->getExitBlocks(ExitBlocks);
3119 if (ExitBlocks.size() != 1)
3120 OS << "<multiple exits> ";
3122 if (SE->hasLoopInvariantIterationCount(L)) {
3123 OS << *SE->getIterationCount(L) << " iterations! ";
3125 OS << "Unpredictable iteration count. ";
3131 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3132 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3133 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3135 OS << "Classifying expressions for: " << F.getName() << "\n";
3136 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3137 if (I->getType()->isInteger()) {
3140 SCEVHandle SV = getSCEV(&*I);
3144 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3146 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3147 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3148 OS << "<<Unknown>>";
3158 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3159 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3160 PrintLoopInfo(OS, this, *I);