1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/Instructions.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Assembly/Writer.h"
70 #include "llvm/Transforms/Scalar.h"
71 #include "llvm/Support/CFG.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ConstantRange.h"
75 #include "llvm/Support/InstIterator.h"
76 #include "llvm/Support/ManagedStatic.h"
77 #include "llvm/Support/Streams.h"
78 #include "llvm/ADT/Statistic.h"
85 RegisterPass<ScalarEvolution>
86 R("scalar-evolution", "Scalar Evolution Analysis");
89 NumBruteForceEvaluations("scalar-evolution",
90 "Number of brute force evaluations needed to "
91 "calculate high-order polynomial exit values");
93 NumArrayLenItCounts("scalar-evolution",
94 "Number of trip counts computed with array length");
96 NumTripCountsComputed("scalar-evolution",
97 "Number of loops with predictable loop counts");
99 NumTripCountsNotComputed("scalar-evolution",
100 "Number of loops without predictable loop counts");
102 NumBruteForceTripCountsComputed("scalar-evolution",
103 "Number of loops with trip counts computed by force");
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant derived loop"),
112 //===----------------------------------------------------------------------===//
113 // SCEV class definitions
114 //===----------------------------------------------------------------------===//
116 //===----------------------------------------------------------------------===//
117 // Implementation of the SCEV class.
120 void SCEV::dump() const {
124 /// getValueRange - Return the tightest constant bounds that this value is
125 /// known to have. This method is only valid on integer SCEV objects.
126 ConstantRange SCEV::getValueRange() const {
127 const Type *Ty = getType();
128 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
129 Ty = Ty->getUnsignedVersion();
130 // Default to a full range if no better information is available.
131 return ConstantRange(getType());
135 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 SCEVHandle SCEVCouldNotCompute::
153 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
154 const SCEVHandle &Conc) const {
158 void SCEVCouldNotCompute::print(std::ostream &OS) const {
159 OS << "***COULDNOTCOMPUTE***";
162 bool SCEVCouldNotCompute::classof(const SCEV *S) {
163 return S->getSCEVType() == scCouldNotCompute;
167 // SCEVConstants - Only allow the creation of one SCEVConstant for any
168 // particular value. Don't use a SCEVHandle here, or else the object will
170 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
173 SCEVConstant::~SCEVConstant() {
174 SCEVConstants->erase(V);
177 SCEVHandle SCEVConstant::get(ConstantInt *V) {
178 // Make sure that SCEVConstant instances are all unsigned.
179 if (V->getType()->isSigned()) {
180 const Type *NewTy = V->getType()->getUnsignedVersion();
181 V = cast<ConstantInt>(
182 ConstantExpr::getBitCast(V, NewTy));
185 SCEVConstant *&R = (*SCEVConstants)[V];
186 if (R == 0) R = new SCEVConstant(V);
190 ConstantRange SCEVConstant::getValueRange() const {
191 return ConstantRange(V);
194 const Type *SCEVConstant::getType() const { return V->getType(); }
196 void SCEVConstant::print(std::ostream &OS) const {
197 WriteAsOperand(OS, V, false);
200 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
201 // particular input. Don't use a SCEVHandle here, or else the object will
203 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
204 SCEVTruncateExpr*> > SCEVTruncates;
206 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
207 : SCEV(scTruncate), Op(op), Ty(ty) {
208 assert(Op->getType()->isInteger() && Ty->isInteger() &&
209 "Cannot truncate non-integer value!");
210 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
211 "This is not a truncating conversion!");
214 SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates->erase(std::make_pair(Op, Ty));
218 ConstantRange SCEVTruncateExpr::getValueRange() const {
219 return getOperand()->getValueRange().truncate(getType());
222 void SCEVTruncateExpr::print(std::ostream &OS) const {
223 OS << "(truncate " << *Op << " to " << *Ty << ")";
226 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227 // particular input. Don't use a SCEVHandle here, or else the object will never
229 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
230 SCEVZeroExtendExpr*> > SCEVZeroExtends;
232 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
233 : SCEV(scZeroExtend), Op(op), Ty(ty) {
234 assert(Op->getType()->isInteger() && Ty->isInteger() &&
235 "Cannot zero extend non-integer value!");
236 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
237 "This is not an extending conversion!");
240 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
241 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
244 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
245 return getOperand()->getValueRange().zeroExtend(getType());
248 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
249 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
252 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
253 // particular input. Don't use a SCEVHandle here, or else the object will never
255 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
256 SCEVCommutativeExpr*> > SCEVCommExprs;
258 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
259 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
260 std::vector<SCEV*>(Operands.begin(),
264 void SCEVCommutativeExpr::print(std::ostream &OS) const {
265 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
266 const char *OpStr = getOperationStr();
267 OS << "(" << *Operands[0];
268 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
269 OS << OpStr << *Operands[i];
273 SCEVHandle SCEVCommutativeExpr::
274 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
275 const SCEVHandle &Conc) const {
276 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
277 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
278 if (H != getOperand(i)) {
279 std::vector<SCEVHandle> NewOps;
280 NewOps.reserve(getNumOperands());
281 for (unsigned j = 0; j != i; ++j)
282 NewOps.push_back(getOperand(j));
284 for (++i; i != e; ++i)
285 NewOps.push_back(getOperand(i)->
286 replaceSymbolicValuesWithConcrete(Sym, Conc));
288 if (isa<SCEVAddExpr>(this))
289 return SCEVAddExpr::get(NewOps);
290 else if (isa<SCEVMulExpr>(this))
291 return SCEVMulExpr::get(NewOps);
293 assert(0 && "Unknown commutative expr!");
300 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
301 // input. Don't use a SCEVHandle here, or else the object will never be
303 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
304 SCEVSDivExpr*> > SCEVSDivs;
306 SCEVSDivExpr::~SCEVSDivExpr() {
307 SCEVSDivs->erase(std::make_pair(LHS, RHS));
310 void SCEVSDivExpr::print(std::ostream &OS) const {
311 OS << "(" << *LHS << " /s " << *RHS << ")";
314 const Type *SCEVSDivExpr::getType() const {
315 const Type *Ty = LHS->getType();
316 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
320 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
321 // particular input. Don't use a SCEVHandle here, or else the object will never
323 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
324 SCEVAddRecExpr*> > SCEVAddRecExprs;
326 SCEVAddRecExpr::~SCEVAddRecExpr() {
327 SCEVAddRecExprs->erase(std::make_pair(L,
328 std::vector<SCEV*>(Operands.begin(),
332 SCEVHandle SCEVAddRecExpr::
333 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
334 const SCEVHandle &Conc) const {
335 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
336 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
337 if (H != getOperand(i)) {
338 std::vector<SCEVHandle> NewOps;
339 NewOps.reserve(getNumOperands());
340 for (unsigned j = 0; j != i; ++j)
341 NewOps.push_back(getOperand(j));
343 for (++i; i != e; ++i)
344 NewOps.push_back(getOperand(i)->
345 replaceSymbolicValuesWithConcrete(Sym, Conc));
347 return get(NewOps, L);
354 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
355 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
356 // contain L and if the start is invariant.
357 return !QueryLoop->contains(L->getHeader()) &&
358 getOperand(0)->isLoopInvariant(QueryLoop);
362 void SCEVAddRecExpr::print(std::ostream &OS) const {
363 OS << "{" << *Operands[0];
364 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
365 OS << ",+," << *Operands[i];
366 OS << "}<" << L->getHeader()->getName() + ">";
369 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
370 // value. Don't use a SCEVHandle here, or else the object will never be
372 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
374 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
376 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
377 // All non-instruction values are loop invariant. All instructions are loop
378 // invariant if they are not contained in the specified loop.
379 if (Instruction *I = dyn_cast<Instruction>(V))
380 return !L->contains(I->getParent());
384 const Type *SCEVUnknown::getType() const {
388 void SCEVUnknown::print(std::ostream &OS) const {
389 WriteAsOperand(OS, V, false);
392 //===----------------------------------------------------------------------===//
394 //===----------------------------------------------------------------------===//
397 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
398 /// than the complexity of the RHS. This comparator is used to canonicalize
400 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
401 bool operator()(SCEV *LHS, SCEV *RHS) {
402 return LHS->getSCEVType() < RHS->getSCEVType();
407 /// GroupByComplexity - Given a list of SCEV objects, order them by their
408 /// complexity, and group objects of the same complexity together by value.
409 /// When this routine is finished, we know that any duplicates in the vector are
410 /// consecutive and that complexity is monotonically increasing.
412 /// Note that we go take special precautions to ensure that we get determinstic
413 /// results from this routine. In other words, we don't want the results of
414 /// this to depend on where the addresses of various SCEV objects happened to
417 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
418 if (Ops.size() < 2) return; // Noop
419 if (Ops.size() == 2) {
420 // This is the common case, which also happens to be trivially simple.
422 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
423 std::swap(Ops[0], Ops[1]);
427 // Do the rough sort by complexity.
428 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
430 // Now that we are sorted by complexity, group elements of the same
431 // complexity. Note that this is, at worst, N^2, but the vector is likely to
432 // be extremely short in practice. Note that we take this approach because we
433 // do not want to depend on the addresses of the objects we are grouping.
434 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
436 unsigned Complexity = S->getSCEVType();
438 // If there are any objects of the same complexity and same value as this
440 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
441 if (Ops[j] == S) { // Found a duplicate.
442 // Move it to immediately after i'th element.
443 std::swap(Ops[i+1], Ops[j]);
444 ++i; // no need to rescan it.
445 if (i == e-2) return; // Done!
453 //===----------------------------------------------------------------------===//
454 // Simple SCEV method implementations
455 //===----------------------------------------------------------------------===//
457 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
458 /// specified signed integer value and return a SCEV for the constant.
459 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
462 C = Constant::getNullValue(Ty);
463 else if (Ty->isFloatingPoint())
464 C = ConstantFP::get(Ty, Val);
465 else if (Ty->isSigned())
466 C = ConstantInt::get(Ty, Val);
468 C = ConstantInt::get(Ty->getSignedVersion(), Val);
469 C = ConstantExpr::getBitCast(C, Ty);
471 return SCEVUnknown::get(C);
474 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
475 /// input value to the specified type. If the type must be extended, it is zero
477 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
478 const Type *SrcTy = V->getType();
479 assert(SrcTy->isInteger() && Ty->isInteger() &&
480 "Cannot truncate or zero extend with non-integer arguments!");
481 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
482 return V; // No conversion
483 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
484 return SCEVTruncateExpr::get(V, Ty);
485 return SCEVZeroExtendExpr::get(V, Ty);
488 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
490 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
491 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
492 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
494 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
497 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
499 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
501 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
505 /// PartialFact - Compute V!/(V-NumSteps)!
506 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
507 // Handle this case efficiently, it is common to have constant iteration
508 // counts while computing loop exit values.
509 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
510 uint64_t Val = SC->getValue()->getZExtValue();
512 for (; NumSteps; --NumSteps)
513 Result *= Val-(NumSteps-1);
514 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
515 return SCEVUnknown::get(
516 ConstantExpr::getTruncOrBitCast(Res, V->getType()));
519 const Type *Ty = V->getType();
521 return SCEVUnknown::getIntegerSCEV(1, Ty);
523 SCEVHandle Result = V;
524 for (unsigned i = 1; i != NumSteps; ++i)
525 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
526 SCEVUnknown::getIntegerSCEV(i, Ty)));
531 /// evaluateAtIteration - Return the value of this chain of recurrences at
532 /// the specified iteration number. We can evaluate this recurrence by
533 /// multiplying each element in the chain by the binomial coefficient
534 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
536 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
538 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
539 /// Is the binomial equation safe using modular arithmetic??
541 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
542 SCEVHandle Result = getStart();
544 const Type *Ty = It->getType();
545 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
546 SCEVHandle BC = PartialFact(It, i);
548 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
549 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
550 Result = SCEVAddExpr::get(Result, Val);
556 //===----------------------------------------------------------------------===//
557 // SCEV Expression folder implementations
558 //===----------------------------------------------------------------------===//
560 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
561 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
562 return SCEVUnknown::get(
563 ConstantExpr::getTrunc(SC->getValue(), Ty));
565 // If the input value is a chrec scev made out of constants, truncate
566 // all of the constants.
567 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
568 std::vector<SCEVHandle> Operands;
569 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
570 // FIXME: This should allow truncation of other expression types!
571 if (isa<SCEVConstant>(AddRec->getOperand(i)))
572 Operands.push_back(get(AddRec->getOperand(i), Ty));
575 if (Operands.size() == AddRec->getNumOperands())
576 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
579 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
580 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
584 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
585 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
586 return SCEVUnknown::get(
587 ConstantExpr::getZeroExtend(SC->getValue(), Ty));
589 // FIXME: If the input value is a chrec scev, and we can prove that the value
590 // did not overflow the old, smaller, value, we can zero extend all of the
591 // operands (often constants). This would allow analysis of something like
592 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
594 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
595 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
599 // get - Get a canonical add expression, or something simpler if possible.
600 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
601 assert(!Ops.empty() && "Cannot get empty add!");
602 if (Ops.size() == 1) return Ops[0];
604 // Sort by complexity, this groups all similar expression types together.
605 GroupByComplexity(Ops);
607 // If there are any constants, fold them together.
609 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
611 assert(Idx < Ops.size());
612 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
613 // We found two constants, fold them together!
614 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
615 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
616 Ops[0] = SCEVConstant::get(CI);
617 Ops.erase(Ops.begin()+1); // Erase the folded element
618 if (Ops.size() == 1) return Ops[0];
619 LHSC = cast<SCEVConstant>(Ops[0]);
621 // If we couldn't fold the expression, move to the next constant. Note
622 // that this is impossible to happen in practice because we always
623 // constant fold constant ints to constant ints.
628 // If we are left with a constant zero being added, strip it off.
629 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
630 Ops.erase(Ops.begin());
635 if (Ops.size() == 1) return Ops[0];
637 // Okay, check to see if the same value occurs in the operand list twice. If
638 // so, merge them together into an multiply expression. Since we sorted the
639 // list, these values are required to be adjacent.
640 const Type *Ty = Ops[0]->getType();
641 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
642 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
643 // Found a match, merge the two values into a multiply, and add any
644 // remaining values to the result.
645 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
646 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
649 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
651 return SCEVAddExpr::get(Ops);
654 // Okay, now we know the first non-constant operand. If there are add
655 // operands they would be next.
656 if (Idx < Ops.size()) {
657 bool DeletedAdd = false;
658 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
659 // If we have an add, expand the add operands onto the end of the operands
661 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
662 Ops.erase(Ops.begin()+Idx);
666 // If we deleted at least one add, we added operands to the end of the list,
667 // and they are not necessarily sorted. Recurse to resort and resimplify
668 // any operands we just aquired.
673 // Skip over the add expression until we get to a multiply.
674 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
677 // If we are adding something to a multiply expression, make sure the
678 // something is not already an operand of the multiply. If so, merge it into
680 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
681 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
682 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
683 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
684 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
685 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
686 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
687 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
688 if (Mul->getNumOperands() != 2) {
689 // If the multiply has more than two operands, we must get the
691 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
692 MulOps.erase(MulOps.begin()+MulOp);
693 InnerMul = SCEVMulExpr::get(MulOps);
695 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
696 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
697 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
698 if (Ops.size() == 2) return OuterMul;
700 Ops.erase(Ops.begin()+AddOp);
701 Ops.erase(Ops.begin()+Idx-1);
703 Ops.erase(Ops.begin()+Idx);
704 Ops.erase(Ops.begin()+AddOp-1);
706 Ops.push_back(OuterMul);
707 return SCEVAddExpr::get(Ops);
710 // Check this multiply against other multiplies being added together.
711 for (unsigned OtherMulIdx = Idx+1;
712 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
714 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
715 // If MulOp occurs in OtherMul, we can fold the two multiplies
717 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
718 OMulOp != e; ++OMulOp)
719 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
720 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
721 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
722 if (Mul->getNumOperands() != 2) {
723 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
724 MulOps.erase(MulOps.begin()+MulOp);
725 InnerMul1 = SCEVMulExpr::get(MulOps);
727 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
728 if (OtherMul->getNumOperands() != 2) {
729 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
731 MulOps.erase(MulOps.begin()+OMulOp);
732 InnerMul2 = SCEVMulExpr::get(MulOps);
734 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
735 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
736 if (Ops.size() == 2) return OuterMul;
737 Ops.erase(Ops.begin()+Idx);
738 Ops.erase(Ops.begin()+OtherMulIdx-1);
739 Ops.push_back(OuterMul);
740 return SCEVAddExpr::get(Ops);
746 // If there are any add recurrences in the operands list, see if any other
747 // added values are loop invariant. If so, we can fold them into the
749 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
752 // Scan over all recurrences, trying to fold loop invariants into them.
753 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
754 // Scan all of the other operands to this add and add them to the vector if
755 // they are loop invariant w.r.t. the recurrence.
756 std::vector<SCEVHandle> LIOps;
757 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
758 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
759 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
760 LIOps.push_back(Ops[i]);
761 Ops.erase(Ops.begin()+i);
765 // If we found some loop invariants, fold them into the recurrence.
766 if (!LIOps.empty()) {
767 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
768 LIOps.push_back(AddRec->getStart());
770 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
771 AddRecOps[0] = SCEVAddExpr::get(LIOps);
773 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
774 // If all of the other operands were loop invariant, we are done.
775 if (Ops.size() == 1) return NewRec;
777 // Otherwise, add the folded AddRec by the non-liv parts.
778 for (unsigned i = 0;; ++i)
779 if (Ops[i] == AddRec) {
783 return SCEVAddExpr::get(Ops);
786 // Okay, if there weren't any loop invariants to be folded, check to see if
787 // there are multiple AddRec's with the same loop induction variable being
788 // added together. If so, we can fold them.
789 for (unsigned OtherIdx = Idx+1;
790 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
791 if (OtherIdx != Idx) {
792 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
793 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
794 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
795 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
796 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
797 if (i >= NewOps.size()) {
798 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
799 OtherAddRec->op_end());
802 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
804 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
806 if (Ops.size() == 2) return NewAddRec;
808 Ops.erase(Ops.begin()+Idx);
809 Ops.erase(Ops.begin()+OtherIdx-1);
810 Ops.push_back(NewAddRec);
811 return SCEVAddExpr::get(Ops);
815 // Otherwise couldn't fold anything into this recurrence. Move onto the
819 // Okay, it looks like we really DO need an add expr. Check to see if we
820 // already have one, otherwise create a new one.
821 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
822 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
824 if (Result == 0) Result = new SCEVAddExpr(Ops);
829 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
830 assert(!Ops.empty() && "Cannot get empty mul!");
832 // Sort by complexity, this groups all similar expression types together.
833 GroupByComplexity(Ops);
835 // If there are any constants, fold them together.
837 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
839 // C1*(C2+V) -> C1*C2 + C1*V
841 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
842 if (Add->getNumOperands() == 2 &&
843 isa<SCEVConstant>(Add->getOperand(0)))
844 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
845 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
849 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
850 // We found two constants, fold them together!
851 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
852 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
853 Ops[0] = SCEVConstant::get(CI);
854 Ops.erase(Ops.begin()+1); // Erase the folded element
855 if (Ops.size() == 1) return Ops[0];
856 LHSC = cast<SCEVConstant>(Ops[0]);
858 // If we couldn't fold the expression, move to the next constant. Note
859 // that this is impossible to happen in practice because we always
860 // constant fold constant ints to constant ints.
865 // If we are left with a constant one being multiplied, strip it off.
866 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
867 Ops.erase(Ops.begin());
869 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
870 // If we have a multiply of zero, it will always be zero.
875 // Skip over the add expression until we get to a multiply.
876 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
882 // If there are mul operands inline them all into this expression.
883 if (Idx < Ops.size()) {
884 bool DeletedMul = false;
885 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
886 // If we have an mul, expand the mul operands onto the end of the operands
888 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
889 Ops.erase(Ops.begin()+Idx);
893 // If we deleted at least one mul, we added operands to the end of the list,
894 // and they are not necessarily sorted. Recurse to resort and resimplify
895 // any operands we just aquired.
900 // If there are any add recurrences in the operands list, see if any other
901 // added values are loop invariant. If so, we can fold them into the
903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
906 // Scan over all recurrences, trying to fold loop invariants into them.
907 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
908 // Scan all of the other operands to this mul and add them to the vector if
909 // they are loop invariant w.r.t. the recurrence.
910 std::vector<SCEVHandle> LIOps;
911 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
912 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
913 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
914 LIOps.push_back(Ops[i]);
915 Ops.erase(Ops.begin()+i);
919 // If we found some loop invariants, fold them into the recurrence.
920 if (!LIOps.empty()) {
921 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
922 std::vector<SCEVHandle> NewOps;
923 NewOps.reserve(AddRec->getNumOperands());
924 if (LIOps.size() == 1) {
925 SCEV *Scale = LIOps[0];
926 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
927 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
929 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
930 std::vector<SCEVHandle> MulOps(LIOps);
931 MulOps.push_back(AddRec->getOperand(i));
932 NewOps.push_back(SCEVMulExpr::get(MulOps));
936 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
938 // If all of the other operands were loop invariant, we are done.
939 if (Ops.size() == 1) return NewRec;
941 // Otherwise, multiply the folded AddRec by the non-liv parts.
942 for (unsigned i = 0;; ++i)
943 if (Ops[i] == AddRec) {
947 return SCEVMulExpr::get(Ops);
950 // Okay, if there weren't any loop invariants to be folded, check to see if
951 // there are multiple AddRec's with the same loop induction variable being
952 // multiplied together. If so, we can fold them.
953 for (unsigned OtherIdx = Idx+1;
954 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
955 if (OtherIdx != Idx) {
956 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
957 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
958 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
959 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
960 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
962 SCEVHandle B = F->getStepRecurrence();
963 SCEVHandle D = G->getStepRecurrence();
964 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
965 SCEVMulExpr::get(G, B),
966 SCEVMulExpr::get(B, D));
967 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
969 if (Ops.size() == 2) return NewAddRec;
971 Ops.erase(Ops.begin()+Idx);
972 Ops.erase(Ops.begin()+OtherIdx-1);
973 Ops.push_back(NewAddRec);
974 return SCEVMulExpr::get(Ops);
978 // Otherwise couldn't fold anything into this recurrence. Move onto the
982 // Okay, it looks like we really DO need an mul expr. Check to see if we
983 // already have one, otherwise create a new one.
984 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
985 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
988 Result = new SCEVMulExpr(Ops);
992 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
993 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
994 if (RHSC->getValue()->equalsInt(1))
995 return LHS; // X sdiv 1 --> x
996 if (RHSC->getValue()->isAllOnesValue())
997 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
999 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1000 Constant *LHSCV = LHSC->getValue();
1001 Constant *RHSCV = RHSC->getValue();
1002 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
1006 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1008 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1009 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1014 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1015 /// specified loop. Simplify the expression as much as possible.
1016 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1017 const SCEVHandle &Step, const Loop *L) {
1018 std::vector<SCEVHandle> Operands;
1019 Operands.push_back(Start);
1020 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1021 if (StepChrec->getLoop() == L) {
1022 Operands.insert(Operands.end(), StepChrec->op_begin(),
1023 StepChrec->op_end());
1024 return get(Operands, L);
1027 Operands.push_back(Step);
1028 return get(Operands, L);
1031 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1032 /// specified loop. Simplify the expression as much as possible.
1033 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1035 if (Operands.size() == 1) return Operands[0];
1037 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1038 if (StepC->getValue()->isNullValue()) {
1039 Operands.pop_back();
1040 return get(Operands, L); // { X,+,0 } --> X
1043 SCEVAddRecExpr *&Result =
1044 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1046 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1050 SCEVHandle SCEVUnknown::get(Value *V) {
1051 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1052 return SCEVConstant::get(CI);
1053 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1054 if (Result == 0) Result = new SCEVUnknown(V);
1059 //===----------------------------------------------------------------------===//
1060 // ScalarEvolutionsImpl Definition and Implementation
1061 //===----------------------------------------------------------------------===//
1063 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1067 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1068 /// F - The function we are analyzing.
1072 /// LI - The loop information for the function we are currently analyzing.
1076 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1078 SCEVHandle UnknownValue;
1080 /// Scalars - This is a cache of the scalars we have analyzed so far.
1082 std::map<Value*, SCEVHandle> Scalars;
1084 /// IterationCounts - Cache the iteration count of the loops for this
1085 /// function as they are computed.
1086 std::map<const Loop*, SCEVHandle> IterationCounts;
1088 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1089 /// the PHI instructions that we attempt to compute constant evolutions for.
1090 /// This allows us to avoid potentially expensive recomputation of these
1091 /// properties. An instruction maps to null if we are unable to compute its
1093 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1096 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1097 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1099 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1100 /// expression and create a new one.
1101 SCEVHandle getSCEV(Value *V);
1103 /// hasSCEV - Return true if the SCEV for this value has already been
1105 bool hasSCEV(Value *V) const {
1106 return Scalars.count(V);
1109 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1110 /// the specified value.
1111 void setSCEV(Value *V, const SCEVHandle &H) {
1112 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1113 assert(isNew && "This entry already existed!");
1117 /// getSCEVAtScope - Compute the value of the specified expression within
1118 /// the indicated loop (which may be null to indicate in no loop). If the
1119 /// expression cannot be evaluated, return UnknownValue itself.
1120 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1123 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1124 /// an analyzable loop-invariant iteration count.
1125 bool hasLoopInvariantIterationCount(const Loop *L);
1127 /// getIterationCount - If the specified loop has a predictable iteration
1128 /// count, return it. Note that it is not valid to call this method on a
1129 /// loop without a loop-invariant iteration count.
1130 SCEVHandle getIterationCount(const Loop *L);
1132 /// deleteInstructionFromRecords - This method should be called by the
1133 /// client before it removes an instruction from the program, to make sure
1134 /// that no dangling references are left around.
1135 void deleteInstructionFromRecords(Instruction *I);
1138 /// createSCEV - We know that there is no SCEV for the specified value.
1139 /// Analyze the expression.
1140 SCEVHandle createSCEV(Value *V);
1142 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1144 SCEVHandle createNodeForPHI(PHINode *PN);
1146 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1147 /// for the specified instruction and replaces any references to the
1148 /// symbolic value SymName with the specified value. This is used during
1150 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1151 const SCEVHandle &SymName,
1152 const SCEVHandle &NewVal);
1154 /// ComputeIterationCount - Compute the number of times the specified loop
1156 SCEVHandle ComputeIterationCount(const Loop *L);
1158 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1159 /// 'setcc load X, cst', try to se if we can compute the trip count.
1160 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1163 unsigned SetCCOpcode);
1165 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1166 /// constant number of times (the condition evolves only from constants),
1167 /// try to evaluate a few iterations of the loop until we get the exit
1168 /// condition gets a value of ExitWhen (true or false). If we cannot
1169 /// evaluate the trip count of the loop, return UnknownValue.
1170 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1173 /// HowFarToZero - Return the number of times a backedge comparing the
1174 /// specified value to zero will execute. If not computable, return
1176 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1178 /// HowFarToNonZero - Return the number of times a backedge checking the
1179 /// specified value for nonzero will execute. If not computable, return
1181 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1183 /// HowManyLessThans - Return the number of times a backedge containing the
1184 /// specified less-than comparison will execute. If not computable, return
1186 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1188 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1189 /// in the header of its containing loop, we know the loop executes a
1190 /// constant number of times, and the PHI node is just a recurrence
1191 /// involving constants, fold it.
1192 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1197 //===----------------------------------------------------------------------===//
1198 // Basic SCEV Analysis and PHI Idiom Recognition Code
1201 /// deleteInstructionFromRecords - This method should be called by the
1202 /// client before it removes an instruction from the program, to make sure
1203 /// that no dangling references are left around.
1204 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1206 if (PHINode *PN = dyn_cast<PHINode>(I))
1207 ConstantEvolutionLoopExitValue.erase(PN);
1211 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1212 /// expression and create a new one.
1213 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1214 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1216 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1217 if (I != Scalars.end()) return I->second;
1218 SCEVHandle S = createSCEV(V);
1219 Scalars.insert(std::make_pair(V, S));
1223 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1224 /// the specified instruction and replaces any references to the symbolic value
1225 /// SymName with the specified value. This is used during PHI resolution.
1226 void ScalarEvolutionsImpl::
1227 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1228 const SCEVHandle &NewVal) {
1229 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1230 if (SI == Scalars.end()) return;
1233 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1234 if (NV == SI->second) return; // No change.
1236 SI->second = NV; // Update the scalars map!
1238 // Any instruction values that use this instruction might also need to be
1240 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1245 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1246 /// a loop header, making it a potential recurrence, or it doesn't.
1248 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1249 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1250 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1251 if (L->getHeader() == PN->getParent()) {
1252 // If it lives in the loop header, it has two incoming values, one
1253 // from outside the loop, and one from inside.
1254 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1255 unsigned BackEdge = IncomingEdge^1;
1257 // While we are analyzing this PHI node, handle its value symbolically.
1258 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1259 assert(Scalars.find(PN) == Scalars.end() &&
1260 "PHI node already processed?");
1261 Scalars.insert(std::make_pair(PN, SymbolicName));
1263 // Using this symbolic name for the PHI, analyze the value coming around
1265 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1267 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1268 // has a special value for the first iteration of the loop.
1270 // If the value coming around the backedge is an add with the symbolic
1271 // value we just inserted, then we found a simple induction variable!
1272 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1273 // If there is a single occurrence of the symbolic value, replace it
1274 // with a recurrence.
1275 unsigned FoundIndex = Add->getNumOperands();
1276 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1277 if (Add->getOperand(i) == SymbolicName)
1278 if (FoundIndex == e) {
1283 if (FoundIndex != Add->getNumOperands()) {
1284 // Create an add with everything but the specified operand.
1285 std::vector<SCEVHandle> Ops;
1286 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1287 if (i != FoundIndex)
1288 Ops.push_back(Add->getOperand(i));
1289 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1291 // This is not a valid addrec if the step amount is varying each
1292 // loop iteration, but is not itself an addrec in this loop.
1293 if (Accum->isLoopInvariant(L) ||
1294 (isa<SCEVAddRecExpr>(Accum) &&
1295 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1296 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1297 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1299 // Okay, for the entire analysis of this edge we assumed the PHI
1300 // to be symbolic. We now need to go back and update all of the
1301 // entries for the scalars that use the PHI (except for the PHI
1302 // itself) to use the new analyzed value instead of the "symbolic"
1304 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1308 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1309 // Otherwise, this could be a loop like this:
1310 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1311 // In this case, j = {1,+,1} and BEValue is j.
1312 // Because the other in-value of i (0) fits the evolution of BEValue
1313 // i really is an addrec evolution.
1314 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1315 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1317 // If StartVal = j.start - j.stride, we can use StartVal as the
1318 // initial step of the addrec evolution.
1319 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1320 AddRec->getOperand(1))) {
1321 SCEVHandle PHISCEV =
1322 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1324 // Okay, for the entire analysis of this edge we assumed the PHI
1325 // to be symbolic. We now need to go back and update all of the
1326 // entries for the scalars that use the PHI (except for the PHI
1327 // itself) to use the new analyzed value instead of the "symbolic"
1329 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1335 return SymbolicName;
1338 // If it's not a loop phi, we can't handle it yet.
1339 return SCEVUnknown::get(PN);
1343 /// createSCEV - We know that there is no SCEV for the specified value.
1344 /// Analyze the expression.
1346 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1347 if (Instruction *I = dyn_cast<Instruction>(V)) {
1348 switch (I->getOpcode()) {
1349 case Instruction::Add:
1350 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1351 getSCEV(I->getOperand(1)));
1352 case Instruction::Mul:
1353 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1354 getSCEV(I->getOperand(1)));
1355 case Instruction::SDiv:
1356 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1357 getSCEV(I->getOperand(1)));
1360 case Instruction::Sub:
1361 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1362 getSCEV(I->getOperand(1)));
1364 case Instruction::Shl:
1365 // Turn shift left of a constant amount into a multiply.
1366 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1367 Constant *X = ConstantInt::get(V->getType(), 1);
1368 X = ConstantExpr::getShl(X, SA);
1369 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1373 case Instruction::Trunc:
1374 // We don't handle trunc to bool yet.
1375 if (I->getType()->isInteger())
1376 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1377 I->getType()->getUnsignedVersion());
1380 case Instruction::ZExt:
1381 // We don't handle zext from bool yet.
1382 if (I->getOperand(0)->getType()->isInteger())
1383 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1384 I->getType()->getUnsignedVersion());
1387 case Instruction::BitCast:
1388 // BitCasts are no-op casts so we just eliminate the cast.
1389 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1390 return getSCEV(I->getOperand(0));
1393 case Instruction::PHI:
1394 return createNodeForPHI(cast<PHINode>(I));
1396 default: // We cannot analyze this expression.
1401 return SCEVUnknown::get(V);
1406 //===----------------------------------------------------------------------===//
1407 // Iteration Count Computation Code
1410 /// getIterationCount - If the specified loop has a predictable iteration
1411 /// count, return it. Note that it is not valid to call this method on a
1412 /// loop without a loop-invariant iteration count.
1413 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1414 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1415 if (I == IterationCounts.end()) {
1416 SCEVHandle ItCount = ComputeIterationCount(L);
1417 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1418 if (ItCount != UnknownValue) {
1419 assert(ItCount->isLoopInvariant(L) &&
1420 "Computed trip count isn't loop invariant for loop!");
1421 ++NumTripCountsComputed;
1422 } else if (isa<PHINode>(L->getHeader()->begin())) {
1423 // Only count loops that have phi nodes as not being computable.
1424 ++NumTripCountsNotComputed;
1430 /// ComputeIterationCount - Compute the number of times the specified loop
1432 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1433 // If the loop has a non-one exit block count, we can't analyze it.
1434 std::vector<BasicBlock*> ExitBlocks;
1435 L->getExitBlocks(ExitBlocks);
1436 if (ExitBlocks.size() != 1) return UnknownValue;
1438 // Okay, there is one exit block. Try to find the condition that causes the
1439 // loop to be exited.
1440 BasicBlock *ExitBlock = ExitBlocks[0];
1442 BasicBlock *ExitingBlock = 0;
1443 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1445 if (L->contains(*PI)) {
1446 if (ExitingBlock == 0)
1449 return UnknownValue; // More than one block exiting!
1451 assert(ExitingBlock && "No exits from loop, something is broken!");
1453 // Okay, we've computed the exiting block. See what condition causes us to
1456 // FIXME: we should be able to handle switch instructions (with a single exit)
1457 // FIXME: We should handle cast of int to bool as well
1458 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1459 if (ExitBr == 0) return UnknownValue;
1460 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1461 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1462 if (ExitCond == 0) // Not a setcc
1463 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1464 ExitBr->getSuccessor(0) == ExitBlock);
1466 // If the condition was exit on true, convert the condition to exit on false.
1467 Instruction::BinaryOps Cond;
1468 if (ExitBr->getSuccessor(1) == ExitBlock)
1469 Cond = ExitCond->getOpcode();
1471 Cond = ExitCond->getInverseCondition();
1473 // Handle common loops like: for (X = "string"; *X; ++X)
1474 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1475 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1477 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1478 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1481 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1482 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1484 // Try to evaluate any dependencies out of the loop.
1485 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1486 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1487 Tmp = getSCEVAtScope(RHS, L);
1488 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1490 // At this point, we would like to compute how many iterations of the loop the
1491 // predicate will return true for these inputs.
1492 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1493 // If there is a constant, force it into the RHS.
1494 std::swap(LHS, RHS);
1495 Cond = SetCondInst::getSwappedCondition(Cond);
1498 // FIXME: think about handling pointer comparisons! i.e.:
1499 // while (P != P+100) ++P;
1501 // If we have a comparison of a chrec against a constant, try to use value
1502 // ranges to answer this query.
1503 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1504 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1505 if (AddRec->getLoop() == L) {
1506 // Form the comparison range using the constant of the correct type so
1507 // that the ConstantRange class knows to do a signed or unsigned
1509 ConstantInt *CompVal = RHSC->getValue();
1510 const Type *RealTy = ExitCond->getOperand(0)->getType();
1511 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1513 // Form the constant range.
1514 ConstantRange CompRange(Cond, CompVal);
1516 // Now that we have it, if it's signed, convert it to an unsigned
1518 if (CompRange.getLower()->getType()->isSigned()) {
1519 const Type *NewTy = RHSC->getValue()->getType();
1520 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1521 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1522 CompRange = ConstantRange(NewL, NewU);
1525 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1526 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1531 case Instruction::SetNE: // while (X != Y)
1532 // Convert to: while (X-Y != 0)
1533 if (LHS->getType()->isInteger()) {
1534 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1535 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1538 case Instruction::SetEQ:
1539 // Convert to: while (X-Y == 0) // while (X == Y)
1540 if (LHS->getType()->isInteger()) {
1541 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1542 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1545 case Instruction::SetLT:
1546 if (LHS->getType()->isInteger() &&
1547 ExitCond->getOperand(0)->getType()->isSigned()) {
1548 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1549 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1552 case Instruction::SetGT:
1553 if (LHS->getType()->isInteger() &&
1554 ExitCond->getOperand(0)->getType()->isSigned()) {
1555 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1556 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1561 cerr << "ComputeIterationCount ";
1562 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1563 cerr << "[unsigned] ";
1565 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1570 return ComputeIterationCountExhaustively(L, ExitCond,
1571 ExitBr->getSuccessor(0) == ExitBlock);
1574 static ConstantInt *
1575 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1576 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1577 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1578 assert(isa<SCEVConstant>(Val) &&
1579 "Evaluation of SCEV at constant didn't fold correctly?");
1580 return cast<SCEVConstant>(Val)->getValue();
1583 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1584 /// and a GEP expression (missing the pointer index) indexing into it, return
1585 /// the addressed element of the initializer or null if the index expression is
1588 GetAddressedElementFromGlobal(GlobalVariable *GV,
1589 const std::vector<ConstantInt*> &Indices) {
1590 Constant *Init = GV->getInitializer();
1591 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1592 uint64_t Idx = Indices[i]->getZExtValue();
1593 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1594 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1595 Init = cast<Constant>(CS->getOperand(Idx));
1596 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1597 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1598 Init = cast<Constant>(CA->getOperand(Idx));
1599 } else if (isa<ConstantAggregateZero>(Init)) {
1600 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1601 assert(Idx < STy->getNumElements() && "Bad struct index!");
1602 Init = Constant::getNullValue(STy->getElementType(Idx));
1603 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1604 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1605 Init = Constant::getNullValue(ATy->getElementType());
1607 assert(0 && "Unknown constant aggregate type!");
1611 return 0; // Unknown initializer type
1617 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1618 /// 'setcc load X, cst', try to se if we can compute the trip count.
1619 SCEVHandle ScalarEvolutionsImpl::
1620 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1621 const Loop *L, unsigned SetCCOpcode) {
1622 if (LI->isVolatile()) return UnknownValue;
1624 // Check to see if the loaded pointer is a getelementptr of a global.
1625 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1626 if (!GEP) return UnknownValue;
1628 // Make sure that it is really a constant global we are gepping, with an
1629 // initializer, and make sure the first IDX is really 0.
1630 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1631 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1632 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1633 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1634 return UnknownValue;
1636 // Okay, we allow one non-constant index into the GEP instruction.
1638 std::vector<ConstantInt*> Indexes;
1639 unsigned VarIdxNum = 0;
1640 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1641 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1642 Indexes.push_back(CI);
1643 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1644 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1645 VarIdx = GEP->getOperand(i);
1647 Indexes.push_back(0);
1650 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1651 // Check to see if X is a loop variant variable value now.
1652 SCEVHandle Idx = getSCEV(VarIdx);
1653 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1654 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1656 // We can only recognize very limited forms of loop index expressions, in
1657 // particular, only affine AddRec's like {C1,+,C2}.
1658 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1659 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1660 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1661 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1662 return UnknownValue;
1664 unsigned MaxSteps = MaxBruteForceIterations;
1665 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1666 ConstantInt *ItCst =
1667 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1668 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1670 // Form the GEP offset.
1671 Indexes[VarIdxNum] = Val;
1673 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1674 if (Result == 0) break; // Cannot compute!
1676 // Evaluate the condition for this iteration.
1677 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1678 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1679 if (cast<ConstantBool>(Result)->getValue() == false) {
1681 cerr << "\n***\n*** Computed loop count " << *ItCst
1682 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1685 ++NumArrayLenItCounts;
1686 return SCEVConstant::get(ItCst); // Found terminating iteration!
1689 return UnknownValue;
1693 /// CanConstantFold - Return true if we can constant fold an instruction of the
1694 /// specified type, assuming that all operands were constants.
1695 static bool CanConstantFold(const Instruction *I) {
1696 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1697 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1700 if (const CallInst *CI = dyn_cast<CallInst>(I))
1701 if (const Function *F = CI->getCalledFunction())
1702 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1706 /// ConstantFold - Constant fold an instruction of the specified type with the
1707 /// specified constant operands. This function may modify the operands vector.
1708 static Constant *ConstantFold(const Instruction *I,
1709 std::vector<Constant*> &Operands) {
1710 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1711 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1713 if (isa<CastInst>(I))
1714 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1716 switch (I->getOpcode()) {
1717 case Instruction::Select:
1718 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1719 case Instruction::Call:
1720 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1721 Operands.erase(Operands.begin());
1722 return ConstantFoldCall(cast<Function>(GV), Operands);
1725 case Instruction::GetElementPtr:
1726 Constant *Base = Operands[0];
1727 Operands.erase(Operands.begin());
1728 return ConstantExpr::getGetElementPtr(Base, Operands);
1734 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1735 /// in the loop that V is derived from. We allow arbitrary operations along the
1736 /// way, but the operands of an operation must either be constants or a value
1737 /// derived from a constant PHI. If this expression does not fit with these
1738 /// constraints, return null.
1739 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1740 // If this is not an instruction, or if this is an instruction outside of the
1741 // loop, it can't be derived from a loop PHI.
1742 Instruction *I = dyn_cast<Instruction>(V);
1743 if (I == 0 || !L->contains(I->getParent())) return 0;
1745 if (PHINode *PN = dyn_cast<PHINode>(I))
1746 if (L->getHeader() == I->getParent())
1749 // We don't currently keep track of the control flow needed to evaluate
1750 // PHIs, so we cannot handle PHIs inside of loops.
1753 // If we won't be able to constant fold this expression even if the operands
1754 // are constants, return early.
1755 if (!CanConstantFold(I)) return 0;
1757 // Otherwise, we can evaluate this instruction if all of its operands are
1758 // constant or derived from a PHI node themselves.
1760 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1761 if (!(isa<Constant>(I->getOperand(Op)) ||
1762 isa<GlobalValue>(I->getOperand(Op)))) {
1763 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1764 if (P == 0) return 0; // Not evolving from PHI
1768 return 0; // Evolving from multiple different PHIs.
1771 // This is a expression evolving from a constant PHI!
1775 /// EvaluateExpression - Given an expression that passes the
1776 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1777 /// in the loop has the value PHIVal. If we can't fold this expression for some
1778 /// reason, return null.
1779 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1780 if (isa<PHINode>(V)) return PHIVal;
1781 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1783 if (Constant *C = dyn_cast<Constant>(V)) return C;
1784 Instruction *I = cast<Instruction>(V);
1786 std::vector<Constant*> Operands;
1787 Operands.resize(I->getNumOperands());
1789 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1790 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1791 if (Operands[i] == 0) return 0;
1794 return ConstantFold(I, Operands);
1797 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1798 /// in the header of its containing loop, we know the loop executes a
1799 /// constant number of times, and the PHI node is just a recurrence
1800 /// involving constants, fold it.
1801 Constant *ScalarEvolutionsImpl::
1802 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1803 std::map<PHINode*, Constant*>::iterator I =
1804 ConstantEvolutionLoopExitValue.find(PN);
1805 if (I != ConstantEvolutionLoopExitValue.end())
1808 if (Its > MaxBruteForceIterations)
1809 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1811 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1813 // Since the loop is canonicalized, the PHI node must have two entries. One
1814 // entry must be a constant (coming in from outside of the loop), and the
1815 // second must be derived from the same PHI.
1816 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1817 Constant *StartCST =
1818 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1820 return RetVal = 0; // Must be a constant.
1822 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1823 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1825 return RetVal = 0; // Not derived from same PHI.
1827 // Execute the loop symbolically to determine the exit value.
1828 unsigned IterationNum = 0;
1829 unsigned NumIterations = Its;
1830 if (NumIterations != Its)
1831 return RetVal = 0; // More than 2^32 iterations??
1833 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1834 if (IterationNum == NumIterations)
1835 return RetVal = PHIVal; // Got exit value!
1837 // Compute the value of the PHI node for the next iteration.
1838 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1839 if (NextPHI == PHIVal)
1840 return RetVal = NextPHI; // Stopped evolving!
1842 return 0; // Couldn't evaluate!
1847 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1848 /// constant number of times (the condition evolves only from constants),
1849 /// try to evaluate a few iterations of the loop until we get the exit
1850 /// condition gets a value of ExitWhen (true or false). If we cannot
1851 /// evaluate the trip count of the loop, return UnknownValue.
1852 SCEVHandle ScalarEvolutionsImpl::
1853 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1854 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1855 if (PN == 0) return UnknownValue;
1857 // Since the loop is canonicalized, the PHI node must have two entries. One
1858 // entry must be a constant (coming in from outside of the loop), and the
1859 // second must be derived from the same PHI.
1860 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1861 Constant *StartCST =
1862 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1863 if (StartCST == 0) return UnknownValue; // Must be a constant.
1865 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1866 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1867 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1869 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1870 // the loop symbolically to determine when the condition gets a value of
1872 unsigned IterationNum = 0;
1873 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1874 for (Constant *PHIVal = StartCST;
1875 IterationNum != MaxIterations; ++IterationNum) {
1876 ConstantBool *CondVal =
1877 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1878 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1880 if (CondVal->getValue() == ExitWhen) {
1881 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1882 ++NumBruteForceTripCountsComputed;
1883 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
1886 // Compute the value of the PHI node for the next iteration.
1887 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1888 if (NextPHI == 0 || NextPHI == PHIVal)
1889 return UnknownValue; // Couldn't evaluate or not making progress...
1893 // Too many iterations were needed to evaluate.
1894 return UnknownValue;
1897 /// getSCEVAtScope - Compute the value of the specified expression within the
1898 /// indicated loop (which may be null to indicate in no loop). If the
1899 /// expression cannot be evaluated, return UnknownValue.
1900 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1901 // FIXME: this should be turned into a virtual method on SCEV!
1903 if (isa<SCEVConstant>(V)) return V;
1905 // If this instruction is evolves from a constant-evolving PHI, compute the
1906 // exit value from the loop without using SCEVs.
1907 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1908 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1909 const Loop *LI = this->LI[I->getParent()];
1910 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1911 if (PHINode *PN = dyn_cast<PHINode>(I))
1912 if (PN->getParent() == LI->getHeader()) {
1913 // Okay, there is no closed form solution for the PHI node. Check
1914 // to see if the loop that contains it has a known iteration count.
1915 // If so, we may be able to force computation of the exit value.
1916 SCEVHandle IterationCount = getIterationCount(LI);
1917 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1918 // Okay, we know how many times the containing loop executes. If
1919 // this is a constant evolving PHI node, get the final value at
1920 // the specified iteration number.
1921 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1922 ICC->getValue()->getZExtValue(),
1924 if (RV) return SCEVUnknown::get(RV);
1928 // Okay, this is an expression that we cannot symbolically evaluate
1929 // into a SCEV. Check to see if it's possible to symbolically evaluate
1930 // the arguments into constants, and if so, try to constant propagate the
1931 // result. This is particularly useful for computing loop exit values.
1932 if (CanConstantFold(I)) {
1933 std::vector<Constant*> Operands;
1934 Operands.reserve(I->getNumOperands());
1935 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1936 Value *Op = I->getOperand(i);
1937 if (Constant *C = dyn_cast<Constant>(Op)) {
1938 Operands.push_back(C);
1940 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1941 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1942 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1944 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1945 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1946 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1954 return SCEVUnknown::get(ConstantFold(I, Operands));
1958 // This is some other type of SCEVUnknown, just return it.
1962 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1963 // Avoid performing the look-up in the common case where the specified
1964 // expression has no loop-variant portions.
1965 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1966 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1967 if (OpAtScope != Comm->getOperand(i)) {
1968 if (OpAtScope == UnknownValue) return UnknownValue;
1969 // Okay, at least one of these operands is loop variant but might be
1970 // foldable. Build a new instance of the folded commutative expression.
1971 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1972 NewOps.push_back(OpAtScope);
1974 for (++i; i != e; ++i) {
1975 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1976 if (OpAtScope == UnknownValue) return UnknownValue;
1977 NewOps.push_back(OpAtScope);
1979 if (isa<SCEVAddExpr>(Comm))
1980 return SCEVAddExpr::get(NewOps);
1981 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1982 return SCEVMulExpr::get(NewOps);
1985 // If we got here, all operands are loop invariant.
1989 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1990 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
1991 if (LHS == UnknownValue) return LHS;
1992 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
1993 if (RHS == UnknownValue) return RHS;
1994 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1995 return Div; // must be loop invariant
1996 return SCEVSDivExpr::get(LHS, RHS);
1999 // If this is a loop recurrence for a loop that does not contain L, then we
2000 // are dealing with the final value computed by the loop.
2001 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2002 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2003 // To evaluate this recurrence, we need to know how many times the AddRec
2004 // loop iterates. Compute this now.
2005 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2006 if (IterationCount == UnknownValue) return UnknownValue;
2007 IterationCount = getTruncateOrZeroExtend(IterationCount,
2010 // If the value is affine, simplify the expression evaluation to just
2011 // Start + Step*IterationCount.
2012 if (AddRec->isAffine())
2013 return SCEVAddExpr::get(AddRec->getStart(),
2014 SCEVMulExpr::get(IterationCount,
2015 AddRec->getOperand(1)));
2017 // Otherwise, evaluate it the hard way.
2018 return AddRec->evaluateAtIteration(IterationCount);
2020 return UnknownValue;
2023 //assert(0 && "Unknown SCEV type!");
2024 return UnknownValue;
2028 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2029 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2030 /// might be the same) or two SCEVCouldNotCompute objects.
2032 static std::pair<SCEVHandle,SCEVHandle>
2033 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2034 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2035 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2036 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2037 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2039 // We currently can only solve this if the coefficients are constants.
2040 if (!L || !M || !N) {
2041 SCEV *CNC = new SCEVCouldNotCompute();
2042 return std::make_pair(CNC, CNC);
2045 Constant *C = L->getValue();
2046 Constant *Two = ConstantInt::get(C->getType(), 2);
2048 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2049 // The B coefficient is M-N/2
2050 Constant *B = ConstantExpr::getSub(M->getValue(),
2051 ConstantExpr::getSDiv(N->getValue(),
2053 // The A coefficient is N/2
2054 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
2056 // Compute the B^2-4ac term.
2057 Constant *SqrtTerm =
2058 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2059 ConstantExpr::getMul(A, C));
2060 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2062 // Compute floor(sqrt(B^2-4ac))
2063 ConstantInt *SqrtVal =
2064 cast<ConstantInt>(ConstantExpr::getCast(SqrtTerm,
2065 SqrtTerm->getType()->getUnsignedVersion()));
2066 uint64_t SqrtValV = SqrtVal->getZExtValue();
2067 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2068 // The square root might not be precise for arbitrary 64-bit integer
2069 // values. Do some sanity checks to ensure it's correct.
2070 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2071 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2072 SCEV *CNC = new SCEVCouldNotCompute();
2073 return std::make_pair(CNC, CNC);
2076 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
2077 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2079 Constant *NegB = ConstantExpr::getNeg(B);
2080 Constant *TwoA = ConstantExpr::getMul(A, Two);
2082 // The divisions must be performed as signed divisions.
2083 const Type *SignedTy = NegB->getType()->getSignedVersion();
2084 NegB = ConstantExpr::getCast(NegB, SignedTy);
2085 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2086 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2088 Constant *Solution1 =
2089 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2090 Constant *Solution2 =
2091 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2092 return std::make_pair(SCEVUnknown::get(Solution1),
2093 SCEVUnknown::get(Solution2));
2096 /// HowFarToZero - Return the number of times a backedge comparing the specified
2097 /// value to zero will execute. If not computable, return UnknownValue
2098 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2099 // If the value is a constant
2100 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2101 // If the value is already zero, the branch will execute zero times.
2102 if (C->getValue()->isNullValue()) return C;
2103 return UnknownValue; // Otherwise it will loop infinitely.
2106 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2107 if (!AddRec || AddRec->getLoop() != L)
2108 return UnknownValue;
2110 if (AddRec->isAffine()) {
2111 // If this is an affine expression the execution count of this branch is
2114 // (0 - Start/Step) iff Start % Step == 0
2116 // Get the initial value for the loop.
2117 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2118 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2119 SCEVHandle Step = AddRec->getOperand(1);
2121 Step = getSCEVAtScope(Step, L->getParentLoop());
2123 // Figure out if Start % Step == 0.
2124 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2125 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2126 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2127 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
2128 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2129 return Start; // 0 - Start/-1 == Start
2131 // Check to see if Start is divisible by SC with no remainder.
2132 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2133 ConstantInt *StartCC = StartC->getValue();
2134 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2135 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2136 if (Rem->isNullValue()) {
2137 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2138 return SCEVUnknown::get(Result);
2142 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2143 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2144 // the quadratic equation to solve it.
2145 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2146 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2147 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2150 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2151 << " sol#2: " << *R2 << "\n";
2153 // Pick the smallest positive root value.
2154 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2155 if (ConstantBool *CB =
2156 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2158 if (CB->getValue() == false)
2159 std::swap(R1, R2); // R1 is the minimum root now.
2161 // We can only use this value if the chrec ends up with an exact zero
2162 // value at this index. When solving for "X*X != 5", for example, we
2163 // should not accept a root of 2.
2164 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2165 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2166 if (EvalVal->getValue()->isNullValue())
2167 return R1; // We found a quadratic root!
2172 return UnknownValue;
2175 /// HowFarToNonZero - Return the number of times a backedge checking the
2176 /// specified value for nonzero will execute. If not computable, return
2178 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2179 // Loops that look like: while (X == 0) are very strange indeed. We don't
2180 // handle them yet except for the trivial case. This could be expanded in the
2181 // future as needed.
2183 // If the value is a constant, check to see if it is known to be non-zero
2184 // already. If so, the backedge will execute zero times.
2185 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2186 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2187 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2188 if (NonZero == ConstantBool::getTrue())
2189 return getSCEV(Zero);
2190 return UnknownValue; // Otherwise it will loop infinitely.
2193 // We could implement others, but I really doubt anyone writes loops like
2194 // this, and if they did, they would already be constant folded.
2195 return UnknownValue;
2198 /// HowManyLessThans - Return the number of times a backedge containing the
2199 /// specified less-than comparison will execute. If not computable, return
2201 SCEVHandle ScalarEvolutionsImpl::
2202 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2203 // Only handle: "ADDREC < LoopInvariant".
2204 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2206 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2207 if (!AddRec || AddRec->getLoop() != L)
2208 return UnknownValue;
2210 if (AddRec->isAffine()) {
2211 // FORNOW: We only support unit strides.
2212 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2213 if (AddRec->getOperand(1) != One)
2214 return UnknownValue;
2216 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2217 // know that m is >= n on input to the loop. If it is, the condition return
2218 // true zero times. What we really should return, for full generality, is
2219 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2220 // canonical loop form: most do-loops will have a check that dominates the
2221 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2222 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2224 // Search for the check.
2225 BasicBlock *Preheader = L->getLoopPreheader();
2226 BasicBlock *PreheaderDest = L->getHeader();
2227 if (Preheader == 0) return UnknownValue;
2229 BranchInst *LoopEntryPredicate =
2230 dyn_cast<BranchInst>(Preheader->getTerminator());
2231 if (!LoopEntryPredicate) return UnknownValue;
2233 // This might be a critical edge broken out. If the loop preheader ends in
2234 // an unconditional branch to the loop, check to see if the preheader has a
2235 // single predecessor, and if so, look for its terminator.
2236 while (LoopEntryPredicate->isUnconditional()) {
2237 PreheaderDest = Preheader;
2238 Preheader = Preheader->getSinglePredecessor();
2239 if (!Preheader) return UnknownValue; // Multiple preds.
2241 LoopEntryPredicate =
2242 dyn_cast<BranchInst>(Preheader->getTerminator());
2243 if (!LoopEntryPredicate) return UnknownValue;
2246 // Now that we found a conditional branch that dominates the loop, check to
2247 // see if it is the comparison we are looking for.
2248 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2249 if (!SCI) return UnknownValue;
2250 Value *PreCondLHS = SCI->getOperand(0);
2251 Value *PreCondRHS = SCI->getOperand(1);
2252 Instruction::BinaryOps Cond;
2253 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2254 Cond = SCI->getOpcode();
2256 Cond = SCI->getInverseCondition();
2259 case Instruction::SetGT:
2260 std::swap(PreCondLHS, PreCondRHS);
2261 Cond = Instruction::SetLT;
2263 case Instruction::SetLT:
2264 if (PreCondLHS->getType()->isInteger() &&
2265 PreCondLHS->getType()->isSigned()) {
2266 if (RHS != getSCEV(PreCondRHS))
2267 return UnknownValue; // Not a comparison against 'm'.
2269 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2270 != getSCEV(PreCondLHS))
2271 return UnknownValue; // Not a comparison against 'n-1'.
2274 return UnknownValue;
2279 //cerr << "Computed Loop Trip Count as: "
2280 // << *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2281 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2284 return UnknownValue;
2287 /// getNumIterationsInRange - Return the number of iterations of this loop that
2288 /// produce values in the specified constant range. Another way of looking at
2289 /// this is that it returns the first iteration number where the value is not in
2290 /// the condition, thus computing the exit count. If the iteration count can't
2291 /// be computed, an instance of SCEVCouldNotCompute is returned.
2292 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2293 if (Range.isFullSet()) // Infinite loop.
2294 return new SCEVCouldNotCompute();
2296 // If the start is a non-zero constant, shift the range to simplify things.
2297 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2298 if (!SC->getValue()->isNullValue()) {
2299 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2300 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2301 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2302 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2303 return ShiftedAddRec->getNumIterationsInRange(
2304 Range.subtract(SC->getValue()));
2305 // This is strange and shouldn't happen.
2306 return new SCEVCouldNotCompute();
2309 // The only time we can solve this is when we have all constant indices.
2310 // Otherwise, we cannot determine the overflow conditions.
2311 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2312 if (!isa<SCEVConstant>(getOperand(i)))
2313 return new SCEVCouldNotCompute();
2316 // Okay at this point we know that all elements of the chrec are constants and
2317 // that the start element is zero.
2319 // First check to see if the range contains zero. If not, the first
2321 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2322 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2325 // If this is an affine expression then we have this situation:
2326 // Solve {0,+,A} in Range === Ax in Range
2328 // Since we know that zero is in the range, we know that the upper value of
2329 // the range must be the first possible exit value. Also note that we
2330 // already checked for a full range.
2331 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2332 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2333 ConstantInt *One = ConstantInt::get(getType(), 1);
2335 // The exit value should be (Upper+A-1)/A.
2336 Constant *ExitValue = Upper;
2338 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2339 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
2341 assert(isa<ConstantInt>(ExitValue) &&
2342 "Constant folding of integers not implemented?");
2344 // Evaluate at the exit value. If we really did fall out of the valid
2345 // range, then we computed our trip count, otherwise wrap around or other
2346 // things must have happened.
2347 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2348 if (Range.contains(Val))
2349 return new SCEVCouldNotCompute(); // Something strange happened
2351 // Ensure that the previous value is in the range. This is a sanity check.
2352 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2353 ConstantExpr::getSub(ExitValue, One))) &&
2354 "Linear scev computation is off in a bad way!");
2355 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2356 } else if (isQuadratic()) {
2357 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2358 // quadratic equation to solve it. To do this, we must frame our problem in
2359 // terms of figuring out when zero is crossed, instead of when
2360 // Range.getUpper() is crossed.
2361 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2362 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2363 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2365 // Next, solve the constructed addrec
2366 std::pair<SCEVHandle,SCEVHandle> Roots =
2367 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2368 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2369 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2371 // Pick the smallest positive root value.
2372 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2373 if (ConstantBool *CB =
2374 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2376 if (CB->getValue() == false)
2377 std::swap(R1, R2); // R1 is the minimum root now.
2379 // Make sure the root is not off by one. The returned iteration should
2380 // not be in the range, but the previous one should be. When solving
2381 // for "X*X < 5", for example, we should not return a root of 2.
2382 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2384 if (Range.contains(R1Val)) {
2385 // The next iteration must be out of the range...
2387 ConstantExpr::getAdd(R1->getValue(),
2388 ConstantInt::get(R1->getType(), 1));
2390 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2391 if (!Range.contains(R1Val))
2392 return SCEVUnknown::get(NextVal);
2393 return new SCEVCouldNotCompute(); // Something strange happened
2396 // If R1 was not in the range, then it is a good return value. Make
2397 // sure that R1-1 WAS in the range though, just in case.
2399 ConstantExpr::getSub(R1->getValue(),
2400 ConstantInt::get(R1->getType(), 1));
2401 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2402 if (Range.contains(R1Val))
2404 return new SCEVCouldNotCompute(); // Something strange happened
2409 // Fallback, if this is a general polynomial, figure out the progression
2410 // through brute force: evaluate until we find an iteration that fails the
2411 // test. This is likely to be slow, but getting an accurate trip count is
2412 // incredibly important, we will be able to simplify the exit test a lot, and
2413 // we are almost guaranteed to get a trip count in this case.
2414 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2415 ConstantInt *One = ConstantInt::get(getType(), 1);
2416 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2418 ++NumBruteForceEvaluations;
2419 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2420 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2421 return new SCEVCouldNotCompute();
2423 // Check to see if we found the value!
2424 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2425 return SCEVConstant::get(TestVal);
2427 // Increment to test the next index.
2428 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2429 } while (TestVal != EndVal);
2431 return new SCEVCouldNotCompute();
2436 //===----------------------------------------------------------------------===//
2437 // ScalarEvolution Class Implementation
2438 //===----------------------------------------------------------------------===//
2440 bool ScalarEvolution::runOnFunction(Function &F) {
2441 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2445 void ScalarEvolution::releaseMemory() {
2446 delete (ScalarEvolutionsImpl*)Impl;
2450 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2451 AU.setPreservesAll();
2452 AU.addRequiredTransitive<LoopInfo>();
2455 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2456 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2459 /// hasSCEV - Return true if the SCEV for this value has already been
2461 bool ScalarEvolution::hasSCEV(Value *V) const {
2462 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2466 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2467 /// the specified value.
2468 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2469 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2473 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2474 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2477 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2478 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2481 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2482 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2485 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2486 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2489 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2491 // Print all inner loops first
2492 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2493 PrintLoopInfo(OS, SE, *I);
2495 cerr << "Loop " << L->getHeader()->getName() << ": ";
2497 std::vector<BasicBlock*> ExitBlocks;
2498 L->getExitBlocks(ExitBlocks);
2499 if (ExitBlocks.size() != 1)
2500 cerr << "<multiple exits> ";
2502 if (SE->hasLoopInvariantIterationCount(L)) {
2503 cerr << *SE->getIterationCount(L) << " iterations! ";
2505 cerr << "Unpredictable iteration count. ";
2511 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2512 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2513 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2515 OS << "Classifying expressions for: " << F.getName() << "\n";
2516 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2517 if (I->getType()->isInteger()) {
2520 SCEVHandle SV = getSCEV(&*I);
2524 if ((*I).getType()->isIntegral()) {
2525 ConstantRange Bounds = SV->getValueRange();
2526 if (!Bounds.isFullSet())
2527 OS << "Bounds: " << Bounds << " ";
2530 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2532 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2533 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2534 OS << "<<Unknown>>";
2544 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2545 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2546 PrintLoopInfo(OS, this, *I);