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 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
752 return getAddRecExpr(Operands, AddRec->getLoop());
755 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
756 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
760 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
763 "This is not an extending conversion!");
764 assert(isSCEVable(Ty) &&
765 "This is not a conversion to a SCEVable type!");
766 Ty = getEffectiveSCEVType(Ty);
768 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
769 const Type *IntTy = getEffectiveSCEVType(Ty);
770 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
771 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
772 return getUnknown(C);
775 // zext(zext(x)) --> zext(x)
776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
777 return getZeroExtendExpr(SZ->getOperand(), Ty);
779 // If the input value is a chrec scev, and we can prove that the value
780 // did not overflow the old, smaller, value, we can zero extend all of the
781 // operands (often constants). This allows analysis of something like
782 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
784 if (AR->isAffine()) {
785 // Check whether the backedge-taken count is SCEVCouldNotCompute.
786 // Note that this serves two purposes: It filters out loops that are
787 // simply not analyzable, and it covers the case where this code is
788 // being called from within backedge-taken count analysis, such that
789 // attempting to ask for the backedge-taken count would likely result
790 // in infinite recursion. In the later case, the analysis code will
791 // cope with a conservative value, and it will take care to purge
792 // that value once it has finished.
793 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
794 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
795 // Manually compute the final value for AR, checking for
797 SCEVHandle Start = AR->getStart();
798 SCEVHandle Step = AR->getStepRecurrence(*this);
800 // Check whether the backedge-taken count can be losslessly casted to
801 // the addrec's type. The count is always unsigned.
802 SCEVHandle CastedMaxBECount =
803 getTruncateOrZeroExtend(MaxBECount, Start->getType());
805 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
807 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
808 // Check whether Start+Step*MaxBECount has no unsigned overflow.
810 getMulExpr(CastedMaxBECount,
811 getTruncateOrZeroExtend(Step, Start->getType()));
812 SCEVHandle Add = getAddExpr(Start, ZMul);
813 if (getZeroExtendExpr(Add, WideTy) ==
814 getAddExpr(getZeroExtendExpr(Start, WideTy),
815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
816 getZeroExtendExpr(Step, WideTy))))
817 // Return the expression with the addrec on the outside.
818 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
819 getZeroExtendExpr(Step, Ty),
822 // Similar to above, only this time treat the step value as signed.
823 // This covers loops that count down.
825 getMulExpr(CastedMaxBECount,
826 getTruncateOrSignExtend(Step, Start->getType()));
827 Add = getAddExpr(Start, SMul);
828 if (getZeroExtendExpr(Add, WideTy) ==
829 getAddExpr(getZeroExtendExpr(Start, WideTy),
830 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
831 getSignExtendExpr(Step, WideTy))))
832 // Return the expression with the addrec on the outside.
833 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
834 getSignExtendExpr(Step, Ty),
840 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
841 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
845 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
848 "This is not an extending conversion!");
849 assert(isSCEVable(Ty) &&
850 "This is not a conversion to a SCEVable type!");
851 Ty = getEffectiveSCEVType(Ty);
853 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
854 const Type *IntTy = getEffectiveSCEVType(Ty);
855 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
856 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
857 return getUnknown(C);
860 // sext(sext(x)) --> sext(x)
861 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
862 return getSignExtendExpr(SS->getOperand(), Ty);
864 // If the input value is a chrec scev, and we can prove that the value
865 // did not overflow the old, smaller, value, we can sign extend all of the
866 // operands (often constants). This allows analysis of something like
867 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
869 if (AR->isAffine()) {
870 // Check whether the backedge-taken count is SCEVCouldNotCompute.
871 // Note that this serves two purposes: It filters out loops that are
872 // simply not analyzable, and it covers the case where this code is
873 // being called from within backedge-taken count analysis, such that
874 // attempting to ask for the backedge-taken count would likely result
875 // in infinite recursion. In the later case, the analysis code will
876 // cope with a conservative value, and it will take care to purge
877 // that value once it has finished.
878 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
879 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
880 // Manually compute the final value for AR, checking for
882 SCEVHandle Start = AR->getStart();
883 SCEVHandle Step = AR->getStepRecurrence(*this);
885 // Check whether the backedge-taken count can be losslessly casted to
886 // the addrec's type. The count is always unsigned.
887 SCEVHandle CastedMaxBECount =
888 getTruncateOrZeroExtend(MaxBECount, Start->getType());
890 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
892 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
893 // Check whether Start+Step*MaxBECount has no signed overflow.
895 getMulExpr(CastedMaxBECount,
896 getTruncateOrSignExtend(Step, Start->getType()));
897 SCEVHandle Add = getAddExpr(Start, SMul);
898 if (getSignExtendExpr(Add, WideTy) ==
899 getAddExpr(getSignExtendExpr(Start, WideTy),
900 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
901 getSignExtendExpr(Step, WideTy))))
902 // Return the expression with the addrec on the outside.
903 return getAddRecExpr(getSignExtendExpr(Start, Ty),
904 getSignExtendExpr(Step, Ty),
910 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
911 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
915 // get - Get a canonical add expression, or something simpler if possible.
916 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
917 assert(!Ops.empty() && "Cannot get empty add!");
918 if (Ops.size() == 1) return Ops[0];
920 // Sort by complexity, this groups all similar expression types together.
921 GroupByComplexity(Ops, LI);
923 // If there are any constants, fold them together.
925 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
927 assert(Idx < Ops.size());
928 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
929 // We found two constants, fold them together!
930 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
931 RHSC->getValue()->getValue());
932 Ops[0] = getConstant(Fold);
933 Ops.erase(Ops.begin()+1); // Erase the folded element
934 if (Ops.size() == 1) return Ops[0];
935 LHSC = cast<SCEVConstant>(Ops[0]);
938 // If we are left with a constant zero being added, strip it off.
939 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
940 Ops.erase(Ops.begin());
945 if (Ops.size() == 1) return Ops[0];
947 // Okay, check to see if the same value occurs in the operand list twice. If
948 // so, merge them together into an multiply expression. Since we sorted the
949 // list, these values are required to be adjacent.
950 const Type *Ty = Ops[0]->getType();
951 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
952 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
953 // Found a match, merge the two values into a multiply, and add any
954 // remaining values to the result.
955 SCEVHandle Two = getIntegerSCEV(2, Ty);
956 SCEVHandle Mul = getMulExpr(Ops[i], Two);
959 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
961 return getAddExpr(Ops);
964 // Check for truncates. If all the operands are truncated from the same
965 // type, see if factoring out the truncate would permit the result to be
966 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
967 // if the contents of the resulting outer trunc fold to something simple.
968 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
969 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
970 const Type *DstType = Trunc->getType();
971 const Type *SrcType = Trunc->getOperand()->getType();
972 std::vector<SCEVHandle> LargeOps;
974 // Check all the operands to see if they can be represented in the
975 // source type of the truncate.
976 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
977 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
978 if (T->getOperand()->getType() != SrcType) {
982 LargeOps.push_back(T->getOperand());
983 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
984 // This could be either sign or zero extension, but sign extension
985 // is much more likely to be foldable here.
986 LargeOps.push_back(getSignExtendExpr(C, SrcType));
987 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
988 std::vector<SCEVHandle> LargeMulOps;
989 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
990 if (const SCEVTruncateExpr *T =
991 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
992 if (T->getOperand()->getType() != SrcType) {
996 LargeMulOps.push_back(T->getOperand());
997 } else if (const SCEVConstant *C =
998 dyn_cast<SCEVConstant>(M->getOperand(j))) {
999 // This could be either sign or zero extension, but sign extension
1000 // is much more likely to be foldable here.
1001 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1008 LargeOps.push_back(getMulExpr(LargeMulOps));
1015 // Evaluate the expression in the larger type.
1016 SCEVHandle Fold = getAddExpr(LargeOps);
1017 // If it folds to something simple, use it. Otherwise, don't.
1018 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1019 return getTruncateExpr(Fold, DstType);
1023 // Skip past any other cast SCEVs.
1024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1027 // If there are add operands they would be next.
1028 if (Idx < Ops.size()) {
1029 bool DeletedAdd = false;
1030 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1031 // If we have an add, expand the add operands onto the end of the operands
1033 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1034 Ops.erase(Ops.begin()+Idx);
1038 // If we deleted at least one add, we added operands to the end of the list,
1039 // and they are not necessarily sorted. Recurse to resort and resimplify
1040 // any operands we just aquired.
1042 return getAddExpr(Ops);
1045 // Skip over the add expression until we get to a multiply.
1046 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1049 // If we are adding something to a multiply expression, make sure the
1050 // something is not already an operand of the multiply. If so, merge it into
1052 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1053 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1054 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1055 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1056 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1057 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1058 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1059 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1060 if (Mul->getNumOperands() != 2) {
1061 // If the multiply has more than two operands, we must get the
1063 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1064 MulOps.erase(MulOps.begin()+MulOp);
1065 InnerMul = getMulExpr(MulOps);
1067 SCEVHandle One = getIntegerSCEV(1, Ty);
1068 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1069 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1070 if (Ops.size() == 2) return OuterMul;
1072 Ops.erase(Ops.begin()+AddOp);
1073 Ops.erase(Ops.begin()+Idx-1);
1075 Ops.erase(Ops.begin()+Idx);
1076 Ops.erase(Ops.begin()+AddOp-1);
1078 Ops.push_back(OuterMul);
1079 return getAddExpr(Ops);
1082 // Check this multiply against other multiplies being added together.
1083 for (unsigned OtherMulIdx = Idx+1;
1084 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1086 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1087 // If MulOp occurs in OtherMul, we can fold the two multiplies
1089 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1090 OMulOp != e; ++OMulOp)
1091 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1092 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1093 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1094 if (Mul->getNumOperands() != 2) {
1095 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1096 MulOps.erase(MulOps.begin()+MulOp);
1097 InnerMul1 = getMulExpr(MulOps);
1099 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1100 if (OtherMul->getNumOperands() != 2) {
1101 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1102 OtherMul->op_end());
1103 MulOps.erase(MulOps.begin()+OMulOp);
1104 InnerMul2 = getMulExpr(MulOps);
1106 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1107 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1108 if (Ops.size() == 2) return OuterMul;
1109 Ops.erase(Ops.begin()+Idx);
1110 Ops.erase(Ops.begin()+OtherMulIdx-1);
1111 Ops.push_back(OuterMul);
1112 return getAddExpr(Ops);
1118 // If there are any add recurrences in the operands list, see if any other
1119 // added values are loop invariant. If so, we can fold them into the
1121 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1124 // Scan over all recurrences, trying to fold loop invariants into them.
1125 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1126 // Scan all of the other operands to this add and add them to the vector if
1127 // they are loop invariant w.r.t. the recurrence.
1128 std::vector<SCEVHandle> LIOps;
1129 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1130 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1131 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1132 LIOps.push_back(Ops[i]);
1133 Ops.erase(Ops.begin()+i);
1137 // If we found some loop invariants, fold them into the recurrence.
1138 if (!LIOps.empty()) {
1139 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1140 LIOps.push_back(AddRec->getStart());
1142 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
1143 AddRecOps[0] = getAddExpr(LIOps);
1145 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1146 // If all of the other operands were loop invariant, we are done.
1147 if (Ops.size() == 1) return NewRec;
1149 // Otherwise, add the folded AddRec by the non-liv parts.
1150 for (unsigned i = 0;; ++i)
1151 if (Ops[i] == AddRec) {
1155 return getAddExpr(Ops);
1158 // Okay, if there weren't any loop invariants to be folded, check to see if
1159 // there are multiple AddRec's with the same loop induction variable being
1160 // added together. If so, we can fold them.
1161 for (unsigned OtherIdx = Idx+1;
1162 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1163 if (OtherIdx != Idx) {
1164 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1165 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1166 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1167 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1168 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1169 if (i >= NewOps.size()) {
1170 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1171 OtherAddRec->op_end());
1174 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1176 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1178 if (Ops.size() == 2) return NewAddRec;
1180 Ops.erase(Ops.begin()+Idx);
1181 Ops.erase(Ops.begin()+OtherIdx-1);
1182 Ops.push_back(NewAddRec);
1183 return getAddExpr(Ops);
1187 // Otherwise couldn't fold anything into this recurrence. Move onto the
1191 // Okay, it looks like we really DO need an add expr. Check to see if we
1192 // already have one, otherwise create a new one.
1193 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1194 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1196 if (Result == 0) Result = new SCEVAddExpr(Ops);
1201 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
1202 assert(!Ops.empty() && "Cannot get empty mul!");
1204 // Sort by complexity, this groups all similar expression types together.
1205 GroupByComplexity(Ops, LI);
1207 // If there are any constants, fold them together.
1209 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1211 // C1*(C2+V) -> C1*C2 + C1*V
1212 if (Ops.size() == 2)
1213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1214 if (Add->getNumOperands() == 2 &&
1215 isa<SCEVConstant>(Add->getOperand(0)))
1216 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1217 getMulExpr(LHSC, Add->getOperand(1)));
1221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1222 // We found two constants, fold them together!
1223 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1224 RHSC->getValue()->getValue());
1225 Ops[0] = getConstant(Fold);
1226 Ops.erase(Ops.begin()+1); // Erase the folded element
1227 if (Ops.size() == 1) return Ops[0];
1228 LHSC = cast<SCEVConstant>(Ops[0]);
1231 // If we are left with a constant one being multiplied, strip it off.
1232 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1233 Ops.erase(Ops.begin());
1235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1236 // If we have a multiply of zero, it will always be zero.
1241 // Skip over the add expression until we get to a multiply.
1242 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1245 if (Ops.size() == 1)
1248 // If there are mul operands inline them all into this expression.
1249 if (Idx < Ops.size()) {
1250 bool DeletedMul = false;
1251 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1252 // If we have an mul, expand the mul operands onto the end of the operands
1254 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1255 Ops.erase(Ops.begin()+Idx);
1259 // If we deleted at least one mul, we added operands to the end of the list,
1260 // and they are not necessarily sorted. Recurse to resort and resimplify
1261 // any operands we just aquired.
1263 return getMulExpr(Ops);
1266 // If there are any add recurrences in the operands list, see if any other
1267 // added values are loop invariant. If so, we can fold them into the
1269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1272 // Scan over all recurrences, trying to fold loop invariants into them.
1273 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1274 // Scan all of the other operands to this mul and add them to the vector if
1275 // they are loop invariant w.r.t. the recurrence.
1276 std::vector<SCEVHandle> LIOps;
1277 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1278 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1279 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1280 LIOps.push_back(Ops[i]);
1281 Ops.erase(Ops.begin()+i);
1285 // If we found some loop invariants, fold them into the recurrence.
1286 if (!LIOps.empty()) {
1287 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1288 std::vector<SCEVHandle> NewOps;
1289 NewOps.reserve(AddRec->getNumOperands());
1290 if (LIOps.size() == 1) {
1291 const SCEV *Scale = LIOps[0];
1292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1293 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1295 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1296 std::vector<SCEVHandle> MulOps(LIOps);
1297 MulOps.push_back(AddRec->getOperand(i));
1298 NewOps.push_back(getMulExpr(MulOps));
1302 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1304 // If all of the other operands were loop invariant, we are done.
1305 if (Ops.size() == 1) return NewRec;
1307 // Otherwise, multiply the folded AddRec by the non-liv parts.
1308 for (unsigned i = 0;; ++i)
1309 if (Ops[i] == AddRec) {
1313 return getMulExpr(Ops);
1316 // Okay, if there weren't any loop invariants to be folded, check to see if
1317 // there are multiple AddRec's with the same loop induction variable being
1318 // multiplied together. If so, we can fold them.
1319 for (unsigned OtherIdx = Idx+1;
1320 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1321 if (OtherIdx != Idx) {
1322 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1323 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1324 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1325 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1326 SCEVHandle NewStart = getMulExpr(F->getStart(),
1328 SCEVHandle B = F->getStepRecurrence(*this);
1329 SCEVHandle D = G->getStepRecurrence(*this);
1330 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1333 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1335 if (Ops.size() == 2) return NewAddRec;
1337 Ops.erase(Ops.begin()+Idx);
1338 Ops.erase(Ops.begin()+OtherIdx-1);
1339 Ops.push_back(NewAddRec);
1340 return getMulExpr(Ops);
1344 // Otherwise couldn't fold anything into this recurrence. Move onto the
1348 // Okay, it looks like we really DO need an mul expr. Check to see if we
1349 // already have one, otherwise create a new one.
1350 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1351 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1354 Result = new SCEVMulExpr(Ops);
1358 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
1360 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1361 if (RHSC->getValue()->equalsInt(1))
1362 return LHS; // X udiv 1 --> x
1364 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1366 // Determine if the division can be folded into the operands of
1368 // TODO: Generalize this to non-constants by using known-bits information.
1369 const Type *Ty = LHS->getType();
1370 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1371 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1372 // For non-power-of-two values, effectively round the value up to the
1373 // nearest power of two.
1374 if (!RHSC->getValue()->getValue().isPowerOf2())
1376 const IntegerType *ExtTy =
1377 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1378 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1380 if (const SCEVConstant *Step =
1381 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1382 if (!Step->getValue()->getValue()
1383 .urem(RHSC->getValue()->getValue()) &&
1384 getZeroExtendExpr(AR, ExtTy) ==
1385 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1386 getZeroExtendExpr(Step, ExtTy),
1388 std::vector<SCEVHandle> Operands;
1389 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1390 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1391 return getAddRecExpr(Operands, AR->getLoop());
1393 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1394 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1395 std::vector<SCEVHandle> Operands;
1396 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1397 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1398 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1399 // Find an operand that's safely divisible.
1400 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1401 SCEVHandle Op = M->getOperand(i);
1402 SCEVHandle Div = getUDivExpr(Op, RHSC);
1403 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1404 Operands = M->getOperands();
1406 return getMulExpr(Operands);
1410 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1411 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1412 std::vector<SCEVHandle> Operands;
1413 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1414 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1415 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1417 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1418 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1419 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1421 Operands.push_back(Op);
1423 if (Operands.size() == A->getNumOperands())
1424 return getAddExpr(Operands);
1428 // Fold if both operands are constant.
1429 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1430 Constant *LHSCV = LHSC->getValue();
1431 Constant *RHSCV = RHSC->getValue();
1432 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1436 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1437 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1442 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1443 /// specified loop. Simplify the expression as much as possible.
1444 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1445 const SCEVHandle &Step, const Loop *L) {
1446 std::vector<SCEVHandle> Operands;
1447 Operands.push_back(Start);
1448 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1449 if (StepChrec->getLoop() == L) {
1450 Operands.insert(Operands.end(), StepChrec->op_begin(),
1451 StepChrec->op_end());
1452 return getAddRecExpr(Operands, L);
1455 Operands.push_back(Step);
1456 return getAddRecExpr(Operands, L);
1459 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1460 /// specified loop. Simplify the expression as much as possible.
1461 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1463 if (Operands.size() == 1) return Operands[0];
1465 if (Operands.back()->isZero()) {
1466 Operands.pop_back();
1467 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1470 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1471 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1472 const Loop* NestedLoop = NestedAR->getLoop();
1473 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1474 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1475 NestedAR->op_end());
1476 SCEVHandle NestedARHandle(NestedAR);
1477 Operands[0] = NestedAR->getStart();
1478 NestedOperands[0] = getAddRecExpr(Operands, L);
1479 return getAddRecExpr(NestedOperands, NestedLoop);
1483 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1484 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1485 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1489 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1490 const SCEVHandle &RHS) {
1491 std::vector<SCEVHandle> Ops;
1494 return getSMaxExpr(Ops);
1497 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1498 assert(!Ops.empty() && "Cannot get empty smax!");
1499 if (Ops.size() == 1) return Ops[0];
1501 // Sort by complexity, this groups all similar expression types together.
1502 GroupByComplexity(Ops, LI);
1504 // If there are any constants, fold them together.
1506 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1508 assert(Idx < Ops.size());
1509 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1510 // We found two constants, fold them together!
1511 ConstantInt *Fold = ConstantInt::get(
1512 APIntOps::smax(LHSC->getValue()->getValue(),
1513 RHSC->getValue()->getValue()));
1514 Ops[0] = getConstant(Fold);
1515 Ops.erase(Ops.begin()+1); // Erase the folded element
1516 if (Ops.size() == 1) return Ops[0];
1517 LHSC = cast<SCEVConstant>(Ops[0]);
1520 // If we are left with a constant -inf, strip it off.
1521 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1522 Ops.erase(Ops.begin());
1527 if (Ops.size() == 1) return Ops[0];
1529 // Find the first SMax
1530 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1533 // Check to see if one of the operands is an SMax. If so, expand its operands
1534 // onto our operand list, and recurse to simplify.
1535 if (Idx < Ops.size()) {
1536 bool DeletedSMax = false;
1537 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1538 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1539 Ops.erase(Ops.begin()+Idx);
1544 return getSMaxExpr(Ops);
1547 // Okay, check to see if the same value occurs in the operand list twice. If
1548 // so, delete one. Since we sorted the list, these values are required to
1550 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1551 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1552 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1556 if (Ops.size() == 1) return Ops[0];
1558 assert(!Ops.empty() && "Reduced smax down to nothing!");
1560 // Okay, it looks like we really DO need an smax expr. Check to see if we
1561 // already have one, otherwise create a new one.
1562 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1563 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1565 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1569 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1570 const SCEVHandle &RHS) {
1571 std::vector<SCEVHandle> Ops;
1574 return getUMaxExpr(Ops);
1577 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1578 assert(!Ops.empty() && "Cannot get empty umax!");
1579 if (Ops.size() == 1) return Ops[0];
1581 // Sort by complexity, this groups all similar expression types together.
1582 GroupByComplexity(Ops, LI);
1584 // If there are any constants, fold them together.
1586 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1588 assert(Idx < Ops.size());
1589 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1590 // We found two constants, fold them together!
1591 ConstantInt *Fold = ConstantInt::get(
1592 APIntOps::umax(LHSC->getValue()->getValue(),
1593 RHSC->getValue()->getValue()));
1594 Ops[0] = getConstant(Fold);
1595 Ops.erase(Ops.begin()+1); // Erase the folded element
1596 if (Ops.size() == 1) return Ops[0];
1597 LHSC = cast<SCEVConstant>(Ops[0]);
1600 // If we are left with a constant zero, strip it off.
1601 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1602 Ops.erase(Ops.begin());
1607 if (Ops.size() == 1) return Ops[0];
1609 // Find the first UMax
1610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1613 // Check to see if one of the operands is a UMax. If so, expand its operands
1614 // onto our operand list, and recurse to simplify.
1615 if (Idx < Ops.size()) {
1616 bool DeletedUMax = false;
1617 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1618 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1619 Ops.erase(Ops.begin()+Idx);
1624 return getUMaxExpr(Ops);
1627 // Okay, check to see if the same value occurs in the operand list twice. If
1628 // so, delete one. Since we sorted the list, these values are required to
1630 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1631 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1632 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1636 if (Ops.size() == 1) return Ops[0];
1638 assert(!Ops.empty() && "Reduced umax down to nothing!");
1640 // Okay, it looks like we really DO need a umax expr. Check to see if we
1641 // already have one, otherwise create a new one.
1642 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1643 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1645 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1649 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1651 return getConstant(CI);
1652 if (isa<ConstantPointerNull>(V))
1653 return getIntegerSCEV(0, V->getType());
1654 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1655 if (Result == 0) Result = new SCEVUnknown(V);
1659 //===----------------------------------------------------------------------===//
1660 // Basic SCEV Analysis and PHI Idiom Recognition Code
1663 /// isSCEVable - Test if values of the given type are analyzable within
1664 /// the SCEV framework. This primarily includes integer types, and it
1665 /// can optionally include pointer types if the ScalarEvolution class
1666 /// has access to target-specific information.
1667 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1668 // Integers are always SCEVable.
1669 if (Ty->isInteger())
1672 // Pointers are SCEVable if TargetData information is available
1673 // to provide pointer size information.
1674 if (isa<PointerType>(Ty))
1677 // Otherwise it's not SCEVable.
1681 /// getTypeSizeInBits - Return the size in bits of the specified type,
1682 /// for which isSCEVable must return true.
1683 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1684 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1686 // If we have a TargetData, use it!
1688 return TD->getTypeSizeInBits(Ty);
1690 // Otherwise, we support only integer types.
1691 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1692 return Ty->getPrimitiveSizeInBits();
1695 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1696 /// the given type and which represents how SCEV will treat the given
1697 /// type, for which isSCEVable must return true. For pointer types,
1698 /// this is the pointer-sized integer type.
1699 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1700 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1702 if (Ty->isInteger())
1705 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1706 return TD->getIntPtrType();
1709 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1710 return UnknownValue;
1713 /// hasSCEV - Return true if the SCEV for this value has already been
1715 bool ScalarEvolution::hasSCEV(Value *V) const {
1716 return Scalars.count(V);
1719 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1720 /// expression and create a new one.
1721 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1722 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1724 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1725 if (I != Scalars.end()) return I->second;
1726 SCEVHandle S = createSCEV(V);
1727 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1731 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1732 /// specified signed integer value and return a SCEV for the constant.
1733 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1734 Ty = getEffectiveSCEVType(Ty);
1737 C = Constant::getNullValue(Ty);
1738 else if (Ty->isFloatingPoint())
1739 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1740 APFloat::IEEEdouble, Val));
1742 C = ConstantInt::get(Ty, Val);
1743 return getUnknown(C);
1746 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1748 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
1749 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1750 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
1752 const Type *Ty = V->getType();
1753 Ty = getEffectiveSCEVType(Ty);
1754 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
1757 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1758 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
1759 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1760 return getUnknown(ConstantExpr::getNot(VC->getValue()));
1762 const Type *Ty = V->getType();
1763 Ty = getEffectiveSCEVType(Ty);
1764 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
1765 return getMinusSCEV(AllOnes, V);
1768 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1770 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
1771 const SCEVHandle &RHS) {
1773 return getAddExpr(LHS, getNegativeSCEV(RHS));
1776 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1777 /// input value to the specified type. If the type must be extended, it is zero
1780 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
1782 const Type *SrcTy = V->getType();
1783 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1784 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1785 "Cannot truncate or zero extend with non-integer arguments!");
1786 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1787 return V; // No conversion
1788 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1789 return getTruncateExpr(V, Ty);
1790 return getZeroExtendExpr(V, Ty);
1793 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1794 /// input value to the specified type. If the type must be extended, it is sign
1797 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
1799 const Type *SrcTy = V->getType();
1800 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1801 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1802 "Cannot truncate or zero extend with non-integer arguments!");
1803 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1804 return V; // No conversion
1805 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1806 return getTruncateExpr(V, Ty);
1807 return getSignExtendExpr(V, Ty);
1810 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1811 /// the specified instruction and replaces any references to the symbolic value
1812 /// SymName with the specified value. This is used during PHI resolution.
1813 void ScalarEvolution::
1814 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1815 const SCEVHandle &NewVal) {
1816 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1817 Scalars.find(SCEVCallbackVH(I, this));
1818 if (SI == Scalars.end()) return;
1821 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
1822 if (NV == SI->second) return; // No change.
1824 SI->second = NV; // Update the scalars map!
1826 // Any instruction values that use this instruction might also need to be
1828 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1830 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1833 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1834 /// a loop header, making it a potential recurrence, or it doesn't.
1836 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
1837 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1838 if (const Loop *L = LI->getLoopFor(PN->getParent()))
1839 if (L->getHeader() == PN->getParent()) {
1840 // If it lives in the loop header, it has two incoming values, one
1841 // from outside the loop, and one from inside.
1842 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1843 unsigned BackEdge = IncomingEdge^1;
1845 // While we are analyzing this PHI node, handle its value symbolically.
1846 SCEVHandle SymbolicName = getUnknown(PN);
1847 assert(Scalars.find(PN) == Scalars.end() &&
1848 "PHI node already processed?");
1849 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
1851 // Using this symbolic name for the PHI, analyze the value coming around
1853 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1855 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1856 // has a special value for the first iteration of the loop.
1858 // If the value coming around the backedge is an add with the symbolic
1859 // value we just inserted, then we found a simple induction variable!
1860 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1861 // If there is a single occurrence of the symbolic value, replace it
1862 // with a recurrence.
1863 unsigned FoundIndex = Add->getNumOperands();
1864 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1865 if (Add->getOperand(i) == SymbolicName)
1866 if (FoundIndex == e) {
1871 if (FoundIndex != Add->getNumOperands()) {
1872 // Create an add with everything but the specified operand.
1873 std::vector<SCEVHandle> Ops;
1874 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1875 if (i != FoundIndex)
1876 Ops.push_back(Add->getOperand(i));
1877 SCEVHandle Accum = getAddExpr(Ops);
1879 // This is not a valid addrec if the step amount is varying each
1880 // loop iteration, but is not itself an addrec in this loop.
1881 if (Accum->isLoopInvariant(L) ||
1882 (isa<SCEVAddRecExpr>(Accum) &&
1883 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1884 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1885 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
1887 // Okay, for the entire analysis of this edge we assumed the PHI
1888 // to be symbolic. We now need to go back and update all of the
1889 // entries for the scalars that use the PHI (except for the PHI
1890 // itself) to use the new analyzed value instead of the "symbolic"
1892 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1896 } else if (const SCEVAddRecExpr *AddRec =
1897 dyn_cast<SCEVAddRecExpr>(BEValue)) {
1898 // Otherwise, this could be a loop like this:
1899 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1900 // In this case, j = {1,+,1} and BEValue is j.
1901 // Because the other in-value of i (0) fits the evolution of BEValue
1902 // i really is an addrec evolution.
1903 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1904 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1906 // If StartVal = j.start - j.stride, we can use StartVal as the
1907 // initial step of the addrec evolution.
1908 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
1909 AddRec->getOperand(1))) {
1910 SCEVHandle PHISCEV =
1911 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1913 // Okay, for the entire analysis of this edge we assumed the PHI
1914 // to be symbolic. We now need to go back and update all of the
1915 // entries for the scalars that use the PHI (except for the PHI
1916 // itself) to use the new analyzed value instead of the "symbolic"
1918 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1924 return SymbolicName;
1927 // If it's not a loop phi, we can't handle it yet.
1928 return getUnknown(PN);
1931 /// createNodeForGEP - Expand GEP instructions into add and multiply
1932 /// operations. This allows them to be analyzed by regular SCEV code.
1934 SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
1936 const Type *IntPtrTy = TD->getIntPtrType();
1937 Value *Base = GEP->getOperand(0);
1938 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
1939 gep_type_iterator GTI = gep_type_begin(GEP);
1940 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
1944 // Compute the (potentially symbolic) offset in bytes for this index.
1945 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1946 // For a struct, add the member offset.
1947 const StructLayout &SL = *TD->getStructLayout(STy);
1948 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1949 uint64_t Offset = SL.getElementOffset(FieldNo);
1950 TotalOffset = getAddExpr(TotalOffset,
1951 getIntegerSCEV(Offset, IntPtrTy));
1953 // For an array, add the element offset, explicitly scaled.
1954 SCEVHandle LocalOffset = getSCEV(Index);
1955 if (!isa<PointerType>(LocalOffset->getType()))
1956 // Getelementptr indicies are signed.
1957 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1960 getMulExpr(LocalOffset,
1961 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1963 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
1966 return getAddExpr(getSCEV(Base), TotalOffset);
1969 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1970 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1971 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1972 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1973 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1974 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1975 return C->getValue()->getValue().countTrailingZeros();
1977 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1978 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1979 (uint32_t)SE.getTypeSizeInBits(T->getType()));
1981 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1982 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1983 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1984 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1987 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1988 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1989 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1990 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1993 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1994 // The result is the min of all operands results.
1995 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1996 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1997 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2001 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2002 // The result is the sum of all operands results.
2003 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2004 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
2005 for (unsigned i = 1, e = M->getNumOperands();
2006 SumOpRes != BitWidth && i != e; ++i)
2007 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
2012 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2013 // The result is the min of all operands results.
2014 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
2015 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2016 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2020 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2021 // The result is the min of all operands results.
2022 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2023 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2024 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2028 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2029 // The result is the min of all operands results.
2030 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2031 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2032 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2036 // SCEVUDivExpr, SCEVUnknown
2040 /// createSCEV - We know that there is no SCEV for the specified value.
2041 /// Analyze the expression.
2043 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
2044 if (!isSCEVable(V->getType()))
2045 return getUnknown(V);
2047 unsigned Opcode = Instruction::UserOp1;
2048 if (Instruction *I = dyn_cast<Instruction>(V))
2049 Opcode = I->getOpcode();
2050 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2051 Opcode = CE->getOpcode();
2053 return getUnknown(V);
2055 User *U = cast<User>(V);
2057 case Instruction::Add:
2058 return getAddExpr(getSCEV(U->getOperand(0)),
2059 getSCEV(U->getOperand(1)));
2060 case Instruction::Mul:
2061 return getMulExpr(getSCEV(U->getOperand(0)),
2062 getSCEV(U->getOperand(1)));
2063 case Instruction::UDiv:
2064 return getUDivExpr(getSCEV(U->getOperand(0)),
2065 getSCEV(U->getOperand(1)));
2066 case Instruction::Sub:
2067 return getMinusSCEV(getSCEV(U->getOperand(0)),
2068 getSCEV(U->getOperand(1)));
2069 case Instruction::And:
2070 // For an expression like x&255 that merely masks off the high bits,
2071 // use zext(trunc(x)) as the SCEV expression.
2072 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2073 if (CI->isNullValue())
2074 return getSCEV(U->getOperand(1));
2075 if (CI->isAllOnesValue())
2076 return getSCEV(U->getOperand(0));
2077 const APInt &A = CI->getValue();
2078 unsigned Ones = A.countTrailingOnes();
2079 if (APIntOps::isMask(Ones, A))
2081 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2082 IntegerType::get(Ones)),
2086 case Instruction::Or:
2087 // If the RHS of the Or is a constant, we may have something like:
2088 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2089 // optimizations will transparently handle this case.
2091 // In order for this transformation to be safe, the LHS must be of the
2092 // form X*(2^n) and the Or constant must be less than 2^n.
2093 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2094 SCEVHandle LHS = getSCEV(U->getOperand(0));
2095 const APInt &CIVal = CI->getValue();
2096 if (GetMinTrailingZeros(LHS, *this) >=
2097 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2098 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2101 case Instruction::Xor:
2102 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2103 // If the RHS of the xor is a signbit, then this is just an add.
2104 // Instcombine turns add of signbit into xor as a strength reduction step.
2105 if (CI->getValue().isSignBit())
2106 return getAddExpr(getSCEV(U->getOperand(0)),
2107 getSCEV(U->getOperand(1)));
2109 // If the RHS of xor is -1, then this is a not operation.
2110 else if (CI->isAllOnesValue())
2111 return getNotSCEV(getSCEV(U->getOperand(0)));
2115 case Instruction::Shl:
2116 // Turn shift left of a constant amount into a multiply.
2117 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2118 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2119 Constant *X = ConstantInt::get(
2120 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2121 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2125 case Instruction::LShr:
2126 // Turn logical shift right of a constant into a unsigned divide.
2127 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2128 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2129 Constant *X = ConstantInt::get(
2130 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2131 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2135 case Instruction::AShr:
2136 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2137 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2138 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2139 if (L->getOpcode() == Instruction::Shl &&
2140 L->getOperand(1) == U->getOperand(1)) {
2141 unsigned BitWidth = getTypeSizeInBits(U->getType());
2142 uint64_t Amt = BitWidth - CI->getZExtValue();
2143 if (Amt == BitWidth)
2144 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2146 return getIntegerSCEV(0, U->getType()); // value is undefined
2148 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2149 IntegerType::get(Amt)),
2154 case Instruction::Trunc:
2155 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2157 case Instruction::ZExt:
2158 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2160 case Instruction::SExt:
2161 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2163 case Instruction::BitCast:
2164 // BitCasts are no-op casts so we just eliminate the cast.
2165 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2166 return getSCEV(U->getOperand(0));
2169 case Instruction::IntToPtr:
2170 if (!TD) break; // Without TD we can't analyze pointers.
2171 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2172 TD->getIntPtrType());
2174 case Instruction::PtrToInt:
2175 if (!TD) break; // Without TD we can't analyze pointers.
2176 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2179 case Instruction::GetElementPtr:
2180 if (!TD) break; // Without TD we can't analyze pointers.
2181 return createNodeForGEP(U);
2183 case Instruction::PHI:
2184 return createNodeForPHI(cast<PHINode>(U));
2186 case Instruction::Select:
2187 // This could be a smax or umax that was lowered earlier.
2188 // Try to recover it.
2189 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2190 Value *LHS = ICI->getOperand(0);
2191 Value *RHS = ICI->getOperand(1);
2192 switch (ICI->getPredicate()) {
2193 case ICmpInst::ICMP_SLT:
2194 case ICmpInst::ICMP_SLE:
2195 std::swap(LHS, RHS);
2197 case ICmpInst::ICMP_SGT:
2198 case ICmpInst::ICMP_SGE:
2199 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2200 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2201 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2202 // ~smax(~x, ~y) == smin(x, y).
2203 return getNotSCEV(getSMaxExpr(
2204 getNotSCEV(getSCEV(LHS)),
2205 getNotSCEV(getSCEV(RHS))));
2207 case ICmpInst::ICMP_ULT:
2208 case ICmpInst::ICMP_ULE:
2209 std::swap(LHS, RHS);
2211 case ICmpInst::ICMP_UGT:
2212 case ICmpInst::ICMP_UGE:
2213 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2214 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2215 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2216 // ~umax(~x, ~y) == umin(x, y)
2217 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2218 getNotSCEV(getSCEV(RHS))));
2225 default: // We cannot analyze this expression.
2229 return getUnknown(V);
2234 //===----------------------------------------------------------------------===//
2235 // Iteration Count Computation Code
2238 /// getBackedgeTakenCount - If the specified loop has a predictable
2239 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2240 /// object. The backedge-taken count is the number of times the loop header
2241 /// will be branched to from within the loop. This is one less than the
2242 /// trip count of the loop, since it doesn't count the first iteration,
2243 /// when the header is branched to from outside the loop.
2245 /// Note that it is not valid to call this method on a loop without a
2246 /// loop-invariant backedge-taken count (see
2247 /// hasLoopInvariantBackedgeTakenCount).
2249 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2250 return getBackedgeTakenInfo(L).Exact;
2253 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2254 /// return the least SCEV value that is known never to be less than the
2255 /// actual backedge taken count.
2256 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2257 return getBackedgeTakenInfo(L).Max;
2260 const ScalarEvolution::BackedgeTakenInfo &
2261 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2262 // Initially insert a CouldNotCompute for this loop. If the insertion
2263 // succeeds, procede to actually compute a backedge-taken count and
2264 // update the value. The temporary CouldNotCompute value tells SCEV
2265 // code elsewhere that it shouldn't attempt to request a new
2266 // backedge-taken count, which could result in infinite recursion.
2267 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2268 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2270 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2271 if (ItCount.Exact != UnknownValue) {
2272 assert(ItCount.Exact->isLoopInvariant(L) &&
2273 ItCount.Max->isLoopInvariant(L) &&
2274 "Computed trip count isn't loop invariant for loop!");
2275 ++NumTripCountsComputed;
2277 // Update the value in the map.
2278 Pair.first->second = ItCount;
2279 } else if (isa<PHINode>(L->getHeader()->begin())) {
2280 // Only count loops that have phi nodes as not being computable.
2281 ++NumTripCountsNotComputed;
2284 // Now that we know more about the trip count for this loop, forget any
2285 // existing SCEV values for PHI nodes in this loop since they are only
2286 // conservative estimates made without the benefit
2287 // of trip count information.
2288 if (ItCount.hasAnyInfo())
2291 return Pair.first->second;
2294 /// forgetLoopBackedgeTakenCount - This method should be called by the
2295 /// client when it has changed a loop in a way that may effect
2296 /// ScalarEvolution's ability to compute a trip count, or if the loop
2298 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2299 BackedgeTakenCounts.erase(L);
2303 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2304 /// PHI nodes in the given loop. This is used when the trip count of
2305 /// the loop may have changed.
2306 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2307 BasicBlock *Header = L->getHeader();
2309 SmallVector<Instruction *, 16> Worklist;
2310 for (BasicBlock::iterator I = Header->begin();
2311 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2312 Worklist.push_back(PN);
2314 while (!Worklist.empty()) {
2315 Instruction *I = Worklist.pop_back_val();
2316 if (Scalars.erase(I))
2317 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2319 Worklist.push_back(cast<Instruction>(UI));
2323 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2324 /// of the specified loop will execute.
2325 ScalarEvolution::BackedgeTakenInfo
2326 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2327 // If the loop has a non-one exit block count, we can't analyze it.
2328 SmallVector<BasicBlock*, 8> ExitBlocks;
2329 L->getExitBlocks(ExitBlocks);
2330 if (ExitBlocks.size() != 1) return UnknownValue;
2332 // Okay, there is one exit block. Try to find the condition that causes the
2333 // loop to be exited.
2334 BasicBlock *ExitBlock = ExitBlocks[0];
2336 BasicBlock *ExitingBlock = 0;
2337 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2339 if (L->contains(*PI)) {
2340 if (ExitingBlock == 0)
2343 return UnknownValue; // More than one block exiting!
2345 assert(ExitingBlock && "No exits from loop, something is broken!");
2347 // Okay, we've computed the exiting block. See what condition causes us to
2350 // FIXME: we should be able to handle switch instructions (with a single exit)
2351 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2352 if (ExitBr == 0) return UnknownValue;
2353 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2355 // At this point, we know we have a conditional branch that determines whether
2356 // the loop is exited. However, we don't know if the branch is executed each
2357 // time through the loop. If not, then the execution count of the branch will
2358 // not be equal to the trip count of the loop.
2360 // Currently we check for this by checking to see if the Exit branch goes to
2361 // the loop header. If so, we know it will always execute the same number of
2362 // times as the loop. We also handle the case where the exit block *is* the
2363 // loop header. This is common for un-rotated loops. More extensive analysis
2364 // could be done to handle more cases here.
2365 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2366 ExitBr->getSuccessor(1) != L->getHeader() &&
2367 ExitBr->getParent() != L->getHeader())
2368 return UnknownValue;
2370 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2372 // If it's not an integer comparison then compute it the hard way.
2373 // Note that ICmpInst deals with pointer comparisons too so we must check
2374 // the type of the operand.
2375 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2376 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2377 ExitBr->getSuccessor(0) == ExitBlock);
2379 // If the condition was exit on true, convert the condition to exit on false
2380 ICmpInst::Predicate Cond;
2381 if (ExitBr->getSuccessor(1) == ExitBlock)
2382 Cond = ExitCond->getPredicate();
2384 Cond = ExitCond->getInversePredicate();
2386 // Handle common loops like: for (X = "string"; *X; ++X)
2387 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2388 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2390 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2391 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2394 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2395 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2397 // Try to evaluate any dependencies out of the loop.
2398 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2399 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2400 Tmp = getSCEVAtScope(RHS, L);
2401 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2403 // At this point, we would like to compute how many iterations of the
2404 // loop the predicate will return true for these inputs.
2405 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2406 // If there is a loop-invariant, force it into the RHS.
2407 std::swap(LHS, RHS);
2408 Cond = ICmpInst::getSwappedPredicate(Cond);
2411 // If we have a comparison of a chrec against a constant, try to use value
2412 // ranges to answer this query.
2413 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2414 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2415 if (AddRec->getLoop() == L) {
2416 // Form the comparison range using the constant of the correct type so
2417 // that the ConstantRange class knows to do a signed or unsigned
2419 ConstantInt *CompVal = RHSC->getValue();
2420 const Type *RealTy = ExitCond->getOperand(0)->getType();
2421 CompVal = dyn_cast<ConstantInt>(
2422 ConstantExpr::getBitCast(CompVal, RealTy));
2424 // Form the constant range.
2425 ConstantRange CompRange(
2426 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2428 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2429 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2434 case ICmpInst::ICMP_NE: { // while (X != Y)
2435 // Convert to: while (X-Y != 0)
2436 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2437 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2440 case ICmpInst::ICMP_EQ: {
2441 // Convert to: while (X-Y == 0) // while (X == Y)
2442 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2443 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2446 case ICmpInst::ICMP_SLT: {
2447 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2448 if (BTI.hasAnyInfo()) return BTI;
2451 case ICmpInst::ICMP_SGT: {
2452 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2453 getNotSCEV(RHS), L, true);
2454 if (BTI.hasAnyInfo()) return BTI;
2457 case ICmpInst::ICMP_ULT: {
2458 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2459 if (BTI.hasAnyInfo()) return BTI;
2462 case ICmpInst::ICMP_UGT: {
2463 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2464 getNotSCEV(RHS), L, false);
2465 if (BTI.hasAnyInfo()) return BTI;
2470 errs() << "ComputeBackedgeTakenCount ";
2471 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2472 errs() << "[unsigned] ";
2473 errs() << *LHS << " "
2474 << Instruction::getOpcodeName(Instruction::ICmp)
2475 << " " << *RHS << "\n";
2480 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2481 ExitBr->getSuccessor(0) == ExitBlock);
2484 static ConstantInt *
2485 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2486 ScalarEvolution &SE) {
2487 SCEVHandle InVal = SE.getConstant(C);
2488 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2489 assert(isa<SCEVConstant>(Val) &&
2490 "Evaluation of SCEV at constant didn't fold correctly?");
2491 return cast<SCEVConstant>(Val)->getValue();
2494 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2495 /// and a GEP expression (missing the pointer index) indexing into it, return
2496 /// the addressed element of the initializer or null if the index expression is
2499 GetAddressedElementFromGlobal(GlobalVariable *GV,
2500 const std::vector<ConstantInt*> &Indices) {
2501 Constant *Init = GV->getInitializer();
2502 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2503 uint64_t Idx = Indices[i]->getZExtValue();
2504 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2505 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2506 Init = cast<Constant>(CS->getOperand(Idx));
2507 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2508 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2509 Init = cast<Constant>(CA->getOperand(Idx));
2510 } else if (isa<ConstantAggregateZero>(Init)) {
2511 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2512 assert(Idx < STy->getNumElements() && "Bad struct index!");
2513 Init = Constant::getNullValue(STy->getElementType(Idx));
2514 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2515 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2516 Init = Constant::getNullValue(ATy->getElementType());
2518 assert(0 && "Unknown constant aggregate type!");
2522 return 0; // Unknown initializer type
2528 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2529 /// 'icmp op load X, cst', try to see if we can compute the backedge
2530 /// execution count.
2531 SCEVHandle ScalarEvolution::
2532 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2534 ICmpInst::Predicate predicate) {
2535 if (LI->isVolatile()) return UnknownValue;
2537 // Check to see if the loaded pointer is a getelementptr of a global.
2538 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2539 if (!GEP) return UnknownValue;
2541 // Make sure that it is really a constant global we are gepping, with an
2542 // initializer, and make sure the first IDX is really 0.
2543 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2544 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2545 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2546 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2547 return UnknownValue;
2549 // Okay, we allow one non-constant index into the GEP instruction.
2551 std::vector<ConstantInt*> Indexes;
2552 unsigned VarIdxNum = 0;
2553 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2554 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2555 Indexes.push_back(CI);
2556 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2557 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2558 VarIdx = GEP->getOperand(i);
2560 Indexes.push_back(0);
2563 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2564 // Check to see if X is a loop variant variable value now.
2565 SCEVHandle Idx = getSCEV(VarIdx);
2566 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2567 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2569 // We can only recognize very limited forms of loop index expressions, in
2570 // particular, only affine AddRec's like {C1,+,C2}.
2571 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2572 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2573 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2574 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2575 return UnknownValue;
2577 unsigned MaxSteps = MaxBruteForceIterations;
2578 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2579 ConstantInt *ItCst =
2580 ConstantInt::get(IdxExpr->getType(), IterationNum);
2581 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2583 // Form the GEP offset.
2584 Indexes[VarIdxNum] = Val;
2586 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2587 if (Result == 0) break; // Cannot compute!
2589 // Evaluate the condition for this iteration.
2590 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2591 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2592 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2594 errs() << "\n***\n*** Computed loop count " << *ItCst
2595 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2598 ++NumArrayLenItCounts;
2599 return getConstant(ItCst); // Found terminating iteration!
2602 return UnknownValue;
2606 /// CanConstantFold - Return true if we can constant fold an instruction of the
2607 /// specified type, assuming that all operands were constants.
2608 static bool CanConstantFold(const Instruction *I) {
2609 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2610 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2613 if (const CallInst *CI = dyn_cast<CallInst>(I))
2614 if (const Function *F = CI->getCalledFunction())
2615 return canConstantFoldCallTo(F);
2619 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2620 /// in the loop that V is derived from. We allow arbitrary operations along the
2621 /// way, but the operands of an operation must either be constants or a value
2622 /// derived from a constant PHI. If this expression does not fit with these
2623 /// constraints, return null.
2624 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2625 // If this is not an instruction, or if this is an instruction outside of the
2626 // loop, it can't be derived from a loop PHI.
2627 Instruction *I = dyn_cast<Instruction>(V);
2628 if (I == 0 || !L->contains(I->getParent())) return 0;
2630 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2631 if (L->getHeader() == I->getParent())
2634 // We don't currently keep track of the control flow needed to evaluate
2635 // PHIs, so we cannot handle PHIs inside of loops.
2639 // If we won't be able to constant fold this expression even if the operands
2640 // are constants, return early.
2641 if (!CanConstantFold(I)) return 0;
2643 // Otherwise, we can evaluate this instruction if all of its operands are
2644 // constant or derived from a PHI node themselves.
2646 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2647 if (!(isa<Constant>(I->getOperand(Op)) ||
2648 isa<GlobalValue>(I->getOperand(Op)))) {
2649 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2650 if (P == 0) return 0; // Not evolving from PHI
2654 return 0; // Evolving from multiple different PHIs.
2657 // This is a expression evolving from a constant PHI!
2661 /// EvaluateExpression - Given an expression that passes the
2662 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2663 /// in the loop has the value PHIVal. If we can't fold this expression for some
2664 /// reason, return null.
2665 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2666 if (isa<PHINode>(V)) return PHIVal;
2667 if (Constant *C = dyn_cast<Constant>(V)) return C;
2668 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2669 Instruction *I = cast<Instruction>(V);
2671 std::vector<Constant*> Operands;
2672 Operands.resize(I->getNumOperands());
2674 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2675 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2676 if (Operands[i] == 0) return 0;
2679 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2680 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2681 &Operands[0], Operands.size());
2683 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2684 &Operands[0], Operands.size());
2687 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2688 /// in the header of its containing loop, we know the loop executes a
2689 /// constant number of times, and the PHI node is just a recurrence
2690 /// involving constants, fold it.
2691 Constant *ScalarEvolution::
2692 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2693 std::map<PHINode*, Constant*>::iterator I =
2694 ConstantEvolutionLoopExitValue.find(PN);
2695 if (I != ConstantEvolutionLoopExitValue.end())
2698 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2699 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2701 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2703 // Since the loop is canonicalized, the PHI node must have two entries. One
2704 // entry must be a constant (coming in from outside of the loop), and the
2705 // second must be derived from the same PHI.
2706 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2707 Constant *StartCST =
2708 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2710 return RetVal = 0; // Must be a constant.
2712 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2713 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2715 return RetVal = 0; // Not derived from same PHI.
2717 // Execute the loop symbolically to determine the exit value.
2718 if (BEs.getActiveBits() >= 32)
2719 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2721 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2722 unsigned IterationNum = 0;
2723 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2724 if (IterationNum == NumIterations)
2725 return RetVal = PHIVal; // Got exit value!
2727 // Compute the value of the PHI node for the next iteration.
2728 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2729 if (NextPHI == PHIVal)
2730 return RetVal = NextPHI; // Stopped evolving!
2732 return 0; // Couldn't evaluate!
2737 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2738 /// constant number of times (the condition evolves only from constants),
2739 /// try to evaluate a few iterations of the loop until we get the exit
2740 /// condition gets a value of ExitWhen (true or false). If we cannot
2741 /// evaluate the trip count of the loop, return UnknownValue.
2742 SCEVHandle ScalarEvolution::
2743 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2744 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2745 if (PN == 0) return UnknownValue;
2747 // Since the loop is canonicalized, the PHI node must have two entries. One
2748 // entry must be a constant (coming in from outside of the loop), and the
2749 // second must be derived from the same PHI.
2750 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2751 Constant *StartCST =
2752 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2753 if (StartCST == 0) return UnknownValue; // Must be a constant.
2755 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2756 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2757 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2759 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2760 // the loop symbolically to determine when the condition gets a value of
2762 unsigned IterationNum = 0;
2763 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2764 for (Constant *PHIVal = StartCST;
2765 IterationNum != MaxIterations; ++IterationNum) {
2766 ConstantInt *CondVal =
2767 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2769 // Couldn't symbolically evaluate.
2770 if (!CondVal) return UnknownValue;
2772 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2773 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2774 ++NumBruteForceTripCountsComputed;
2775 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2778 // Compute the value of the PHI node for the next iteration.
2779 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2780 if (NextPHI == 0 || NextPHI == PHIVal)
2781 return UnknownValue; // Couldn't evaluate or not making progress...
2785 // Too many iterations were needed to evaluate.
2786 return UnknownValue;
2789 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
2790 /// at the specified scope in the program. The L value specifies a loop
2791 /// nest to evaluate the expression at, where null is the top-level or a
2792 /// specified loop is immediately inside of the loop.
2794 /// This method can be used to compute the exit value for a variable defined
2795 /// in a loop by querying what the value will hold in the parent loop.
2797 /// If this value is not computable at this scope, a SCEVCouldNotCompute
2798 /// object is returned.
2799 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
2800 // FIXME: this should be turned into a virtual method on SCEV!
2802 if (isa<SCEVConstant>(V)) return V;
2804 // If this instruction is evolved from a constant-evolving PHI, compute the
2805 // exit value from the loop without using SCEVs.
2806 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2807 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2808 const Loop *LI = (*this->LI)[I->getParent()];
2809 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2810 if (PHINode *PN = dyn_cast<PHINode>(I))
2811 if (PN->getParent() == LI->getHeader()) {
2812 // Okay, there is no closed form solution for the PHI node. Check
2813 // to see if the loop that contains it has a known backedge-taken
2814 // count. If so, we may be able to force computation of the exit
2816 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2817 if (const SCEVConstant *BTCC =
2818 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2819 // Okay, we know how many times the containing loop executes. If
2820 // this is a constant evolving PHI node, get the final value at
2821 // the specified iteration number.
2822 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2823 BTCC->getValue()->getValue(),
2825 if (RV) return getUnknown(RV);
2829 // Okay, this is an expression that we cannot symbolically evaluate
2830 // into a SCEV. Check to see if it's possible to symbolically evaluate
2831 // the arguments into constants, and if so, try to constant propagate the
2832 // result. This is particularly useful for computing loop exit values.
2833 if (CanConstantFold(I)) {
2834 // Check to see if we've folded this instruction at this loop before.
2835 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2836 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2837 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2839 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2841 std::vector<Constant*> Operands;
2842 Operands.reserve(I->getNumOperands());
2843 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2844 Value *Op = I->getOperand(i);
2845 if (Constant *C = dyn_cast<Constant>(Op)) {
2846 Operands.push_back(C);
2848 // If any of the operands is non-constant and if they are
2849 // non-integer and non-pointer, don't even try to analyze them
2850 // with scev techniques.
2851 if (!isSCEVable(Op->getType()))
2854 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2855 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2856 Constant *C = SC->getValue();
2857 if (C->getType() != Op->getType())
2858 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2862 Operands.push_back(C);
2863 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2864 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2865 if (C->getType() != Op->getType())
2867 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2871 Operands.push_back(C);
2881 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2882 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2883 &Operands[0], Operands.size());
2885 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2886 &Operands[0], Operands.size());
2887 Pair.first->second = C;
2888 return getUnknown(C);
2892 // This is some other type of SCEVUnknown, just return it.
2896 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2897 // Avoid performing the look-up in the common case where the specified
2898 // expression has no loop-variant portions.
2899 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2900 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2901 if (OpAtScope != Comm->getOperand(i)) {
2902 if (OpAtScope == UnknownValue) return UnknownValue;
2903 // Okay, at least one of these operands is loop variant but might be
2904 // foldable. Build a new instance of the folded commutative expression.
2905 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2906 NewOps.push_back(OpAtScope);
2908 for (++i; i != e; ++i) {
2909 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2910 if (OpAtScope == UnknownValue) return UnknownValue;
2911 NewOps.push_back(OpAtScope);
2913 if (isa<SCEVAddExpr>(Comm))
2914 return getAddExpr(NewOps);
2915 if (isa<SCEVMulExpr>(Comm))
2916 return getMulExpr(NewOps);
2917 if (isa<SCEVSMaxExpr>(Comm))
2918 return getSMaxExpr(NewOps);
2919 if (isa<SCEVUMaxExpr>(Comm))
2920 return getUMaxExpr(NewOps);
2921 assert(0 && "Unknown commutative SCEV type!");
2924 // If we got here, all operands are loop invariant.
2928 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2929 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2930 if (LHS == UnknownValue) return LHS;
2931 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2932 if (RHS == UnknownValue) return RHS;
2933 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2934 return Div; // must be loop invariant
2935 return getUDivExpr(LHS, RHS);
2938 // If this is a loop recurrence for a loop that does not contain L, then we
2939 // are dealing with the final value computed by the loop.
2940 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2941 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2942 // To evaluate this recurrence, we need to know how many times the AddRec
2943 // loop iterates. Compute this now.
2944 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2945 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2947 // Then, evaluate the AddRec.
2948 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
2950 return UnknownValue;
2953 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2954 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2955 if (Op == UnknownValue) return Op;
2956 if (Op == Cast->getOperand())
2957 return Cast; // must be loop invariant
2958 return getZeroExtendExpr(Op, Cast->getType());
2961 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2962 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2963 if (Op == UnknownValue) return Op;
2964 if (Op == Cast->getOperand())
2965 return Cast; // must be loop invariant
2966 return getSignExtendExpr(Op, Cast->getType());
2969 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2970 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2971 if (Op == UnknownValue) return Op;
2972 if (Op == Cast->getOperand())
2973 return Cast; // must be loop invariant
2974 return getTruncateExpr(Op, Cast->getType());
2977 assert(0 && "Unknown SCEV type!");
2980 /// getSCEVAtScope - This is a convenience function which does
2981 /// getSCEVAtScope(getSCEV(V), L).
2982 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2983 return getSCEVAtScope(getSCEV(V), L);
2986 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2987 /// following equation:
2989 /// A * X = B (mod N)
2991 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2992 /// A and B isn't important.
2994 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2995 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2996 ScalarEvolution &SE) {
2997 uint32_t BW = A.getBitWidth();
2998 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2999 assert(A != 0 && "A must be non-zero.");
3003 // The gcd of A and N may have only one prime factor: 2. The number of
3004 // trailing zeros in A is its multiplicity
3005 uint32_t Mult2 = A.countTrailingZeros();
3008 // 2. Check if B is divisible by D.
3010 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3011 // is not less than multiplicity of this prime factor for D.
3012 if (B.countTrailingZeros() < Mult2)
3013 return SE.getCouldNotCompute();
3015 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3018 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3019 // bit width during computations.
3020 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3021 APInt Mod(BW + 1, 0);
3022 Mod.set(BW - Mult2); // Mod = N / D
3023 APInt I = AD.multiplicativeInverse(Mod);
3025 // 4. Compute the minimum unsigned root of the equation:
3026 // I * (B / D) mod (N / D)
3027 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3029 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3031 return SE.getConstant(Result.trunc(BW));
3034 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3035 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3036 /// might be the same) or two SCEVCouldNotCompute objects.
3038 static std::pair<SCEVHandle,SCEVHandle>
3039 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3040 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3041 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3042 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3043 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3045 // We currently can only solve this if the coefficients are constants.
3046 if (!LC || !MC || !NC) {
3047 const SCEV *CNC = SE.getCouldNotCompute();
3048 return std::make_pair(CNC, CNC);
3051 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3052 const APInt &L = LC->getValue()->getValue();
3053 const APInt &M = MC->getValue()->getValue();
3054 const APInt &N = NC->getValue()->getValue();
3055 APInt Two(BitWidth, 2);
3056 APInt Four(BitWidth, 4);
3059 using namespace APIntOps;
3061 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3062 // The B coefficient is M-N/2
3066 // The A coefficient is N/2
3067 APInt A(N.sdiv(Two));
3069 // Compute the B^2-4ac term.
3072 SqrtTerm -= Four * (A * C);
3074 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3075 // integer value or else APInt::sqrt() will assert.
3076 APInt SqrtVal(SqrtTerm.sqrt());
3078 // Compute the two solutions for the quadratic formula.
3079 // The divisions must be performed as signed divisions.
3081 APInt TwoA( A << 1 );
3082 if (TwoA.isMinValue()) {
3083 const SCEV *CNC = SE.getCouldNotCompute();
3084 return std::make_pair(CNC, CNC);
3087 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3088 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3090 return std::make_pair(SE.getConstant(Solution1),
3091 SE.getConstant(Solution2));
3092 } // end APIntOps namespace
3095 /// HowFarToZero - Return the number of times a backedge comparing the specified
3096 /// value to zero will execute. If not computable, return UnknownValue
3097 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3098 // If the value is a constant
3099 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3100 // If the value is already zero, the branch will execute zero times.
3101 if (C->getValue()->isZero()) return C;
3102 return UnknownValue; // Otherwise it will loop infinitely.
3105 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3106 if (!AddRec || AddRec->getLoop() != L)
3107 return UnknownValue;
3109 if (AddRec->isAffine()) {
3110 // If this is an affine expression, the execution count of this branch is
3111 // the minimum unsigned root of the following equation:
3113 // Start + Step*N = 0 (mod 2^BW)
3117 // Step*N = -Start (mod 2^BW)
3119 // where BW is the common bit width of Start and Step.
3121 // Get the initial value for the loop.
3122 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3123 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
3125 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
3127 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3128 // For now we handle only constant steps.
3130 // First, handle unitary steps.
3131 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3132 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3133 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3134 return Start; // N = Start (as unsigned)
3136 // Then, try to solve the above equation provided that Start is constant.
3137 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3138 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3139 -StartC->getValue()->getValue(),
3142 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3143 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3144 // the quadratic equation to solve it.
3145 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3147 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3148 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3151 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3152 << " sol#2: " << *R2 << "\n";
3154 // Pick the smallest positive root value.
3155 if (ConstantInt *CB =
3156 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3157 R1->getValue(), R2->getValue()))) {
3158 if (CB->getZExtValue() == false)
3159 std::swap(R1, R2); // R1 is the minimum root now.
3161 // We can only use this value if the chrec ends up with an exact zero
3162 // value at this index. When solving for "X*X != 5", for example, we
3163 // should not accept a root of 2.
3164 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3166 return R1; // We found a quadratic root!
3171 return UnknownValue;
3174 /// HowFarToNonZero - Return the number of times a backedge checking the
3175 /// specified value for nonzero will execute. If not computable, return
3177 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3178 // Loops that look like: while (X == 0) are very strange indeed. We don't
3179 // handle them yet except for the trivial case. This could be expanded in the
3180 // future as needed.
3182 // If the value is a constant, check to see if it is known to be non-zero
3183 // already. If so, the backedge will execute zero times.
3184 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3185 if (!C->getValue()->isNullValue())
3186 return getIntegerSCEV(0, C->getType());
3187 return UnknownValue; // Otherwise it will loop infinitely.
3190 // We could implement others, but I really doubt anyone writes loops like
3191 // this, and if they did, they would already be constant folded.
3192 return UnknownValue;
3195 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3196 /// (which may not be an immediate predecessor) which has exactly one
3197 /// successor from which BB is reachable, or null if no such block is
3201 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3202 // If the block has a unique predecessor, then there is no path from the
3203 // predecessor to the block that does not go through the direct edge
3204 // from the predecessor to the block.
3205 if (BasicBlock *Pred = BB->getSinglePredecessor())
3208 // A loop's header is defined to be a block that dominates the loop.
3209 // If the loop has a preheader, it must be a block that has exactly
3210 // one successor that can reach BB. This is slightly more strict
3211 // than necessary, but works if critical edges are split.
3212 if (Loop *L = LI->getLoopFor(BB))
3213 return L->getLoopPreheader();
3218 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3219 /// a conditional between LHS and RHS. This is used to help avoid max
3220 /// expressions in loop trip counts.
3221 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3222 ICmpInst::Predicate Pred,
3223 const SCEV *LHS, const SCEV *RHS) {
3224 BasicBlock *Preheader = L->getLoopPreheader();
3225 BasicBlock *PreheaderDest = L->getHeader();
3227 // Starting at the preheader, climb up the predecessor chain, as long as
3228 // there are predecessors that can be found that have unique successors
3229 // leading to the original header.
3231 PreheaderDest = Preheader,
3232 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
3234 BranchInst *LoopEntryPredicate =
3235 dyn_cast<BranchInst>(Preheader->getTerminator());
3236 if (!LoopEntryPredicate ||
3237 LoopEntryPredicate->isUnconditional())
3240 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3243 // Now that we found a conditional branch that dominates the loop, check to
3244 // see if it is the comparison we are looking for.
3245 Value *PreCondLHS = ICI->getOperand(0);
3246 Value *PreCondRHS = ICI->getOperand(1);
3247 ICmpInst::Predicate Cond;
3248 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3249 Cond = ICI->getPredicate();
3251 Cond = ICI->getInversePredicate();
3254 ; // An exact match.
3255 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3256 ; // The actual condition is beyond sufficient.
3258 // Check a few special cases.
3260 case ICmpInst::ICMP_UGT:
3261 if (Pred == ICmpInst::ICMP_ULT) {
3262 std::swap(PreCondLHS, PreCondRHS);
3263 Cond = ICmpInst::ICMP_ULT;
3267 case ICmpInst::ICMP_SGT:
3268 if (Pred == ICmpInst::ICMP_SLT) {
3269 std::swap(PreCondLHS, PreCondRHS);
3270 Cond = ICmpInst::ICMP_SLT;
3274 case ICmpInst::ICMP_NE:
3275 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3276 // so check for this case by checking if the NE is comparing against
3277 // a minimum or maximum constant.
3278 if (!ICmpInst::isTrueWhenEqual(Pred))
3279 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3280 const APInt &A = CI->getValue();
3282 case ICmpInst::ICMP_SLT:
3283 if (A.isMaxSignedValue()) break;
3285 case ICmpInst::ICMP_SGT:
3286 if (A.isMinSignedValue()) break;
3288 case ICmpInst::ICMP_ULT:
3289 if (A.isMaxValue()) break;
3291 case ICmpInst::ICMP_UGT:
3292 if (A.isMinValue()) break;
3297 Cond = ICmpInst::ICMP_NE;
3298 // NE is symmetric but the original comparison may not be. Swap
3299 // the operands if necessary so that they match below.
3300 if (isa<SCEVConstant>(LHS))
3301 std::swap(PreCondLHS, PreCondRHS);
3306 // We weren't able to reconcile the condition.
3310 if (!PreCondLHS->getType()->isInteger()) continue;
3312 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3313 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3314 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3315 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3316 RHS == getNotSCEV(PreCondLHSSCEV)))
3323 /// HowManyLessThans - Return the number of times a backedge containing the
3324 /// specified less-than comparison will execute. If not computable, return
3326 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
3327 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3328 const Loop *L, bool isSigned) {
3329 // Only handle: "ADDREC < LoopInvariant".
3330 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3332 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3333 if (!AddRec || AddRec->getLoop() != L)
3334 return UnknownValue;
3336 if (AddRec->isAffine()) {
3337 // FORNOW: We only support unit strides.
3338 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3339 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3340 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3342 // TODO: handle non-constant strides.
3343 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3344 if (!CStep || CStep->isZero())
3345 return UnknownValue;
3346 if (CStep->getValue()->getValue() == 1) {
3347 // With unit stride, the iteration never steps past the limit value.
3348 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3349 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3350 // Test whether a positive iteration iteration can step past the limit
3351 // value and past the maximum value for its type in a single step.
3353 APInt Max = APInt::getSignedMaxValue(BitWidth);
3354 if ((Max - CStep->getValue()->getValue())
3355 .slt(CLimit->getValue()->getValue()))
3356 return UnknownValue;
3358 APInt Max = APInt::getMaxValue(BitWidth);
3359 if ((Max - CStep->getValue()->getValue())
3360 .ult(CLimit->getValue()->getValue()))
3361 return UnknownValue;
3364 // TODO: handle non-constant limit values below.
3365 return UnknownValue;
3367 // TODO: handle negative strides below.
3368 return UnknownValue;
3370 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3371 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3372 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
3373 // treat m-n as signed nor unsigned due to overflow possibility.
3375 // First, we get the value of the LHS in the first iteration: n
3376 SCEVHandle Start = AddRec->getOperand(0);
3378 // Determine the minimum constant start value.
3379 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3380 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3381 APInt::getMinValue(BitWidth));
3383 // If we know that the condition is true in order to enter the loop,
3384 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3385 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3386 // division must round up.
3387 SCEVHandle End = RHS;
3388 if (!isLoopGuardedByCond(L,
3389 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3390 getMinusSCEV(Start, Step), RHS))
3391 End = isSigned ? getSMaxExpr(RHS, Start)
3392 : getUMaxExpr(RHS, Start);
3394 // Determine the maximum constant end value.
3395 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3396 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3397 APInt::getMaxValue(BitWidth));
3399 // Finally, we subtract these two values and divide, rounding up, to get
3400 // the number of times the backedge is executed.
3401 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3402 getAddExpr(Step, NegOne)),
3405 // The maximum backedge count is similar, except using the minimum start
3406 // value and the maximum end value.
3407 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3409 getAddExpr(Step, NegOne)),
3412 return BackedgeTakenInfo(BECount, MaxBECount);
3415 return UnknownValue;
3418 /// getNumIterationsInRange - Return the number of iterations of this loop that
3419 /// produce values in the specified constant range. Another way of looking at
3420 /// this is that it returns the first iteration number where the value is not in
3421 /// the condition, thus computing the exit count. If the iteration count can't
3422 /// be computed, an instance of SCEVCouldNotCompute is returned.
3423 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3424 ScalarEvolution &SE) const {
3425 if (Range.isFullSet()) // Infinite loop.
3426 return SE.getCouldNotCompute();
3428 // If the start is a non-zero constant, shift the range to simplify things.
3429 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3430 if (!SC->getValue()->isZero()) {
3431 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3432 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3433 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3434 if (const SCEVAddRecExpr *ShiftedAddRec =
3435 dyn_cast<SCEVAddRecExpr>(Shifted))
3436 return ShiftedAddRec->getNumIterationsInRange(
3437 Range.subtract(SC->getValue()->getValue()), SE);
3438 // This is strange and shouldn't happen.
3439 return SE.getCouldNotCompute();
3442 // The only time we can solve this is when we have all constant indices.
3443 // Otherwise, we cannot determine the overflow conditions.
3444 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3445 if (!isa<SCEVConstant>(getOperand(i)))
3446 return SE.getCouldNotCompute();
3449 // Okay at this point we know that all elements of the chrec are constants and
3450 // that the start element is zero.
3452 // First check to see if the range contains zero. If not, the first
3454 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3455 if (!Range.contains(APInt(BitWidth, 0)))
3456 return SE.getConstant(ConstantInt::get(getType(),0));
3459 // If this is an affine expression then we have this situation:
3460 // Solve {0,+,A} in Range === Ax in Range
3462 // We know that zero is in the range. If A is positive then we know that
3463 // the upper value of the range must be the first possible exit value.
3464 // If A is negative then the lower of the range is the last possible loop
3465 // value. Also note that we already checked for a full range.
3466 APInt One(BitWidth,1);
3467 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3468 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3470 // The exit value should be (End+A)/A.
3471 APInt ExitVal = (End + A).udiv(A);
3472 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3474 // Evaluate at the exit value. If we really did fall out of the valid
3475 // range, then we computed our trip count, otherwise wrap around or other
3476 // things must have happened.
3477 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3478 if (Range.contains(Val->getValue()))
3479 return SE.getCouldNotCompute(); // Something strange happened
3481 // Ensure that the previous value is in the range. This is a sanity check.
3482 assert(Range.contains(
3483 EvaluateConstantChrecAtConstant(this,
3484 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3485 "Linear scev computation is off in a bad way!");
3486 return SE.getConstant(ExitValue);
3487 } else if (isQuadratic()) {
3488 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3489 // quadratic equation to solve it. To do this, we must frame our problem in
3490 // terms of figuring out when zero is crossed, instead of when
3491 // Range.getUpper() is crossed.
3492 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3493 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3494 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3496 // Next, solve the constructed addrec
3497 std::pair<SCEVHandle,SCEVHandle> Roots =
3498 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3499 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3500 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3502 // Pick the smallest positive root value.
3503 if (ConstantInt *CB =
3504 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3505 R1->getValue(), R2->getValue()))) {
3506 if (CB->getZExtValue() == false)
3507 std::swap(R1, R2); // R1 is the minimum root now.
3509 // Make sure the root is not off by one. The returned iteration should
3510 // not be in the range, but the previous one should be. When solving
3511 // for "X*X < 5", for example, we should not return a root of 2.
3512 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3515 if (Range.contains(R1Val->getValue())) {
3516 // The next iteration must be out of the range...
3517 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3519 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3520 if (!Range.contains(R1Val->getValue()))
3521 return SE.getConstant(NextVal);
3522 return SE.getCouldNotCompute(); // Something strange happened
3525 // If R1 was not in the range, then it is a good return value. Make
3526 // sure that R1-1 WAS in the range though, just in case.
3527 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3528 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3529 if (Range.contains(R1Val->getValue()))
3531 return SE.getCouldNotCompute(); // Something strange happened
3536 return SE.getCouldNotCompute();
3541 //===----------------------------------------------------------------------===//
3542 // SCEVCallbackVH Class Implementation
3543 //===----------------------------------------------------------------------===//
3545 void SCEVCallbackVH::deleted() {
3546 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3547 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3548 SE->ConstantEvolutionLoopExitValue.erase(PN);
3549 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3550 SE->ValuesAtScopes.erase(I);
3551 SE->Scalars.erase(getValPtr());
3552 // this now dangles!
3555 void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3556 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3558 // Forget all the expressions associated with users of the old value,
3559 // so that future queries will recompute the expressions using the new
3561 SmallVector<User *, 16> Worklist;
3562 Value *Old = getValPtr();
3563 bool DeleteOld = false;
3564 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3566 Worklist.push_back(*UI);
3567 while (!Worklist.empty()) {
3568 User *U = Worklist.pop_back_val();
3569 // Deleting the Old value will cause this to dangle. Postpone
3570 // that until everything else is done.
3575 if (PHINode *PN = dyn_cast<PHINode>(U))
3576 SE->ConstantEvolutionLoopExitValue.erase(PN);
3577 if (Instruction *I = dyn_cast<Instruction>(U))
3578 SE->ValuesAtScopes.erase(I);
3579 if (SE->Scalars.erase(U))
3580 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3582 Worklist.push_back(*UI);
3585 if (PHINode *PN = dyn_cast<PHINode>(Old))
3586 SE->ConstantEvolutionLoopExitValue.erase(PN);
3587 if (Instruction *I = dyn_cast<Instruction>(Old))
3588 SE->ValuesAtScopes.erase(I);
3589 SE->Scalars.erase(Old);
3590 // this now dangles!
3595 SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3596 : CallbackVH(V), SE(se) {}
3598 //===----------------------------------------------------------------------===//
3599 // ScalarEvolution Class Implementation
3600 //===----------------------------------------------------------------------===//
3602 ScalarEvolution::ScalarEvolution()
3603 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3606 bool ScalarEvolution::runOnFunction(Function &F) {
3608 LI = &getAnalysis<LoopInfo>();
3609 TD = getAnalysisIfAvailable<TargetData>();
3613 void ScalarEvolution::releaseMemory() {
3615 BackedgeTakenCounts.clear();
3616 ConstantEvolutionLoopExitValue.clear();
3617 ValuesAtScopes.clear();
3620 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3621 AU.setPreservesAll();
3622 AU.addRequiredTransitive<LoopInfo>();
3625 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3626 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3629 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3631 // Print all inner loops first
3632 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3633 PrintLoopInfo(OS, SE, *I);
3635 OS << "Loop " << L->getHeader()->getName() << ": ";
3637 SmallVector<BasicBlock*, 8> ExitBlocks;
3638 L->getExitBlocks(ExitBlocks);
3639 if (ExitBlocks.size() != 1)
3640 OS << "<multiple exits> ";
3642 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3643 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3645 OS << "Unpredictable backedge-taken count. ";
3651 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3652 // ScalarEvolution's implementaiton of the print method is to print
3653 // out SCEV values of all instructions that are interesting. Doing
3654 // this potentially causes it to create new SCEV objects though,
3655 // which technically conflicts with the const qualifier. This isn't
3656 // observable from outside the class though (the hasSCEV function
3657 // notwithstanding), so casting away the const isn't dangerous.
3658 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3660 OS << "Classifying expressions for: " << F->getName() << "\n";
3661 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3662 if (isSCEVable(I->getType())) {
3665 SCEVHandle SV = SE.getSCEV(&*I);
3669 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
3671 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
3672 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3673 OS << "<<Unknown>>";
3683 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3684 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3685 PrintLoopInfo(OS, &SE, *I);
3688 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3689 raw_os_ostream OS(o);