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 // Lexicographically compare udiv expressions.
506 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
507 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
508 if (operator()(LC->getLHS(), RC->getLHS()))
510 if (operator()(RC->getLHS(), LC->getLHS()))
512 if (operator()(LC->getRHS(), RC->getRHS()))
514 if (operator()(RC->getRHS(), LC->getRHS()))
519 // Compare cast expressions by operand.
520 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
521 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
522 return operator()(LC->getOperand(), RC->getOperand());
525 assert(0 && "Unknown SCEV kind!");
531 /// GroupByComplexity - Given a list of SCEV objects, order them by their
532 /// complexity, and group objects of the same complexity together by value.
533 /// When this routine is finished, we know that any duplicates in the vector are
534 /// consecutive and that complexity is monotonically increasing.
536 /// Note that we go take special precautions to ensure that we get determinstic
537 /// results from this routine. In other words, we don't want the results of
538 /// this to depend on where the addresses of various SCEV objects happened to
541 static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
543 if (Ops.size() < 2) return; // Noop
544 if (Ops.size() == 2) {
545 // This is the common case, which also happens to be trivially simple.
547 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
548 std::swap(Ops[0], Ops[1]);
552 // Do the rough sort by complexity.
553 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
555 // Now that we are sorted by complexity, group elements of the same
556 // complexity. Note that this is, at worst, N^2, but the vector is likely to
557 // be extremely short in practice. Note that we take this approach because we
558 // do not want to depend on the addresses of the objects we are grouping.
559 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
560 const SCEV *S = Ops[i];
561 unsigned Complexity = S->getSCEVType();
563 // If there are any objects of the same complexity and same value as this
565 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
566 if (Ops[j] == S) { // Found a duplicate.
567 // Move it to immediately after i'th element.
568 std::swap(Ops[i+1], Ops[j]);
569 ++i; // no need to rescan it.
570 if (i == e-2) return; // Done!
578 //===----------------------------------------------------------------------===//
579 // Simple SCEV method implementations
580 //===----------------------------------------------------------------------===//
582 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
584 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
586 const Type* ResultTy) {
587 // Handle the simplest case efficiently.
589 return SE.getTruncateOrZeroExtend(It, ResultTy);
591 // We are using the following formula for BC(It, K):
593 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
595 // Suppose, W is the bitwidth of the return value. We must be prepared for
596 // overflow. Hence, we must assure that the result of our computation is
597 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
598 // safe in modular arithmetic.
600 // However, this code doesn't use exactly that formula; the formula it uses
601 // is something like the following, where T is the number of factors of 2 in
602 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
605 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
607 // This formula is trivially equivalent to the previous formula. However,
608 // this formula can be implemented much more efficiently. The trick is that
609 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
610 // arithmetic. To do exact division in modular arithmetic, all we have
611 // to do is multiply by the inverse. Therefore, this step can be done at
614 // The next issue is how to safely do the division by 2^T. The way this
615 // is done is by doing the multiplication step at a width of at least W + T
616 // bits. This way, the bottom W+T bits of the product are accurate. Then,
617 // when we perform the division by 2^T (which is equivalent to a right shift
618 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
619 // truncated out after the division by 2^T.
621 // In comparison to just directly using the first formula, this technique
622 // is much more efficient; using the first formula requires W * K bits,
623 // but this formula less than W + K bits. Also, the first formula requires
624 // a division step, whereas this formula only requires multiplies and shifts.
626 // It doesn't matter whether the subtraction step is done in the calculation
627 // width or the input iteration count's width; if the subtraction overflows,
628 // the result must be zero anyway. We prefer here to do it in the width of
629 // the induction variable because it helps a lot for certain cases; CodeGen
630 // isn't smart enough to ignore the overflow, which leads to much less
631 // efficient code if the width of the subtraction is wider than the native
634 // (It's possible to not widen at all by pulling out factors of 2 before
635 // the multiplication; for example, K=2 can be calculated as
636 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
637 // extra arithmetic, so it's not an obvious win, and it gets
638 // much more complicated for K > 3.)
640 // Protection from insane SCEVs; this bound is conservative,
641 // but it probably doesn't matter.
643 return SE.getCouldNotCompute();
645 unsigned W = SE.getTypeSizeInBits(ResultTy);
647 // Calculate K! / 2^T and T; we divide out the factors of two before
648 // multiplying for calculating K! / 2^T to avoid overflow.
649 // Other overflow doesn't matter because we only care about the bottom
650 // W bits of the result.
651 APInt OddFactorial(W, 1);
653 for (unsigned i = 3; i <= K; ++i) {
655 unsigned TwoFactors = Mult.countTrailingZeros();
657 Mult = Mult.lshr(TwoFactors);
658 OddFactorial *= Mult;
661 // We need at least W + T bits for the multiplication step
662 unsigned CalculationBits = W + T;
664 // Calcuate 2^T, at width T+W.
665 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
667 // Calculate the multiplicative inverse of K! / 2^T;
668 // this multiplication factor will perform the exact division by
670 APInt Mod = APInt::getSignedMinValue(W+1);
671 APInt MultiplyFactor = OddFactorial.zext(W+1);
672 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
673 MultiplyFactor = MultiplyFactor.trunc(W);
675 // Calculate the product, at width T+W
676 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
677 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
678 for (unsigned i = 1; i != K; ++i) {
679 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
680 Dividend = SE.getMulExpr(Dividend,
681 SE.getTruncateOrZeroExtend(S, CalculationTy));
685 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
687 // Truncate the result, and divide by K! / 2^T.
689 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
690 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
693 /// evaluateAtIteration - Return the value of this chain of recurrences at
694 /// the specified iteration number. We can evaluate this recurrence by
695 /// multiplying each element in the chain by the binomial coefficient
696 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
698 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
700 /// where BC(It, k) stands for binomial coefficient.
702 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
703 ScalarEvolution &SE) const {
704 SCEVHandle Result = getStart();
705 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
706 // The computation is correct in the face of overflow provided that the
707 // multiplication is performed _after_ the evaluation of the binomial
709 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
710 if (isa<SCEVCouldNotCompute>(Coeff))
713 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
718 //===----------------------------------------------------------------------===//
719 // SCEV Expression folder implementations
720 //===----------------------------------------------------------------------===//
722 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
724 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
725 "This is not a truncating conversion!");
726 assert(isSCEVable(Ty) &&
727 "This is not a conversion to a SCEVable type!");
728 Ty = getEffectiveSCEVType(Ty);
730 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
732 ConstantExpr::getTrunc(SC->getValue(), Ty));
734 // trunc(trunc(x)) --> trunc(x)
735 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
736 return getTruncateExpr(ST->getOperand(), Ty);
738 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
739 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
740 return getTruncateOrSignExtend(SS->getOperand(), Ty);
742 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
743 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
744 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
746 // If the input value is a chrec scev made out of constants, truncate
747 // all of the constants.
748 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
749 std::vector<SCEVHandle> Operands;
750 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
751 // FIXME: This should allow truncation of other expression types!
752 if (isa<SCEVConstant>(AddRec->getOperand(i)))
753 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
756 if (Operands.size() == AddRec->getNumOperands())
757 return getAddRecExpr(Operands, AddRec->getLoop());
760 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
761 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
765 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
767 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
768 "This is not an extending conversion!");
769 assert(isSCEVable(Ty) &&
770 "This is not a conversion to a SCEVable type!");
771 Ty = getEffectiveSCEVType(Ty);
773 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
774 const Type *IntTy = getEffectiveSCEVType(Ty);
775 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
776 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
777 return getUnknown(C);
780 // zext(zext(x)) --> zext(x)
781 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
782 return getZeroExtendExpr(SZ->getOperand(), Ty);
784 // If the input value is a chrec scev, and we can prove that the value
785 // did not overflow the old, smaller, value, we can zero extend all of the
786 // operands (often constants). This allows analysis of something like
787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
789 if (AR->isAffine()) {
790 // Check whether the backedge-taken count is SCEVCouldNotCompute.
791 // Note that this serves two purposes: It filters out loops that are
792 // simply not analyzable, and it covers the case where this code is
793 // being called from within backedge-taken count analysis, such that
794 // attempting to ask for the backedge-taken count would likely result
795 // in infinite recursion. In the later case, the analysis code will
796 // cope with a conservative value, and it will take care to purge
797 // that value once it has finished.
798 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
799 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
800 // Manually compute the final value for AR, checking for
802 SCEVHandle Start = AR->getStart();
803 SCEVHandle Step = AR->getStepRecurrence(*this);
805 // Check whether the backedge-taken count can be losslessly casted to
806 // the addrec's type. The count is always unsigned.
807 SCEVHandle CastedMaxBECount =
808 getTruncateOrZeroExtend(MaxBECount, Start->getType());
810 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
812 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
813 // Check whether Start+Step*MaxBECount has no unsigned overflow.
815 getMulExpr(CastedMaxBECount,
816 getTruncateOrZeroExtend(Step, Start->getType()));
817 SCEVHandle Add = getAddExpr(Start, ZMul);
818 if (getZeroExtendExpr(Add, WideTy) ==
819 getAddExpr(getZeroExtendExpr(Start, WideTy),
820 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
821 getZeroExtendExpr(Step, WideTy))))
822 // Return the expression with the addrec on the outside.
823 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
824 getZeroExtendExpr(Step, Ty),
827 // Similar to above, only this time treat the step value as signed.
828 // This covers loops that count down.
830 getMulExpr(CastedMaxBECount,
831 getTruncateOrSignExtend(Step, Start->getType()));
832 Add = getAddExpr(Start, SMul);
833 if (getZeroExtendExpr(Add, WideTy) ==
834 getAddExpr(getZeroExtendExpr(Start, WideTy),
835 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
836 getSignExtendExpr(Step, WideTy))))
837 // Return the expression with the addrec on the outside.
838 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
839 getSignExtendExpr(Step, Ty),
845 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
846 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
850 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
852 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
853 "This is not an extending conversion!");
854 assert(isSCEVable(Ty) &&
855 "This is not a conversion to a SCEVable type!");
856 Ty = getEffectiveSCEVType(Ty);
858 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
859 const Type *IntTy = getEffectiveSCEVType(Ty);
860 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
861 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
862 return getUnknown(C);
865 // sext(sext(x)) --> sext(x)
866 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
867 return getSignExtendExpr(SS->getOperand(), Ty);
869 // If the input value is a chrec scev, and we can prove that the value
870 // did not overflow the old, smaller, value, we can sign extend all of the
871 // operands (often constants). This allows analysis of something like
872 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
873 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
874 if (AR->isAffine()) {
875 // Check whether the backedge-taken count is SCEVCouldNotCompute.
876 // Note that this serves two purposes: It filters out loops that are
877 // simply not analyzable, and it covers the case where this code is
878 // being called from within backedge-taken count analysis, such that
879 // attempting to ask for the backedge-taken count would likely result
880 // in infinite recursion. In the later case, the analysis code will
881 // cope with a conservative value, and it will take care to purge
882 // that value once it has finished.
883 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
884 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
885 // Manually compute the final value for AR, checking for
887 SCEVHandle Start = AR->getStart();
888 SCEVHandle Step = AR->getStepRecurrence(*this);
890 // Check whether the backedge-taken count can be losslessly casted to
891 // the addrec's type. The count is always unsigned.
892 SCEVHandle CastedMaxBECount =
893 getTruncateOrZeroExtend(MaxBECount, Start->getType());
895 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
897 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
898 // Check whether Start+Step*MaxBECount has no signed overflow.
900 getMulExpr(CastedMaxBECount,
901 getTruncateOrSignExtend(Step, Start->getType()));
902 SCEVHandle Add = getAddExpr(Start, SMul);
903 if (getSignExtendExpr(Add, WideTy) ==
904 getAddExpr(getSignExtendExpr(Start, WideTy),
905 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
906 getSignExtendExpr(Step, WideTy))))
907 // Return the expression with the addrec on the outside.
908 return getAddRecExpr(getSignExtendExpr(Start, Ty),
909 getSignExtendExpr(Step, Ty),
915 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
916 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
920 // get - Get a canonical add expression, or something simpler if possible.
921 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
922 assert(!Ops.empty() && "Cannot get empty add!");
923 if (Ops.size() == 1) return Ops[0];
925 // Sort by complexity, this groups all similar expression types together.
926 GroupByComplexity(Ops, LI);
928 // If there are any constants, fold them together.
930 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
932 assert(Idx < Ops.size());
933 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
934 // We found two constants, fold them together!
935 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
936 RHSC->getValue()->getValue());
937 Ops[0] = getConstant(Fold);
938 Ops.erase(Ops.begin()+1); // Erase the folded element
939 if (Ops.size() == 1) return Ops[0];
940 LHSC = cast<SCEVConstant>(Ops[0]);
943 // If we are left with a constant zero being added, strip it off.
944 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
945 Ops.erase(Ops.begin());
950 if (Ops.size() == 1) return Ops[0];
952 // Okay, check to see if the same value occurs in the operand list twice. If
953 // so, merge them together into an multiply expression. Since we sorted the
954 // list, these values are required to be adjacent.
955 const Type *Ty = Ops[0]->getType();
956 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
957 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
958 // Found a match, merge the two values into a multiply, and add any
959 // remaining values to the result.
960 SCEVHandle Two = getIntegerSCEV(2, Ty);
961 SCEVHandle Mul = getMulExpr(Ops[i], Two);
964 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
966 return getAddExpr(Ops);
969 // Now we know the first non-constant operand. Skip past any cast SCEVs.
970 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
973 // If there are add operands they would be next.
974 if (Idx < Ops.size()) {
975 bool DeletedAdd = false;
976 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
977 // If we have an add, expand the add operands onto the end of the operands
979 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
980 Ops.erase(Ops.begin()+Idx);
984 // If we deleted at least one add, we added operands to the end of the list,
985 // and they are not necessarily sorted. Recurse to resort and resimplify
986 // any operands we just aquired.
988 return getAddExpr(Ops);
991 // Skip over the add expression until we get to a multiply.
992 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
995 // If we are adding something to a multiply expression, make sure the
996 // something is not already an operand of the multiply. If so, merge it into
998 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
999 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1000 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1001 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1002 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1003 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1004 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1005 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1006 if (Mul->getNumOperands() != 2) {
1007 // If the multiply has more than two operands, we must get the
1009 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1010 MulOps.erase(MulOps.begin()+MulOp);
1011 InnerMul = getMulExpr(MulOps);
1013 SCEVHandle One = getIntegerSCEV(1, Ty);
1014 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1015 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1016 if (Ops.size() == 2) return OuterMul;
1018 Ops.erase(Ops.begin()+AddOp);
1019 Ops.erase(Ops.begin()+Idx-1);
1021 Ops.erase(Ops.begin()+Idx);
1022 Ops.erase(Ops.begin()+AddOp-1);
1024 Ops.push_back(OuterMul);
1025 return getAddExpr(Ops);
1028 // Check this multiply against other multiplies being added together.
1029 for (unsigned OtherMulIdx = Idx+1;
1030 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1032 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1033 // If MulOp occurs in OtherMul, we can fold the two multiplies
1035 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1036 OMulOp != e; ++OMulOp)
1037 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1038 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1039 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1040 if (Mul->getNumOperands() != 2) {
1041 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1042 MulOps.erase(MulOps.begin()+MulOp);
1043 InnerMul1 = getMulExpr(MulOps);
1045 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1046 if (OtherMul->getNumOperands() != 2) {
1047 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1048 OtherMul->op_end());
1049 MulOps.erase(MulOps.begin()+OMulOp);
1050 InnerMul2 = getMulExpr(MulOps);
1052 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1053 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1054 if (Ops.size() == 2) return OuterMul;
1055 Ops.erase(Ops.begin()+Idx);
1056 Ops.erase(Ops.begin()+OtherMulIdx-1);
1057 Ops.push_back(OuterMul);
1058 return getAddExpr(Ops);
1064 // If there are any add recurrences in the operands list, see if any other
1065 // added values are loop invariant. If so, we can fold them into the
1067 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1070 // Scan over all recurrences, trying to fold loop invariants into them.
1071 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1072 // Scan all of the other operands to this add and add them to the vector if
1073 // they are loop invariant w.r.t. the recurrence.
1074 std::vector<SCEVHandle> LIOps;
1075 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1076 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1077 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1078 LIOps.push_back(Ops[i]);
1079 Ops.erase(Ops.begin()+i);
1083 // If we found some loop invariants, fold them into the recurrence.
1084 if (!LIOps.empty()) {
1085 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1086 LIOps.push_back(AddRec->getStart());
1088 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
1089 AddRecOps[0] = getAddExpr(LIOps);
1091 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1092 // If all of the other operands were loop invariant, we are done.
1093 if (Ops.size() == 1) return NewRec;
1095 // Otherwise, add the folded AddRec by the non-liv parts.
1096 for (unsigned i = 0;; ++i)
1097 if (Ops[i] == AddRec) {
1101 return getAddExpr(Ops);
1104 // Okay, if there weren't any loop invariants to be folded, check to see if
1105 // there are multiple AddRec's with the same loop induction variable being
1106 // added together. If so, we can fold them.
1107 for (unsigned OtherIdx = Idx+1;
1108 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1109 if (OtherIdx != Idx) {
1110 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1111 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1112 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1113 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1114 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1115 if (i >= NewOps.size()) {
1116 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1117 OtherAddRec->op_end());
1120 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1122 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1124 if (Ops.size() == 2) return NewAddRec;
1126 Ops.erase(Ops.begin()+Idx);
1127 Ops.erase(Ops.begin()+OtherIdx-1);
1128 Ops.push_back(NewAddRec);
1129 return getAddExpr(Ops);
1133 // Otherwise couldn't fold anything into this recurrence. Move onto the
1137 // Okay, it looks like we really DO need an add expr. Check to see if we
1138 // already have one, otherwise create a new one.
1139 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1140 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1142 if (Result == 0) Result = new SCEVAddExpr(Ops);
1147 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
1148 assert(!Ops.empty() && "Cannot get empty mul!");
1150 // Sort by complexity, this groups all similar expression types together.
1151 GroupByComplexity(Ops, LI);
1153 // If there are any constants, fold them together.
1155 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1157 // C1*(C2+V) -> C1*C2 + C1*V
1158 if (Ops.size() == 2)
1159 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1160 if (Add->getNumOperands() == 2 &&
1161 isa<SCEVConstant>(Add->getOperand(0)))
1162 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1163 getMulExpr(LHSC, Add->getOperand(1)));
1167 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1168 // We found two constants, fold them together!
1169 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1170 RHSC->getValue()->getValue());
1171 Ops[0] = getConstant(Fold);
1172 Ops.erase(Ops.begin()+1); // Erase the folded element
1173 if (Ops.size() == 1) return Ops[0];
1174 LHSC = cast<SCEVConstant>(Ops[0]);
1177 // If we are left with a constant one being multiplied, strip it off.
1178 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1179 Ops.erase(Ops.begin());
1181 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1182 // If we have a multiply of zero, it will always be zero.
1187 // Skip over the add expression until we get to a multiply.
1188 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1191 if (Ops.size() == 1)
1194 // If there are mul operands inline them all into this expression.
1195 if (Idx < Ops.size()) {
1196 bool DeletedMul = false;
1197 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1198 // If we have an mul, expand the mul operands onto the end of the operands
1200 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1201 Ops.erase(Ops.begin()+Idx);
1205 // If we deleted at least one mul, we added operands to the end of the list,
1206 // and they are not necessarily sorted. Recurse to resort and resimplify
1207 // any operands we just aquired.
1209 return getMulExpr(Ops);
1212 // If there are any add recurrences in the operands list, see if any other
1213 // added values are loop invariant. If so, we can fold them into the
1215 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1218 // Scan over all recurrences, trying to fold loop invariants into them.
1219 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1220 // Scan all of the other operands to this mul and add them to the vector if
1221 // they are loop invariant w.r.t. the recurrence.
1222 std::vector<SCEVHandle> LIOps;
1223 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1224 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1225 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1226 LIOps.push_back(Ops[i]);
1227 Ops.erase(Ops.begin()+i);
1231 // If we found some loop invariants, fold them into the recurrence.
1232 if (!LIOps.empty()) {
1233 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1234 std::vector<SCEVHandle> NewOps;
1235 NewOps.reserve(AddRec->getNumOperands());
1236 if (LIOps.size() == 1) {
1237 const SCEV *Scale = LIOps[0];
1238 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1239 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1241 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1242 std::vector<SCEVHandle> MulOps(LIOps);
1243 MulOps.push_back(AddRec->getOperand(i));
1244 NewOps.push_back(getMulExpr(MulOps));
1248 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1250 // If all of the other operands were loop invariant, we are done.
1251 if (Ops.size() == 1) return NewRec;
1253 // Otherwise, multiply the folded AddRec by the non-liv parts.
1254 for (unsigned i = 0;; ++i)
1255 if (Ops[i] == AddRec) {
1259 return getMulExpr(Ops);
1262 // Okay, if there weren't any loop invariants to be folded, check to see if
1263 // there are multiple AddRec's with the same loop induction variable being
1264 // multiplied together. If so, we can fold them.
1265 for (unsigned OtherIdx = Idx+1;
1266 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1267 if (OtherIdx != Idx) {
1268 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1269 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1270 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1271 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1272 SCEVHandle NewStart = getMulExpr(F->getStart(),
1274 SCEVHandle B = F->getStepRecurrence(*this);
1275 SCEVHandle D = G->getStepRecurrence(*this);
1276 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1279 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1281 if (Ops.size() == 2) return NewAddRec;
1283 Ops.erase(Ops.begin()+Idx);
1284 Ops.erase(Ops.begin()+OtherIdx-1);
1285 Ops.push_back(NewAddRec);
1286 return getMulExpr(Ops);
1290 // Otherwise couldn't fold anything into this recurrence. Move onto the
1294 // Okay, it looks like we really DO need an mul expr. Check to see if we
1295 // already have one, otherwise create a new one.
1296 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1297 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1300 Result = new SCEVMulExpr(Ops);
1304 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1305 const SCEVHandle &RHS) {
1306 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1307 if (RHSC->getValue()->equalsInt(1))
1308 return LHS; // X udiv 1 --> x
1310 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1312 // Determine if the division can be folded into the operands of
1314 // TODO: Generalize this to non-constants by using known-bits information.
1315 const Type *Ty = LHS->getType();
1316 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1317 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1318 // For non-power-of-two values, effectively round the value up to the
1319 // nearest power of two.
1320 if (!RHSC->getValue()->getValue().isPowerOf2())
1322 const IntegerType *ExtTy =
1323 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1324 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1325 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1326 if (const SCEVConstant *Step =
1327 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1328 if (!Step->getValue()->getValue()
1329 .urem(RHSC->getValue()->getValue()) &&
1330 getTruncateExpr(getZeroExtendExpr(AR, ExtTy), Ty) == AR) {
1331 std::vector<SCEVHandle> Operands;
1332 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1333 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1334 return getAddRecExpr(Operands, AR->getLoop());
1336 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1337 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS))
1338 if (getTruncateExpr(getZeroExtendExpr(M, ExtTy), Ty) == M)
1339 // Find an operand that's safely divisible.
1340 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1341 SCEVHandle Op = M->getOperand(i);
1342 SCEVHandle Div = getUDivExpr(Op, RHSC);
1343 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1344 std::vector<SCEVHandle> Operands = M->getOperands();
1346 return getMulExpr(Operands);
1349 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1350 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS))
1351 if (getTruncateExpr(getZeroExtendExpr(A, ExtTy), Ty) == A) {
1352 std::vector<SCEVHandle> Operands;
1353 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1354 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1355 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1357 Operands.push_back(Op);
1359 if (Operands.size() == A->getNumOperands())
1360 return getAddExpr(Operands);
1363 // Fold if both operands are constant.
1364 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1365 Constant *LHSCV = LHSC->getValue();
1366 Constant *RHSCV = RHSC->getValue();
1367 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1371 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1372 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1377 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1378 /// specified loop. Simplify the expression as much as possible.
1379 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1380 const SCEVHandle &Step, const Loop *L) {
1381 std::vector<SCEVHandle> Operands;
1382 Operands.push_back(Start);
1383 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1384 if (StepChrec->getLoop() == L) {
1385 Operands.insert(Operands.end(), StepChrec->op_begin(),
1386 StepChrec->op_end());
1387 return getAddRecExpr(Operands, L);
1390 Operands.push_back(Step);
1391 return getAddRecExpr(Operands, L);
1394 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1395 /// specified loop. Simplify the expression as much as possible.
1396 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1398 if (Operands.size() == 1) return Operands[0];
1400 if (Operands.back()->isZero()) {
1401 Operands.pop_back();
1402 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1405 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1406 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1407 const Loop* NestedLoop = NestedAR->getLoop();
1408 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1409 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1410 NestedAR->op_end());
1411 SCEVHandle NestedARHandle(NestedAR);
1412 Operands[0] = NestedAR->getStart();
1413 NestedOperands[0] = getAddRecExpr(Operands, L);
1414 return getAddRecExpr(NestedOperands, NestedLoop);
1418 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1419 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1420 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1424 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1425 const SCEVHandle &RHS) {
1426 std::vector<SCEVHandle> Ops;
1429 return getSMaxExpr(Ops);
1432 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1433 assert(!Ops.empty() && "Cannot get empty smax!");
1434 if (Ops.size() == 1) return Ops[0];
1436 // Sort by complexity, this groups all similar expression types together.
1437 GroupByComplexity(Ops, LI);
1439 // If there are any constants, fold them together.
1441 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1443 assert(Idx < Ops.size());
1444 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1445 // We found two constants, fold them together!
1446 ConstantInt *Fold = ConstantInt::get(
1447 APIntOps::smax(LHSC->getValue()->getValue(),
1448 RHSC->getValue()->getValue()));
1449 Ops[0] = getConstant(Fold);
1450 Ops.erase(Ops.begin()+1); // Erase the folded element
1451 if (Ops.size() == 1) return Ops[0];
1452 LHSC = cast<SCEVConstant>(Ops[0]);
1455 // If we are left with a constant -inf, strip it off.
1456 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1457 Ops.erase(Ops.begin());
1462 if (Ops.size() == 1) return Ops[0];
1464 // Find the first SMax
1465 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1468 // Check to see if one of the operands is an SMax. If so, expand its operands
1469 // onto our operand list, and recurse to simplify.
1470 if (Idx < Ops.size()) {
1471 bool DeletedSMax = false;
1472 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1473 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1474 Ops.erase(Ops.begin()+Idx);
1479 return getSMaxExpr(Ops);
1482 // Okay, check to see if the same value occurs in the operand list twice. If
1483 // so, delete one. Since we sorted the list, these values are required to
1485 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1486 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1487 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1491 if (Ops.size() == 1) return Ops[0];
1493 assert(!Ops.empty() && "Reduced smax down to nothing!");
1495 // Okay, it looks like we really DO need an smax expr. Check to see if we
1496 // already have one, otherwise create a new one.
1497 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1498 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1500 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1504 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1505 const SCEVHandle &RHS) {
1506 std::vector<SCEVHandle> Ops;
1509 return getUMaxExpr(Ops);
1512 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1513 assert(!Ops.empty() && "Cannot get empty umax!");
1514 if (Ops.size() == 1) return Ops[0];
1516 // Sort by complexity, this groups all similar expression types together.
1517 GroupByComplexity(Ops, LI);
1519 // If there are any constants, fold them together.
1521 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1523 assert(Idx < Ops.size());
1524 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1525 // We found two constants, fold them together!
1526 ConstantInt *Fold = ConstantInt::get(
1527 APIntOps::umax(LHSC->getValue()->getValue(),
1528 RHSC->getValue()->getValue()));
1529 Ops[0] = getConstant(Fold);
1530 Ops.erase(Ops.begin()+1); // Erase the folded element
1531 if (Ops.size() == 1) return Ops[0];
1532 LHSC = cast<SCEVConstant>(Ops[0]);
1535 // If we are left with a constant zero, strip it off.
1536 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1537 Ops.erase(Ops.begin());
1542 if (Ops.size() == 1) return Ops[0];
1544 // Find the first UMax
1545 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1548 // Check to see if one of the operands is a UMax. If so, expand its operands
1549 // onto our operand list, and recurse to simplify.
1550 if (Idx < Ops.size()) {
1551 bool DeletedUMax = false;
1552 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1553 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1554 Ops.erase(Ops.begin()+Idx);
1559 return getUMaxExpr(Ops);
1562 // Okay, check to see if the same value occurs in the operand list twice. If
1563 // so, delete one. Since we sorted the list, these values are required to
1565 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1566 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1567 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1571 if (Ops.size() == 1) return Ops[0];
1573 assert(!Ops.empty() && "Reduced umax down to nothing!");
1575 // Okay, it looks like we really DO need a umax expr. Check to see if we
1576 // already have one, otherwise create a new one.
1577 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1578 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1580 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1584 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1585 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1586 return getConstant(CI);
1587 if (isa<ConstantPointerNull>(V))
1588 return getIntegerSCEV(0, V->getType());
1589 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1590 if (Result == 0) Result = new SCEVUnknown(V);
1594 //===----------------------------------------------------------------------===//
1595 // Basic SCEV Analysis and PHI Idiom Recognition Code
1598 /// isSCEVable - Test if values of the given type are analyzable within
1599 /// the SCEV framework. This primarily includes integer types, and it
1600 /// can optionally include pointer types if the ScalarEvolution class
1601 /// has access to target-specific information.
1602 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1603 // Integers are always SCEVable.
1604 if (Ty->isInteger())
1607 // Pointers are SCEVable if TargetData information is available
1608 // to provide pointer size information.
1609 if (isa<PointerType>(Ty))
1612 // Otherwise it's not SCEVable.
1616 /// getTypeSizeInBits - Return the size in bits of the specified type,
1617 /// for which isSCEVable must return true.
1618 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1619 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1621 // If we have a TargetData, use it!
1623 return TD->getTypeSizeInBits(Ty);
1625 // Otherwise, we support only integer types.
1626 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1627 return Ty->getPrimitiveSizeInBits();
1630 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1631 /// the given type and which represents how SCEV will treat the given
1632 /// type, for which isSCEVable must return true. For pointer types,
1633 /// this is the pointer-sized integer type.
1634 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1635 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1637 if (Ty->isInteger())
1640 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1641 return TD->getIntPtrType();
1644 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1645 return UnknownValue;
1648 /// hasSCEV - Return true if the SCEV for this value has already been
1650 bool ScalarEvolution::hasSCEV(Value *V) const {
1651 return Scalars.count(V);
1654 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1655 /// expression and create a new one.
1656 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1657 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1659 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1660 if (I != Scalars.end()) return I->second;
1661 SCEVHandle S = createSCEV(V);
1662 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1666 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1667 /// specified signed integer value and return a SCEV for the constant.
1668 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1669 Ty = getEffectiveSCEVType(Ty);
1672 C = Constant::getNullValue(Ty);
1673 else if (Ty->isFloatingPoint())
1674 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1675 APFloat::IEEEdouble, Val));
1677 C = ConstantInt::get(Ty, Val);
1678 return getUnknown(C);
1681 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1683 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
1684 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1685 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
1687 const Type *Ty = V->getType();
1688 Ty = getEffectiveSCEVType(Ty);
1689 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
1692 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1693 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
1694 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1695 return getUnknown(ConstantExpr::getNot(VC->getValue()));
1697 const Type *Ty = V->getType();
1698 Ty = getEffectiveSCEVType(Ty);
1699 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
1700 return getMinusSCEV(AllOnes, V);
1703 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1705 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
1706 const SCEVHandle &RHS) {
1708 return getAddExpr(LHS, getNegativeSCEV(RHS));
1711 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1712 /// input value to the specified type. If the type must be extended, it is zero
1715 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
1717 const Type *SrcTy = V->getType();
1718 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1719 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1720 "Cannot truncate or zero extend with non-integer arguments!");
1721 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1722 return V; // No conversion
1723 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1724 return getTruncateExpr(V, Ty);
1725 return getZeroExtendExpr(V, Ty);
1728 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1729 /// input value to the specified type. If the type must be extended, it is sign
1732 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
1734 const Type *SrcTy = V->getType();
1735 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1736 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1737 "Cannot truncate or zero extend with non-integer arguments!");
1738 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1739 return V; // No conversion
1740 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1741 return getTruncateExpr(V, Ty);
1742 return getSignExtendExpr(V, Ty);
1745 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1746 /// the specified instruction and replaces any references to the symbolic value
1747 /// SymName with the specified value. This is used during PHI resolution.
1748 void ScalarEvolution::
1749 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1750 const SCEVHandle &NewVal) {
1751 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1752 Scalars.find(SCEVCallbackVH(I, this));
1753 if (SI == Scalars.end()) return;
1756 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
1757 if (NV == SI->second) return; // No change.
1759 SI->second = NV; // Update the scalars map!
1761 // Any instruction values that use this instruction might also need to be
1763 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1765 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1768 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1769 /// a loop header, making it a potential recurrence, or it doesn't.
1771 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
1772 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1773 if (const Loop *L = LI->getLoopFor(PN->getParent()))
1774 if (L->getHeader() == PN->getParent()) {
1775 // If it lives in the loop header, it has two incoming values, one
1776 // from outside the loop, and one from inside.
1777 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1778 unsigned BackEdge = IncomingEdge^1;
1780 // While we are analyzing this PHI node, handle its value symbolically.
1781 SCEVHandle SymbolicName = getUnknown(PN);
1782 assert(Scalars.find(PN) == Scalars.end() &&
1783 "PHI node already processed?");
1784 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
1786 // Using this symbolic name for the PHI, analyze the value coming around
1788 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1790 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1791 // has a special value for the first iteration of the loop.
1793 // If the value coming around the backedge is an add with the symbolic
1794 // value we just inserted, then we found a simple induction variable!
1795 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1796 // If there is a single occurrence of the symbolic value, replace it
1797 // with a recurrence.
1798 unsigned FoundIndex = Add->getNumOperands();
1799 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1800 if (Add->getOperand(i) == SymbolicName)
1801 if (FoundIndex == e) {
1806 if (FoundIndex != Add->getNumOperands()) {
1807 // Create an add with everything but the specified operand.
1808 std::vector<SCEVHandle> Ops;
1809 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1810 if (i != FoundIndex)
1811 Ops.push_back(Add->getOperand(i));
1812 SCEVHandle Accum = getAddExpr(Ops);
1814 // This is not a valid addrec if the step amount is varying each
1815 // loop iteration, but is not itself an addrec in this loop.
1816 if (Accum->isLoopInvariant(L) ||
1817 (isa<SCEVAddRecExpr>(Accum) &&
1818 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1819 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1820 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
1822 // Okay, for the entire analysis of this edge we assumed the PHI
1823 // to be symbolic. We now need to go back and update all of the
1824 // entries for the scalars that use the PHI (except for the PHI
1825 // itself) to use the new analyzed value instead of the "symbolic"
1827 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1831 } else if (const SCEVAddRecExpr *AddRec =
1832 dyn_cast<SCEVAddRecExpr>(BEValue)) {
1833 // Otherwise, this could be a loop like this:
1834 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1835 // In this case, j = {1,+,1} and BEValue is j.
1836 // Because the other in-value of i (0) fits the evolution of BEValue
1837 // i really is an addrec evolution.
1838 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1839 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1841 // If StartVal = j.start - j.stride, we can use StartVal as the
1842 // initial step of the addrec evolution.
1843 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
1844 AddRec->getOperand(1))) {
1845 SCEVHandle PHISCEV =
1846 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1848 // Okay, for the entire analysis of this edge we assumed the PHI
1849 // to be symbolic. We now need to go back and update all of the
1850 // entries for the scalars that use the PHI (except for the PHI
1851 // itself) to use the new analyzed value instead of the "symbolic"
1853 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1859 return SymbolicName;
1862 // If it's not a loop phi, we can't handle it yet.
1863 return getUnknown(PN);
1866 /// createNodeForGEP - Expand GEP instructions into add and multiply
1867 /// operations. This allows them to be analyzed by regular SCEV code.
1869 SCEVHandle ScalarEvolution::createNodeForGEP(GetElementPtrInst *GEP) {
1871 const Type *IntPtrTy = TD->getIntPtrType();
1872 Value *Base = GEP->getOperand(0);
1873 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
1874 gep_type_iterator GTI = gep_type_begin(GEP);
1875 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
1879 // Compute the (potentially symbolic) offset in bytes for this index.
1880 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1881 // For a struct, add the member offset.
1882 const StructLayout &SL = *TD->getStructLayout(STy);
1883 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1884 uint64_t Offset = SL.getElementOffset(FieldNo);
1885 TotalOffset = getAddExpr(TotalOffset,
1886 getIntegerSCEV(Offset, IntPtrTy));
1888 // For an array, add the element offset, explicitly scaled.
1889 SCEVHandle LocalOffset = getSCEV(Index);
1890 if (!isa<PointerType>(LocalOffset->getType()))
1891 // Getelementptr indicies are signed.
1892 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1895 getMulExpr(LocalOffset,
1896 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1898 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
1901 return getAddExpr(getSCEV(Base), TotalOffset);
1904 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1905 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1906 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1907 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1908 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1909 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1910 return C->getValue()->getValue().countTrailingZeros();
1912 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1913 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1914 (uint32_t)SE.getTypeSizeInBits(T->getType()));
1916 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1917 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1918 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1919 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1922 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1923 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1924 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1925 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1928 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1929 // The result is the min of all operands results.
1930 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1931 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1932 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1936 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1937 // The result is the sum of all operands results.
1938 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1939 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1940 for (unsigned i = 1, e = M->getNumOperands();
1941 SumOpRes != BitWidth && i != e; ++i)
1942 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1947 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1948 // The result is the min of all operands results.
1949 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1950 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1951 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1955 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1956 // The result is the min of all operands results.
1957 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1958 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1959 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1963 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1964 // The result is the min of all operands results.
1965 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1966 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1967 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1971 // SCEVUDivExpr, SCEVUnknown
1975 /// createSCEV - We know that there is no SCEV for the specified value.
1976 /// Analyze the expression.
1978 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
1979 if (!isSCEVable(V->getType()))
1980 return getUnknown(V);
1982 unsigned Opcode = Instruction::UserOp1;
1983 if (Instruction *I = dyn_cast<Instruction>(V))
1984 Opcode = I->getOpcode();
1985 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1986 Opcode = CE->getOpcode();
1988 return getUnknown(V);
1990 User *U = cast<User>(V);
1992 case Instruction::Add:
1993 return getAddExpr(getSCEV(U->getOperand(0)),
1994 getSCEV(U->getOperand(1)));
1995 case Instruction::Mul:
1996 return getMulExpr(getSCEV(U->getOperand(0)),
1997 getSCEV(U->getOperand(1)));
1998 case Instruction::UDiv:
1999 return getUDivExpr(getSCEV(U->getOperand(0)),
2000 getSCEV(U->getOperand(1)));
2001 case Instruction::Sub:
2002 return getMinusSCEV(getSCEV(U->getOperand(0)),
2003 getSCEV(U->getOperand(1)));
2004 case Instruction::And:
2005 // For an expression like x&255 that merely masks off the high bits,
2006 // use zext(trunc(x)) as the SCEV expression.
2007 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2008 if (CI->isNullValue())
2009 return getSCEV(U->getOperand(1));
2010 if (CI->isAllOnesValue())
2011 return getSCEV(U->getOperand(0));
2012 const APInt &A = CI->getValue();
2013 unsigned Ones = A.countTrailingOnes();
2014 if (APIntOps::isMask(Ones, A))
2016 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2017 IntegerType::get(Ones)),
2021 case Instruction::Or:
2022 // If the RHS of the Or is a constant, we may have something like:
2023 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2024 // optimizations will transparently handle this case.
2026 // In order for this transformation to be safe, the LHS must be of the
2027 // form X*(2^n) and the Or constant must be less than 2^n.
2028 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2029 SCEVHandle LHS = getSCEV(U->getOperand(0));
2030 const APInt &CIVal = CI->getValue();
2031 if (GetMinTrailingZeros(LHS, *this) >=
2032 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2033 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2036 case Instruction::Xor:
2037 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2038 // If the RHS of the xor is a signbit, then this is just an add.
2039 // Instcombine turns add of signbit into xor as a strength reduction step.
2040 if (CI->getValue().isSignBit())
2041 return getAddExpr(getSCEV(U->getOperand(0)),
2042 getSCEV(U->getOperand(1)));
2044 // If the RHS of xor is -1, then this is a not operation.
2045 else if (CI->isAllOnesValue())
2046 return getNotSCEV(getSCEV(U->getOperand(0)));
2050 case Instruction::Shl:
2051 // Turn shift left of a constant amount into a multiply.
2052 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2053 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2054 Constant *X = ConstantInt::get(
2055 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2056 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2060 case Instruction::LShr:
2061 // Turn logical shift right of a constant into a unsigned divide.
2062 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2063 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2064 Constant *X = ConstantInt::get(
2065 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2066 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2070 case Instruction::AShr:
2071 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2072 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2073 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2074 if (L->getOpcode() == Instruction::Shl &&
2075 L->getOperand(1) == U->getOperand(1)) {
2076 unsigned BitWidth = getTypeSizeInBits(U->getType());
2077 uint64_t Amt = BitWidth - CI->getZExtValue();
2078 if (Amt == BitWidth)
2079 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2081 return getIntegerSCEV(0, U->getType()); // value is undefined
2083 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2084 IntegerType::get(Amt)),
2089 case Instruction::Trunc:
2090 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2092 case Instruction::ZExt:
2093 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2095 case Instruction::SExt:
2096 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2098 case Instruction::BitCast:
2099 // BitCasts are no-op casts so we just eliminate the cast.
2100 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2101 return getSCEV(U->getOperand(0));
2104 case Instruction::IntToPtr:
2105 if (!TD) break; // Without TD we can't analyze pointers.
2106 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2107 TD->getIntPtrType());
2109 case Instruction::PtrToInt:
2110 if (!TD) break; // Without TD we can't analyze pointers.
2111 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2114 case Instruction::GetElementPtr:
2115 if (!TD) break; // Without TD we can't analyze pointers.
2116 return createNodeForGEP(cast<GetElementPtrInst>(U));
2118 case Instruction::PHI:
2119 return createNodeForPHI(cast<PHINode>(U));
2121 case Instruction::Select:
2122 // This could be a smax or umax that was lowered earlier.
2123 // Try to recover it.
2124 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2125 Value *LHS = ICI->getOperand(0);
2126 Value *RHS = ICI->getOperand(1);
2127 switch (ICI->getPredicate()) {
2128 case ICmpInst::ICMP_SLT:
2129 case ICmpInst::ICMP_SLE:
2130 std::swap(LHS, RHS);
2132 case ICmpInst::ICMP_SGT:
2133 case ICmpInst::ICMP_SGE:
2134 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2135 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2136 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2137 // ~smax(~x, ~y) == smin(x, y).
2138 return getNotSCEV(getSMaxExpr(
2139 getNotSCEV(getSCEV(LHS)),
2140 getNotSCEV(getSCEV(RHS))));
2142 case ICmpInst::ICMP_ULT:
2143 case ICmpInst::ICMP_ULE:
2144 std::swap(LHS, RHS);
2146 case ICmpInst::ICMP_UGT:
2147 case ICmpInst::ICMP_UGE:
2148 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2149 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2150 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2151 // ~umax(~x, ~y) == umin(x, y)
2152 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2153 getNotSCEV(getSCEV(RHS))));
2160 default: // We cannot analyze this expression.
2164 return getUnknown(V);
2169 //===----------------------------------------------------------------------===//
2170 // Iteration Count Computation Code
2173 /// getBackedgeTakenCount - If the specified loop has a predictable
2174 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2175 /// object. The backedge-taken count is the number of times the loop header
2176 /// will be branched to from within the loop. This is one less than the
2177 /// trip count of the loop, since it doesn't count the first iteration,
2178 /// when the header is branched to from outside the loop.
2180 /// Note that it is not valid to call this method on a loop without a
2181 /// loop-invariant backedge-taken count (see
2182 /// hasLoopInvariantBackedgeTakenCount).
2184 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2185 return getBackedgeTakenInfo(L).Exact;
2188 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2189 /// return the least SCEV value that is known never to be less than the
2190 /// actual backedge taken count.
2191 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2192 return getBackedgeTakenInfo(L).Max;
2195 const ScalarEvolution::BackedgeTakenInfo &
2196 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2197 // Initially insert a CouldNotCompute for this loop. If the insertion
2198 // succeeds, procede to actually compute a backedge-taken count and
2199 // update the value. The temporary CouldNotCompute value tells SCEV
2200 // code elsewhere that it shouldn't attempt to request a new
2201 // backedge-taken count, which could result in infinite recursion.
2202 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2203 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2205 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2206 if (ItCount.Exact != UnknownValue) {
2207 assert(ItCount.Exact->isLoopInvariant(L) &&
2208 ItCount.Max->isLoopInvariant(L) &&
2209 "Computed trip count isn't loop invariant for loop!");
2210 ++NumTripCountsComputed;
2212 // Update the value in the map.
2213 Pair.first->second = ItCount;
2214 } else if (isa<PHINode>(L->getHeader()->begin())) {
2215 // Only count loops that have phi nodes as not being computable.
2216 ++NumTripCountsNotComputed;
2219 // Now that we know more about the trip count for this loop, forget any
2220 // existing SCEV values for PHI nodes in this loop since they are only
2221 // conservative estimates made without the benefit
2222 // of trip count information.
2223 if (ItCount.hasAnyInfo())
2226 return Pair.first->second;
2229 /// forgetLoopBackedgeTakenCount - This method should be called by the
2230 /// client when it has changed a loop in a way that may effect
2231 /// ScalarEvolution's ability to compute a trip count, or if the loop
2233 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2234 BackedgeTakenCounts.erase(L);
2238 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2239 /// PHI nodes in the given loop. This is used when the trip count of
2240 /// the loop may have changed.
2241 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2242 BasicBlock *Header = L->getHeader();
2244 SmallVector<Instruction *, 16> Worklist;
2245 for (BasicBlock::iterator I = Header->begin();
2246 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2247 Worklist.push_back(PN);
2249 while (!Worklist.empty()) {
2250 Instruction *I = Worklist.pop_back_val();
2251 if (Scalars.erase(I))
2252 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2254 Worklist.push_back(cast<Instruction>(UI));
2258 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2259 /// of the specified loop will execute.
2260 ScalarEvolution::BackedgeTakenInfo
2261 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2262 // If the loop has a non-one exit block count, we can't analyze it.
2263 SmallVector<BasicBlock*, 8> ExitBlocks;
2264 L->getExitBlocks(ExitBlocks);
2265 if (ExitBlocks.size() != 1) return UnknownValue;
2267 // Okay, there is one exit block. Try to find the condition that causes the
2268 // loop to be exited.
2269 BasicBlock *ExitBlock = ExitBlocks[0];
2271 BasicBlock *ExitingBlock = 0;
2272 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2274 if (L->contains(*PI)) {
2275 if (ExitingBlock == 0)
2278 return UnknownValue; // More than one block exiting!
2280 assert(ExitingBlock && "No exits from loop, something is broken!");
2282 // Okay, we've computed the exiting block. See what condition causes us to
2285 // FIXME: we should be able to handle switch instructions (with a single exit)
2286 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2287 if (ExitBr == 0) return UnknownValue;
2288 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2290 // At this point, we know we have a conditional branch that determines whether
2291 // the loop is exited. However, we don't know if the branch is executed each
2292 // time through the loop. If not, then the execution count of the branch will
2293 // not be equal to the trip count of the loop.
2295 // Currently we check for this by checking to see if the Exit branch goes to
2296 // the loop header. If so, we know it will always execute the same number of
2297 // times as the loop. We also handle the case where the exit block *is* the
2298 // loop header. This is common for un-rotated loops. More extensive analysis
2299 // could be done to handle more cases here.
2300 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2301 ExitBr->getSuccessor(1) != L->getHeader() &&
2302 ExitBr->getParent() != L->getHeader())
2303 return UnknownValue;
2305 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2307 // If it's not an integer comparison then compute it the hard way.
2308 // Note that ICmpInst deals with pointer comparisons too so we must check
2309 // the type of the operand.
2310 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2311 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2312 ExitBr->getSuccessor(0) == ExitBlock);
2314 // If the condition was exit on true, convert the condition to exit on false
2315 ICmpInst::Predicate Cond;
2316 if (ExitBr->getSuccessor(1) == ExitBlock)
2317 Cond = ExitCond->getPredicate();
2319 Cond = ExitCond->getInversePredicate();
2321 // Handle common loops like: for (X = "string"; *X; ++X)
2322 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2323 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2325 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2326 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2329 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2330 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2332 // Try to evaluate any dependencies out of the loop.
2333 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2334 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2335 Tmp = getSCEVAtScope(RHS, L);
2336 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2338 // At this point, we would like to compute how many iterations of the
2339 // loop the predicate will return true for these inputs.
2340 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2341 // If there is a loop-invariant, force it into the RHS.
2342 std::swap(LHS, RHS);
2343 Cond = ICmpInst::getSwappedPredicate(Cond);
2346 // If we have a comparison of a chrec against a constant, try to use value
2347 // ranges to answer this query.
2348 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2349 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2350 if (AddRec->getLoop() == L) {
2351 // Form the comparison range using the constant of the correct type so
2352 // that the ConstantRange class knows to do a signed or unsigned
2354 ConstantInt *CompVal = RHSC->getValue();
2355 const Type *RealTy = ExitCond->getOperand(0)->getType();
2356 CompVal = dyn_cast<ConstantInt>(
2357 ConstantExpr::getBitCast(CompVal, RealTy));
2359 // Form the constant range.
2360 ConstantRange CompRange(
2361 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2363 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2364 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2369 case ICmpInst::ICMP_NE: { // while (X != Y)
2370 // Convert to: while (X-Y != 0)
2371 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2372 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2375 case ICmpInst::ICMP_EQ: {
2376 // Convert to: while (X-Y == 0) // while (X == Y)
2377 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2378 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2381 case ICmpInst::ICMP_SLT: {
2382 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2383 if (BTI.hasAnyInfo()) return BTI;
2386 case ICmpInst::ICMP_SGT: {
2387 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2388 getNotSCEV(RHS), L, true);
2389 if (BTI.hasAnyInfo()) return BTI;
2392 case ICmpInst::ICMP_ULT: {
2393 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2394 if (BTI.hasAnyInfo()) return BTI;
2397 case ICmpInst::ICMP_UGT: {
2398 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2399 getNotSCEV(RHS), L, false);
2400 if (BTI.hasAnyInfo()) return BTI;
2405 errs() << "ComputeBackedgeTakenCount ";
2406 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2407 errs() << "[unsigned] ";
2408 errs() << *LHS << " "
2409 << Instruction::getOpcodeName(Instruction::ICmp)
2410 << " " << *RHS << "\n";
2415 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2416 ExitBr->getSuccessor(0) == ExitBlock);
2419 static ConstantInt *
2420 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2421 ScalarEvolution &SE) {
2422 SCEVHandle InVal = SE.getConstant(C);
2423 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2424 assert(isa<SCEVConstant>(Val) &&
2425 "Evaluation of SCEV at constant didn't fold correctly?");
2426 return cast<SCEVConstant>(Val)->getValue();
2429 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2430 /// and a GEP expression (missing the pointer index) indexing into it, return
2431 /// the addressed element of the initializer or null if the index expression is
2434 GetAddressedElementFromGlobal(GlobalVariable *GV,
2435 const std::vector<ConstantInt*> &Indices) {
2436 Constant *Init = GV->getInitializer();
2437 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2438 uint64_t Idx = Indices[i]->getZExtValue();
2439 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2440 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2441 Init = cast<Constant>(CS->getOperand(Idx));
2442 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2443 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2444 Init = cast<Constant>(CA->getOperand(Idx));
2445 } else if (isa<ConstantAggregateZero>(Init)) {
2446 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2447 assert(Idx < STy->getNumElements() && "Bad struct index!");
2448 Init = Constant::getNullValue(STy->getElementType(Idx));
2449 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2450 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2451 Init = Constant::getNullValue(ATy->getElementType());
2453 assert(0 && "Unknown constant aggregate type!");
2457 return 0; // Unknown initializer type
2463 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2464 /// 'icmp op load X, cst', try to see if we can compute the backedge
2465 /// execution count.
2466 SCEVHandle ScalarEvolution::
2467 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2469 ICmpInst::Predicate predicate) {
2470 if (LI->isVolatile()) return UnknownValue;
2472 // Check to see if the loaded pointer is a getelementptr of a global.
2473 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2474 if (!GEP) return UnknownValue;
2476 // Make sure that it is really a constant global we are gepping, with an
2477 // initializer, and make sure the first IDX is really 0.
2478 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2479 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2480 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2481 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2482 return UnknownValue;
2484 // Okay, we allow one non-constant index into the GEP instruction.
2486 std::vector<ConstantInt*> Indexes;
2487 unsigned VarIdxNum = 0;
2488 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2489 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2490 Indexes.push_back(CI);
2491 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2492 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2493 VarIdx = GEP->getOperand(i);
2495 Indexes.push_back(0);
2498 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2499 // Check to see if X is a loop variant variable value now.
2500 SCEVHandle Idx = getSCEV(VarIdx);
2501 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2502 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2504 // We can only recognize very limited forms of loop index expressions, in
2505 // particular, only affine AddRec's like {C1,+,C2}.
2506 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2507 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2508 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2509 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2510 return UnknownValue;
2512 unsigned MaxSteps = MaxBruteForceIterations;
2513 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2514 ConstantInt *ItCst =
2515 ConstantInt::get(IdxExpr->getType(), IterationNum);
2516 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2518 // Form the GEP offset.
2519 Indexes[VarIdxNum] = Val;
2521 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2522 if (Result == 0) break; // Cannot compute!
2524 // Evaluate the condition for this iteration.
2525 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2526 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2527 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2529 errs() << "\n***\n*** Computed loop count " << *ItCst
2530 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2533 ++NumArrayLenItCounts;
2534 return getConstant(ItCst); // Found terminating iteration!
2537 return UnknownValue;
2541 /// CanConstantFold - Return true if we can constant fold an instruction of the
2542 /// specified type, assuming that all operands were constants.
2543 static bool CanConstantFold(const Instruction *I) {
2544 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2545 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2548 if (const CallInst *CI = dyn_cast<CallInst>(I))
2549 if (const Function *F = CI->getCalledFunction())
2550 return canConstantFoldCallTo(F);
2554 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2555 /// in the loop that V is derived from. We allow arbitrary operations along the
2556 /// way, but the operands of an operation must either be constants or a value
2557 /// derived from a constant PHI. If this expression does not fit with these
2558 /// constraints, return null.
2559 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2560 // If this is not an instruction, or if this is an instruction outside of the
2561 // loop, it can't be derived from a loop PHI.
2562 Instruction *I = dyn_cast<Instruction>(V);
2563 if (I == 0 || !L->contains(I->getParent())) return 0;
2565 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2566 if (L->getHeader() == I->getParent())
2569 // We don't currently keep track of the control flow needed to evaluate
2570 // PHIs, so we cannot handle PHIs inside of loops.
2574 // If we won't be able to constant fold this expression even if the operands
2575 // are constants, return early.
2576 if (!CanConstantFold(I)) return 0;
2578 // Otherwise, we can evaluate this instruction if all of its operands are
2579 // constant or derived from a PHI node themselves.
2581 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2582 if (!(isa<Constant>(I->getOperand(Op)) ||
2583 isa<GlobalValue>(I->getOperand(Op)))) {
2584 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2585 if (P == 0) return 0; // Not evolving from PHI
2589 return 0; // Evolving from multiple different PHIs.
2592 // This is a expression evolving from a constant PHI!
2596 /// EvaluateExpression - Given an expression that passes the
2597 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2598 /// in the loop has the value PHIVal. If we can't fold this expression for some
2599 /// reason, return null.
2600 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2601 if (isa<PHINode>(V)) return PHIVal;
2602 if (Constant *C = dyn_cast<Constant>(V)) return C;
2603 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2604 Instruction *I = cast<Instruction>(V);
2606 std::vector<Constant*> Operands;
2607 Operands.resize(I->getNumOperands());
2609 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2610 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2611 if (Operands[i] == 0) return 0;
2614 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2615 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2616 &Operands[0], Operands.size());
2618 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2619 &Operands[0], Operands.size());
2622 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2623 /// in the header of its containing loop, we know the loop executes a
2624 /// constant number of times, and the PHI node is just a recurrence
2625 /// involving constants, fold it.
2626 Constant *ScalarEvolution::
2627 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2628 std::map<PHINode*, Constant*>::iterator I =
2629 ConstantEvolutionLoopExitValue.find(PN);
2630 if (I != ConstantEvolutionLoopExitValue.end())
2633 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2634 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2636 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2638 // Since the loop is canonicalized, the PHI node must have two entries. One
2639 // entry must be a constant (coming in from outside of the loop), and the
2640 // second must be derived from the same PHI.
2641 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2642 Constant *StartCST =
2643 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2645 return RetVal = 0; // Must be a constant.
2647 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2648 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2650 return RetVal = 0; // Not derived from same PHI.
2652 // Execute the loop symbolically to determine the exit value.
2653 if (BEs.getActiveBits() >= 32)
2654 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2656 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2657 unsigned IterationNum = 0;
2658 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2659 if (IterationNum == NumIterations)
2660 return RetVal = PHIVal; // Got exit value!
2662 // Compute the value of the PHI node for the next iteration.
2663 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2664 if (NextPHI == PHIVal)
2665 return RetVal = NextPHI; // Stopped evolving!
2667 return 0; // Couldn't evaluate!
2672 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2673 /// constant number of times (the condition evolves only from constants),
2674 /// try to evaluate a few iterations of the loop until we get the exit
2675 /// condition gets a value of ExitWhen (true or false). If we cannot
2676 /// evaluate the trip count of the loop, return UnknownValue.
2677 SCEVHandle ScalarEvolution::
2678 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2679 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2680 if (PN == 0) return UnknownValue;
2682 // Since the loop is canonicalized, the PHI node must have two entries. One
2683 // entry must be a constant (coming in from outside of the loop), and the
2684 // second must be derived from the same PHI.
2685 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2686 Constant *StartCST =
2687 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2688 if (StartCST == 0) return UnknownValue; // Must be a constant.
2690 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2691 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2692 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2694 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2695 // the loop symbolically to determine when the condition gets a value of
2697 unsigned IterationNum = 0;
2698 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2699 for (Constant *PHIVal = StartCST;
2700 IterationNum != MaxIterations; ++IterationNum) {
2701 ConstantInt *CondVal =
2702 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2704 // Couldn't symbolically evaluate.
2705 if (!CondVal) return UnknownValue;
2707 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2708 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2709 ++NumBruteForceTripCountsComputed;
2710 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2713 // Compute the value of the PHI node for the next iteration.
2714 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2715 if (NextPHI == 0 || NextPHI == PHIVal)
2716 return UnknownValue; // Couldn't evaluate or not making progress...
2720 // Too many iterations were needed to evaluate.
2721 return UnknownValue;
2724 /// getSCEVAtScope - Compute the value of the specified expression within the
2725 /// indicated loop (which may be null to indicate in no loop). If the
2726 /// expression cannot be evaluated, return UnknownValue.
2727 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
2728 // FIXME: this should be turned into a virtual method on SCEV!
2730 if (isa<SCEVConstant>(V)) return V;
2732 // If this instruction is evolved from a constant-evolving PHI, compute the
2733 // exit value from the loop without using SCEVs.
2734 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2735 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2736 const Loop *LI = (*this->LI)[I->getParent()];
2737 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2738 if (PHINode *PN = dyn_cast<PHINode>(I))
2739 if (PN->getParent() == LI->getHeader()) {
2740 // Okay, there is no closed form solution for the PHI node. Check
2741 // to see if the loop that contains it has a known backedge-taken
2742 // count. If so, we may be able to force computation of the exit
2744 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2745 if (const SCEVConstant *BTCC =
2746 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2747 // Okay, we know how many times the containing loop executes. If
2748 // this is a constant evolving PHI node, get the final value at
2749 // the specified iteration number.
2750 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2751 BTCC->getValue()->getValue(),
2753 if (RV) return getUnknown(RV);
2757 // Okay, this is an expression that we cannot symbolically evaluate
2758 // into a SCEV. Check to see if it's possible to symbolically evaluate
2759 // the arguments into constants, and if so, try to constant propagate the
2760 // result. This is particularly useful for computing loop exit values.
2761 if (CanConstantFold(I)) {
2762 std::vector<Constant*> Operands;
2763 Operands.reserve(I->getNumOperands());
2764 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2765 Value *Op = I->getOperand(i);
2766 if (Constant *C = dyn_cast<Constant>(Op)) {
2767 Operands.push_back(C);
2769 // If any of the operands is non-constant and if they are
2770 // non-integer and non-pointer, don't even try to analyze them
2771 // with scev techniques.
2772 if (!isSCEVable(Op->getType()))
2775 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2776 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2777 Constant *C = SC->getValue();
2778 if (C->getType() != Op->getType())
2779 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2783 Operands.push_back(C);
2784 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2785 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2786 if (C->getType() != Op->getType())
2788 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2792 Operands.push_back(C);
2802 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2803 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2804 &Operands[0], Operands.size());
2806 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2807 &Operands[0], Operands.size());
2808 return getUnknown(C);
2812 // This is some other type of SCEVUnknown, just return it.
2816 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2817 // Avoid performing the look-up in the common case where the specified
2818 // expression has no loop-variant portions.
2819 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2820 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2821 if (OpAtScope != Comm->getOperand(i)) {
2822 if (OpAtScope == UnknownValue) return UnknownValue;
2823 // Okay, at least one of these operands is loop variant but might be
2824 // foldable. Build a new instance of the folded commutative expression.
2825 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2826 NewOps.push_back(OpAtScope);
2828 for (++i; i != e; ++i) {
2829 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2830 if (OpAtScope == UnknownValue) return UnknownValue;
2831 NewOps.push_back(OpAtScope);
2833 if (isa<SCEVAddExpr>(Comm))
2834 return getAddExpr(NewOps);
2835 if (isa<SCEVMulExpr>(Comm))
2836 return getMulExpr(NewOps);
2837 if (isa<SCEVSMaxExpr>(Comm))
2838 return getSMaxExpr(NewOps);
2839 if (isa<SCEVUMaxExpr>(Comm))
2840 return getUMaxExpr(NewOps);
2841 assert(0 && "Unknown commutative SCEV type!");
2844 // If we got here, all operands are loop invariant.
2848 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2849 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2850 if (LHS == UnknownValue) return LHS;
2851 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2852 if (RHS == UnknownValue) return RHS;
2853 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2854 return Div; // must be loop invariant
2855 return getUDivExpr(LHS, RHS);
2858 // If this is a loop recurrence for a loop that does not contain L, then we
2859 // are dealing with the final value computed by the loop.
2860 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2861 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2862 // To evaluate this recurrence, we need to know how many times the AddRec
2863 // loop iterates. Compute this now.
2864 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2865 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2867 // Then, evaluate the AddRec.
2868 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
2870 return UnknownValue;
2873 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2874 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2875 if (Op == UnknownValue) return Op;
2876 if (Op == Cast->getOperand())
2877 return Cast; // must be loop invariant
2878 return getZeroExtendExpr(Op, Cast->getType());
2881 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2882 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2883 if (Op == UnknownValue) return Op;
2884 if (Op == Cast->getOperand())
2885 return Cast; // must be loop invariant
2886 return getSignExtendExpr(Op, Cast->getType());
2889 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2890 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2891 if (Op == UnknownValue) return Op;
2892 if (Op == Cast->getOperand())
2893 return Cast; // must be loop invariant
2894 return getTruncateExpr(Op, Cast->getType());
2897 assert(0 && "Unknown SCEV type!");
2900 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
2901 /// at the specified scope in the program. The L value specifies a loop
2902 /// nest to evaluate the expression at, where null is the top-level or a
2903 /// specified loop is immediately inside of the loop.
2905 /// This method can be used to compute the exit value for a variable defined
2906 /// in a loop by querying what the value will hold in the parent loop.
2908 /// If this value is not computable at this scope, a SCEVCouldNotCompute
2909 /// object is returned.
2910 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2911 return getSCEVAtScope(getSCEV(V), L);
2914 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2915 /// following equation:
2917 /// A * X = B (mod N)
2919 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2920 /// A and B isn't important.
2922 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2923 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2924 ScalarEvolution &SE) {
2925 uint32_t BW = A.getBitWidth();
2926 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2927 assert(A != 0 && "A must be non-zero.");
2931 // The gcd of A and N may have only one prime factor: 2. The number of
2932 // trailing zeros in A is its multiplicity
2933 uint32_t Mult2 = A.countTrailingZeros();
2936 // 2. Check if B is divisible by D.
2938 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2939 // is not less than multiplicity of this prime factor for D.
2940 if (B.countTrailingZeros() < Mult2)
2941 return SE.getCouldNotCompute();
2943 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2946 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2947 // bit width during computations.
2948 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2949 APInt Mod(BW + 1, 0);
2950 Mod.set(BW - Mult2); // Mod = N / D
2951 APInt I = AD.multiplicativeInverse(Mod);
2953 // 4. Compute the minimum unsigned root of the equation:
2954 // I * (B / D) mod (N / D)
2955 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2957 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2959 return SE.getConstant(Result.trunc(BW));
2962 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2963 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2964 /// might be the same) or two SCEVCouldNotCompute objects.
2966 static std::pair<SCEVHandle,SCEVHandle>
2967 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2968 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2969 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2970 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2971 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2973 // We currently can only solve this if the coefficients are constants.
2974 if (!LC || !MC || !NC) {
2975 const SCEV *CNC = SE.getCouldNotCompute();
2976 return std::make_pair(CNC, CNC);
2979 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2980 const APInt &L = LC->getValue()->getValue();
2981 const APInt &M = MC->getValue()->getValue();
2982 const APInt &N = NC->getValue()->getValue();
2983 APInt Two(BitWidth, 2);
2984 APInt Four(BitWidth, 4);
2987 using namespace APIntOps;
2989 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2990 // The B coefficient is M-N/2
2994 // The A coefficient is N/2
2995 APInt A(N.sdiv(Two));
2997 // Compute the B^2-4ac term.
3000 SqrtTerm -= Four * (A * C);
3002 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3003 // integer value or else APInt::sqrt() will assert.
3004 APInt SqrtVal(SqrtTerm.sqrt());
3006 // Compute the two solutions for the quadratic formula.
3007 // The divisions must be performed as signed divisions.
3009 APInt TwoA( A << 1 );
3010 if (TwoA.isMinValue()) {
3011 const SCEV *CNC = SE.getCouldNotCompute();
3012 return std::make_pair(CNC, CNC);
3015 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3016 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3018 return std::make_pair(SE.getConstant(Solution1),
3019 SE.getConstant(Solution2));
3020 } // end APIntOps namespace
3023 /// HowFarToZero - Return the number of times a backedge comparing the specified
3024 /// value to zero will execute. If not computable, return UnknownValue
3025 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3026 // If the value is a constant
3027 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3028 // If the value is already zero, the branch will execute zero times.
3029 if (C->getValue()->isZero()) return C;
3030 return UnknownValue; // Otherwise it will loop infinitely.
3033 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3034 if (!AddRec || AddRec->getLoop() != L)
3035 return UnknownValue;
3037 if (AddRec->isAffine()) {
3038 // If this is an affine expression, the execution count of this branch is
3039 // the minimum unsigned root of the following equation:
3041 // Start + Step*N = 0 (mod 2^BW)
3045 // Step*N = -Start (mod 2^BW)
3047 // where BW is the common bit width of Start and Step.
3049 // Get the initial value for the loop.
3050 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3051 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
3053 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
3055 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3056 // For now we handle only constant steps.
3058 // First, handle unitary steps.
3059 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3060 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3061 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3062 return Start; // N = Start (as unsigned)
3064 // Then, try to solve the above equation provided that Start is constant.
3065 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3066 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3067 -StartC->getValue()->getValue(),
3070 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3071 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3072 // the quadratic equation to solve it.
3073 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3075 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3076 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3079 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3080 << " sol#2: " << *R2 << "\n";
3082 // Pick the smallest positive root value.
3083 if (ConstantInt *CB =
3084 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3085 R1->getValue(), R2->getValue()))) {
3086 if (CB->getZExtValue() == false)
3087 std::swap(R1, R2); // R1 is the minimum root now.
3089 // We can only use this value if the chrec ends up with an exact zero
3090 // value at this index. When solving for "X*X != 5", for example, we
3091 // should not accept a root of 2.
3092 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3094 return R1; // We found a quadratic root!
3099 return UnknownValue;
3102 /// HowFarToNonZero - Return the number of times a backedge checking the
3103 /// specified value for nonzero will execute. If not computable, return
3105 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3106 // Loops that look like: while (X == 0) are very strange indeed. We don't
3107 // handle them yet except for the trivial case. This could be expanded in the
3108 // future as needed.
3110 // If the value is a constant, check to see if it is known to be non-zero
3111 // already. If so, the backedge will execute zero times.
3112 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3113 if (!C->getValue()->isNullValue())
3114 return getIntegerSCEV(0, C->getType());
3115 return UnknownValue; // Otherwise it will loop infinitely.
3118 // We could implement others, but I really doubt anyone writes loops like
3119 // this, and if they did, they would already be constant folded.
3120 return UnknownValue;
3123 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3124 /// (which may not be an immediate predecessor) which has exactly one
3125 /// successor from which BB is reachable, or null if no such block is
3129 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3130 // If the block has a unique predecessor, then there is no path from the
3131 // predecessor to the block that does not go through the direct edge
3132 // from the predecessor to the block.
3133 if (BasicBlock *Pred = BB->getSinglePredecessor())
3136 // A loop's header is defined to be a block that dominates the loop.
3137 // If the loop has a preheader, it must be a block that has exactly
3138 // one successor that can reach BB. This is slightly more strict
3139 // than necessary, but works if critical edges are split.
3140 if (Loop *L = LI->getLoopFor(BB))
3141 return L->getLoopPreheader();
3146 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3147 /// a conditional between LHS and RHS. This is used to help avoid max
3148 /// expressions in loop trip counts.
3149 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3150 ICmpInst::Predicate Pred,
3151 const SCEV *LHS, const SCEV *RHS) {
3152 BasicBlock *Preheader = L->getLoopPreheader();
3153 BasicBlock *PreheaderDest = L->getHeader();
3155 // Starting at the preheader, climb up the predecessor chain, as long as
3156 // there are predecessors that can be found that have unique successors
3157 // leading to the original header.
3159 PreheaderDest = Preheader,
3160 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
3162 BranchInst *LoopEntryPredicate =
3163 dyn_cast<BranchInst>(Preheader->getTerminator());
3164 if (!LoopEntryPredicate ||
3165 LoopEntryPredicate->isUnconditional())
3168 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3171 // Now that we found a conditional branch that dominates the loop, check to
3172 // see if it is the comparison we are looking for.
3173 Value *PreCondLHS = ICI->getOperand(0);
3174 Value *PreCondRHS = ICI->getOperand(1);
3175 ICmpInst::Predicate Cond;
3176 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3177 Cond = ICI->getPredicate();
3179 Cond = ICI->getInversePredicate();
3182 ; // An exact match.
3183 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3184 ; // The actual condition is beyond sufficient.
3186 // Check a few special cases.
3188 case ICmpInst::ICMP_UGT:
3189 if (Pred == ICmpInst::ICMP_ULT) {
3190 std::swap(PreCondLHS, PreCondRHS);
3191 Cond = ICmpInst::ICMP_ULT;
3195 case ICmpInst::ICMP_SGT:
3196 if (Pred == ICmpInst::ICMP_SLT) {
3197 std::swap(PreCondLHS, PreCondRHS);
3198 Cond = ICmpInst::ICMP_SLT;
3202 case ICmpInst::ICMP_NE:
3203 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3204 // so check for this case by checking if the NE is comparing against
3205 // a minimum or maximum constant.
3206 if (!ICmpInst::isTrueWhenEqual(Pred))
3207 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3208 const APInt &A = CI->getValue();
3210 case ICmpInst::ICMP_SLT:
3211 if (A.isMaxSignedValue()) break;
3213 case ICmpInst::ICMP_SGT:
3214 if (A.isMinSignedValue()) break;
3216 case ICmpInst::ICMP_ULT:
3217 if (A.isMaxValue()) break;
3219 case ICmpInst::ICMP_UGT:
3220 if (A.isMinValue()) break;
3225 Cond = ICmpInst::ICMP_NE;
3226 // NE is symmetric but the original comparison may not be. Swap
3227 // the operands if necessary so that they match below.
3228 if (isa<SCEVConstant>(LHS))
3229 std::swap(PreCondLHS, PreCondRHS);
3234 // We weren't able to reconcile the condition.
3238 if (!PreCondLHS->getType()->isInteger()) continue;
3240 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3241 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3242 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3243 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3244 RHS == getNotSCEV(PreCondLHSSCEV)))
3251 /// HowManyLessThans - Return the number of times a backedge containing the
3252 /// specified less-than comparison will execute. If not computable, return
3254 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
3255 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3256 const Loop *L, bool isSigned) {
3257 // Only handle: "ADDREC < LoopInvariant".
3258 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3260 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3261 if (!AddRec || AddRec->getLoop() != L)
3262 return UnknownValue;
3264 if (AddRec->isAffine()) {
3265 // FORNOW: We only support unit strides.
3266 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3267 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3268 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3270 // TODO: handle non-constant strides.
3271 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3272 if (!CStep || CStep->isZero())
3273 return UnknownValue;
3274 if (CStep->getValue()->getValue() == 1) {
3275 // With unit stride, the iteration never steps past the limit value.
3276 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3277 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3278 // Test whether a positive iteration iteration can step past the limit
3279 // value and past the maximum value for its type in a single step.
3281 APInt Max = APInt::getSignedMaxValue(BitWidth);
3282 if ((Max - CStep->getValue()->getValue())
3283 .slt(CLimit->getValue()->getValue()))
3284 return UnknownValue;
3286 APInt Max = APInt::getMaxValue(BitWidth);
3287 if ((Max - CStep->getValue()->getValue())
3288 .ult(CLimit->getValue()->getValue()))
3289 return UnknownValue;
3292 // TODO: handle non-constant limit values below.
3293 return UnknownValue;
3295 // TODO: handle negative strides below.
3296 return UnknownValue;
3298 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3299 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3300 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
3301 // treat m-n as signed nor unsigned due to overflow possibility.
3303 // First, we get the value of the LHS in the first iteration: n
3304 SCEVHandle Start = AddRec->getOperand(0);
3306 // Determine the minimum constant start value.
3307 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3308 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3309 APInt::getMinValue(BitWidth));
3311 // If we know that the condition is true in order to enter the loop,
3312 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3313 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3314 // division must round up.
3315 SCEVHandle End = RHS;
3316 if (!isLoopGuardedByCond(L,
3317 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3318 getMinusSCEV(Start, Step), RHS))
3319 End = isSigned ? getSMaxExpr(RHS, Start)
3320 : getUMaxExpr(RHS, Start);
3322 // Determine the maximum constant end value.
3323 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3324 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3325 APInt::getMaxValue(BitWidth));
3327 // Finally, we subtract these two values and divide, rounding up, to get
3328 // the number of times the backedge is executed.
3329 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3330 getAddExpr(Step, NegOne)),
3333 // The maximum backedge count is similar, except using the minimum start
3334 // value and the maximum end value.
3335 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3337 getAddExpr(Step, NegOne)),
3340 return BackedgeTakenInfo(BECount, MaxBECount);
3343 return UnknownValue;
3346 /// getNumIterationsInRange - Return the number of iterations of this loop that
3347 /// produce values in the specified constant range. Another way of looking at
3348 /// this is that it returns the first iteration number where the value is not in
3349 /// the condition, thus computing the exit count. If the iteration count can't
3350 /// be computed, an instance of SCEVCouldNotCompute is returned.
3351 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3352 ScalarEvolution &SE) const {
3353 if (Range.isFullSet()) // Infinite loop.
3354 return SE.getCouldNotCompute();
3356 // If the start is a non-zero constant, shift the range to simplify things.
3357 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3358 if (!SC->getValue()->isZero()) {
3359 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3360 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3361 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3362 if (const SCEVAddRecExpr *ShiftedAddRec =
3363 dyn_cast<SCEVAddRecExpr>(Shifted))
3364 return ShiftedAddRec->getNumIterationsInRange(
3365 Range.subtract(SC->getValue()->getValue()), SE);
3366 // This is strange and shouldn't happen.
3367 return SE.getCouldNotCompute();
3370 // The only time we can solve this is when we have all constant indices.
3371 // Otherwise, we cannot determine the overflow conditions.
3372 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3373 if (!isa<SCEVConstant>(getOperand(i)))
3374 return SE.getCouldNotCompute();
3377 // Okay at this point we know that all elements of the chrec are constants and
3378 // that the start element is zero.
3380 // First check to see if the range contains zero. If not, the first
3382 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3383 if (!Range.contains(APInt(BitWidth, 0)))
3384 return SE.getConstant(ConstantInt::get(getType(),0));
3387 // If this is an affine expression then we have this situation:
3388 // Solve {0,+,A} in Range === Ax in Range
3390 // We know that zero is in the range. If A is positive then we know that
3391 // the upper value of the range must be the first possible exit value.
3392 // If A is negative then the lower of the range is the last possible loop
3393 // value. Also note that we already checked for a full range.
3394 APInt One(BitWidth,1);
3395 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3396 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3398 // The exit value should be (End+A)/A.
3399 APInt ExitVal = (End + A).udiv(A);
3400 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3402 // Evaluate at the exit value. If we really did fall out of the valid
3403 // range, then we computed our trip count, otherwise wrap around or other
3404 // things must have happened.
3405 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3406 if (Range.contains(Val->getValue()))
3407 return SE.getCouldNotCompute(); // Something strange happened
3409 // Ensure that the previous value is in the range. This is a sanity check.
3410 assert(Range.contains(
3411 EvaluateConstantChrecAtConstant(this,
3412 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3413 "Linear scev computation is off in a bad way!");
3414 return SE.getConstant(ExitValue);
3415 } else if (isQuadratic()) {
3416 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3417 // quadratic equation to solve it. To do this, we must frame our problem in
3418 // terms of figuring out when zero is crossed, instead of when
3419 // Range.getUpper() is crossed.
3420 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3421 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3422 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3424 // Next, solve the constructed addrec
3425 std::pair<SCEVHandle,SCEVHandle> Roots =
3426 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3427 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3428 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3430 // Pick the smallest positive root value.
3431 if (ConstantInt *CB =
3432 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3433 R1->getValue(), R2->getValue()))) {
3434 if (CB->getZExtValue() == false)
3435 std::swap(R1, R2); // R1 is the minimum root now.
3437 // Make sure the root is not off by one. The returned iteration should
3438 // not be in the range, but the previous one should be. When solving
3439 // for "X*X < 5", for example, we should not return a root of 2.
3440 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3443 if (Range.contains(R1Val->getValue())) {
3444 // The next iteration must be out of the range...
3445 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3447 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3448 if (!Range.contains(R1Val->getValue()))
3449 return SE.getConstant(NextVal);
3450 return SE.getCouldNotCompute(); // Something strange happened
3453 // If R1 was not in the range, then it is a good return value. Make
3454 // sure that R1-1 WAS in the range though, just in case.
3455 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3456 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3457 if (Range.contains(R1Val->getValue()))
3459 return SE.getCouldNotCompute(); // Something strange happened
3464 return SE.getCouldNotCompute();
3469 //===----------------------------------------------------------------------===//
3470 // SCEVCallbackVH Class Implementation
3471 //===----------------------------------------------------------------------===//
3473 void SCEVCallbackVH::deleted() {
3474 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3475 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3476 SE->ConstantEvolutionLoopExitValue.erase(PN);
3477 SE->Scalars.erase(getValPtr());
3478 // this now dangles!
3481 void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3482 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3484 // Forget all the expressions associated with users of the old value,
3485 // so that future queries will recompute the expressions using the new
3487 SmallVector<User *, 16> Worklist;
3488 Value *Old = getValPtr();
3489 bool DeleteOld = false;
3490 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3492 Worklist.push_back(*UI);
3493 while (!Worklist.empty()) {
3494 User *U = Worklist.pop_back_val();
3495 // Deleting the Old value will cause this to dangle. Postpone
3496 // that until everything else is done.
3501 if (PHINode *PN = dyn_cast<PHINode>(U))
3502 SE->ConstantEvolutionLoopExitValue.erase(PN);
3503 if (SE->Scalars.erase(U))
3504 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3506 Worklist.push_back(*UI);
3509 if (PHINode *PN = dyn_cast<PHINode>(Old))
3510 SE->ConstantEvolutionLoopExitValue.erase(PN);
3511 SE->Scalars.erase(Old);
3512 // this now dangles!
3517 SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3518 : CallbackVH(V), SE(se) {}
3520 //===----------------------------------------------------------------------===//
3521 // ScalarEvolution Class Implementation
3522 //===----------------------------------------------------------------------===//
3524 ScalarEvolution::ScalarEvolution()
3525 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3528 bool ScalarEvolution::runOnFunction(Function &F) {
3530 LI = &getAnalysis<LoopInfo>();
3531 TD = getAnalysisIfAvailable<TargetData>();
3535 void ScalarEvolution::releaseMemory() {
3537 BackedgeTakenCounts.clear();
3538 ConstantEvolutionLoopExitValue.clear();
3541 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3542 AU.setPreservesAll();
3543 AU.addRequiredTransitive<LoopInfo>();
3546 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3547 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3550 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3552 // Print all inner loops first
3553 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3554 PrintLoopInfo(OS, SE, *I);
3556 OS << "Loop " << L->getHeader()->getName() << ": ";
3558 SmallVector<BasicBlock*, 8> ExitBlocks;
3559 L->getExitBlocks(ExitBlocks);
3560 if (ExitBlocks.size() != 1)
3561 OS << "<multiple exits> ";
3563 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3564 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3566 OS << "Unpredictable backedge-taken count. ";
3572 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3573 // ScalarEvolution's implementaiton of the print method is to print
3574 // out SCEV values of all instructions that are interesting. Doing
3575 // this potentially causes it to create new SCEV objects though,
3576 // which technically conflicts with the const qualifier. This isn't
3577 // observable from outside the class though (the hasSCEV function
3578 // notwithstanding), so casting away the const isn't dangerous.
3579 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3581 OS << "Classifying expressions for: " << F->getName() << "\n";
3582 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3583 if (isSCEVable(I->getType())) {
3586 SCEVHandle SV = SE.getSCEV(&*I);
3590 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
3592 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
3593 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3594 OS << "<<Unknown>>";
3604 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3605 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3606 PrintLoopInfo(OS, &SE, *I);
3609 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3610 raw_os_ostream OS(o);