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/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Assembly/Writer.h"
72 #include "llvm/Target/TargetData.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/GetElementPtrTypeIterator.h"
77 #include "llvm/Support/InstIterator.h"
78 #include "llvm/Support/ManagedStatic.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include "llvm/ADT/Statistic.h"
82 #include "llvm/ADT/STLExtras.h"
87 STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89 STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91 STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93 STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
96 static cl::opt<unsigned>
97 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
102 static RegisterPass<ScalarEvolution>
103 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
104 char ScalarEvolution::ID = 0;
106 //===----------------------------------------------------------------------===//
107 // SCEV class definitions
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
111 // Implementation of the SCEV class.
114 void SCEV::dump() const {
119 void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
124 bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132 SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
134 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 SCEVHandle SCEVCouldNotCompute::
150 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
156 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
157 OS << "***COULDNOTCOMPUTE***";
160 bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
165 // SCEVConstants - Only allow the creation of one SCEVConstant for any
166 // particular value. Don't use a SCEVHandle here, or else the object will
168 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
171 SCEVConstant::~SCEVConstant() {
172 SCEVConstants->erase(V);
175 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
176 SCEVConstant *&R = (*SCEVConstants)[V];
177 if (R == 0) R = new SCEVConstant(V);
181 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
185 const Type *SCEVConstant::getType() const { return V->getType(); }
187 void SCEVConstant::print(raw_ostream &OS) const {
188 WriteAsOperand(OS, V, false);
191 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
192 const SCEVHandle &op, const Type *ty)
193 : SCEV(SCEVTy), Op(op), Ty(ty) {}
195 SCEVCastExpr::~SCEVCastExpr() {}
197 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
198 return Op->dominates(BB, DT);
201 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202 // particular input. Don't use a SCEVHandle here, or else the object will
204 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
207 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEVCastExpr(scTruncate, op, ty) {
209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
210 (Ty->isInteger() || isa<PointerType>(Ty)) &&
211 "Cannot truncate non-integer value!");
214 SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates->erase(std::make_pair(Op, Ty));
218 void SCEVTruncateExpr::print(raw_ostream &OS) const {
219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
222 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223 // particular input. Don't use a SCEVHandle here, or else the object will never
225 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
229 : SCEVCastExpr(scZeroExtend, op, ty) {
230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
232 "Cannot zero extend non-integer value!");
235 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
239 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
243 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244 // particular input. Don't use a SCEVHandle here, or else the object will never
246 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
247 SCEVSignExtendExpr*> > SCEVSignExtends;
249 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
250 : SCEVCastExpr(scSignExtend, op, ty) {
251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
253 "Cannot sign extend non-integer value!");
256 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
260 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
264 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265 // particular input. Don't use a SCEVHandle here, or else the object will never
267 static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
268 SCEVCommutativeExpr*> > SCEVCommExprs;
270 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
275 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
277 const char *OpStr = getOperationStr();
278 OS << "(" << *Operands[0];
279 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
280 OS << OpStr << *Operands[i];
284 SCEVHandle SCEVCommutativeExpr::
285 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
286 const SCEVHandle &Conc,
287 ScalarEvolution &SE) const {
288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
291 if (H != getOperand(i)) {
292 std::vector<SCEVHandle> NewOps;
293 NewOps.reserve(getNumOperands());
294 for (unsigned j = 0; j != i; ++j)
295 NewOps.push_back(getOperand(j));
297 for (++i; i != e; ++i)
298 NewOps.push_back(getOperand(i)->
299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
301 if (isa<SCEVAddExpr>(this))
302 return SE.getAddExpr(NewOps);
303 else if (isa<SCEVMulExpr>(this))
304 return SE.getMulExpr(NewOps);
305 else if (isa<SCEVSMaxExpr>(this))
306 return SE.getSMaxExpr(NewOps);
307 else if (isa<SCEVUMaxExpr>(this))
308 return SE.getUMaxExpr(NewOps);
310 assert(0 && "Unknown commutative expr!");
316 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
318 if (!getOperand(i)->dominates(BB, DT))
325 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
326 // input. Don't use a SCEVHandle here, or else the object will never be
328 static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
329 SCEVUDivExpr*> > SCEVUDivs;
331 SCEVUDivExpr::~SCEVUDivExpr() {
332 SCEVUDivs->erase(std::make_pair(LHS, RHS));
335 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
339 void SCEVUDivExpr::print(raw_ostream &OS) const {
340 OS << "(" << *LHS << " /u " << *RHS << ")";
343 const Type *SCEVUDivExpr::getType() const {
344 return LHS->getType();
347 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348 // particular input. Don't use a SCEVHandle here, or else the object will never
350 static ManagedStatic<std::map<std::pair<const Loop *,
351 std::vector<const SCEV*> >,
352 SCEVAddRecExpr*> > SCEVAddRecExprs;
354 SCEVAddRecExpr::~SCEVAddRecExpr() {
355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
359 SCEVHandle SCEVAddRecExpr::
360 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
376 return SE.getAddRecExpr(NewOps, L);
383 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
391 void SCEVAddRecExpr::print(raw_ostream &OS) const {
392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
398 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399 // value. Don't use a SCEVHandle here, or else the object will never be
401 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
403 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
405 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
413 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
419 const Type *SCEVUnknown::getType() const {
423 void SCEVUnknown::print(raw_ostream &OS) const {
424 WriteAsOperand(OS, V, false);
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
454 // Compare getValueID values.
455 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
456 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
458 // Sort arguments by their position.
459 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
460 const Argument *RA = cast<Argument>(RU->getValue());
461 return LA->getArgNo() < RA->getArgNo();
464 // For instructions, compare their loop depth, and their opcode.
465 // This is pretty loose.
466 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
467 Instruction *RV = cast<Instruction>(RU->getValue());
469 // Compare loop depths.
470 if (LI->getLoopDepth(LV->getParent()) !=
471 LI->getLoopDepth(RV->getParent()))
472 return LI->getLoopDepth(LV->getParent()) <
473 LI->getLoopDepth(RV->getParent());
476 if (LV->getOpcode() != RV->getOpcode())
477 return LV->getOpcode() < RV->getOpcode();
479 // Compare the number of operands.
480 if (LV->getNumOperands() != RV->getNumOperands())
481 return LV->getNumOperands() < RV->getNumOperands();
487 // Constant sorting doesn't matter since they'll be folded.
488 if (isa<SCEVConstant>(LHS))
491 // Lexicographically compare n-ary expressions.
492 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
493 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
494 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
495 if (i >= RC->getNumOperands())
497 if (operator()(LC->getOperand(i), RC->getOperand(i)))
499 if (operator()(RC->getOperand(i), LC->getOperand(i)))
502 return LC->getNumOperands() < RC->getNumOperands();
505 // Compare cast expressions by operand.
506 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
507 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
508 return operator()(LC->getOperand(), RC->getOperand());
511 assert(0 && "Unknown SCEV kind!");
517 /// GroupByComplexity - Given a list of SCEV objects, order them by their
518 /// complexity, and group objects of the same complexity together by value.
519 /// When this routine is finished, we know that any duplicates in the vector are
520 /// consecutive and that complexity is monotonically increasing.
522 /// Note that we go take special precautions to ensure that we get determinstic
523 /// results from this routine. In other words, we don't want the results of
524 /// this to depend on where the addresses of various SCEV objects happened to
527 static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
529 if (Ops.size() < 2) return; // Noop
530 if (Ops.size() == 2) {
531 // This is the common case, which also happens to be trivially simple.
533 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
534 std::swap(Ops[0], Ops[1]);
538 // Do the rough sort by complexity.
539 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
541 // Now that we are sorted by complexity, group elements of the same
542 // complexity. Note that this is, at worst, N^2, but the vector is likely to
543 // be extremely short in practice. Note that we take this approach because we
544 // do not want to depend on the addresses of the objects we are grouping.
545 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
546 const SCEV *S = Ops[i];
547 unsigned Complexity = S->getSCEVType();
549 // If there are any objects of the same complexity and same value as this
551 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
552 if (Ops[j] == S) { // Found a duplicate.
553 // Move it to immediately after i'th element.
554 std::swap(Ops[i+1], Ops[j]);
555 ++i; // no need to rescan it.
556 if (i == e-2) return; // Done!
564 //===----------------------------------------------------------------------===//
565 // Simple SCEV method implementations
566 //===----------------------------------------------------------------------===//
568 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
570 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
572 const Type* ResultTy) {
573 // Handle the simplest case efficiently.
575 return SE.getTruncateOrZeroExtend(It, ResultTy);
577 // We are using the following formula for BC(It, K):
579 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
581 // Suppose, W is the bitwidth of the return value. We must be prepared for
582 // overflow. Hence, we must assure that the result of our computation is
583 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
584 // safe in modular arithmetic.
586 // However, this code doesn't use exactly that formula; the formula it uses
587 // is something like the following, where T is the number of factors of 2 in
588 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
591 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
593 // This formula is trivially equivalent to the previous formula. However,
594 // this formula can be implemented much more efficiently. The trick is that
595 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
596 // arithmetic. To do exact division in modular arithmetic, all we have
597 // to do is multiply by the inverse. Therefore, this step can be done at
600 // The next issue is how to safely do the division by 2^T. The way this
601 // is done is by doing the multiplication step at a width of at least W + T
602 // bits. This way, the bottom W+T bits of the product are accurate. Then,
603 // when we perform the division by 2^T (which is equivalent to a right shift
604 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
605 // truncated out after the division by 2^T.
607 // In comparison to just directly using the first formula, this technique
608 // is much more efficient; using the first formula requires W * K bits,
609 // but this formula less than W + K bits. Also, the first formula requires
610 // a division step, whereas this formula only requires multiplies and shifts.
612 // It doesn't matter whether the subtraction step is done in the calculation
613 // width or the input iteration count's width; if the subtraction overflows,
614 // the result must be zero anyway. We prefer here to do it in the width of
615 // the induction variable because it helps a lot for certain cases; CodeGen
616 // isn't smart enough to ignore the overflow, which leads to much less
617 // efficient code if the width of the subtraction is wider than the native
620 // (It's possible to not widen at all by pulling out factors of 2 before
621 // the multiplication; for example, K=2 can be calculated as
622 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
623 // extra arithmetic, so it's not an obvious win, and it gets
624 // much more complicated for K > 3.)
626 // Protection from insane SCEVs; this bound is conservative,
627 // but it probably doesn't matter.
629 return SE.getCouldNotCompute();
631 unsigned W = SE.getTypeSizeInBits(ResultTy);
633 // Calculate K! / 2^T and T; we divide out the factors of two before
634 // multiplying for calculating K! / 2^T to avoid overflow.
635 // Other overflow doesn't matter because we only care about the bottom
636 // W bits of the result.
637 APInt OddFactorial(W, 1);
639 for (unsigned i = 3; i <= K; ++i) {
641 unsigned TwoFactors = Mult.countTrailingZeros();
643 Mult = Mult.lshr(TwoFactors);
644 OddFactorial *= Mult;
647 // We need at least W + T bits for the multiplication step
648 unsigned CalculationBits = W + T;
650 // Calcuate 2^T, at width T+W.
651 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
653 // Calculate the multiplicative inverse of K! / 2^T;
654 // this multiplication factor will perform the exact division by
656 APInt Mod = APInt::getSignedMinValue(W+1);
657 APInt MultiplyFactor = OddFactorial.zext(W+1);
658 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
659 MultiplyFactor = MultiplyFactor.trunc(W);
661 // Calculate the product, at width T+W
662 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
663 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
664 for (unsigned i = 1; i != K; ++i) {
665 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
666 Dividend = SE.getMulExpr(Dividend,
667 SE.getTruncateOrZeroExtend(S, CalculationTy));
671 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
673 // Truncate the result, and divide by K! / 2^T.
675 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
676 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
679 /// evaluateAtIteration - Return the value of this chain of recurrences at
680 /// the specified iteration number. We can evaluate this recurrence by
681 /// multiplying each element in the chain by the binomial coefficient
682 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
684 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
686 /// where BC(It, k) stands for binomial coefficient.
688 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
689 ScalarEvolution &SE) const {
690 SCEVHandle Result = getStart();
691 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
692 // The computation is correct in the face of overflow provided that the
693 // multiplication is performed _after_ the evaluation of the binomial
695 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
696 if (isa<SCEVCouldNotCompute>(Coeff))
699 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
704 //===----------------------------------------------------------------------===//
705 // SCEV Expression folder implementations
706 //===----------------------------------------------------------------------===//
708 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
710 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
711 "This is not a truncating conversion!");
712 assert(isSCEVable(Ty) &&
713 "This is not a conversion to a SCEVable type!");
714 Ty = getEffectiveSCEVType(Ty);
716 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
718 ConstantExpr::getTrunc(SC->getValue(), Ty));
720 // trunc(trunc(x)) --> trunc(x)
721 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
722 return getTruncateExpr(ST->getOperand(), Ty);
724 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
725 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
726 return getTruncateOrSignExtend(SS->getOperand(), Ty);
728 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
729 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
730 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
732 // If the input value is a chrec scev made out of constants, truncate
733 // all of the constants.
734 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
735 std::vector<SCEVHandle> Operands;
736 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
737 // FIXME: This should allow truncation of other expression types!
738 if (isa<SCEVConstant>(AddRec->getOperand(i)))
739 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
742 if (Operands.size() == AddRec->getNumOperands())
743 return getAddRecExpr(Operands, AddRec->getLoop());
746 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
747 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
751 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
753 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
754 "This is not an extending conversion!");
755 assert(isSCEVable(Ty) &&
756 "This is not a conversion to a SCEVable type!");
757 Ty = getEffectiveSCEVType(Ty);
759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
760 const Type *IntTy = getEffectiveSCEVType(Ty);
761 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
762 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
763 return getUnknown(C);
766 // zext(zext(x)) --> zext(x)
767 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
768 return getZeroExtendExpr(SZ->getOperand(), Ty);
770 // If the input value is a chrec scev, and we can prove that the value
771 // did not overflow the old, smaller, value, we can zero extend all of the
772 // operands (often constants). This allows analysis of something like
773 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
774 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
775 if (AR->isAffine()) {
776 // Check whether the backedge-taken count is SCEVCouldNotCompute.
777 // Note that this serves two purposes: It filters out loops that are
778 // simply not analyzable, and it covers the case where this code is
779 // being called from within backedge-taken count analysis, such that
780 // attempting to ask for the backedge-taken count would likely result
781 // in infinite recursion. In the later case, the analysis code will
782 // cope with a conservative value, and it will take care to purge
783 // that value once it has finished.
784 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
785 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
786 // Manually compute the final value for AR, checking for
788 SCEVHandle Start = AR->getStart();
789 SCEVHandle Step = AR->getStepRecurrence(*this);
791 // Check whether the backedge-taken count can be losslessly casted to
792 // the addrec's type. The count is always unsigned.
793 SCEVHandle CastedMaxBECount =
794 getTruncateOrZeroExtend(MaxBECount, Start->getType());
796 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
798 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
799 // Check whether Start+Step*MaxBECount has no unsigned overflow.
801 getMulExpr(CastedMaxBECount,
802 getTruncateOrZeroExtend(Step, Start->getType()));
803 SCEVHandle Add = getAddExpr(Start, ZMul);
804 if (getZeroExtendExpr(Add, WideTy) ==
805 getAddExpr(getZeroExtendExpr(Start, WideTy),
806 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
807 getZeroExtendExpr(Step, WideTy))))
808 // Return the expression with the addrec on the outside.
809 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
810 getZeroExtendExpr(Step, Ty),
813 // Similar to above, only this time treat the step value as signed.
814 // This covers loops that count down.
816 getMulExpr(CastedMaxBECount,
817 getTruncateOrSignExtend(Step, Start->getType()));
818 Add = getAddExpr(Start, SMul);
819 if (getZeroExtendExpr(Add, WideTy) ==
820 getAddExpr(getZeroExtendExpr(Start, WideTy),
821 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
822 getSignExtendExpr(Step, WideTy))))
823 // Return the expression with the addrec on the outside.
824 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
825 getSignExtendExpr(Step, Ty),
831 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
832 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
836 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
838 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
839 "This is not an extending conversion!");
840 assert(isSCEVable(Ty) &&
841 "This is not a conversion to a SCEVable type!");
842 Ty = getEffectiveSCEVType(Ty);
844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
845 const Type *IntTy = getEffectiveSCEVType(Ty);
846 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
847 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
848 return getUnknown(C);
851 // sext(sext(x)) --> sext(x)
852 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
853 return getSignExtendExpr(SS->getOperand(), Ty);
855 // If the input value is a chrec scev, and we can prove that the value
856 // did not overflow the old, smaller, value, we can sign extend all of the
857 // operands (often constants). This allows analysis of something like
858 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
859 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
860 if (AR->isAffine()) {
861 // Check whether the backedge-taken count is SCEVCouldNotCompute.
862 // Note that this serves two purposes: It filters out loops that are
863 // simply not analyzable, and it covers the case where this code is
864 // being called from within backedge-taken count analysis, such that
865 // attempting to ask for the backedge-taken count would likely result
866 // in infinite recursion. In the later case, the analysis code will
867 // cope with a conservative value, and it will take care to purge
868 // that value once it has finished.
869 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
870 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
871 // Manually compute the final value for AR, checking for
873 SCEVHandle Start = AR->getStart();
874 SCEVHandle Step = AR->getStepRecurrence(*this);
876 // Check whether the backedge-taken count can be losslessly casted to
877 // the addrec's type. The count is always unsigned.
878 SCEVHandle CastedMaxBECount =
879 getTruncateOrZeroExtend(MaxBECount, Start->getType());
881 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
883 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
884 // Check whether Start+Step*MaxBECount has no signed overflow.
886 getMulExpr(CastedMaxBECount,
887 getTruncateOrSignExtend(Step, Start->getType()));
888 SCEVHandle Add = getAddExpr(Start, SMul);
889 if (getSignExtendExpr(Add, WideTy) ==
890 getAddExpr(getSignExtendExpr(Start, WideTy),
891 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
892 getSignExtendExpr(Step, WideTy))))
893 // Return the expression with the addrec on the outside.
894 return getAddRecExpr(getSignExtendExpr(Start, Ty),
895 getSignExtendExpr(Step, Ty),
901 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
902 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
906 // get - Get a canonical add expression, or something simpler if possible.
907 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
908 assert(!Ops.empty() && "Cannot get empty add!");
909 if (Ops.size() == 1) return Ops[0];
911 // Sort by complexity, this groups all similar expression types together.
912 GroupByComplexity(Ops, LI);
914 // If there are any constants, fold them together.
916 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
918 assert(Idx < Ops.size());
919 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
920 // We found two constants, fold them together!
921 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
922 RHSC->getValue()->getValue());
923 Ops[0] = getConstant(Fold);
924 Ops.erase(Ops.begin()+1); // Erase the folded element
925 if (Ops.size() == 1) return Ops[0];
926 LHSC = cast<SCEVConstant>(Ops[0]);
929 // If we are left with a constant zero being added, strip it off.
930 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
931 Ops.erase(Ops.begin());
936 if (Ops.size() == 1) return Ops[0];
938 // Okay, check to see if the same value occurs in the operand list twice. If
939 // so, merge them together into an multiply expression. Since we sorted the
940 // list, these values are required to be adjacent.
941 const Type *Ty = Ops[0]->getType();
942 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
943 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
944 // Found a match, merge the two values into a multiply, and add any
945 // remaining values to the result.
946 SCEVHandle Two = getIntegerSCEV(2, Ty);
947 SCEVHandle Mul = getMulExpr(Ops[i], Two);
950 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
952 return getAddExpr(Ops);
955 // Now we know the first non-constant operand. Skip past any cast SCEVs.
956 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
959 // If there are add operands they would be next.
960 if (Idx < Ops.size()) {
961 bool DeletedAdd = false;
962 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
963 // If we have an add, expand the add operands onto the end of the operands
965 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
966 Ops.erase(Ops.begin()+Idx);
970 // If we deleted at least one add, we added operands to the end of the list,
971 // and they are not necessarily sorted. Recurse to resort and resimplify
972 // any operands we just aquired.
974 return getAddExpr(Ops);
977 // Skip over the add expression until we get to a multiply.
978 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
981 // If we are adding something to a multiply expression, make sure the
982 // something is not already an operand of the multiply. If so, merge it into
984 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
985 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
986 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
987 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
988 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
989 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
990 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
991 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
992 if (Mul->getNumOperands() != 2) {
993 // If the multiply has more than two operands, we must get the
995 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
996 MulOps.erase(MulOps.begin()+MulOp);
997 InnerMul = getMulExpr(MulOps);
999 SCEVHandle One = getIntegerSCEV(1, Ty);
1000 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1001 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1002 if (Ops.size() == 2) return OuterMul;
1004 Ops.erase(Ops.begin()+AddOp);
1005 Ops.erase(Ops.begin()+Idx-1);
1007 Ops.erase(Ops.begin()+Idx);
1008 Ops.erase(Ops.begin()+AddOp-1);
1010 Ops.push_back(OuterMul);
1011 return getAddExpr(Ops);
1014 // Check this multiply against other multiplies being added together.
1015 for (unsigned OtherMulIdx = Idx+1;
1016 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1018 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1019 // If MulOp occurs in OtherMul, we can fold the two multiplies
1021 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1022 OMulOp != e; ++OMulOp)
1023 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1024 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1025 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1026 if (Mul->getNumOperands() != 2) {
1027 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1028 MulOps.erase(MulOps.begin()+MulOp);
1029 InnerMul1 = getMulExpr(MulOps);
1031 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1032 if (OtherMul->getNumOperands() != 2) {
1033 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1034 OtherMul->op_end());
1035 MulOps.erase(MulOps.begin()+OMulOp);
1036 InnerMul2 = getMulExpr(MulOps);
1038 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1039 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1040 if (Ops.size() == 2) return OuterMul;
1041 Ops.erase(Ops.begin()+Idx);
1042 Ops.erase(Ops.begin()+OtherMulIdx-1);
1043 Ops.push_back(OuterMul);
1044 return getAddExpr(Ops);
1050 // If there are any add recurrences in the operands list, see if any other
1051 // added values are loop invariant. If so, we can fold them into the
1053 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1056 // Scan over all recurrences, trying to fold loop invariants into them.
1057 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1058 // Scan all of the other operands to this add and add them to the vector if
1059 // they are loop invariant w.r.t. the recurrence.
1060 std::vector<SCEVHandle> LIOps;
1061 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1062 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1063 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1064 LIOps.push_back(Ops[i]);
1065 Ops.erase(Ops.begin()+i);
1069 // If we found some loop invariants, fold them into the recurrence.
1070 if (!LIOps.empty()) {
1071 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1072 LIOps.push_back(AddRec->getStart());
1074 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
1075 AddRecOps[0] = getAddExpr(LIOps);
1077 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1078 // If all of the other operands were loop invariant, we are done.
1079 if (Ops.size() == 1) return NewRec;
1081 // Otherwise, add the folded AddRec by the non-liv parts.
1082 for (unsigned i = 0;; ++i)
1083 if (Ops[i] == AddRec) {
1087 return getAddExpr(Ops);
1090 // Okay, if there weren't any loop invariants to be folded, check to see if
1091 // there are multiple AddRec's with the same loop induction variable being
1092 // added together. If so, we can fold them.
1093 for (unsigned OtherIdx = Idx+1;
1094 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1095 if (OtherIdx != Idx) {
1096 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1097 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1098 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1099 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1100 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1101 if (i >= NewOps.size()) {
1102 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1103 OtherAddRec->op_end());
1106 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1108 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1110 if (Ops.size() == 2) return NewAddRec;
1112 Ops.erase(Ops.begin()+Idx);
1113 Ops.erase(Ops.begin()+OtherIdx-1);
1114 Ops.push_back(NewAddRec);
1115 return getAddExpr(Ops);
1119 // Otherwise couldn't fold anything into this recurrence. Move onto the
1123 // Okay, it looks like we really DO need an add expr. Check to see if we
1124 // already have one, otherwise create a new one.
1125 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1126 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1128 if (Result == 0) Result = new SCEVAddExpr(Ops);
1133 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
1134 assert(!Ops.empty() && "Cannot get empty mul!");
1136 // Sort by complexity, this groups all similar expression types together.
1137 GroupByComplexity(Ops, LI);
1139 // If there are any constants, fold them together.
1141 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1143 // C1*(C2+V) -> C1*C2 + C1*V
1144 if (Ops.size() == 2)
1145 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1146 if (Add->getNumOperands() == 2 &&
1147 isa<SCEVConstant>(Add->getOperand(0)))
1148 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1149 getMulExpr(LHSC, Add->getOperand(1)));
1153 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1154 // We found two constants, fold them together!
1155 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1156 RHSC->getValue()->getValue());
1157 Ops[0] = getConstant(Fold);
1158 Ops.erase(Ops.begin()+1); // Erase the folded element
1159 if (Ops.size() == 1) return Ops[0];
1160 LHSC = cast<SCEVConstant>(Ops[0]);
1163 // If we are left with a constant one being multiplied, strip it off.
1164 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1165 Ops.erase(Ops.begin());
1167 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1168 // If we have a multiply of zero, it will always be zero.
1173 // Skip over the add expression until we get to a multiply.
1174 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1177 if (Ops.size() == 1)
1180 // If there are mul operands inline them all into this expression.
1181 if (Idx < Ops.size()) {
1182 bool DeletedMul = false;
1183 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1184 // If we have an mul, expand the mul operands onto the end of the operands
1186 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1187 Ops.erase(Ops.begin()+Idx);
1191 // If we deleted at least one mul, we added operands to the end of the list,
1192 // and they are not necessarily sorted. Recurse to resort and resimplify
1193 // any operands we just aquired.
1195 return getMulExpr(Ops);
1198 // If there are any add recurrences in the operands list, see if any other
1199 // added values are loop invariant. If so, we can fold them into the
1201 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1204 // Scan over all recurrences, trying to fold loop invariants into them.
1205 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1206 // Scan all of the other operands to this mul and add them to the vector if
1207 // they are loop invariant w.r.t. the recurrence.
1208 std::vector<SCEVHandle> LIOps;
1209 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1210 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1211 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1212 LIOps.push_back(Ops[i]);
1213 Ops.erase(Ops.begin()+i);
1217 // If we found some loop invariants, fold them into the recurrence.
1218 if (!LIOps.empty()) {
1219 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1220 std::vector<SCEVHandle> NewOps;
1221 NewOps.reserve(AddRec->getNumOperands());
1222 if (LIOps.size() == 1) {
1223 const SCEV *Scale = LIOps[0];
1224 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1225 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1227 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1228 std::vector<SCEVHandle> MulOps(LIOps);
1229 MulOps.push_back(AddRec->getOperand(i));
1230 NewOps.push_back(getMulExpr(MulOps));
1234 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1236 // If all of the other operands were loop invariant, we are done.
1237 if (Ops.size() == 1) return NewRec;
1239 // Otherwise, multiply the folded AddRec by the non-liv parts.
1240 for (unsigned i = 0;; ++i)
1241 if (Ops[i] == AddRec) {
1245 return getMulExpr(Ops);
1248 // Okay, if there weren't any loop invariants to be folded, check to see if
1249 // there are multiple AddRec's with the same loop induction variable being
1250 // multiplied together. If so, we can fold them.
1251 for (unsigned OtherIdx = Idx+1;
1252 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1253 if (OtherIdx != Idx) {
1254 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1255 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1256 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1257 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1258 SCEVHandle NewStart = getMulExpr(F->getStart(),
1260 SCEVHandle B = F->getStepRecurrence(*this);
1261 SCEVHandle D = G->getStepRecurrence(*this);
1262 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1265 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1267 if (Ops.size() == 2) return NewAddRec;
1269 Ops.erase(Ops.begin()+Idx);
1270 Ops.erase(Ops.begin()+OtherIdx-1);
1271 Ops.push_back(NewAddRec);
1272 return getMulExpr(Ops);
1276 // Otherwise couldn't fold anything into this recurrence. Move onto the
1280 // Okay, it looks like we really DO need an mul expr. Check to see if we
1281 // already have one, otherwise create a new one.
1282 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1283 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1286 Result = new SCEVMulExpr(Ops);
1290 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1291 const SCEVHandle &RHS) {
1292 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1293 if (RHSC->getValue()->equalsInt(1))
1294 return LHS; // X udiv 1 --> x
1296 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1297 Constant *LHSCV = LHSC->getValue();
1298 Constant *RHSCV = RHSC->getValue();
1299 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1303 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1305 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1306 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1311 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1312 /// specified loop. Simplify the expression as much as possible.
1313 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1314 const SCEVHandle &Step, const Loop *L) {
1315 std::vector<SCEVHandle> Operands;
1316 Operands.push_back(Start);
1317 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1318 if (StepChrec->getLoop() == L) {
1319 Operands.insert(Operands.end(), StepChrec->op_begin(),
1320 StepChrec->op_end());
1321 return getAddRecExpr(Operands, L);
1324 Operands.push_back(Step);
1325 return getAddRecExpr(Operands, L);
1328 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1329 /// specified loop. Simplify the expression as much as possible.
1330 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1332 if (Operands.size() == 1) return Operands[0];
1334 if (Operands.back()->isZero()) {
1335 Operands.pop_back();
1336 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1339 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1340 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1341 const Loop* NestedLoop = NestedAR->getLoop();
1342 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1343 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1344 NestedAR->op_end());
1345 SCEVHandle NestedARHandle(NestedAR);
1346 Operands[0] = NestedAR->getStart();
1347 NestedOperands[0] = getAddRecExpr(Operands, L);
1348 return getAddRecExpr(NestedOperands, NestedLoop);
1352 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1353 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1354 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1358 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
1360 std::vector<SCEVHandle> Ops;
1363 return getSMaxExpr(Ops);
1366 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1367 assert(!Ops.empty() && "Cannot get empty smax!");
1368 if (Ops.size() == 1) return Ops[0];
1370 // Sort by complexity, this groups all similar expression types together.
1371 GroupByComplexity(Ops, LI);
1373 // If there are any constants, fold them together.
1375 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1377 assert(Idx < Ops.size());
1378 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1379 // We found two constants, fold them together!
1380 ConstantInt *Fold = ConstantInt::get(
1381 APIntOps::smax(LHSC->getValue()->getValue(),
1382 RHSC->getValue()->getValue()));
1383 Ops[0] = getConstant(Fold);
1384 Ops.erase(Ops.begin()+1); // Erase the folded element
1385 if (Ops.size() == 1) return Ops[0];
1386 LHSC = cast<SCEVConstant>(Ops[0]);
1389 // If we are left with a constant -inf, strip it off.
1390 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1391 Ops.erase(Ops.begin());
1396 if (Ops.size() == 1) return Ops[0];
1398 // Find the first SMax
1399 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1402 // Check to see if one of the operands is an SMax. If so, expand its operands
1403 // onto our operand list, and recurse to simplify.
1404 if (Idx < Ops.size()) {
1405 bool DeletedSMax = false;
1406 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1407 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1408 Ops.erase(Ops.begin()+Idx);
1413 return getSMaxExpr(Ops);
1416 // Okay, check to see if the same value occurs in the operand list twice. If
1417 // so, delete one. Since we sorted the list, these values are required to
1419 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1420 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1421 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1425 if (Ops.size() == 1) return Ops[0];
1427 assert(!Ops.empty() && "Reduced smax down to nothing!");
1429 // Okay, it looks like we really DO need an smax expr. Check to see if we
1430 // already have one, otherwise create a new one.
1431 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1432 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1434 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1438 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1439 const SCEVHandle &RHS) {
1440 std::vector<SCEVHandle> Ops;
1443 return getUMaxExpr(Ops);
1446 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1447 assert(!Ops.empty() && "Cannot get empty umax!");
1448 if (Ops.size() == 1) return Ops[0];
1450 // Sort by complexity, this groups all similar expression types together.
1451 GroupByComplexity(Ops, LI);
1453 // If there are any constants, fold them together.
1455 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1457 assert(Idx < Ops.size());
1458 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1459 // We found two constants, fold them together!
1460 ConstantInt *Fold = ConstantInt::get(
1461 APIntOps::umax(LHSC->getValue()->getValue(),
1462 RHSC->getValue()->getValue()));
1463 Ops[0] = getConstant(Fold);
1464 Ops.erase(Ops.begin()+1); // Erase the folded element
1465 if (Ops.size() == 1) return Ops[0];
1466 LHSC = cast<SCEVConstant>(Ops[0]);
1469 // If we are left with a constant zero, strip it off.
1470 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1471 Ops.erase(Ops.begin());
1476 if (Ops.size() == 1) return Ops[0];
1478 // Find the first UMax
1479 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1482 // Check to see if one of the operands is a UMax. If so, expand its operands
1483 // onto our operand list, and recurse to simplify.
1484 if (Idx < Ops.size()) {
1485 bool DeletedUMax = false;
1486 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1487 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1488 Ops.erase(Ops.begin()+Idx);
1493 return getUMaxExpr(Ops);
1496 // Okay, check to see if the same value occurs in the operand list twice. If
1497 // so, delete one. Since we sorted the list, these values are required to
1499 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1500 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1501 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1505 if (Ops.size() == 1) return Ops[0];
1507 assert(!Ops.empty() && "Reduced umax down to nothing!");
1509 // Okay, it looks like we really DO need a umax expr. Check to see if we
1510 // already have one, otherwise create a new one.
1511 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1512 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1514 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1518 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1519 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1520 return getConstant(CI);
1521 if (isa<ConstantPointerNull>(V))
1522 return getIntegerSCEV(0, V->getType());
1523 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1524 if (Result == 0) Result = new SCEVUnknown(V);
1528 //===----------------------------------------------------------------------===//
1529 // Basic SCEV Analysis and PHI Idiom Recognition Code
1532 /// isSCEVable - Test if values of the given type are analyzable within
1533 /// the SCEV framework. This primarily includes integer types, and it
1534 /// can optionally include pointer types if the ScalarEvolution class
1535 /// has access to target-specific information.
1536 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1537 // Integers are always SCEVable.
1538 if (Ty->isInteger())
1541 // Pointers are SCEVable if TargetData information is available
1542 // to provide pointer size information.
1543 if (isa<PointerType>(Ty))
1546 // Otherwise it's not SCEVable.
1550 /// getTypeSizeInBits - Return the size in bits of the specified type,
1551 /// for which isSCEVable must return true.
1552 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1553 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1555 // If we have a TargetData, use it!
1557 return TD->getTypeSizeInBits(Ty);
1559 // Otherwise, we support only integer types.
1560 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1561 return Ty->getPrimitiveSizeInBits();
1564 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1565 /// the given type and which represents how SCEV will treat the given
1566 /// type, for which isSCEVable must return true. For pointer types,
1567 /// this is the pointer-sized integer type.
1568 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1569 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1571 if (Ty->isInteger())
1574 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1575 return TD->getIntPtrType();
1578 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1579 return UnknownValue;
1582 /// hasSCEV - Return true if the SCEV for this value has already been
1584 bool ScalarEvolution::hasSCEV(Value *V) const {
1585 return Scalars.count(V);
1588 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1589 /// expression and create a new one.
1590 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1591 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1593 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1594 if (I != Scalars.end()) return I->second;
1595 SCEVHandle S = createSCEV(V);
1596 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1600 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1601 /// specified signed integer value and return a SCEV for the constant.
1602 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1603 Ty = getEffectiveSCEVType(Ty);
1606 C = Constant::getNullValue(Ty);
1607 else if (Ty->isFloatingPoint())
1608 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1609 APFloat::IEEEdouble, Val));
1611 C = ConstantInt::get(Ty, Val);
1612 return getUnknown(C);
1615 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1617 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
1618 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1619 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
1621 const Type *Ty = V->getType();
1622 Ty = getEffectiveSCEVType(Ty);
1623 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
1626 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1627 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
1628 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1629 return getUnknown(ConstantExpr::getNot(VC->getValue()));
1631 const Type *Ty = V->getType();
1632 Ty = getEffectiveSCEVType(Ty);
1633 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
1634 return getMinusSCEV(AllOnes, V);
1637 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1639 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
1640 const SCEVHandle &RHS) {
1642 return getAddExpr(LHS, getNegativeSCEV(RHS));
1645 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1646 /// input value to the specified type. If the type must be extended, it is zero
1649 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
1651 const Type *SrcTy = V->getType();
1652 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1653 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1654 "Cannot truncate or zero extend with non-integer arguments!");
1655 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1656 return V; // No conversion
1657 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1658 return getTruncateExpr(V, Ty);
1659 return getZeroExtendExpr(V, Ty);
1662 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1663 /// input value to the specified type. If the type must be extended, it is sign
1666 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
1668 const Type *SrcTy = V->getType();
1669 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1670 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1671 "Cannot truncate or zero extend with non-integer arguments!");
1672 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1673 return V; // No conversion
1674 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1675 return getTruncateExpr(V, Ty);
1676 return getSignExtendExpr(V, Ty);
1679 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1680 /// the specified instruction and replaces any references to the symbolic value
1681 /// SymName with the specified value. This is used during PHI resolution.
1682 void ScalarEvolution::
1683 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1684 const SCEVHandle &NewVal) {
1685 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1686 Scalars.find(SCEVCallbackVH(I, this));
1687 if (SI == Scalars.end()) return;
1690 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
1691 if (NV == SI->second) return; // No change.
1693 SI->second = NV; // Update the scalars map!
1695 // Any instruction values that use this instruction might also need to be
1697 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1699 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1702 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1703 /// a loop header, making it a potential recurrence, or it doesn't.
1705 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
1706 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1707 if (const Loop *L = LI->getLoopFor(PN->getParent()))
1708 if (L->getHeader() == PN->getParent()) {
1709 // If it lives in the loop header, it has two incoming values, one
1710 // from outside the loop, and one from inside.
1711 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1712 unsigned BackEdge = IncomingEdge^1;
1714 // While we are analyzing this PHI node, handle its value symbolically.
1715 SCEVHandle SymbolicName = getUnknown(PN);
1716 assert(Scalars.find(PN) == Scalars.end() &&
1717 "PHI node already processed?");
1718 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
1720 // Using this symbolic name for the PHI, analyze the value coming around
1722 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1724 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1725 // has a special value for the first iteration of the loop.
1727 // If the value coming around the backedge is an add with the symbolic
1728 // value we just inserted, then we found a simple induction variable!
1729 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1730 // If there is a single occurrence of the symbolic value, replace it
1731 // with a recurrence.
1732 unsigned FoundIndex = Add->getNumOperands();
1733 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1734 if (Add->getOperand(i) == SymbolicName)
1735 if (FoundIndex == e) {
1740 if (FoundIndex != Add->getNumOperands()) {
1741 // Create an add with everything but the specified operand.
1742 std::vector<SCEVHandle> Ops;
1743 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1744 if (i != FoundIndex)
1745 Ops.push_back(Add->getOperand(i));
1746 SCEVHandle Accum = getAddExpr(Ops);
1748 // This is not a valid addrec if the step amount is varying each
1749 // loop iteration, but is not itself an addrec in this loop.
1750 if (Accum->isLoopInvariant(L) ||
1751 (isa<SCEVAddRecExpr>(Accum) &&
1752 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1753 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1754 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
1756 // Okay, for the entire analysis of this edge we assumed the PHI
1757 // to be symbolic. We now need to go back and update all of the
1758 // entries for the scalars that use the PHI (except for the PHI
1759 // itself) to use the new analyzed value instead of the "symbolic"
1761 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1765 } else if (const SCEVAddRecExpr *AddRec =
1766 dyn_cast<SCEVAddRecExpr>(BEValue)) {
1767 // Otherwise, this could be a loop like this:
1768 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1769 // In this case, j = {1,+,1} and BEValue is j.
1770 // Because the other in-value of i (0) fits the evolution of BEValue
1771 // i really is an addrec evolution.
1772 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1773 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1775 // If StartVal = j.start - j.stride, we can use StartVal as the
1776 // initial step of the addrec evolution.
1777 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
1778 AddRec->getOperand(1))) {
1779 SCEVHandle PHISCEV =
1780 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1782 // Okay, for the entire analysis of this edge we assumed the PHI
1783 // to be symbolic. We now need to go back and update all of the
1784 // entries for the scalars that use the PHI (except for the PHI
1785 // itself) to use the new analyzed value instead of the "symbolic"
1787 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1793 return SymbolicName;
1796 // If it's not a loop phi, we can't handle it yet.
1797 return getUnknown(PN);
1800 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1801 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1802 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1803 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1804 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1805 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1806 return C->getValue()->getValue().countTrailingZeros();
1808 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1809 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1810 (uint32_t)SE.getTypeSizeInBits(T->getType()));
1812 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1813 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1814 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1815 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1818 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1819 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1820 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1821 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1824 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1825 // The result is the min of all operands results.
1826 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1827 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1828 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1832 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1833 // The result is the sum of all operands results.
1834 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1835 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1836 for (unsigned i = 1, e = M->getNumOperands();
1837 SumOpRes != BitWidth && i != e; ++i)
1838 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1843 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1844 // The result is the min of all operands results.
1845 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1846 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1847 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1851 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1852 // The result is the min of all operands results.
1853 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1854 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1855 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1859 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1860 // The result is the min of all operands results.
1861 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1862 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1863 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1867 // SCEVUDivExpr, SCEVUnknown
1871 /// createSCEV - We know that there is no SCEV for the specified value.
1872 /// Analyze the expression.
1874 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
1875 if (!isSCEVable(V->getType()))
1876 return getUnknown(V);
1878 unsigned Opcode = Instruction::UserOp1;
1879 if (Instruction *I = dyn_cast<Instruction>(V))
1880 Opcode = I->getOpcode();
1881 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1882 Opcode = CE->getOpcode();
1884 return getUnknown(V);
1886 User *U = cast<User>(V);
1888 case Instruction::Add:
1889 return getAddExpr(getSCEV(U->getOperand(0)),
1890 getSCEV(U->getOperand(1)));
1891 case Instruction::Mul:
1892 return getMulExpr(getSCEV(U->getOperand(0)),
1893 getSCEV(U->getOperand(1)));
1894 case Instruction::UDiv:
1895 return getUDivExpr(getSCEV(U->getOperand(0)),
1896 getSCEV(U->getOperand(1)));
1897 case Instruction::Sub:
1898 return getMinusSCEV(getSCEV(U->getOperand(0)),
1899 getSCEV(U->getOperand(1)));
1900 case Instruction::And:
1901 // For an expression like x&255 that merely masks off the high bits,
1902 // use zext(trunc(x)) as the SCEV expression.
1903 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1904 if (CI->isNullValue())
1905 return getSCEV(U->getOperand(1));
1906 if (CI->isAllOnesValue())
1907 return getSCEV(U->getOperand(0));
1908 const APInt &A = CI->getValue();
1909 unsigned Ones = A.countTrailingOnes();
1910 if (APIntOps::isMask(Ones, A))
1912 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1913 IntegerType::get(Ones)),
1917 case Instruction::Or:
1918 // If the RHS of the Or is a constant, we may have something like:
1919 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1920 // optimizations will transparently handle this case.
1922 // In order for this transformation to be safe, the LHS must be of the
1923 // form X*(2^n) and the Or constant must be less than 2^n.
1924 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1925 SCEVHandle LHS = getSCEV(U->getOperand(0));
1926 const APInt &CIVal = CI->getValue();
1927 if (GetMinTrailingZeros(LHS, *this) >=
1928 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1929 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
1932 case Instruction::Xor:
1933 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1934 // If the RHS of the xor is a signbit, then this is just an add.
1935 // Instcombine turns add of signbit into xor as a strength reduction step.
1936 if (CI->getValue().isSignBit())
1937 return getAddExpr(getSCEV(U->getOperand(0)),
1938 getSCEV(U->getOperand(1)));
1940 // If the RHS of xor is -1, then this is a not operation.
1941 else if (CI->isAllOnesValue())
1942 return getNotSCEV(getSCEV(U->getOperand(0)));
1946 case Instruction::Shl:
1947 // Turn shift left of a constant amount into a multiply.
1948 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1949 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1950 Constant *X = ConstantInt::get(
1951 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1952 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1956 case Instruction::LShr:
1957 // Turn logical shift right of a constant into a unsigned divide.
1958 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1959 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1960 Constant *X = ConstantInt::get(
1961 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1962 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1966 case Instruction::AShr:
1967 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1968 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1969 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1970 if (L->getOpcode() == Instruction::Shl &&
1971 L->getOperand(1) == U->getOperand(1)) {
1972 unsigned BitWidth = getTypeSizeInBits(U->getType());
1973 uint64_t Amt = BitWidth - CI->getZExtValue();
1974 if (Amt == BitWidth)
1975 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1977 return getIntegerSCEV(0, U->getType()); // value is undefined
1979 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
1980 IntegerType::get(Amt)),
1985 case Instruction::Trunc:
1986 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1988 case Instruction::ZExt:
1989 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1991 case Instruction::SExt:
1992 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1994 case Instruction::BitCast:
1995 // BitCasts are no-op casts so we just eliminate the cast.
1996 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
1997 return getSCEV(U->getOperand(0));
2000 case Instruction::IntToPtr:
2001 if (!TD) break; // Without TD we can't analyze pointers.
2002 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2003 TD->getIntPtrType());
2005 case Instruction::PtrToInt:
2006 if (!TD) break; // Without TD we can't analyze pointers.
2007 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2010 case Instruction::GetElementPtr: {
2011 if (!TD) break; // Without TD we can't analyze pointers.
2012 const Type *IntPtrTy = TD->getIntPtrType();
2013 Value *Base = U->getOperand(0);
2014 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
2015 gep_type_iterator GTI = gep_type_begin(U);
2016 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2020 // Compute the (potentially symbolic) offset in bytes for this index.
2021 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2022 // For a struct, add the member offset.
2023 const StructLayout &SL = *TD->getStructLayout(STy);
2024 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2025 uint64_t Offset = SL.getElementOffset(FieldNo);
2026 TotalOffset = getAddExpr(TotalOffset,
2027 getIntegerSCEV(Offset, IntPtrTy));
2029 // For an array, add the element offset, explicitly scaled.
2030 SCEVHandle LocalOffset = getSCEV(Index);
2031 if (!isa<PointerType>(LocalOffset->getType()))
2032 // Getelementptr indicies are signed.
2033 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2036 getMulExpr(LocalOffset,
2037 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2039 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2042 return getAddExpr(getSCEV(Base), TotalOffset);
2045 case Instruction::PHI:
2046 return createNodeForPHI(cast<PHINode>(U));
2048 case Instruction::Select:
2049 // This could be a smax or umax that was lowered earlier.
2050 // Try to recover it.
2051 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2052 Value *LHS = ICI->getOperand(0);
2053 Value *RHS = ICI->getOperand(1);
2054 switch (ICI->getPredicate()) {
2055 case ICmpInst::ICMP_SLT:
2056 case ICmpInst::ICMP_SLE:
2057 std::swap(LHS, RHS);
2059 case ICmpInst::ICMP_SGT:
2060 case ICmpInst::ICMP_SGE:
2061 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2062 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2063 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2064 // ~smax(~x, ~y) == smin(x, y).
2065 return getNotSCEV(getSMaxExpr(
2066 getNotSCEV(getSCEV(LHS)),
2067 getNotSCEV(getSCEV(RHS))));
2069 case ICmpInst::ICMP_ULT:
2070 case ICmpInst::ICMP_ULE:
2071 std::swap(LHS, RHS);
2073 case ICmpInst::ICMP_UGT:
2074 case ICmpInst::ICMP_UGE:
2075 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2076 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2077 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2078 // ~umax(~x, ~y) == umin(x, y)
2079 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2080 getNotSCEV(getSCEV(RHS))));
2087 default: // We cannot analyze this expression.
2091 return getUnknown(V);
2096 //===----------------------------------------------------------------------===//
2097 // Iteration Count Computation Code
2100 /// getBackedgeTakenCount - If the specified loop has a predictable
2101 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2102 /// object. The backedge-taken count is the number of times the loop header
2103 /// will be branched to from within the loop. This is one less than the
2104 /// trip count of the loop, since it doesn't count the first iteration,
2105 /// when the header is branched to from outside the loop.
2107 /// Note that it is not valid to call this method on a loop without a
2108 /// loop-invariant backedge-taken count (see
2109 /// hasLoopInvariantBackedgeTakenCount).
2111 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2112 return getBackedgeTakenInfo(L).Exact;
2115 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2116 /// return the least SCEV value that is known never to be less than the
2117 /// actual backedge taken count.
2118 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2119 return getBackedgeTakenInfo(L).Max;
2122 const ScalarEvolution::BackedgeTakenInfo &
2123 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2124 // Initially insert a CouldNotCompute for this loop. If the insertion
2125 // succeeds, procede to actually compute a backedge-taken count and
2126 // update the value. The temporary CouldNotCompute value tells SCEV
2127 // code elsewhere that it shouldn't attempt to request a new
2128 // backedge-taken count, which could result in infinite recursion.
2129 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2130 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2132 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2133 if (ItCount.Exact != UnknownValue) {
2134 assert(ItCount.Exact->isLoopInvariant(L) &&
2135 ItCount.Max->isLoopInvariant(L) &&
2136 "Computed trip count isn't loop invariant for loop!");
2137 ++NumTripCountsComputed;
2139 // Update the value in the map.
2140 Pair.first->second = ItCount;
2141 } else if (isa<PHINode>(L->getHeader()->begin())) {
2142 // Only count loops that have phi nodes as not being computable.
2143 ++NumTripCountsNotComputed;
2146 // Now that we know more about the trip count for this loop, forget any
2147 // existing SCEV values for PHI nodes in this loop since they are only
2148 // conservative estimates made without the benefit
2149 // of trip count information.
2150 if (ItCount.hasAnyInfo())
2153 return Pair.first->second;
2156 /// forgetLoopBackedgeTakenCount - This method should be called by the
2157 /// client when it has changed a loop in a way that may effect
2158 /// ScalarEvolution's ability to compute a trip count, or if the loop
2160 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2161 BackedgeTakenCounts.erase(L);
2165 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2166 /// PHI nodes in the given loop. This is used when the trip count of
2167 /// the loop may have changed.
2168 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2169 BasicBlock *Header = L->getHeader();
2171 SmallVector<Instruction *, 16> Worklist;
2172 for (BasicBlock::iterator I = Header->begin();
2173 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2174 Worklist.push_back(PN);
2176 while (!Worklist.empty()) {
2177 Instruction *I = Worklist.pop_back_val();
2178 if (Scalars.erase(I))
2179 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2181 Worklist.push_back(cast<Instruction>(UI));
2185 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2186 /// of the specified loop will execute.
2187 ScalarEvolution::BackedgeTakenInfo
2188 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2189 // If the loop has a non-one exit block count, we can't analyze it.
2190 SmallVector<BasicBlock*, 8> ExitBlocks;
2191 L->getExitBlocks(ExitBlocks);
2192 if (ExitBlocks.size() != 1) return UnknownValue;
2194 // Okay, there is one exit block. Try to find the condition that causes the
2195 // loop to be exited.
2196 BasicBlock *ExitBlock = ExitBlocks[0];
2198 BasicBlock *ExitingBlock = 0;
2199 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2201 if (L->contains(*PI)) {
2202 if (ExitingBlock == 0)
2205 return UnknownValue; // More than one block exiting!
2207 assert(ExitingBlock && "No exits from loop, something is broken!");
2209 // Okay, we've computed the exiting block. See what condition causes us to
2212 // FIXME: we should be able to handle switch instructions (with a single exit)
2213 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2214 if (ExitBr == 0) return UnknownValue;
2215 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2217 // At this point, we know we have a conditional branch that determines whether
2218 // the loop is exited. However, we don't know if the branch is executed each
2219 // time through the loop. If not, then the execution count of the branch will
2220 // not be equal to the trip count of the loop.
2222 // Currently we check for this by checking to see if the Exit branch goes to
2223 // the loop header. If so, we know it will always execute the same number of
2224 // times as the loop. We also handle the case where the exit block *is* the
2225 // loop header. This is common for un-rotated loops. More extensive analysis
2226 // could be done to handle more cases here.
2227 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2228 ExitBr->getSuccessor(1) != L->getHeader() &&
2229 ExitBr->getParent() != L->getHeader())
2230 return UnknownValue;
2232 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2234 // If it's not an integer comparison then compute it the hard way.
2235 // Note that ICmpInst deals with pointer comparisons too so we must check
2236 // the type of the operand.
2237 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2238 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2239 ExitBr->getSuccessor(0) == ExitBlock);
2241 // If the condition was exit on true, convert the condition to exit on false
2242 ICmpInst::Predicate Cond;
2243 if (ExitBr->getSuccessor(1) == ExitBlock)
2244 Cond = ExitCond->getPredicate();
2246 Cond = ExitCond->getInversePredicate();
2248 // Handle common loops like: for (X = "string"; *X; ++X)
2249 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2250 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2252 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2253 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2256 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2257 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2259 // Try to evaluate any dependencies out of the loop.
2260 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2261 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2262 Tmp = getSCEVAtScope(RHS, L);
2263 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2265 // At this point, we would like to compute how many iterations of the
2266 // loop the predicate will return true for these inputs.
2267 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2268 // If there is a loop-invariant, force it into the RHS.
2269 std::swap(LHS, RHS);
2270 Cond = ICmpInst::getSwappedPredicate(Cond);
2273 // If we have a comparison of a chrec against a constant, try to use value
2274 // ranges to answer this query.
2275 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2276 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2277 if (AddRec->getLoop() == L) {
2278 // Form the comparison range using the constant of the correct type so
2279 // that the ConstantRange class knows to do a signed or unsigned
2281 ConstantInt *CompVal = RHSC->getValue();
2282 const Type *RealTy = ExitCond->getOperand(0)->getType();
2283 CompVal = dyn_cast<ConstantInt>(
2284 ConstantExpr::getBitCast(CompVal, RealTy));
2286 // Form the constant range.
2287 ConstantRange CompRange(
2288 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2290 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2291 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2296 case ICmpInst::ICMP_NE: { // while (X != Y)
2297 // Convert to: while (X-Y != 0)
2298 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2299 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2302 case ICmpInst::ICMP_EQ: {
2303 // Convert to: while (X-Y == 0) // while (X == Y)
2304 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2305 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2308 case ICmpInst::ICMP_SLT: {
2309 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2310 if (BTI.hasAnyInfo()) return BTI;
2313 case ICmpInst::ICMP_SGT: {
2314 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2315 getNotSCEV(RHS), L, true);
2316 if (BTI.hasAnyInfo()) return BTI;
2319 case ICmpInst::ICMP_ULT: {
2320 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2321 if (BTI.hasAnyInfo()) return BTI;
2324 case ICmpInst::ICMP_UGT: {
2325 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2326 getNotSCEV(RHS), L, false);
2327 if (BTI.hasAnyInfo()) return BTI;
2332 errs() << "ComputeBackedgeTakenCount ";
2333 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2334 errs() << "[unsigned] ";
2335 errs() << *LHS << " "
2336 << Instruction::getOpcodeName(Instruction::ICmp)
2337 << " " << *RHS << "\n";
2342 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2343 ExitBr->getSuccessor(0) == ExitBlock);
2346 static ConstantInt *
2347 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2348 ScalarEvolution &SE) {
2349 SCEVHandle InVal = SE.getConstant(C);
2350 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2351 assert(isa<SCEVConstant>(Val) &&
2352 "Evaluation of SCEV at constant didn't fold correctly?");
2353 return cast<SCEVConstant>(Val)->getValue();
2356 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2357 /// and a GEP expression (missing the pointer index) indexing into it, return
2358 /// the addressed element of the initializer or null if the index expression is
2361 GetAddressedElementFromGlobal(GlobalVariable *GV,
2362 const std::vector<ConstantInt*> &Indices) {
2363 Constant *Init = GV->getInitializer();
2364 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2365 uint64_t Idx = Indices[i]->getZExtValue();
2366 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2367 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2368 Init = cast<Constant>(CS->getOperand(Idx));
2369 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2370 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2371 Init = cast<Constant>(CA->getOperand(Idx));
2372 } else if (isa<ConstantAggregateZero>(Init)) {
2373 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2374 assert(Idx < STy->getNumElements() && "Bad struct index!");
2375 Init = Constant::getNullValue(STy->getElementType(Idx));
2376 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2377 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2378 Init = Constant::getNullValue(ATy->getElementType());
2380 assert(0 && "Unknown constant aggregate type!");
2384 return 0; // Unknown initializer type
2390 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2391 /// 'icmp op load X, cst', try to see if we can compute the backedge
2392 /// execution count.
2393 SCEVHandle ScalarEvolution::
2394 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2396 ICmpInst::Predicate predicate) {
2397 if (LI->isVolatile()) return UnknownValue;
2399 // Check to see if the loaded pointer is a getelementptr of a global.
2400 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2401 if (!GEP) return UnknownValue;
2403 // Make sure that it is really a constant global we are gepping, with an
2404 // initializer, and make sure the first IDX is really 0.
2405 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2406 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2407 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2408 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2409 return UnknownValue;
2411 // Okay, we allow one non-constant index into the GEP instruction.
2413 std::vector<ConstantInt*> Indexes;
2414 unsigned VarIdxNum = 0;
2415 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2416 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2417 Indexes.push_back(CI);
2418 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2419 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2420 VarIdx = GEP->getOperand(i);
2422 Indexes.push_back(0);
2425 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2426 // Check to see if X is a loop variant variable value now.
2427 SCEVHandle Idx = getSCEV(VarIdx);
2428 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2429 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2431 // We can only recognize very limited forms of loop index expressions, in
2432 // particular, only affine AddRec's like {C1,+,C2}.
2433 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2434 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2435 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2436 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2437 return UnknownValue;
2439 unsigned MaxSteps = MaxBruteForceIterations;
2440 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2441 ConstantInt *ItCst =
2442 ConstantInt::get(IdxExpr->getType(), IterationNum);
2443 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2445 // Form the GEP offset.
2446 Indexes[VarIdxNum] = Val;
2448 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2449 if (Result == 0) break; // Cannot compute!
2451 // Evaluate the condition for this iteration.
2452 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2453 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2454 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2456 errs() << "\n***\n*** Computed loop count " << *ItCst
2457 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2460 ++NumArrayLenItCounts;
2461 return getConstant(ItCst); // Found terminating iteration!
2464 return UnknownValue;
2468 /// CanConstantFold - Return true if we can constant fold an instruction of the
2469 /// specified type, assuming that all operands were constants.
2470 static bool CanConstantFold(const Instruction *I) {
2471 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2472 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2475 if (const CallInst *CI = dyn_cast<CallInst>(I))
2476 if (const Function *F = CI->getCalledFunction())
2477 return canConstantFoldCallTo(F);
2481 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2482 /// in the loop that V is derived from. We allow arbitrary operations along the
2483 /// way, but the operands of an operation must either be constants or a value
2484 /// derived from a constant PHI. If this expression does not fit with these
2485 /// constraints, return null.
2486 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2487 // If this is not an instruction, or if this is an instruction outside of the
2488 // loop, it can't be derived from a loop PHI.
2489 Instruction *I = dyn_cast<Instruction>(V);
2490 if (I == 0 || !L->contains(I->getParent())) return 0;
2492 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2493 if (L->getHeader() == I->getParent())
2496 // We don't currently keep track of the control flow needed to evaluate
2497 // PHIs, so we cannot handle PHIs inside of loops.
2501 // If we won't be able to constant fold this expression even if the operands
2502 // are constants, return early.
2503 if (!CanConstantFold(I)) return 0;
2505 // Otherwise, we can evaluate this instruction if all of its operands are
2506 // constant or derived from a PHI node themselves.
2508 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2509 if (!(isa<Constant>(I->getOperand(Op)) ||
2510 isa<GlobalValue>(I->getOperand(Op)))) {
2511 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2512 if (P == 0) return 0; // Not evolving from PHI
2516 return 0; // Evolving from multiple different PHIs.
2519 // This is a expression evolving from a constant PHI!
2523 /// EvaluateExpression - Given an expression that passes the
2524 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2525 /// in the loop has the value PHIVal. If we can't fold this expression for some
2526 /// reason, return null.
2527 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2528 if (isa<PHINode>(V)) return PHIVal;
2529 if (Constant *C = dyn_cast<Constant>(V)) return C;
2530 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2531 Instruction *I = cast<Instruction>(V);
2533 std::vector<Constant*> Operands;
2534 Operands.resize(I->getNumOperands());
2536 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2537 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2538 if (Operands[i] == 0) return 0;
2541 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2542 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2543 &Operands[0], Operands.size());
2545 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2546 &Operands[0], Operands.size());
2549 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2550 /// in the header of its containing loop, we know the loop executes a
2551 /// constant number of times, and the PHI node is just a recurrence
2552 /// involving constants, fold it.
2553 Constant *ScalarEvolution::
2554 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2555 std::map<PHINode*, Constant*>::iterator I =
2556 ConstantEvolutionLoopExitValue.find(PN);
2557 if (I != ConstantEvolutionLoopExitValue.end())
2560 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2561 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2563 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2565 // Since the loop is canonicalized, the PHI node must have two entries. One
2566 // entry must be a constant (coming in from outside of the loop), and the
2567 // second must be derived from the same PHI.
2568 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2569 Constant *StartCST =
2570 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2572 return RetVal = 0; // Must be a constant.
2574 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2575 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2577 return RetVal = 0; // Not derived from same PHI.
2579 // Execute the loop symbolically to determine the exit value.
2580 if (BEs.getActiveBits() >= 32)
2581 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2583 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2584 unsigned IterationNum = 0;
2585 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2586 if (IterationNum == NumIterations)
2587 return RetVal = PHIVal; // Got exit value!
2589 // Compute the value of the PHI node for the next iteration.
2590 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2591 if (NextPHI == PHIVal)
2592 return RetVal = NextPHI; // Stopped evolving!
2594 return 0; // Couldn't evaluate!
2599 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2600 /// constant number of times (the condition evolves only from constants),
2601 /// try to evaluate a few iterations of the loop until we get the exit
2602 /// condition gets a value of ExitWhen (true or false). If we cannot
2603 /// evaluate the trip count of the loop, return UnknownValue.
2604 SCEVHandle ScalarEvolution::
2605 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2606 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2607 if (PN == 0) return UnknownValue;
2609 // Since the loop is canonicalized, the PHI node must have two entries. One
2610 // entry must be a constant (coming in from outside of the loop), and the
2611 // second must be derived from the same PHI.
2612 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2613 Constant *StartCST =
2614 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2615 if (StartCST == 0) return UnknownValue; // Must be a constant.
2617 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2618 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2619 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2621 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2622 // the loop symbolically to determine when the condition gets a value of
2624 unsigned IterationNum = 0;
2625 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2626 for (Constant *PHIVal = StartCST;
2627 IterationNum != MaxIterations; ++IterationNum) {
2628 ConstantInt *CondVal =
2629 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2631 // Couldn't symbolically evaluate.
2632 if (!CondVal) return UnknownValue;
2634 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2635 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2636 ++NumBruteForceTripCountsComputed;
2637 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2640 // Compute the value of the PHI node for the next iteration.
2641 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2642 if (NextPHI == 0 || NextPHI == PHIVal)
2643 return UnknownValue; // Couldn't evaluate or not making progress...
2647 // Too many iterations were needed to evaluate.
2648 return UnknownValue;
2651 /// getSCEVAtScope - Compute the value of the specified expression within the
2652 /// indicated loop (which may be null to indicate in no loop). If the
2653 /// expression cannot be evaluated, return UnknownValue.
2654 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
2655 // FIXME: this should be turned into a virtual method on SCEV!
2657 if (isa<SCEVConstant>(V)) return V;
2659 // If this instruction is evolved from a constant-evolving PHI, compute the
2660 // exit value from the loop without using SCEVs.
2661 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2662 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2663 const Loop *LI = (*this->LI)[I->getParent()];
2664 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2665 if (PHINode *PN = dyn_cast<PHINode>(I))
2666 if (PN->getParent() == LI->getHeader()) {
2667 // Okay, there is no closed form solution for the PHI node. Check
2668 // to see if the loop that contains it has a known backedge-taken
2669 // count. If so, we may be able to force computation of the exit
2671 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2672 if (const SCEVConstant *BTCC =
2673 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2674 // Okay, we know how many times the containing loop executes. If
2675 // this is a constant evolving PHI node, get the final value at
2676 // the specified iteration number.
2677 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2678 BTCC->getValue()->getValue(),
2680 if (RV) return getUnknown(RV);
2684 // Okay, this is an expression that we cannot symbolically evaluate
2685 // into a SCEV. Check to see if it's possible to symbolically evaluate
2686 // the arguments into constants, and if so, try to constant propagate the
2687 // result. This is particularly useful for computing loop exit values.
2688 if (CanConstantFold(I)) {
2689 std::vector<Constant*> Operands;
2690 Operands.reserve(I->getNumOperands());
2691 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2692 Value *Op = I->getOperand(i);
2693 if (Constant *C = dyn_cast<Constant>(Op)) {
2694 Operands.push_back(C);
2696 // If any of the operands is non-constant and if they are
2697 // non-integer and non-pointer, don't even try to analyze them
2698 // with scev techniques.
2699 if (!isSCEVable(Op->getType()))
2702 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2703 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2704 Constant *C = SC->getValue();
2705 if (C->getType() != Op->getType())
2706 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2710 Operands.push_back(C);
2711 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2712 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2713 if (C->getType() != Op->getType())
2715 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2719 Operands.push_back(C);
2729 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2730 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2731 &Operands[0], Operands.size());
2733 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2734 &Operands[0], Operands.size());
2735 return getUnknown(C);
2739 // This is some other type of SCEVUnknown, just return it.
2743 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2744 // Avoid performing the look-up in the common case where the specified
2745 // expression has no loop-variant portions.
2746 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2747 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2748 if (OpAtScope != Comm->getOperand(i)) {
2749 if (OpAtScope == UnknownValue) return UnknownValue;
2750 // Okay, at least one of these operands is loop variant but might be
2751 // foldable. Build a new instance of the folded commutative expression.
2752 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2753 NewOps.push_back(OpAtScope);
2755 for (++i; i != e; ++i) {
2756 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2757 if (OpAtScope == UnknownValue) return UnknownValue;
2758 NewOps.push_back(OpAtScope);
2760 if (isa<SCEVAddExpr>(Comm))
2761 return getAddExpr(NewOps);
2762 if (isa<SCEVMulExpr>(Comm))
2763 return getMulExpr(NewOps);
2764 if (isa<SCEVSMaxExpr>(Comm))
2765 return getSMaxExpr(NewOps);
2766 if (isa<SCEVUMaxExpr>(Comm))
2767 return getUMaxExpr(NewOps);
2768 assert(0 && "Unknown commutative SCEV type!");
2771 // If we got here, all operands are loop invariant.
2775 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2776 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2777 if (LHS == UnknownValue) return LHS;
2778 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2779 if (RHS == UnknownValue) return RHS;
2780 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2781 return Div; // must be loop invariant
2782 return getUDivExpr(LHS, RHS);
2785 // If this is a loop recurrence for a loop that does not contain L, then we
2786 // are dealing with the final value computed by the loop.
2787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2788 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2789 // To evaluate this recurrence, we need to know how many times the AddRec
2790 // loop iterates. Compute this now.
2791 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2792 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2794 // Then, evaluate the AddRec.
2795 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
2797 return UnknownValue;
2800 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2801 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2802 if (Op == UnknownValue) return Op;
2803 if (Op == Cast->getOperand())
2804 return Cast; // must be loop invariant
2805 return getZeroExtendExpr(Op, Cast->getType());
2808 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2809 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2810 if (Op == UnknownValue) return Op;
2811 if (Op == Cast->getOperand())
2812 return Cast; // must be loop invariant
2813 return getSignExtendExpr(Op, Cast->getType());
2816 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2817 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2818 if (Op == UnknownValue) return Op;
2819 if (Op == Cast->getOperand())
2820 return Cast; // must be loop invariant
2821 return getTruncateExpr(Op, Cast->getType());
2824 assert(0 && "Unknown SCEV type!");
2827 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
2828 /// at the specified scope in the program. The L value specifies a loop
2829 /// nest to evaluate the expression at, where null is the top-level or a
2830 /// specified loop is immediately inside of the loop.
2832 /// This method can be used to compute the exit value for a variable defined
2833 /// in a loop by querying what the value will hold in the parent loop.
2835 /// If this value is not computable at this scope, a SCEVCouldNotCompute
2836 /// object is returned.
2837 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2838 return getSCEVAtScope(getSCEV(V), L);
2841 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2842 /// following equation:
2844 /// A * X = B (mod N)
2846 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2847 /// A and B isn't important.
2849 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2850 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2851 ScalarEvolution &SE) {
2852 uint32_t BW = A.getBitWidth();
2853 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2854 assert(A != 0 && "A must be non-zero.");
2858 // The gcd of A and N may have only one prime factor: 2. The number of
2859 // trailing zeros in A is its multiplicity
2860 uint32_t Mult2 = A.countTrailingZeros();
2863 // 2. Check if B is divisible by D.
2865 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2866 // is not less than multiplicity of this prime factor for D.
2867 if (B.countTrailingZeros() < Mult2)
2868 return SE.getCouldNotCompute();
2870 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2873 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2874 // bit width during computations.
2875 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2876 APInt Mod(BW + 1, 0);
2877 Mod.set(BW - Mult2); // Mod = N / D
2878 APInt I = AD.multiplicativeInverse(Mod);
2880 // 4. Compute the minimum unsigned root of the equation:
2881 // I * (B / D) mod (N / D)
2882 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2884 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2886 return SE.getConstant(Result.trunc(BW));
2889 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2890 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2891 /// might be the same) or two SCEVCouldNotCompute objects.
2893 static std::pair<SCEVHandle,SCEVHandle>
2894 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2895 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2896 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2897 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2898 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2900 // We currently can only solve this if the coefficients are constants.
2901 if (!LC || !MC || !NC) {
2902 const SCEV *CNC = SE.getCouldNotCompute();
2903 return std::make_pair(CNC, CNC);
2906 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2907 const APInt &L = LC->getValue()->getValue();
2908 const APInt &M = MC->getValue()->getValue();
2909 const APInt &N = NC->getValue()->getValue();
2910 APInt Two(BitWidth, 2);
2911 APInt Four(BitWidth, 4);
2914 using namespace APIntOps;
2916 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2917 // The B coefficient is M-N/2
2921 // The A coefficient is N/2
2922 APInt A(N.sdiv(Two));
2924 // Compute the B^2-4ac term.
2927 SqrtTerm -= Four * (A * C);
2929 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2930 // integer value or else APInt::sqrt() will assert.
2931 APInt SqrtVal(SqrtTerm.sqrt());
2933 // Compute the two solutions for the quadratic formula.
2934 // The divisions must be performed as signed divisions.
2936 APInt TwoA( A << 1 );
2937 if (TwoA.isMinValue()) {
2938 const SCEV *CNC = SE.getCouldNotCompute();
2939 return std::make_pair(CNC, CNC);
2942 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2943 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2945 return std::make_pair(SE.getConstant(Solution1),
2946 SE.getConstant(Solution2));
2947 } // end APIntOps namespace
2950 /// HowFarToZero - Return the number of times a backedge comparing the specified
2951 /// value to zero will execute. If not computable, return UnknownValue
2952 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
2953 // If the value is a constant
2954 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2955 // If the value is already zero, the branch will execute zero times.
2956 if (C->getValue()->isZero()) return C;
2957 return UnknownValue; // Otherwise it will loop infinitely.
2960 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2961 if (!AddRec || AddRec->getLoop() != L)
2962 return UnknownValue;
2964 if (AddRec->isAffine()) {
2965 // If this is an affine expression, the execution count of this branch is
2966 // the minimum unsigned root of the following equation:
2968 // Start + Step*N = 0 (mod 2^BW)
2972 // Step*N = -Start (mod 2^BW)
2974 // where BW is the common bit width of Start and Step.
2976 // Get the initial value for the loop.
2977 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2978 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2980 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2982 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2983 // For now we handle only constant steps.
2985 // First, handle unitary steps.
2986 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2987 return getNegativeSCEV(Start); // N = -Start (as unsigned)
2988 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2989 return Start; // N = Start (as unsigned)
2991 // Then, try to solve the above equation provided that Start is constant.
2992 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2993 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2994 -StartC->getValue()->getValue(),
2997 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2998 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2999 // the quadratic equation to solve it.
3000 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3002 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3003 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3006 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3007 << " sol#2: " << *R2 << "\n";
3009 // Pick the smallest positive root value.
3010 if (ConstantInt *CB =
3011 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3012 R1->getValue(), R2->getValue()))) {
3013 if (CB->getZExtValue() == false)
3014 std::swap(R1, R2); // R1 is the minimum root now.
3016 // We can only use this value if the chrec ends up with an exact zero
3017 // value at this index. When solving for "X*X != 5", for example, we
3018 // should not accept a root of 2.
3019 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3021 return R1; // We found a quadratic root!
3026 return UnknownValue;
3029 /// HowFarToNonZero - Return the number of times a backedge checking the
3030 /// specified value for nonzero will execute. If not computable, return
3032 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3033 // Loops that look like: while (X == 0) are very strange indeed. We don't
3034 // handle them yet except for the trivial case. This could be expanded in the
3035 // future as needed.
3037 // If the value is a constant, check to see if it is known to be non-zero
3038 // already. If so, the backedge will execute zero times.
3039 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3040 if (!C->getValue()->isNullValue())
3041 return getIntegerSCEV(0, C->getType());
3042 return UnknownValue; // Otherwise it will loop infinitely.
3045 // We could implement others, but I really doubt anyone writes loops like
3046 // this, and if they did, they would already be constant folded.
3047 return UnknownValue;
3050 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3051 /// (which may not be an immediate predecessor) which has exactly one
3052 /// successor from which BB is reachable, or null if no such block is
3056 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3057 // If the block has a unique predecessor, then there is no path from the
3058 // predecessor to the block that does not go through the direct edge
3059 // from the predecessor to the block.
3060 if (BasicBlock *Pred = BB->getSinglePredecessor())
3063 // A loop's header is defined to be a block that dominates the loop.
3064 // If the loop has a preheader, it must be a block that has exactly
3065 // one successor that can reach BB. This is slightly more strict
3066 // than necessary, but works if critical edges are split.
3067 if (Loop *L = LI->getLoopFor(BB))
3068 return L->getLoopPreheader();
3073 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3074 /// a conditional between LHS and RHS. This is used to help avoid max
3075 /// expressions in loop trip counts.
3076 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3077 ICmpInst::Predicate Pred,
3078 const SCEV *LHS, const SCEV *RHS) {
3079 BasicBlock *Preheader = L->getLoopPreheader();
3080 BasicBlock *PreheaderDest = L->getHeader();
3082 // Starting at the preheader, climb up the predecessor chain, as long as
3083 // there are predecessors that can be found that have unique successors
3084 // leading to the original header.
3086 PreheaderDest = Preheader,
3087 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
3089 BranchInst *LoopEntryPredicate =
3090 dyn_cast<BranchInst>(Preheader->getTerminator());
3091 if (!LoopEntryPredicate ||
3092 LoopEntryPredicate->isUnconditional())
3095 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3098 // Now that we found a conditional branch that dominates the loop, check to
3099 // see if it is the comparison we are looking for.
3100 Value *PreCondLHS = ICI->getOperand(0);
3101 Value *PreCondRHS = ICI->getOperand(1);
3102 ICmpInst::Predicate Cond;
3103 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3104 Cond = ICI->getPredicate();
3106 Cond = ICI->getInversePredicate();
3109 ; // An exact match.
3110 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3111 ; // The actual condition is beyond sufficient.
3113 // Check a few special cases.
3115 case ICmpInst::ICMP_UGT:
3116 if (Pred == ICmpInst::ICMP_ULT) {
3117 std::swap(PreCondLHS, PreCondRHS);
3118 Cond = ICmpInst::ICMP_ULT;
3122 case ICmpInst::ICMP_SGT:
3123 if (Pred == ICmpInst::ICMP_SLT) {
3124 std::swap(PreCondLHS, PreCondRHS);
3125 Cond = ICmpInst::ICMP_SLT;
3129 case ICmpInst::ICMP_NE:
3130 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3131 // so check for this case by checking if the NE is comparing against
3132 // a minimum or maximum constant.
3133 if (!ICmpInst::isTrueWhenEqual(Pred))
3134 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3135 const APInt &A = CI->getValue();
3137 case ICmpInst::ICMP_SLT:
3138 if (A.isMaxSignedValue()) break;
3140 case ICmpInst::ICMP_SGT:
3141 if (A.isMinSignedValue()) break;
3143 case ICmpInst::ICMP_ULT:
3144 if (A.isMaxValue()) break;
3146 case ICmpInst::ICMP_UGT:
3147 if (A.isMinValue()) break;
3152 Cond = ICmpInst::ICMP_NE;
3153 // NE is symmetric but the original comparison may not be. Swap
3154 // the operands if necessary so that they match below.
3155 if (isa<SCEVConstant>(LHS))
3156 std::swap(PreCondLHS, PreCondRHS);
3161 // We weren't able to reconcile the condition.
3165 if (!PreCondLHS->getType()->isInteger()) continue;
3167 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3168 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3169 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3170 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3171 RHS == getNotSCEV(PreCondLHSSCEV)))
3178 /// HowManyLessThans - Return the number of times a backedge containing the
3179 /// specified less-than comparison will execute. If not computable, return
3181 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
3182 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3183 const Loop *L, bool isSigned) {
3184 // Only handle: "ADDREC < LoopInvariant".
3185 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3187 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3188 if (!AddRec || AddRec->getLoop() != L)
3189 return UnknownValue;
3191 if (AddRec->isAffine()) {
3192 // FORNOW: We only support unit strides.
3193 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3194 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3195 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3197 // TODO: handle non-constant strides.
3198 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3199 if (!CStep || CStep->isZero())
3200 return UnknownValue;
3201 if (CStep->getValue()->getValue() == 1) {
3202 // With unit stride, the iteration never steps past the limit value.
3203 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3204 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3205 // Test whether a positive iteration iteration can step past the limit
3206 // value and past the maximum value for its type in a single step.
3208 APInt Max = APInt::getSignedMaxValue(BitWidth);
3209 if ((Max - CStep->getValue()->getValue())
3210 .slt(CLimit->getValue()->getValue()))
3211 return UnknownValue;
3213 APInt Max = APInt::getMaxValue(BitWidth);
3214 if ((Max - CStep->getValue()->getValue())
3215 .ult(CLimit->getValue()->getValue()))
3216 return UnknownValue;
3219 // TODO: handle non-constant limit values below.
3220 return UnknownValue;
3222 // TODO: handle negative strides below.
3223 return UnknownValue;
3225 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3226 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3227 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
3228 // treat m-n as signed nor unsigned due to overflow possibility.
3230 // First, we get the value of the LHS in the first iteration: n
3231 SCEVHandle Start = AddRec->getOperand(0);
3233 // Determine the minimum constant start value.
3234 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3235 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3236 APInt::getMinValue(BitWidth));
3238 // If we know that the condition is true in order to enter the loop,
3239 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3240 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3241 // division must round up.
3242 SCEVHandle End = RHS;
3243 if (!isLoopGuardedByCond(L,
3244 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3245 getMinusSCEV(Start, Step), RHS))
3246 End = isSigned ? getSMaxExpr(RHS, Start)
3247 : getUMaxExpr(RHS, Start);
3249 // Determine the maximum constant end value.
3250 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3251 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3252 APInt::getMaxValue(BitWidth));
3254 // Finally, we subtract these two values and divide, rounding up, to get
3255 // the number of times the backedge is executed.
3256 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3257 getAddExpr(Step, NegOne)),
3260 // The maximum backedge count is similar, except using the minimum start
3261 // value and the maximum end value.
3262 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3264 getAddExpr(Step, NegOne)),
3267 return BackedgeTakenInfo(BECount, MaxBECount);
3270 return UnknownValue;
3273 /// getNumIterationsInRange - Return the number of iterations of this loop that
3274 /// produce values in the specified constant range. Another way of looking at
3275 /// this is that it returns the first iteration number where the value is not in
3276 /// the condition, thus computing the exit count. If the iteration count can't
3277 /// be computed, an instance of SCEVCouldNotCompute is returned.
3278 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3279 ScalarEvolution &SE) const {
3280 if (Range.isFullSet()) // Infinite loop.
3281 return SE.getCouldNotCompute();
3283 // If the start is a non-zero constant, shift the range to simplify things.
3284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3285 if (!SC->getValue()->isZero()) {
3286 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3287 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3288 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3289 if (const SCEVAddRecExpr *ShiftedAddRec =
3290 dyn_cast<SCEVAddRecExpr>(Shifted))
3291 return ShiftedAddRec->getNumIterationsInRange(
3292 Range.subtract(SC->getValue()->getValue()), SE);
3293 // This is strange and shouldn't happen.
3294 return SE.getCouldNotCompute();
3297 // The only time we can solve this is when we have all constant indices.
3298 // Otherwise, we cannot determine the overflow conditions.
3299 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3300 if (!isa<SCEVConstant>(getOperand(i)))
3301 return SE.getCouldNotCompute();
3304 // Okay at this point we know that all elements of the chrec are constants and
3305 // that the start element is zero.
3307 // First check to see if the range contains zero. If not, the first
3309 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3310 if (!Range.contains(APInt(BitWidth, 0)))
3311 return SE.getConstant(ConstantInt::get(getType(),0));
3314 // If this is an affine expression then we have this situation:
3315 // Solve {0,+,A} in Range === Ax in Range
3317 // We know that zero is in the range. If A is positive then we know that
3318 // the upper value of the range must be the first possible exit value.
3319 // If A is negative then the lower of the range is the last possible loop
3320 // value. Also note that we already checked for a full range.
3321 APInt One(BitWidth,1);
3322 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3323 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3325 // The exit value should be (End+A)/A.
3326 APInt ExitVal = (End + A).udiv(A);
3327 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3329 // Evaluate at the exit value. If we really did fall out of the valid
3330 // range, then we computed our trip count, otherwise wrap around or other
3331 // things must have happened.
3332 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3333 if (Range.contains(Val->getValue()))
3334 return SE.getCouldNotCompute(); // Something strange happened
3336 // Ensure that the previous value is in the range. This is a sanity check.
3337 assert(Range.contains(
3338 EvaluateConstantChrecAtConstant(this,
3339 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3340 "Linear scev computation is off in a bad way!");
3341 return SE.getConstant(ExitValue);
3342 } else if (isQuadratic()) {
3343 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3344 // quadratic equation to solve it. To do this, we must frame our problem in
3345 // terms of figuring out when zero is crossed, instead of when
3346 // Range.getUpper() is crossed.
3347 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3348 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3349 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3351 // Next, solve the constructed addrec
3352 std::pair<SCEVHandle,SCEVHandle> Roots =
3353 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3354 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3355 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3357 // Pick the smallest positive root value.
3358 if (ConstantInt *CB =
3359 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3360 R1->getValue(), R2->getValue()))) {
3361 if (CB->getZExtValue() == false)
3362 std::swap(R1, R2); // R1 is the minimum root now.
3364 // Make sure the root is not off by one. The returned iteration should
3365 // not be in the range, but the previous one should be. When solving
3366 // for "X*X < 5", for example, we should not return a root of 2.
3367 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3370 if (Range.contains(R1Val->getValue())) {
3371 // The next iteration must be out of the range...
3372 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3374 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3375 if (!Range.contains(R1Val->getValue()))
3376 return SE.getConstant(NextVal);
3377 return SE.getCouldNotCompute(); // Something strange happened
3380 // If R1 was not in the range, then it is a good return value. Make
3381 // sure that R1-1 WAS in the range though, just in case.
3382 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3383 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3384 if (Range.contains(R1Val->getValue()))
3386 return SE.getCouldNotCompute(); // Something strange happened
3391 return SE.getCouldNotCompute();
3396 //===----------------------------------------------------------------------===//
3397 // SCEVCallbackVH Class Implementation
3398 //===----------------------------------------------------------------------===//
3400 void SCEVCallbackVH::deleted() {
3401 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3402 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3403 SE->ConstantEvolutionLoopExitValue.erase(PN);
3404 SE->Scalars.erase(getValPtr());
3405 // this now dangles!
3408 void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3409 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3411 // Forget all the expressions associated with users of the old value,
3412 // so that future queries will recompute the expressions using the new
3414 SmallVector<User *, 16> Worklist;
3415 Value *Old = getValPtr();
3416 bool DeleteOld = false;
3417 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3419 Worklist.push_back(*UI);
3420 while (!Worklist.empty()) {
3421 User *U = Worklist.pop_back_val();
3422 // Deleting the Old value will cause this to dangle. Postpone
3423 // that until everything else is done.
3428 if (PHINode *PN = dyn_cast<PHINode>(U))
3429 SE->ConstantEvolutionLoopExitValue.erase(PN);
3430 if (SE->Scalars.erase(U))
3431 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3433 Worklist.push_back(*UI);
3436 if (PHINode *PN = dyn_cast<PHINode>(Old))
3437 SE->ConstantEvolutionLoopExitValue.erase(PN);
3438 SE->Scalars.erase(Old);
3439 // this now dangles!
3444 SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3445 : CallbackVH(V), SE(se) {}
3447 //===----------------------------------------------------------------------===//
3448 // ScalarEvolution Class Implementation
3449 //===----------------------------------------------------------------------===//
3451 ScalarEvolution::ScalarEvolution()
3452 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3455 bool ScalarEvolution::runOnFunction(Function &F) {
3457 LI = &getAnalysis<LoopInfo>();
3458 TD = getAnalysisIfAvailable<TargetData>();
3462 void ScalarEvolution::releaseMemory() {
3464 BackedgeTakenCounts.clear();
3465 ConstantEvolutionLoopExitValue.clear();
3468 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3469 AU.setPreservesAll();
3470 AU.addRequiredTransitive<LoopInfo>();
3473 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3474 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3477 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3479 // Print all inner loops first
3480 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3481 PrintLoopInfo(OS, SE, *I);
3483 OS << "Loop " << L->getHeader()->getName() << ": ";
3485 SmallVector<BasicBlock*, 8> ExitBlocks;
3486 L->getExitBlocks(ExitBlocks);
3487 if (ExitBlocks.size() != 1)
3488 OS << "<multiple exits> ";
3490 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3491 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3493 OS << "Unpredictable backedge-taken count. ";
3499 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3500 // ScalarEvolution's implementaiton of the print method is to print
3501 // out SCEV values of all instructions that are interesting. Doing
3502 // this potentially causes it to create new SCEV objects though,
3503 // which technically conflicts with the const qualifier. This isn't
3504 // observable from outside the class though (the hasSCEV function
3505 // notwithstanding), so casting away the const isn't dangerous.
3506 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3508 OS << "Classifying expressions for: " << F->getName() << "\n";
3509 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3510 if (isSCEVable(I->getType())) {
3513 SCEVHandle SV = SE.getSCEV(&*I);
3517 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
3519 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
3520 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3521 OS << "<<Unknown>>";
3531 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3532 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3533 PrintLoopInfo(OS, &SE, *I);
3536 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3537 raw_os_ostream OS(o);