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(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88 STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90 STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92 STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
95 static cl::opt<unsigned>
96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
101 static RegisterPass<ScalarEvolution>
102 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
103 char ScalarEvolution::ID = 0;
105 //===----------------------------------------------------------------------===//
106 // SCEV class definitions
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
110 // Implementation of the SCEV class.
113 void SCEV::dump() const {
118 uint32_t SCEV::getBitWidth() const {
119 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120 return ITy->getBitWidth();
124 bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
138 const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
148 SCEVHandle SCEVCouldNotCompute::
149 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
150 const SCEVHandle &Conc,
151 ScalarEvolution &SE) const {
155 void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
159 bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
164 // SCEVConstants - Only allow the creation of one SCEVConstant for any
165 // particular value. Don't use a SCEVHandle here, or else the object will
167 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
170 SCEVConstant::~SCEVConstant() {
171 SCEVConstants->erase(V);
174 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
175 SCEVConstant *&R = (*SCEVConstants)[V];
176 if (R == 0) R = new SCEVConstant(V);
180 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181 return getConstant(ConstantInt::get(Val));
184 const Type *SCEVConstant::getType() const { return V->getType(); }
186 void SCEVConstant::print(std::ostream &OS) const {
187 WriteAsOperand(OS, V, false);
190 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191 // particular input. Don't use a SCEVHandle here, or else the object will
193 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
194 SCEVTruncateExpr*> > SCEVTruncates;
196 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197 : SCEV(scTruncate), Op(op), Ty(ty) {
198 assert(Op->getType()->isInteger() && Ty->isInteger() &&
199 "Cannot truncate non-integer value!");
200 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201 && "This is not a truncating conversion!");
204 SCEVTruncateExpr::~SCEVTruncateExpr() {
205 SCEVTruncates->erase(std::make_pair(Op, Ty));
208 void SCEVTruncateExpr::print(std::ostream &OS) const {
209 OS << "(truncate " << *Op << " to " << *Ty << ")";
212 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213 // particular input. Don't use a SCEVHandle here, or else the object will never
215 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216 SCEVZeroExtendExpr*> > SCEVZeroExtends;
218 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
219 : SCEV(scZeroExtend), Op(op), Ty(ty) {
220 assert(Op->getType()->isInteger() && Ty->isInteger() &&
221 "Cannot zero extend non-integer value!");
222 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223 && "This is not an extending conversion!");
226 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
227 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
230 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
234 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235 // particular input. Don't use a SCEVHandle here, or else the object will never
237 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238 SCEVSignExtendExpr*> > SCEVSignExtends;
240 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241 : SCEV(scSignExtend), Op(op), Ty(ty) {
242 assert(Op->getType()->isInteger() && Ty->isInteger() &&
243 "Cannot sign extend non-integer value!");
244 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245 && "This is not an extending conversion!");
248 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249 SCEVSignExtends->erase(std::make_pair(Op, Ty));
252 void SCEVSignExtendExpr::print(std::ostream &OS) const {
253 OS << "(signextend " << *Op << " to " << *Ty << ")";
256 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257 // particular input. Don't use a SCEVHandle here, or else the object will never
259 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260 SCEVCommutativeExpr*> > SCEVCommExprs;
262 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
263 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264 std::vector<SCEV*>(Operands.begin(),
268 void SCEVCommutativeExpr::print(std::ostream &OS) const {
269 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270 const char *OpStr = getOperationStr();
271 OS << "(" << *Operands[0];
272 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273 OS << OpStr << *Operands[i];
277 SCEVHandle SCEVCommutativeExpr::
278 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
279 const SCEVHandle &Conc,
280 ScalarEvolution &SE) const {
281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
283 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
284 if (H != getOperand(i)) {
285 std::vector<SCEVHandle> NewOps;
286 NewOps.reserve(getNumOperands());
287 for (unsigned j = 0; j != i; ++j)
288 NewOps.push_back(getOperand(j));
290 for (++i; i != e; ++i)
291 NewOps.push_back(getOperand(i)->
292 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
294 if (isa<SCEVAddExpr>(this))
295 return SE.getAddExpr(NewOps);
296 else if (isa<SCEVMulExpr>(this))
297 return SE.getMulExpr(NewOps);
298 else if (isa<SCEVSMaxExpr>(this))
299 return SE.getSMaxExpr(NewOps);
300 else if (isa<SCEVUMaxExpr>(this))
301 return SE.getUMaxExpr(NewOps);
303 assert(0 && "Unknown commutative expr!");
310 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
311 // input. Don't use a SCEVHandle here, or else the object will never be
313 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
314 SCEVUDivExpr*> > SCEVUDivs;
316 SCEVUDivExpr::~SCEVUDivExpr() {
317 SCEVUDivs->erase(std::make_pair(LHS, RHS));
320 void SCEVUDivExpr::print(std::ostream &OS) const {
321 OS << "(" << *LHS << " /u " << *RHS << ")";
324 const Type *SCEVUDivExpr::getType() const {
325 return LHS->getType();
328 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
329 // particular input. Don't use a SCEVHandle here, or else the object will never
331 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
332 SCEVAddRecExpr*> > SCEVAddRecExprs;
334 SCEVAddRecExpr::~SCEVAddRecExpr() {
335 SCEVAddRecExprs->erase(std::make_pair(L,
336 std::vector<SCEV*>(Operands.begin(),
340 SCEVHandle SCEVAddRecExpr::
341 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
342 const SCEVHandle &Conc,
343 ScalarEvolution &SE) const {
344 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
346 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
347 if (H != getOperand(i)) {
348 std::vector<SCEVHandle> NewOps;
349 NewOps.reserve(getNumOperands());
350 for (unsigned j = 0; j != i; ++j)
351 NewOps.push_back(getOperand(j));
353 for (++i; i != e; ++i)
354 NewOps.push_back(getOperand(i)->
355 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
357 return SE.getAddRecExpr(NewOps, L);
364 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
365 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
366 // contain L and if the start is invariant.
367 return !QueryLoop->contains(L->getHeader()) &&
368 getOperand(0)->isLoopInvariant(QueryLoop);
372 void SCEVAddRecExpr::print(std::ostream &OS) const {
373 OS << "{" << *Operands[0];
374 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
375 OS << ",+," << *Operands[i];
376 OS << "}<" << L->getHeader()->getName() + ">";
379 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
380 // value. Don't use a SCEVHandle here, or else the object will never be
382 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
384 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
386 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
387 // All non-instruction values are loop invariant. All instructions are loop
388 // invariant if they are not contained in the specified loop.
389 if (Instruction *I = dyn_cast<Instruction>(V))
390 return !L->contains(I->getParent());
394 const Type *SCEVUnknown::getType() const {
398 void SCEVUnknown::print(std::ostream &OS) const {
399 WriteAsOperand(OS, V, false);
402 //===----------------------------------------------------------------------===//
404 //===----------------------------------------------------------------------===//
407 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
408 /// than the complexity of the RHS. This comparator is used to canonicalize
410 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
411 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
412 return LHS->getSCEVType() < RHS->getSCEVType();
417 /// GroupByComplexity - Given a list of SCEV objects, order them by their
418 /// complexity, and group objects of the same complexity together by value.
419 /// When this routine is finished, we know that any duplicates in the vector are
420 /// consecutive and that complexity is monotonically increasing.
422 /// Note that we go take special precautions to ensure that we get determinstic
423 /// results from this routine. In other words, we don't want the results of
424 /// this to depend on where the addresses of various SCEV objects happened to
427 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
428 if (Ops.size() < 2) return; // Noop
429 if (Ops.size() == 2) {
430 // This is the common case, which also happens to be trivially simple.
432 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
433 std::swap(Ops[0], Ops[1]);
437 // Do the rough sort by complexity.
438 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
440 // Now that we are sorted by complexity, group elements of the same
441 // complexity. Note that this is, at worst, N^2, but the vector is likely to
442 // be extremely short in practice. Note that we take this approach because we
443 // do not want to depend on the addresses of the objects we are grouping.
444 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
446 unsigned Complexity = S->getSCEVType();
448 // If there are any objects of the same complexity and same value as this
450 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
451 if (Ops[j] == S) { // Found a duplicate.
452 // Move it to immediately after i'th element.
453 std::swap(Ops[i+1], Ops[j]);
454 ++i; // no need to rescan it.
455 if (i == e-2) return; // Done!
463 //===----------------------------------------------------------------------===//
464 // Simple SCEV method implementations
465 //===----------------------------------------------------------------------===//
467 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
468 /// specified signed integer value and return a SCEV for the constant.
469 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
472 C = Constant::getNullValue(Ty);
473 else if (Ty->isFloatingPoint())
474 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
475 APFloat::IEEEdouble, Val));
477 C = ConstantInt::get(Ty, Val);
478 return getUnknown(C);
481 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
483 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
485 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
487 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
490 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
491 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
492 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
493 return getUnknown(ConstantExpr::getNot(VC->getValue()));
495 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
496 return getMinusSCEV(AllOnes, V);
499 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
501 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
502 const SCEVHandle &RHS) {
504 return getAddExpr(LHS, getNegativeSCEV(RHS));
508 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
510 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
512 const IntegerType* ResultTy) {
513 // Handle the simplest case efficiently.
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
517 // We are using the following formula for BC(It, K):
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
569 return new SCEVCouldNotCompute();
571 unsigned W = ResultTy->getBitWidth();
573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
579 for (unsigned i = 3; i <= K; ++i) {
581 unsigned TwoFactors = Mult.countTrailingZeros();
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
587 // We need at least W + T bits for the multiplication step
588 unsigned CalculationBits = W + T;
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
603 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
604 for (unsigned i = 1; i != K; ++i) {
605 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
611 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613 // Truncate the result, and divide by K! / 2^T.
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
619 /// evaluateAtIteration - Return the value of this chain of recurrences at
620 /// the specified iteration number. We can evaluate this recurrence by
621 /// multiplying each element in the chain by the binomial coefficient
622 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
626 /// where BC(It, k) stands for binomial coefficient.
628 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
629 ScalarEvolution &SE) const {
630 SCEVHandle Result = getStart();
631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
635 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
636 cast<IntegerType>(getType()));
637 if (isa<SCEVCouldNotCompute>(Coeff))
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
645 //===----------------------------------------------------------------------===//
646 // SCEV Expression folder implementations
647 //===----------------------------------------------------------------------===//
649 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
650 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
652 ConstantExpr::getTrunc(SC->getValue(), Ty));
654 // If the input value is a chrec scev made out of constants, truncate
655 // all of the constants.
656 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
657 std::vector<SCEVHandle> Operands;
658 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
659 // FIXME: This should allow truncation of other expression types!
660 if (isa<SCEVConstant>(AddRec->getOperand(i)))
661 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
664 if (Operands.size() == AddRec->getNumOperands())
665 return getAddRecExpr(Operands, AddRec->getLoop());
668 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
669 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
673 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
674 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
676 ConstantExpr::getZExt(SC->getValue(), Ty));
678 // FIXME: If the input value is a chrec scev, and we can prove that the value
679 // did not overflow the old, smaller, value, we can zero extend all of the
680 // operands (often constants). This would allow analysis of something like
681 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
683 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
684 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
688 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
689 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
691 ConstantExpr::getSExt(SC->getValue(), Ty));
693 // FIXME: If the input value is a chrec scev, and we can prove that the value
694 // did not overflow the old, smaller, value, we can sign extend all of the
695 // operands (often constants). This would allow analysis of something like
696 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
698 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
699 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
703 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
704 /// of the input value to the specified type. If the type must be
705 /// extended, it is zero extended.
706 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
708 const Type *SrcTy = V->getType();
709 assert(SrcTy->isInteger() && Ty->isInteger() &&
710 "Cannot truncate or zero extend with non-integer arguments!");
711 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
712 return V; // No conversion
713 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
714 return getTruncateExpr(V, Ty);
715 return getZeroExtendExpr(V, Ty);
718 // get - Get a canonical add expression, or something simpler if possible.
719 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
720 assert(!Ops.empty() && "Cannot get empty add!");
721 if (Ops.size() == 1) return Ops[0];
723 // Sort by complexity, this groups all similar expression types together.
724 GroupByComplexity(Ops);
726 // If there are any constants, fold them together.
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
730 assert(Idx < Ops.size());
731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
741 // If we are left with a constant zero being added, strip it off.
742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
743 Ops.erase(Ops.begin());
748 if (Ops.size() == 1) return Ops[0];
750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
764 return getAddExpr(Ops);
767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
771 // If there are add operands they would be next.
772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
786 return getAddExpr(Ops);
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
809 InnerMul = getMulExpr(MulOps);
811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
814 if (Ops.size() == 2) return OuterMul;
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
822 Ops.push_back(OuterMul);
823 return getAddExpr(Ops);
826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
841 InnerMul1 = getMulExpr(MulOps);
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
847 MulOps.erase(MulOps.begin()+OMulOp);
848 InnerMul2 = getMulExpr(MulOps);
850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
856 return getAddExpr(Ops);
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
884 LIOps.push_back(AddRec->getStart());
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
887 AddRecOps[0] = getAddExpr(LIOps);
889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
899 return getAddExpr(Ops);
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
922 if (Ops.size() == 2) return NewAddRec;
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
927 return getAddExpr(Ops);
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
940 if (Result == 0) Result = new SCEVAddExpr(Ops);
945 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
946 assert(!Ops.empty() && "Cannot get empty mul!");
948 // Sort by complexity, this groups all similar expression types together.
949 GroupByComplexity(Ops);
951 // If there are any constants, fold them together.
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
955 // C1*(C2+V) -> C1*C2 + C1*V
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
980 // If we have a multiply of zero, it will always be zero.
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1007 return getMulExpr(Ops);
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
1031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
1042 NewOps.push_back(getMulExpr(MulOps));
1046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1057 return getMulExpr(Ops);
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1070 SCEVHandle NewStart = getMulExpr(F->getStart(),
1072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1079 if (Ops.size() == 2) return NewAddRec;
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
1084 return getMulExpr(Ops);
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1098 Result = new SCEVMulExpr(Ops);
1102 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
1105 return LHS; // X udiv 1 --> x
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
1110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1122 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123 /// specified loop. Simplify the expression as much as possible.
1124 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
1132 return getAddRecExpr(Operands, L);
1135 Operands.push_back(Step);
1136 return getAddRecExpr(Operands, L);
1139 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140 /// specified loop. Simplify the expression as much as possible.
1141 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1143 if (Operands.size() == 1) return Operands[0];
1145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
1147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1163 SCEVAddRecExpr *&Result =
1164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1170 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1175 return getSMaxExpr(Ops);
1178 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1185 // If there are any constants, fold them together.
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
1192 ConstantInt *Fold = ConstantInt::get(
1193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
1195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1208 if (Ops.size() == 1) return Ops[0];
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1225 return getSMaxExpr(Ops);
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1237 if (Ops.size() == 1) return Ops[0];
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1241 // Okay, it looks like we really DO need an smax expr. Check to see if we
1242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1250 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1255 return getUMaxExpr(Ops);
1258 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1265 // If there are any constants, fold them together.
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1288 if (Ops.size() == 1) return Ops[0];
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1305 return getUMaxExpr(Ops);
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1317 if (Ops.size() == 1) return Ops[0];
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1330 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1332 return getConstant(CI);
1333 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1334 if (Result == 0) Result = new SCEVUnknown(V);
1339 //===----------------------------------------------------------------------===//
1340 // ScalarEvolutionsImpl Definition and Implementation
1341 //===----------------------------------------------------------------------===//
1343 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1347 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1348 /// SE - A reference to the public ScalarEvolution object.
1349 ScalarEvolution &SE;
1351 /// F - The function we are analyzing.
1355 /// LI - The loop information for the function we are currently analyzing.
1359 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1361 SCEVHandle UnknownValue;
1363 /// Scalars - This is a cache of the scalars we have analyzed so far.
1365 std::map<Value*, SCEVHandle> Scalars;
1367 /// IterationCounts - Cache the iteration count of the loops for this
1368 /// function as they are computed.
1369 std::map<const Loop*, SCEVHandle> IterationCounts;
1371 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1372 /// the PHI instructions that we attempt to compute constant evolutions for.
1373 /// This allows us to avoid potentially expensive recomputation of these
1374 /// properties. An instruction maps to null if we are unable to compute its
1376 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1379 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1380 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1382 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1383 /// expression and create a new one.
1384 SCEVHandle getSCEV(Value *V);
1386 /// hasSCEV - Return true if the SCEV for this value has already been
1388 bool hasSCEV(Value *V) const {
1389 return Scalars.count(V);
1392 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1393 /// the specified value.
1394 void setSCEV(Value *V, const SCEVHandle &H) {
1395 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1396 assert(isNew && "This entry already existed!");
1401 /// getSCEVAtScope - Compute the value of the specified expression within
1402 /// the indicated loop (which may be null to indicate in no loop). If the
1403 /// expression cannot be evaluated, return UnknownValue itself.
1404 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1407 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1408 /// a conditional between LHS and RHS.
1409 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1410 SCEV *LHS, SCEV *RHS);
1412 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1413 /// an analyzable loop-invariant iteration count.
1414 bool hasLoopInvariantIterationCount(const Loop *L);
1416 /// getIterationCount - If the specified loop has a predictable iteration
1417 /// count, return it. Note that it is not valid to call this method on a
1418 /// loop without a loop-invariant iteration count.
1419 SCEVHandle getIterationCount(const Loop *L);
1421 /// deleteValueFromRecords - This method should be called by the
1422 /// client before it removes a value from the program, to make sure
1423 /// that no dangling references are left around.
1424 void deleteValueFromRecords(Value *V);
1427 /// createSCEV - We know that there is no SCEV for the specified value.
1428 /// Analyze the expression.
1429 SCEVHandle createSCEV(Value *V);
1431 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1433 SCEVHandle createNodeForPHI(PHINode *PN);
1435 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1436 /// for the specified instruction and replaces any references to the
1437 /// symbolic value SymName with the specified value. This is used during
1439 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1440 const SCEVHandle &SymName,
1441 const SCEVHandle &NewVal);
1443 /// ComputeIterationCount - Compute the number of times the specified loop
1445 SCEVHandle ComputeIterationCount(const Loop *L);
1447 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1448 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1449 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1452 ICmpInst::Predicate p);
1454 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1455 /// constant number of times (the condition evolves only from constants),
1456 /// try to evaluate a few iterations of the loop until we get the exit
1457 /// condition gets a value of ExitWhen (true or false). If we cannot
1458 /// evaluate the trip count of the loop, return UnknownValue.
1459 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1462 /// HowFarToZero - Return the number of times a backedge comparing the
1463 /// specified value to zero will execute. If not computable, return
1465 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1467 /// HowFarToNonZero - Return the number of times a backedge checking the
1468 /// specified value for nonzero will execute. If not computable, return
1470 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1472 /// HowManyLessThans - Return the number of times a backedge containing the
1473 /// specified less-than comparison will execute. If not computable, return
1474 /// UnknownValue. isSigned specifies whether the less-than is signed.
1475 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1478 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1479 /// (which may not be an immediate predecessor) which has exactly one
1480 /// successor from which BB is reachable, or null if no such block is
1482 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1484 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1485 /// in the header of its containing loop, we know the loop executes a
1486 /// constant number of times, and the PHI node is just a recurrence
1487 /// involving constants, fold it.
1488 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1493 //===----------------------------------------------------------------------===//
1494 // Basic SCEV Analysis and PHI Idiom Recognition Code
1497 /// deleteValueFromRecords - This method should be called by the
1498 /// client before it removes an instruction from the program, to make sure
1499 /// that no dangling references are left around.
1500 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1501 SmallVector<Value *, 16> Worklist;
1503 if (Scalars.erase(V)) {
1504 if (PHINode *PN = dyn_cast<PHINode>(V))
1505 ConstantEvolutionLoopExitValue.erase(PN);
1506 Worklist.push_back(V);
1509 while (!Worklist.empty()) {
1510 Value *VV = Worklist.back();
1511 Worklist.pop_back();
1513 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1515 Instruction *Inst = cast<Instruction>(*UI);
1516 if (Scalars.erase(Inst)) {
1517 if (PHINode *PN = dyn_cast<PHINode>(VV))
1518 ConstantEvolutionLoopExitValue.erase(PN);
1519 Worklist.push_back(Inst);
1526 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1527 /// expression and create a new one.
1528 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1529 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1531 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1532 if (I != Scalars.end()) return I->second;
1533 SCEVHandle S = createSCEV(V);
1534 Scalars.insert(std::make_pair(V, S));
1538 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1539 /// the specified instruction and replaces any references to the symbolic value
1540 /// SymName with the specified value. This is used during PHI resolution.
1541 void ScalarEvolutionsImpl::
1542 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1543 const SCEVHandle &NewVal) {
1544 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1545 if (SI == Scalars.end()) return;
1548 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1549 if (NV == SI->second) return; // No change.
1551 SI->second = NV; // Update the scalars map!
1553 // Any instruction values that use this instruction might also need to be
1555 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1557 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1560 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1561 /// a loop header, making it a potential recurrence, or it doesn't.
1563 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1564 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1565 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1566 if (L->getHeader() == PN->getParent()) {
1567 // If it lives in the loop header, it has two incoming values, one
1568 // from outside the loop, and one from inside.
1569 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1570 unsigned BackEdge = IncomingEdge^1;
1572 // While we are analyzing this PHI node, handle its value symbolically.
1573 SCEVHandle SymbolicName = SE.getUnknown(PN);
1574 assert(Scalars.find(PN) == Scalars.end() &&
1575 "PHI node already processed?");
1576 Scalars.insert(std::make_pair(PN, SymbolicName));
1578 // Using this symbolic name for the PHI, analyze the value coming around
1580 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1582 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1583 // has a special value for the first iteration of the loop.
1585 // If the value coming around the backedge is an add with the symbolic
1586 // value we just inserted, then we found a simple induction variable!
1587 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1588 // If there is a single occurrence of the symbolic value, replace it
1589 // with a recurrence.
1590 unsigned FoundIndex = Add->getNumOperands();
1591 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1592 if (Add->getOperand(i) == SymbolicName)
1593 if (FoundIndex == e) {
1598 if (FoundIndex != Add->getNumOperands()) {
1599 // Create an add with everything but the specified operand.
1600 std::vector<SCEVHandle> Ops;
1601 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1602 if (i != FoundIndex)
1603 Ops.push_back(Add->getOperand(i));
1604 SCEVHandle Accum = SE.getAddExpr(Ops);
1606 // This is not a valid addrec if the step amount is varying each
1607 // loop iteration, but is not itself an addrec in this loop.
1608 if (Accum->isLoopInvariant(L) ||
1609 (isa<SCEVAddRecExpr>(Accum) &&
1610 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1611 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1612 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1614 // Okay, for the entire analysis of this edge we assumed the PHI
1615 // to be symbolic. We now need to go back and update all of the
1616 // entries for the scalars that use the PHI (except for the PHI
1617 // itself) to use the new analyzed value instead of the "symbolic"
1619 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1623 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1624 // Otherwise, this could be a loop like this:
1625 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1626 // In this case, j = {1,+,1} and BEValue is j.
1627 // Because the other in-value of i (0) fits the evolution of BEValue
1628 // i really is an addrec evolution.
1629 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1630 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1632 // If StartVal = j.start - j.stride, we can use StartVal as the
1633 // initial step of the addrec evolution.
1634 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1635 AddRec->getOperand(1))) {
1636 SCEVHandle PHISCEV =
1637 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1639 // Okay, for the entire analysis of this edge we assumed the PHI
1640 // to be symbolic. We now need to go back and update all of the
1641 // entries for the scalars that use the PHI (except for the PHI
1642 // itself) to use the new analyzed value instead of the "symbolic"
1644 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1650 return SymbolicName;
1653 // If it's not a loop phi, we can't handle it yet.
1654 return SE.getUnknown(PN);
1657 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1658 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1659 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1660 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1661 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1662 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1663 return C->getValue()->getValue().countTrailingZeros();
1665 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1666 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1668 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1669 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1670 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1673 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1674 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1675 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1678 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1679 // The result is the min of all operands results.
1680 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1681 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1682 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1686 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1687 // The result is the sum of all operands results.
1688 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1689 uint32_t BitWidth = M->getBitWidth();
1690 for (unsigned i = 1, e = M->getNumOperands();
1691 SumOpRes != BitWidth && i != e; ++i)
1692 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1697 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1698 // The result is the min of all operands results.
1699 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1700 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1701 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1705 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1706 // The result is the min of all operands results.
1707 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1708 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1709 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1713 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1714 // The result is the min of all operands results.
1715 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1716 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1717 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1721 // SCEVUDivExpr, SCEVUnknown
1725 /// createSCEV - We know that there is no SCEV for the specified value.
1726 /// Analyze the expression.
1728 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1729 if (!isa<IntegerType>(V->getType()))
1730 return SE.getUnknown(V);
1732 unsigned Opcode = Instruction::UserOp1;
1733 if (Instruction *I = dyn_cast<Instruction>(V))
1734 Opcode = I->getOpcode();
1735 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1736 Opcode = CE->getOpcode();
1738 return SE.getUnknown(V);
1740 User *U = cast<User>(V);
1742 case Instruction::Add:
1743 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1744 getSCEV(U->getOperand(1)));
1745 case Instruction::Mul:
1746 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1747 getSCEV(U->getOperand(1)));
1748 case Instruction::UDiv:
1749 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1750 getSCEV(U->getOperand(1)));
1751 case Instruction::Sub:
1752 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1753 getSCEV(U->getOperand(1)));
1754 case Instruction::Or:
1755 // If the RHS of the Or is a constant, we may have something like:
1756 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1757 // optimizations will transparently handle this case.
1759 // In order for this transformation to be safe, the LHS must be of the
1760 // form X*(2^n) and the Or constant must be less than 2^n.
1761 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1762 SCEVHandle LHS = getSCEV(U->getOperand(0));
1763 const APInt &CIVal = CI->getValue();
1764 if (GetMinTrailingZeros(LHS) >=
1765 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1766 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1769 case Instruction::Xor:
1770 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1771 // If the RHS of the xor is a signbit, then this is just an add.
1772 // Instcombine turns add of signbit into xor as a strength reduction step.
1773 if (CI->getValue().isSignBit())
1774 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1775 getSCEV(U->getOperand(1)));
1777 // If the RHS of xor is -1, then this is a not operation.
1778 else if (CI->isAllOnesValue())
1779 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1783 case Instruction::Shl:
1784 // Turn shift left of a constant amount into a multiply.
1785 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1786 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1787 Constant *X = ConstantInt::get(
1788 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1789 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1793 case Instruction::LShr:
1794 // Turn logical shift right of a constant into a unsigned divide.
1795 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1796 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1797 Constant *X = ConstantInt::get(
1798 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1799 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1803 case Instruction::Trunc:
1804 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1806 case Instruction::ZExt:
1807 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1809 case Instruction::SExt:
1810 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1812 case Instruction::BitCast:
1813 // BitCasts are no-op casts so we just eliminate the cast.
1814 if (U->getType()->isInteger() &&
1815 U->getOperand(0)->getType()->isInteger())
1816 return getSCEV(U->getOperand(0));
1819 case Instruction::PHI:
1820 return createNodeForPHI(cast<PHINode>(U));
1822 case Instruction::Select:
1823 // This could be a smax or umax that was lowered earlier.
1824 // Try to recover it.
1825 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1826 Value *LHS = ICI->getOperand(0);
1827 Value *RHS = ICI->getOperand(1);
1828 switch (ICI->getPredicate()) {
1829 case ICmpInst::ICMP_SLT:
1830 case ICmpInst::ICMP_SLE:
1831 std::swap(LHS, RHS);
1833 case ICmpInst::ICMP_SGT:
1834 case ICmpInst::ICMP_SGE:
1835 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1836 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1837 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1838 // ~smax(~x, ~y) == smin(x, y).
1839 return SE.getNotSCEV(SE.getSMaxExpr(
1840 SE.getNotSCEV(getSCEV(LHS)),
1841 SE.getNotSCEV(getSCEV(RHS))));
1843 case ICmpInst::ICMP_ULT:
1844 case ICmpInst::ICMP_ULE:
1845 std::swap(LHS, RHS);
1847 case ICmpInst::ICMP_UGT:
1848 case ICmpInst::ICMP_UGE:
1849 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1850 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1851 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1852 // ~umax(~x, ~y) == umin(x, y)
1853 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1854 SE.getNotSCEV(getSCEV(RHS))));
1861 default: // We cannot analyze this expression.
1865 return SE.getUnknown(V);
1870 //===----------------------------------------------------------------------===//
1871 // Iteration Count Computation Code
1874 /// getIterationCount - If the specified loop has a predictable iteration
1875 /// count, return it. Note that it is not valid to call this method on a
1876 /// loop without a loop-invariant iteration count.
1877 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1878 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1879 if (I == IterationCounts.end()) {
1880 SCEVHandle ItCount = ComputeIterationCount(L);
1881 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1882 if (ItCount != UnknownValue) {
1883 assert(ItCount->isLoopInvariant(L) &&
1884 "Computed trip count isn't loop invariant for loop!");
1885 ++NumTripCountsComputed;
1886 } else if (isa<PHINode>(L->getHeader()->begin())) {
1887 // Only count loops that have phi nodes as not being computable.
1888 ++NumTripCountsNotComputed;
1894 /// ComputeIterationCount - Compute the number of times the specified loop
1896 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1897 // If the loop has a non-one exit block count, we can't analyze it.
1898 SmallVector<BasicBlock*, 8> ExitBlocks;
1899 L->getExitBlocks(ExitBlocks);
1900 if (ExitBlocks.size() != 1) return UnknownValue;
1902 // Okay, there is one exit block. Try to find the condition that causes the
1903 // loop to be exited.
1904 BasicBlock *ExitBlock = ExitBlocks[0];
1906 BasicBlock *ExitingBlock = 0;
1907 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1909 if (L->contains(*PI)) {
1910 if (ExitingBlock == 0)
1913 return UnknownValue; // More than one block exiting!
1915 assert(ExitingBlock && "No exits from loop, something is broken!");
1917 // Okay, we've computed the exiting block. See what condition causes us to
1920 // FIXME: we should be able to handle switch instructions (with a single exit)
1921 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1922 if (ExitBr == 0) return UnknownValue;
1923 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1925 // At this point, we know we have a conditional branch that determines whether
1926 // the loop is exited. However, we don't know if the branch is executed each
1927 // time through the loop. If not, then the execution count of the branch will
1928 // not be equal to the trip count of the loop.
1930 // Currently we check for this by checking to see if the Exit branch goes to
1931 // the loop header. If so, we know it will always execute the same number of
1932 // times as the loop. We also handle the case where the exit block *is* the
1933 // loop header. This is common for un-rotated loops. More extensive analysis
1934 // could be done to handle more cases here.
1935 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1936 ExitBr->getSuccessor(1) != L->getHeader() &&
1937 ExitBr->getParent() != L->getHeader())
1938 return UnknownValue;
1940 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1942 // If it's not an integer comparison then compute it the hard way.
1943 // Note that ICmpInst deals with pointer comparisons too so we must check
1944 // the type of the operand.
1945 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1946 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1947 ExitBr->getSuccessor(0) == ExitBlock);
1949 // If the condition was exit on true, convert the condition to exit on false
1950 ICmpInst::Predicate Cond;
1951 if (ExitBr->getSuccessor(1) == ExitBlock)
1952 Cond = ExitCond->getPredicate();
1954 Cond = ExitCond->getInversePredicate();
1956 // Handle common loops like: for (X = "string"; *X; ++X)
1957 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1958 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1960 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1961 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1964 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1965 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1967 // Try to evaluate any dependencies out of the loop.
1968 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1969 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1970 Tmp = getSCEVAtScope(RHS, L);
1971 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1973 // At this point, we would like to compute how many iterations of the
1974 // loop the predicate will return true for these inputs.
1975 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1976 // If there is a loop-invariant, force it into the RHS.
1977 std::swap(LHS, RHS);
1978 Cond = ICmpInst::getSwappedPredicate(Cond);
1981 // FIXME: think about handling pointer comparisons! i.e.:
1982 // while (P != P+100) ++P;
1984 // If we have a comparison of a chrec against a constant, try to use value
1985 // ranges to answer this query.
1986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1987 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1988 if (AddRec->getLoop() == L) {
1989 // Form the comparison range using the constant of the correct type so
1990 // that the ConstantRange class knows to do a signed or unsigned
1992 ConstantInt *CompVal = RHSC->getValue();
1993 const Type *RealTy = ExitCond->getOperand(0)->getType();
1994 CompVal = dyn_cast<ConstantInt>(
1995 ConstantExpr::getBitCast(CompVal, RealTy));
1997 // Form the constant range.
1998 ConstantRange CompRange(
1999 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2001 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2002 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2007 case ICmpInst::ICMP_NE: { // while (X != Y)
2008 // Convert to: while (X-Y != 0)
2009 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2010 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2013 case ICmpInst::ICMP_EQ: {
2014 // Convert to: while (X-Y == 0) // while (X == Y)
2015 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2016 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2019 case ICmpInst::ICMP_SLT: {
2020 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2021 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2024 case ICmpInst::ICMP_SGT: {
2025 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2026 SE.getNotSCEV(RHS), L, true);
2027 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2030 case ICmpInst::ICMP_ULT: {
2031 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2032 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2035 case ICmpInst::ICMP_UGT: {
2036 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2037 SE.getNotSCEV(RHS), L, false);
2038 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2043 cerr << "ComputeIterationCount ";
2044 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2045 cerr << "[unsigned] ";
2047 << Instruction::getOpcodeName(Instruction::ICmp)
2048 << " " << *RHS << "\n";
2052 return ComputeIterationCountExhaustively(L, ExitCond,
2053 ExitBr->getSuccessor(0) == ExitBlock);
2056 static ConstantInt *
2057 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2058 ScalarEvolution &SE) {
2059 SCEVHandle InVal = SE.getConstant(C);
2060 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2061 assert(isa<SCEVConstant>(Val) &&
2062 "Evaluation of SCEV at constant didn't fold correctly?");
2063 return cast<SCEVConstant>(Val)->getValue();
2066 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2067 /// and a GEP expression (missing the pointer index) indexing into it, return
2068 /// the addressed element of the initializer or null if the index expression is
2071 GetAddressedElementFromGlobal(GlobalVariable *GV,
2072 const std::vector<ConstantInt*> &Indices) {
2073 Constant *Init = GV->getInitializer();
2074 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2075 uint64_t Idx = Indices[i]->getZExtValue();
2076 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2077 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2078 Init = cast<Constant>(CS->getOperand(Idx));
2079 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2080 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2081 Init = cast<Constant>(CA->getOperand(Idx));
2082 } else if (isa<ConstantAggregateZero>(Init)) {
2083 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2084 assert(Idx < STy->getNumElements() && "Bad struct index!");
2085 Init = Constant::getNullValue(STy->getElementType(Idx));
2086 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2087 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2088 Init = Constant::getNullValue(ATy->getElementType());
2090 assert(0 && "Unknown constant aggregate type!");
2094 return 0; // Unknown initializer type
2100 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2101 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2102 SCEVHandle ScalarEvolutionsImpl::
2103 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2105 ICmpInst::Predicate predicate) {
2106 if (LI->isVolatile()) return UnknownValue;
2108 // Check to see if the loaded pointer is a getelementptr of a global.
2109 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2110 if (!GEP) return UnknownValue;
2112 // Make sure that it is really a constant global we are gepping, with an
2113 // initializer, and make sure the first IDX is really 0.
2114 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2115 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2116 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2117 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2118 return UnknownValue;
2120 // Okay, we allow one non-constant index into the GEP instruction.
2122 std::vector<ConstantInt*> Indexes;
2123 unsigned VarIdxNum = 0;
2124 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2125 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2126 Indexes.push_back(CI);
2127 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2128 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2129 VarIdx = GEP->getOperand(i);
2131 Indexes.push_back(0);
2134 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2135 // Check to see if X is a loop variant variable value now.
2136 SCEVHandle Idx = getSCEV(VarIdx);
2137 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2138 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2140 // We can only recognize very limited forms of loop index expressions, in
2141 // particular, only affine AddRec's like {C1,+,C2}.
2142 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2143 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2144 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2145 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2146 return UnknownValue;
2148 unsigned MaxSteps = MaxBruteForceIterations;
2149 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2150 ConstantInt *ItCst =
2151 ConstantInt::get(IdxExpr->getType(), IterationNum);
2152 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2154 // Form the GEP offset.
2155 Indexes[VarIdxNum] = Val;
2157 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2158 if (Result == 0) break; // Cannot compute!
2160 // Evaluate the condition for this iteration.
2161 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2162 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2163 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2165 cerr << "\n***\n*** Computed loop count " << *ItCst
2166 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2169 ++NumArrayLenItCounts;
2170 return SE.getConstant(ItCst); // Found terminating iteration!
2173 return UnknownValue;
2177 /// CanConstantFold - Return true if we can constant fold an instruction of the
2178 /// specified type, assuming that all operands were constants.
2179 static bool CanConstantFold(const Instruction *I) {
2180 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2181 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2184 if (const CallInst *CI = dyn_cast<CallInst>(I))
2185 if (const Function *F = CI->getCalledFunction())
2186 return canConstantFoldCallTo(F);
2190 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2191 /// in the loop that V is derived from. We allow arbitrary operations along the
2192 /// way, but the operands of an operation must either be constants or a value
2193 /// derived from a constant PHI. If this expression does not fit with these
2194 /// constraints, return null.
2195 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2196 // If this is not an instruction, or if this is an instruction outside of the
2197 // loop, it can't be derived from a loop PHI.
2198 Instruction *I = dyn_cast<Instruction>(V);
2199 if (I == 0 || !L->contains(I->getParent())) return 0;
2201 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2202 if (L->getHeader() == I->getParent())
2205 // We don't currently keep track of the control flow needed to evaluate
2206 // PHIs, so we cannot handle PHIs inside of loops.
2210 // If we won't be able to constant fold this expression even if the operands
2211 // are constants, return early.
2212 if (!CanConstantFold(I)) return 0;
2214 // Otherwise, we can evaluate this instruction if all of its operands are
2215 // constant or derived from a PHI node themselves.
2217 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2218 if (!(isa<Constant>(I->getOperand(Op)) ||
2219 isa<GlobalValue>(I->getOperand(Op)))) {
2220 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2221 if (P == 0) return 0; // Not evolving from PHI
2225 return 0; // Evolving from multiple different PHIs.
2228 // This is a expression evolving from a constant PHI!
2232 /// EvaluateExpression - Given an expression that passes the
2233 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2234 /// in the loop has the value PHIVal. If we can't fold this expression for some
2235 /// reason, return null.
2236 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2237 if (isa<PHINode>(V)) return PHIVal;
2238 if (Constant *C = dyn_cast<Constant>(V)) return C;
2239 Instruction *I = cast<Instruction>(V);
2241 std::vector<Constant*> Operands;
2242 Operands.resize(I->getNumOperands());
2244 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2245 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2246 if (Operands[i] == 0) return 0;
2249 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2250 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2251 &Operands[0], Operands.size());
2253 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2254 &Operands[0], Operands.size());
2257 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2258 /// in the header of its containing loop, we know the loop executes a
2259 /// constant number of times, and the PHI node is just a recurrence
2260 /// involving constants, fold it.
2261 Constant *ScalarEvolutionsImpl::
2262 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2263 std::map<PHINode*, Constant*>::iterator I =
2264 ConstantEvolutionLoopExitValue.find(PN);
2265 if (I != ConstantEvolutionLoopExitValue.end())
2268 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2269 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2271 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2273 // Since the loop is canonicalized, the PHI node must have two entries. One
2274 // entry must be a constant (coming in from outside of the loop), and the
2275 // second must be derived from the same PHI.
2276 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2277 Constant *StartCST =
2278 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2280 return RetVal = 0; // Must be a constant.
2282 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2283 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2285 return RetVal = 0; // Not derived from same PHI.
2287 // Execute the loop symbolically to determine the exit value.
2288 if (Its.getActiveBits() >= 32)
2289 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2291 unsigned NumIterations = Its.getZExtValue(); // must be in range
2292 unsigned IterationNum = 0;
2293 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2294 if (IterationNum == NumIterations)
2295 return RetVal = PHIVal; // Got exit value!
2297 // Compute the value of the PHI node for the next iteration.
2298 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2299 if (NextPHI == PHIVal)
2300 return RetVal = NextPHI; // Stopped evolving!
2302 return 0; // Couldn't evaluate!
2307 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2308 /// constant number of times (the condition evolves only from constants),
2309 /// try to evaluate a few iterations of the loop until we get the exit
2310 /// condition gets a value of ExitWhen (true or false). If we cannot
2311 /// evaluate the trip count of the loop, return UnknownValue.
2312 SCEVHandle ScalarEvolutionsImpl::
2313 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2314 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2315 if (PN == 0) return UnknownValue;
2317 // Since the loop is canonicalized, the PHI node must have two entries. One
2318 // entry must be a constant (coming in from outside of the loop), and the
2319 // second must be derived from the same PHI.
2320 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2321 Constant *StartCST =
2322 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2323 if (StartCST == 0) return UnknownValue; // Must be a constant.
2325 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2326 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2327 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2329 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2330 // the loop symbolically to determine when the condition gets a value of
2332 unsigned IterationNum = 0;
2333 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2334 for (Constant *PHIVal = StartCST;
2335 IterationNum != MaxIterations; ++IterationNum) {
2336 ConstantInt *CondVal =
2337 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2339 // Couldn't symbolically evaluate.
2340 if (!CondVal) return UnknownValue;
2342 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2343 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2344 ++NumBruteForceTripCountsComputed;
2345 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2348 // Compute the value of the PHI node for the next iteration.
2349 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2350 if (NextPHI == 0 || NextPHI == PHIVal)
2351 return UnknownValue; // Couldn't evaluate or not making progress...
2355 // Too many iterations were needed to evaluate.
2356 return UnknownValue;
2359 /// getSCEVAtScope - Compute the value of the specified expression within the
2360 /// indicated loop (which may be null to indicate in no loop). If the
2361 /// expression cannot be evaluated, return UnknownValue.
2362 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2363 // FIXME: this should be turned into a virtual method on SCEV!
2365 if (isa<SCEVConstant>(V)) return V;
2367 // If this instruction is evolved from a constant-evolving PHI, compute the
2368 // exit value from the loop without using SCEVs.
2369 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2370 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2371 const Loop *LI = this->LI[I->getParent()];
2372 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2373 if (PHINode *PN = dyn_cast<PHINode>(I))
2374 if (PN->getParent() == LI->getHeader()) {
2375 // Okay, there is no closed form solution for the PHI node. Check
2376 // to see if the loop that contains it has a known iteration count.
2377 // If so, we may be able to force computation of the exit value.
2378 SCEVHandle IterationCount = getIterationCount(LI);
2379 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2380 // Okay, we know how many times the containing loop executes. If
2381 // this is a constant evolving PHI node, get the final value at
2382 // the specified iteration number.
2383 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2384 ICC->getValue()->getValue(),
2386 if (RV) return SE.getUnknown(RV);
2390 // Okay, this is an expression that we cannot symbolically evaluate
2391 // into a SCEV. Check to see if it's possible to symbolically evaluate
2392 // the arguments into constants, and if so, try to constant propagate the
2393 // result. This is particularly useful for computing loop exit values.
2394 if (CanConstantFold(I)) {
2395 std::vector<Constant*> Operands;
2396 Operands.reserve(I->getNumOperands());
2397 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2398 Value *Op = I->getOperand(i);
2399 if (Constant *C = dyn_cast<Constant>(Op)) {
2400 Operands.push_back(C);
2402 // If any of the operands is non-constant and if they are
2403 // non-integer, don't even try to analyze them with scev techniques.
2404 if (!isa<IntegerType>(Op->getType()))
2407 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2408 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2409 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2412 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2413 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2414 Operands.push_back(ConstantExpr::getIntegerCast(C,
2426 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2427 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2428 &Operands[0], Operands.size());
2430 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2431 &Operands[0], Operands.size());
2432 return SE.getUnknown(C);
2436 // This is some other type of SCEVUnknown, just return it.
2440 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2441 // Avoid performing the look-up in the common case where the specified
2442 // expression has no loop-variant portions.
2443 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2444 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2445 if (OpAtScope != Comm->getOperand(i)) {
2446 if (OpAtScope == UnknownValue) return UnknownValue;
2447 // Okay, at least one of these operands is loop variant but might be
2448 // foldable. Build a new instance of the folded commutative expression.
2449 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2450 NewOps.push_back(OpAtScope);
2452 for (++i; i != e; ++i) {
2453 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2454 if (OpAtScope == UnknownValue) return UnknownValue;
2455 NewOps.push_back(OpAtScope);
2457 if (isa<SCEVAddExpr>(Comm))
2458 return SE.getAddExpr(NewOps);
2459 if (isa<SCEVMulExpr>(Comm))
2460 return SE.getMulExpr(NewOps);
2461 if (isa<SCEVSMaxExpr>(Comm))
2462 return SE.getSMaxExpr(NewOps);
2463 if (isa<SCEVUMaxExpr>(Comm))
2464 return SE.getUMaxExpr(NewOps);
2465 assert(0 && "Unknown commutative SCEV type!");
2468 // If we got here, all operands are loop invariant.
2472 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2473 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2474 if (LHS == UnknownValue) return LHS;
2475 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2476 if (RHS == UnknownValue) return RHS;
2477 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2478 return Div; // must be loop invariant
2479 return SE.getUDivExpr(LHS, RHS);
2482 // If this is a loop recurrence for a loop that does not contain L, then we
2483 // are dealing with the final value computed by the loop.
2484 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2485 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2486 // To evaluate this recurrence, we need to know how many times the AddRec
2487 // loop iterates. Compute this now.
2488 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2489 if (IterationCount == UnknownValue) return UnknownValue;
2491 // Then, evaluate the AddRec.
2492 return AddRec->evaluateAtIteration(IterationCount, SE);
2494 return UnknownValue;
2497 //assert(0 && "Unknown SCEV type!");
2498 return UnknownValue;
2501 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2502 /// following equation:
2504 /// A * X = B (mod N)
2506 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2507 /// A and B isn't important.
2509 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2510 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2511 ScalarEvolution &SE) {
2512 uint32_t BW = A.getBitWidth();
2513 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2514 assert(A != 0 && "A must be non-zero.");
2518 // The gcd of A and N may have only one prime factor: 2. The number of
2519 // trailing zeros in A is its multiplicity
2520 uint32_t Mult2 = A.countTrailingZeros();
2523 // 2. Check if B is divisible by D.
2525 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2526 // is not less than multiplicity of this prime factor for D.
2527 if (B.countTrailingZeros() < Mult2)
2528 return new SCEVCouldNotCompute();
2530 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2533 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2534 // bit width during computations.
2535 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2536 APInt Mod(BW + 1, 0);
2537 Mod.set(BW - Mult2); // Mod = N / D
2538 APInt I = AD.multiplicativeInverse(Mod);
2540 // 4. Compute the minimum unsigned root of the equation:
2541 // I * (B / D) mod (N / D)
2542 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2544 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2546 return SE.getConstant(Result.trunc(BW));
2549 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2550 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2551 /// might be the same) or two SCEVCouldNotCompute objects.
2553 static std::pair<SCEVHandle,SCEVHandle>
2554 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2555 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2556 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2557 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2558 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2560 // We currently can only solve this if the coefficients are constants.
2561 if (!LC || !MC || !NC) {
2562 SCEV *CNC = new SCEVCouldNotCompute();
2563 return std::make_pair(CNC, CNC);
2566 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2567 const APInt &L = LC->getValue()->getValue();
2568 const APInt &M = MC->getValue()->getValue();
2569 const APInt &N = NC->getValue()->getValue();
2570 APInt Two(BitWidth, 2);
2571 APInt Four(BitWidth, 4);
2574 using namespace APIntOps;
2576 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2577 // The B coefficient is M-N/2
2581 // The A coefficient is N/2
2582 APInt A(N.sdiv(Two));
2584 // Compute the B^2-4ac term.
2587 SqrtTerm -= Four * (A * C);
2589 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2590 // integer value or else APInt::sqrt() will assert.
2591 APInt SqrtVal(SqrtTerm.sqrt());
2593 // Compute the two solutions for the quadratic formula.
2594 // The divisions must be performed as signed divisions.
2596 APInt TwoA( A << 1 );
2597 if (TwoA.isMinValue()) {
2598 SCEV *CNC = new SCEVCouldNotCompute();
2599 return std::make_pair(CNC, CNC);
2602 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2603 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2605 return std::make_pair(SE.getConstant(Solution1),
2606 SE.getConstant(Solution2));
2607 } // end APIntOps namespace
2610 /// HowFarToZero - Return the number of times a backedge comparing the specified
2611 /// value to zero will execute. If not computable, return UnknownValue
2612 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2613 // If the value is a constant
2614 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2615 // If the value is already zero, the branch will execute zero times.
2616 if (C->getValue()->isZero()) return C;
2617 return UnknownValue; // Otherwise it will loop infinitely.
2620 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2621 if (!AddRec || AddRec->getLoop() != L)
2622 return UnknownValue;
2624 if (AddRec->isAffine()) {
2625 // If this is an affine expression, the execution count of this branch is
2626 // the minimum unsigned root of the following equation:
2628 // Start + Step*N = 0 (mod 2^BW)
2632 // Step*N = -Start (mod 2^BW)
2634 // where BW is the common bit width of Start and Step.
2636 // Get the initial value for the loop.
2637 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2638 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2640 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2642 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2643 // For now we handle only constant steps.
2645 // First, handle unitary steps.
2646 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2647 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2648 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2649 return Start; // N = Start (as unsigned)
2651 // Then, try to solve the above equation provided that Start is constant.
2652 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2653 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2654 -StartC->getValue()->getValue(),SE);
2656 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2657 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2658 // the quadratic equation to solve it.
2659 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2660 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2661 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2664 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2665 << " sol#2: " << *R2 << "\n";
2667 // Pick the smallest positive root value.
2668 if (ConstantInt *CB =
2669 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2670 R1->getValue(), R2->getValue()))) {
2671 if (CB->getZExtValue() == false)
2672 std::swap(R1, R2); // R1 is the minimum root now.
2674 // We can only use this value if the chrec ends up with an exact zero
2675 // value at this index. When solving for "X*X != 5", for example, we
2676 // should not accept a root of 2.
2677 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2679 return R1; // We found a quadratic root!
2684 return UnknownValue;
2687 /// HowFarToNonZero - Return the number of times a backedge checking the
2688 /// specified value for nonzero will execute. If not computable, return
2690 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2691 // Loops that look like: while (X == 0) are very strange indeed. We don't
2692 // handle them yet except for the trivial case. This could be expanded in the
2693 // future as needed.
2695 // If the value is a constant, check to see if it is known to be non-zero
2696 // already. If so, the backedge will execute zero times.
2697 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2698 if (!C->getValue()->isNullValue())
2699 return SE.getIntegerSCEV(0, C->getType());
2700 return UnknownValue; // Otherwise it will loop infinitely.
2703 // We could implement others, but I really doubt anyone writes loops like
2704 // this, and if they did, they would already be constant folded.
2705 return UnknownValue;
2708 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2709 /// (which may not be an immediate predecessor) which has exactly one
2710 /// successor from which BB is reachable, or null if no such block is
2714 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2715 // If the block has a unique predecessor, the predecessor must have
2716 // no other successors from which BB is reachable.
2717 if (BasicBlock *Pred = BB->getSinglePredecessor())
2720 // A loop's header is defined to be a block that dominates the loop.
2721 // If the loop has a preheader, it must be a block that has exactly
2722 // one successor that can reach BB. This is slightly more strict
2723 // than necessary, but works if critical edges are split.
2724 if (Loop *L = LI.getLoopFor(BB))
2725 return L->getLoopPreheader();
2730 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
2731 /// a conditional between LHS and RHS.
2732 bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2733 ICmpInst::Predicate Pred,
2734 SCEV *LHS, SCEV *RHS) {
2735 BasicBlock *Preheader = L->getLoopPreheader();
2736 BasicBlock *PreheaderDest = L->getHeader();
2738 // Starting at the preheader, climb up the predecessor chain, as long as
2739 // there are predecessors that can be found that have unique successors
2740 // leading to the original header.
2742 PreheaderDest = Preheader,
2743 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2745 BranchInst *LoopEntryPredicate =
2746 dyn_cast<BranchInst>(Preheader->getTerminator());
2747 if (!LoopEntryPredicate ||
2748 LoopEntryPredicate->isUnconditional())
2751 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2754 // Now that we found a conditional branch that dominates the loop, check to
2755 // see if it is the comparison we are looking for.
2756 Value *PreCondLHS = ICI->getOperand(0);
2757 Value *PreCondRHS = ICI->getOperand(1);
2758 ICmpInst::Predicate Cond;
2759 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2760 Cond = ICI->getPredicate();
2762 Cond = ICI->getInversePredicate();
2765 ; // An exact match.
2766 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2767 ; // The actual condition is beyond sufficient.
2769 // Check a few special cases.
2771 case ICmpInst::ICMP_UGT:
2772 if (Pred == ICmpInst::ICMP_ULT) {
2773 std::swap(PreCondLHS, PreCondRHS);
2774 Cond = ICmpInst::ICMP_ULT;
2778 case ICmpInst::ICMP_SGT:
2779 if (Pred == ICmpInst::ICMP_SLT) {
2780 std::swap(PreCondLHS, PreCondRHS);
2781 Cond = ICmpInst::ICMP_SLT;
2785 case ICmpInst::ICMP_NE:
2786 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2787 // so check for this case by checking if the NE is comparing against
2788 // a minimum or maximum constant.
2789 if (!ICmpInst::isTrueWhenEqual(Pred))
2790 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2791 const APInt &A = CI->getValue();
2793 case ICmpInst::ICMP_SLT:
2794 if (A.isMaxSignedValue()) break;
2796 case ICmpInst::ICMP_SGT:
2797 if (A.isMinSignedValue()) break;
2799 case ICmpInst::ICMP_ULT:
2800 if (A.isMaxValue()) break;
2802 case ICmpInst::ICMP_UGT:
2803 if (A.isMinValue()) break;
2808 Cond = ICmpInst::ICMP_NE;
2809 // NE is symmetric but the original comparison may not be. Swap
2810 // the operands if necessary so that they match below.
2811 if (isa<SCEVConstant>(LHS))
2812 std::swap(PreCondLHS, PreCondRHS);
2817 // We weren't able to reconcile the condition.
2821 if (!PreCondLHS->getType()->isInteger()) continue;
2823 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2824 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2825 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2826 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2827 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2834 /// HowManyLessThans - Return the number of times a backedge containing the
2835 /// specified less-than comparison will execute. If not computable, return
2837 SCEVHandle ScalarEvolutionsImpl::
2838 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2839 // Only handle: "ADDREC < LoopInvariant".
2840 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2842 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2843 if (!AddRec || AddRec->getLoop() != L)
2844 return UnknownValue;
2846 if (AddRec->isAffine()) {
2847 // FORNOW: We only support unit strides.
2848 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2849 if (AddRec->getOperand(1) != One)
2850 return UnknownValue;
2852 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2853 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2854 // Note that we cannot simply return max(m-n,0) because it's not safe to
2855 // treat m-n as signed nor unsigned due to overflow possibility.
2857 // First, we get the value of the LHS in the first iteration: n
2858 SCEVHandle Start = AddRec->getOperand(0);
2860 if (isLoopGuardedByCond(L,
2861 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2862 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2863 // Since we know that the condition is true in order to enter the loop,
2864 // we know that it will run exactly m-n times.
2865 return SE.getMinusSCEV(RHS, Start);
2867 // Then, we get the value of the LHS in the first iteration in which the
2868 // above condition doesn't hold. This equals to max(m,n).
2869 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2870 : SE.getUMaxExpr(RHS, Start);
2872 // Finally, we subtract these two values to get the number of times the
2873 // backedge is executed: max(m,n)-n.
2874 return SE.getMinusSCEV(End, Start);
2878 return UnknownValue;
2881 /// getNumIterationsInRange - Return the number of iterations of this loop that
2882 /// produce values in the specified constant range. Another way of looking at
2883 /// this is that it returns the first iteration number where the value is not in
2884 /// the condition, thus computing the exit count. If the iteration count can't
2885 /// be computed, an instance of SCEVCouldNotCompute is returned.
2886 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2887 ScalarEvolution &SE) const {
2888 if (Range.isFullSet()) // Infinite loop.
2889 return new SCEVCouldNotCompute();
2891 // If the start is a non-zero constant, shift the range to simplify things.
2892 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2893 if (!SC->getValue()->isZero()) {
2894 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2895 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2896 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2897 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2898 return ShiftedAddRec->getNumIterationsInRange(
2899 Range.subtract(SC->getValue()->getValue()), SE);
2900 // This is strange and shouldn't happen.
2901 return new SCEVCouldNotCompute();
2904 // The only time we can solve this is when we have all constant indices.
2905 // Otherwise, we cannot determine the overflow conditions.
2906 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2907 if (!isa<SCEVConstant>(getOperand(i)))
2908 return new SCEVCouldNotCompute();
2911 // Okay at this point we know that all elements of the chrec are constants and
2912 // that the start element is zero.
2914 // First check to see if the range contains zero. If not, the first
2916 if (!Range.contains(APInt(getBitWidth(),0)))
2917 return SE.getConstant(ConstantInt::get(getType(),0));
2920 // If this is an affine expression then we have this situation:
2921 // Solve {0,+,A} in Range === Ax in Range
2923 // We know that zero is in the range. If A is positive then we know that
2924 // the upper value of the range must be the first possible exit value.
2925 // If A is negative then the lower of the range is the last possible loop
2926 // value. Also note that we already checked for a full range.
2927 APInt One(getBitWidth(),1);
2928 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2929 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2931 // The exit value should be (End+A)/A.
2932 APInt ExitVal = (End + A).udiv(A);
2933 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2935 // Evaluate at the exit value. If we really did fall out of the valid
2936 // range, then we computed our trip count, otherwise wrap around or other
2937 // things must have happened.
2938 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2939 if (Range.contains(Val->getValue()))
2940 return new SCEVCouldNotCompute(); // Something strange happened
2942 // Ensure that the previous value is in the range. This is a sanity check.
2943 assert(Range.contains(
2944 EvaluateConstantChrecAtConstant(this,
2945 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2946 "Linear scev computation is off in a bad way!");
2947 return SE.getConstant(ExitValue);
2948 } else if (isQuadratic()) {
2949 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2950 // quadratic equation to solve it. To do this, we must frame our problem in
2951 // terms of figuring out when zero is crossed, instead of when
2952 // Range.getUpper() is crossed.
2953 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2954 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2955 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2957 // Next, solve the constructed addrec
2958 std::pair<SCEVHandle,SCEVHandle> Roots =
2959 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2960 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2961 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2963 // Pick the smallest positive root value.
2964 if (ConstantInt *CB =
2965 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2966 R1->getValue(), R2->getValue()))) {
2967 if (CB->getZExtValue() == false)
2968 std::swap(R1, R2); // R1 is the minimum root now.
2970 // Make sure the root is not off by one. The returned iteration should
2971 // not be in the range, but the previous one should be. When solving
2972 // for "X*X < 5", for example, we should not return a root of 2.
2973 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2976 if (Range.contains(R1Val->getValue())) {
2977 // The next iteration must be out of the range...
2978 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2980 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2981 if (!Range.contains(R1Val->getValue()))
2982 return SE.getConstant(NextVal);
2983 return new SCEVCouldNotCompute(); // Something strange happened
2986 // If R1 was not in the range, then it is a good return value. Make
2987 // sure that R1-1 WAS in the range though, just in case.
2988 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2989 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2990 if (Range.contains(R1Val->getValue()))
2992 return new SCEVCouldNotCompute(); // Something strange happened
2997 return new SCEVCouldNotCompute();
3002 //===----------------------------------------------------------------------===//
3003 // ScalarEvolution Class Implementation
3004 //===----------------------------------------------------------------------===//
3006 bool ScalarEvolution::runOnFunction(Function &F) {
3007 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
3011 void ScalarEvolution::releaseMemory() {
3012 delete (ScalarEvolutionsImpl*)Impl;
3016 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3017 AU.setPreservesAll();
3018 AU.addRequiredTransitive<LoopInfo>();
3021 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3022 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3025 /// hasSCEV - Return true if the SCEV for this value has already been
3027 bool ScalarEvolution::hasSCEV(Value *V) const {
3028 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3032 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3033 /// the specified value.
3034 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3035 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3039 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3040 ICmpInst::Predicate Pred,
3041 SCEV *LHS, SCEV *RHS) {
3042 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3046 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3047 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3050 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3051 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3054 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3055 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3058 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3059 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3062 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3064 // Print all inner loops first
3065 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3066 PrintLoopInfo(OS, SE, *I);
3068 OS << "Loop " << L->getHeader()->getName() << ": ";
3070 SmallVector<BasicBlock*, 8> ExitBlocks;
3071 L->getExitBlocks(ExitBlocks);
3072 if (ExitBlocks.size() != 1)
3073 OS << "<multiple exits> ";
3075 if (SE->hasLoopInvariantIterationCount(L)) {
3076 OS << *SE->getIterationCount(L) << " iterations! ";
3078 OS << "Unpredictable iteration count. ";
3084 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3085 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3086 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3088 OS << "Classifying expressions for: " << F.getName() << "\n";
3089 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3090 if (I->getType()->isInteger()) {
3093 SCEVHandle SV = getSCEV(&*I);
3097 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3099 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3100 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3101 OS << "<<Unknown>>";
3111 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3112 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3113 PrintLoopInfo(OS, this, *I);