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/LoopInfo.h"
68 #include "llvm/Assembly/Writer.h"
69 #include "llvm/Transforms/Scalar.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include "llvm/Support/CFG.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/InstIterator.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/ADT/Statistic.h"
81 RegisterAnalysis<ScalarEvolution>
82 R("scalar-evolution", "Scalar Evolution Analysis");
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to "
87 "calculate high-order polynomial exit values");
89 NumArrayLenItCounts("scalar-evolution",
90 "Number of trip counts computed with array length");
92 NumTripCountsComputed("scalar-evolution",
93 "Number of loops with predictable loop counts");
95 NumTripCountsNotComputed("scalar-evolution",
96 "Number of loops without predictable loop counts");
98 NumBruteForceTripCountsComputed("scalar-evolution",
99 "Number of loops with trip counts computed by force");
102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
103 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
107 //===----------------------------------------------------------------------===//
108 // SCEV class definitions
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
112 // Implementation of the SCEV class.
115 void SCEV::dump() const {
119 /// getValueRange - Return the tightest constant bounds that this value is
120 /// known to have. This method is only valid on integer SCEV objects.
121 ConstantRange SCEV::getValueRange() const {
122 const Type *Ty = getType();
123 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
124 Ty = Ty->getUnsignedVersion();
125 // Default to a full range if no better information is available.
126 return ConstantRange(getType());
130 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
137 const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 SCEVHandle SCEVCouldNotCompute::
148 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
149 const SCEVHandle &Conc) const {
153 void SCEVCouldNotCompute::print(std::ostream &OS) const {
154 OS << "***COULDNOTCOMPUTE***";
157 bool SCEVCouldNotCompute::classof(const SCEV *S) {
158 return S->getSCEVType() == scCouldNotCompute;
162 // SCEVConstants - Only allow the creation of one SCEVConstant for any
163 // particular value. Don't use a SCEVHandle here, or else the object will
165 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
168 SCEVConstant::~SCEVConstant() {
169 SCEVConstants.erase(V);
172 SCEVHandle SCEVConstant::get(ConstantInt *V) {
173 // Make sure that SCEVConstant instances are all unsigned.
174 if (V->getType()->isSigned()) {
175 const Type *NewTy = V->getType()->getUnsignedVersion();
176 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
179 SCEVConstant *&R = SCEVConstants[V];
180 if (R == 0) R = new SCEVConstant(V);
184 ConstantRange SCEVConstant::getValueRange() const {
185 return ConstantRange(V);
188 const Type *SCEVConstant::getType() const { return V->getType(); }
190 void SCEVConstant::print(std::ostream &OS) const {
191 WriteAsOperand(OS, V, false);
194 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
195 // particular input. Don't use a SCEVHandle here, or else the object will
197 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
199 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
200 : SCEV(scTruncate), Op(op), Ty(ty) {
201 assert(Op->getType()->isInteger() && Ty->isInteger() &&
203 "Cannot truncate non-integer value!");
204 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
205 "This is not a truncating conversion!");
208 SCEVTruncateExpr::~SCEVTruncateExpr() {
209 SCEVTruncates.erase(std::make_pair(Op, Ty));
212 ConstantRange SCEVTruncateExpr::getValueRange() const {
213 return getOperand()->getValueRange().truncate(getType());
216 void SCEVTruncateExpr::print(std::ostream &OS) const {
217 OS << "(truncate " << *Op << " to " << *Ty << ")";
220 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
221 // particular input. Don't use a SCEVHandle here, or else the object will never
223 static std::map<std::pair<SCEV*, const Type*>,
224 SCEVZeroExtendExpr*> SCEVZeroExtends;
226 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
227 : SCEV(scTruncate), Op(op), Ty(ty) {
228 assert(Op->getType()->isInteger() && Ty->isInteger() &&
230 "Cannot zero extend non-integer value!");
231 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
232 "This is not an extending conversion!");
235 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
239 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
240 return getOperand()->getValueRange().zeroExtend(getType());
243 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
244 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
247 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
248 // particular input. Don't use a SCEVHandle here, or else the object will never
250 static std::map<std::pair<unsigned, std::vector<SCEV*> >,
251 SCEVCommutativeExpr*> SCEVCommExprs;
253 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
254 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
255 std::vector<SCEV*>(Operands.begin(),
259 void SCEVCommutativeExpr::print(std::ostream &OS) const {
260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
261 const char *OpStr = getOperationStr();
262 OS << "(" << *Operands[0];
263 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
264 OS << OpStr << *Operands[i];
268 SCEVHandle SCEVCommutativeExpr::
269 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
270 const SCEVHandle &Conc) const {
271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
272 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
273 if (H != getOperand(i)) {
274 std::vector<SCEVHandle> NewOps;
275 NewOps.reserve(getNumOperands());
276 for (unsigned j = 0; j != i; ++j)
277 NewOps.push_back(getOperand(j));
279 for (++i; i != e; ++i)
280 NewOps.push_back(getOperand(i)->
281 replaceSymbolicValuesWithConcrete(Sym, Conc));
283 if (isa<SCEVAddExpr>(this))
284 return SCEVAddExpr::get(NewOps);
285 else if (isa<SCEVMulExpr>(this))
286 return SCEVMulExpr::get(NewOps);
288 assert(0 && "Unknown commutative expr!");
295 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
296 // input. Don't use a SCEVHandle here, or else the object will never be
298 static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
300 SCEVUDivExpr::~SCEVUDivExpr() {
301 SCEVUDivs.erase(std::make_pair(LHS, RHS));
304 void SCEVUDivExpr::print(std::ostream &OS) const {
305 OS << "(" << *LHS << " /u " << *RHS << ")";
308 const Type *SCEVUDivExpr::getType() const {
309 const Type *Ty = LHS->getType();
310 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
314 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
315 // particular input. Don't use a SCEVHandle here, or else the object will never
317 static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
318 SCEVAddRecExpr*> SCEVAddRecExprs;
320 SCEVAddRecExpr::~SCEVAddRecExpr() {
321 SCEVAddRecExprs.erase(std::make_pair(L,
322 std::vector<SCEV*>(Operands.begin(),
326 SCEVHandle SCEVAddRecExpr::
327 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
328 const SCEVHandle &Conc) const {
329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
330 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
331 if (H != getOperand(i)) {
332 std::vector<SCEVHandle> NewOps;
333 NewOps.reserve(getNumOperands());
334 for (unsigned j = 0; j != i; ++j)
335 NewOps.push_back(getOperand(j));
337 for (++i; i != e; ++i)
338 NewOps.push_back(getOperand(i)->
339 replaceSymbolicValuesWithConcrete(Sym, Conc));
341 return get(NewOps, L);
348 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
349 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
351 return !QueryLoop->contains(L->getHeader());
355 void SCEVAddRecExpr::print(std::ostream &OS) const {
356 OS << "{" << *Operands[0];
357 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
358 OS << ",+," << *Operands[i];
359 OS << "}<" << L->getHeader()->getName() + ">";
362 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
363 // value. Don't use a SCEVHandle here, or else the object will never be
365 static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
367 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
369 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
372 if (Instruction *I = dyn_cast<Instruction>(V))
373 return !L->contains(I->getParent());
377 const Type *SCEVUnknown::getType() const {
381 void SCEVUnknown::print(std::ostream &OS) const {
382 WriteAsOperand(OS, V, false);
385 //===----------------------------------------------------------------------===//
387 //===----------------------------------------------------------------------===//
390 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
391 /// than the complexity of the RHS. This comparator is used to canonicalize
393 struct SCEVComplexityCompare {
394 bool operator()(SCEV *LHS, SCEV *RHS) {
395 return LHS->getSCEVType() < RHS->getSCEVType();
400 /// GroupByComplexity - Given a list of SCEV objects, order them by their
401 /// complexity, and group objects of the same complexity together by value.
402 /// When this routine is finished, we know that any duplicates in the vector are
403 /// consecutive and that complexity is monotonically increasing.
405 /// Note that we go take special precautions to ensure that we get determinstic
406 /// results from this routine. In other words, we don't want the results of
407 /// this to depend on where the addresses of various SCEV objects happened to
410 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
411 if (Ops.size() < 2) return; // Noop
412 if (Ops.size() == 2) {
413 // This is the common case, which also happens to be trivially simple.
415 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
416 std::swap(Ops[0], Ops[1]);
420 // Do the rough sort by complexity.
421 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
423 // Now that we are sorted by complexity, group elements of the same
424 // complexity. Note that this is, at worst, N^2, but the vector is likely to
425 // be extremely short in practice. Note that we take this approach because we
426 // do not want to depend on the addresses of the objects we are grouping.
427 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
429 unsigned Complexity = S->getSCEVType();
431 // If there are any objects of the same complexity and same value as this
433 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
434 if (Ops[j] == S) { // Found a duplicate.
435 // Move it to immediately after i'th element.
436 std::swap(Ops[i+1], Ops[j]);
437 ++i; // no need to rescan it.
438 if (i == e-2) return; // Done!
446 //===----------------------------------------------------------------------===//
447 // Simple SCEV method implementations
448 //===----------------------------------------------------------------------===//
450 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
451 /// specified signed integer value and return a SCEV for the constant.
452 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
455 C = Constant::getNullValue(Ty);
456 else if (Ty->isFloatingPoint())
457 C = ConstantFP::get(Ty, Val);
458 else if (Ty->isSigned())
459 C = ConstantSInt::get(Ty, Val);
461 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
462 C = ConstantExpr::getCast(C, Ty);
464 return SCEVUnknown::get(C);
467 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
468 /// input value to the specified type. If the type must be extended, it is zero
470 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
471 const Type *SrcTy = V->getType();
472 assert(SrcTy->isInteger() && Ty->isInteger() &&
473 "Cannot truncate or zero extend with non-integer arguments!");
474 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
475 return V; // No conversion
476 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
477 return SCEVTruncateExpr::get(V, Ty);
478 return SCEVZeroExtendExpr::get(V, Ty);
481 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
483 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
485 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
487 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
490 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
492 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
494 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
498 /// PartialFact - Compute V!/(V-NumSteps)!
499 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
500 // Handle this case efficiently, it is common to have constant iteration
501 // counts while computing loop exit values.
502 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
503 uint64_t Val = SC->getValue()->getRawValue();
505 for (; NumSteps; --NumSteps)
506 Result *= Val-(NumSteps-1);
507 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
508 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
511 const Type *Ty = V->getType();
513 return SCEVUnknown::getIntegerSCEV(1, Ty);
515 SCEVHandle Result = V;
516 for (unsigned i = 1; i != NumSteps; ++i)
517 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
518 SCEVUnknown::getIntegerSCEV(i, Ty)));
523 /// evaluateAtIteration - Return the value of this chain of recurrences at
524 /// the specified iteration number. We can evaluate this recurrence by
525 /// multiplying each element in the chain by the binomial coefficient
526 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
528 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
530 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
531 /// Is the binomial equation safe using modular arithmetic??
533 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
534 SCEVHandle Result = getStart();
536 const Type *Ty = It->getType();
537 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
538 SCEVHandle BC = PartialFact(It, i);
540 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
541 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
542 Result = SCEVAddExpr::get(Result, Val);
548 //===----------------------------------------------------------------------===//
549 // SCEV Expression folder implementations
550 //===----------------------------------------------------------------------===//
552 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
553 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
554 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
556 // If the input value is a chrec scev made out of constants, truncate
557 // all of the constants.
558 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
559 std::vector<SCEVHandle> Operands;
560 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
561 // FIXME: This should allow truncation of other expression types!
562 if (isa<SCEVConstant>(AddRec->getOperand(i)))
563 Operands.push_back(get(AddRec->getOperand(i), Ty));
566 if (Operands.size() == AddRec->getNumOperands())
567 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
570 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
571 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
575 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
576 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
577 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
579 // FIXME: If the input value is a chrec scev, and we can prove that the value
580 // did not overflow the old, smaller, value, we can zero extend all of the
581 // operands (often constants). This would allow analysis of something like
582 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
584 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
585 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
589 // get - Get a canonical add expression, or something simpler if possible.
590 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
591 assert(!Ops.empty() && "Cannot get empty add!");
592 if (Ops.size() == 1) return Ops[0];
594 // Sort by complexity, this groups all similar expression types together.
595 GroupByComplexity(Ops);
597 // If there are any constants, fold them together.
599 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
601 assert(Idx < Ops.size());
602 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
603 // We found two constants, fold them together!
604 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
605 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
606 Ops[0] = SCEVConstant::get(CI);
607 Ops.erase(Ops.begin()+1); // Erase the folded element
608 if (Ops.size() == 1) return Ops[0];
609 LHSC = cast<SCEVConstant>(Ops[0]);
611 // If we couldn't fold the expression, move to the next constant. Note
612 // that this is impossible to happen in practice because we always
613 // constant fold constant ints to constant ints.
618 // If we are left with a constant zero being added, strip it off.
619 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
620 Ops.erase(Ops.begin());
625 if (Ops.size() == 1) return Ops[0];
627 // Okay, check to see if the same value occurs in the operand list twice. If
628 // so, merge them together into an multiply expression. Since we sorted the
629 // list, these values are required to be adjacent.
630 const Type *Ty = Ops[0]->getType();
631 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
632 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
633 // Found a match, merge the two values into a multiply, and add any
634 // remaining values to the result.
635 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
636 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
639 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
641 return SCEVAddExpr::get(Ops);
644 // Okay, now we know the first non-constant operand. If there are add
645 // operands they would be next.
646 if (Idx < Ops.size()) {
647 bool DeletedAdd = false;
648 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
649 // If we have an add, expand the add operands onto the end of the operands
651 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
652 Ops.erase(Ops.begin()+Idx);
656 // If we deleted at least one add, we added operands to the end of the list,
657 // and they are not necessarily sorted. Recurse to resort and resimplify
658 // any operands we just aquired.
663 // Skip over the add expression until we get to a multiply.
664 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
667 // If we are adding something to a multiply expression, make sure the
668 // something is not already an operand of the multiply. If so, merge it into
670 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
671 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
672 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
673 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
674 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
675 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
676 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
677 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
678 if (Mul->getNumOperands() != 2) {
679 // If the multiply has more than two operands, we must get the
681 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
682 MulOps.erase(MulOps.begin()+MulOp);
683 InnerMul = SCEVMulExpr::get(MulOps);
685 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
686 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
687 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
688 if (Ops.size() == 2) return OuterMul;
690 Ops.erase(Ops.begin()+AddOp);
691 Ops.erase(Ops.begin()+Idx-1);
693 Ops.erase(Ops.begin()+Idx);
694 Ops.erase(Ops.begin()+AddOp-1);
696 Ops.push_back(OuterMul);
697 return SCEVAddExpr::get(Ops);
700 // Check this multiply against other multiplies being added together.
701 for (unsigned OtherMulIdx = Idx+1;
702 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
704 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
705 // If MulOp occurs in OtherMul, we can fold the two multiplies
707 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
708 OMulOp != e; ++OMulOp)
709 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
710 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
711 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
712 if (Mul->getNumOperands() != 2) {
713 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
714 MulOps.erase(MulOps.begin()+MulOp);
715 InnerMul1 = SCEVMulExpr::get(MulOps);
717 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
718 if (OtherMul->getNumOperands() != 2) {
719 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
721 MulOps.erase(MulOps.begin()+OMulOp);
722 InnerMul2 = SCEVMulExpr::get(MulOps);
724 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
725 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
726 if (Ops.size() == 2) return OuterMul;
727 Ops.erase(Ops.begin()+Idx);
728 Ops.erase(Ops.begin()+OtherMulIdx-1);
729 Ops.push_back(OuterMul);
730 return SCEVAddExpr::get(Ops);
736 // If there are any add recurrences in the operands list, see if any other
737 // added values are loop invariant. If so, we can fold them into the
739 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
742 // Scan over all recurrences, trying to fold loop invariants into them.
743 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
744 // Scan all of the other operands to this add and add them to the vector if
745 // they are loop invariant w.r.t. the recurrence.
746 std::vector<SCEVHandle> LIOps;
747 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
748 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
749 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
750 LIOps.push_back(Ops[i]);
751 Ops.erase(Ops.begin()+i);
755 // If we found some loop invariants, fold them into the recurrence.
756 if (!LIOps.empty()) {
757 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
758 LIOps.push_back(AddRec->getStart());
760 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
761 AddRecOps[0] = SCEVAddExpr::get(LIOps);
763 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
764 // If all of the other operands were loop invariant, we are done.
765 if (Ops.size() == 1) return NewRec;
767 // Otherwise, add the folded AddRec by the non-liv parts.
768 for (unsigned i = 0;; ++i)
769 if (Ops[i] == AddRec) {
773 return SCEVAddExpr::get(Ops);
776 // Okay, if there weren't any loop invariants to be folded, check to see if
777 // there are multiple AddRec's with the same loop induction variable being
778 // added together. If so, we can fold them.
779 for (unsigned OtherIdx = Idx+1;
780 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
781 if (OtherIdx != Idx) {
782 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
783 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
784 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
785 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
786 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
787 if (i >= NewOps.size()) {
788 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
789 OtherAddRec->op_end());
792 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
794 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
796 if (Ops.size() == 2) return NewAddRec;
798 Ops.erase(Ops.begin()+Idx);
799 Ops.erase(Ops.begin()+OtherIdx-1);
800 Ops.push_back(NewAddRec);
801 return SCEVAddExpr::get(Ops);
805 // Otherwise couldn't fold anything into this recurrence. Move onto the
809 // Okay, it looks like we really DO need an add expr. Check to see if we
810 // already have one, otherwise create a new one.
811 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
812 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
814 if (Result == 0) Result = new SCEVAddExpr(Ops);
819 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
820 assert(!Ops.empty() && "Cannot get empty mul!");
822 // Sort by complexity, this groups all similar expression types together.
823 GroupByComplexity(Ops);
825 // If there are any constants, fold them together.
827 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
829 // C1*(C2+V) -> C1*C2 + C1*V
831 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
832 if (Add->getNumOperands() == 2 &&
833 isa<SCEVConstant>(Add->getOperand(0)))
834 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
835 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
839 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
840 // We found two constants, fold them together!
841 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
842 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
843 Ops[0] = SCEVConstant::get(CI);
844 Ops.erase(Ops.begin()+1); // Erase the folded element
845 if (Ops.size() == 1) return Ops[0];
846 LHSC = cast<SCEVConstant>(Ops[0]);
848 // If we couldn't fold the expression, move to the next constant. Note
849 // that this is impossible to happen in practice because we always
850 // constant fold constant ints to constant ints.
855 // If we are left with a constant one being multiplied, strip it off.
856 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
857 Ops.erase(Ops.begin());
859 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
860 // If we have a multiply of zero, it will always be zero.
865 // Skip over the add expression until we get to a multiply.
866 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
872 // If there are mul operands inline them all into this expression.
873 if (Idx < Ops.size()) {
874 bool DeletedMul = false;
875 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
876 // If we have an mul, expand the mul operands onto the end of the operands
878 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
879 Ops.erase(Ops.begin()+Idx);
883 // If we deleted at least one mul, we added operands to the end of the list,
884 // and they are not necessarily sorted. Recurse to resort and resimplify
885 // any operands we just aquired.
890 // If there are any add recurrences in the operands list, see if any other
891 // added values are loop invariant. If so, we can fold them into the
893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
896 // Scan over all recurrences, trying to fold loop invariants into them.
897 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
898 // Scan all of the other operands to this mul and add them to the vector if
899 // they are loop invariant w.r.t. the recurrence.
900 std::vector<SCEVHandle> LIOps;
901 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
902 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
903 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
904 LIOps.push_back(Ops[i]);
905 Ops.erase(Ops.begin()+i);
909 // If we found some loop invariants, fold them into the recurrence.
910 if (!LIOps.empty()) {
911 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
912 std::vector<SCEVHandle> NewOps;
913 NewOps.reserve(AddRec->getNumOperands());
914 if (LIOps.size() == 1) {
915 SCEV *Scale = LIOps[0];
916 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
917 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
920 std::vector<SCEVHandle> MulOps(LIOps);
921 MulOps.push_back(AddRec->getOperand(i));
922 NewOps.push_back(SCEVMulExpr::get(MulOps));
926 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
928 // If all of the other operands were loop invariant, we are done.
929 if (Ops.size() == 1) return NewRec;
931 // Otherwise, multiply the folded AddRec by the non-liv parts.
932 for (unsigned i = 0;; ++i)
933 if (Ops[i] == AddRec) {
937 return SCEVMulExpr::get(Ops);
940 // Okay, if there weren't any loop invariants to be folded, check to see if
941 // there are multiple AddRec's with the same loop induction variable being
942 // multiplied together. If so, we can fold them.
943 for (unsigned OtherIdx = Idx+1;
944 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
945 if (OtherIdx != Idx) {
946 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
947 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
948 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
949 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
950 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
952 SCEVHandle B = F->getStepRecurrence();
953 SCEVHandle D = G->getStepRecurrence();
954 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
955 SCEVMulExpr::get(G, B),
956 SCEVMulExpr::get(B, D));
957 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
959 if (Ops.size() == 2) return NewAddRec;
961 Ops.erase(Ops.begin()+Idx);
962 Ops.erase(Ops.begin()+OtherIdx-1);
963 Ops.push_back(NewAddRec);
964 return SCEVMulExpr::get(Ops);
968 // Otherwise couldn't fold anything into this recurrence. Move onto the
972 // Okay, it looks like we really DO need an mul expr. Check to see if we
973 // already have one, otherwise create a new one.
974 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
975 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
978 Result = new SCEVMulExpr(Ops);
982 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
983 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
984 if (RHSC->getValue()->equalsInt(1))
985 return LHS; // X /u 1 --> x
986 if (RHSC->getValue()->isAllOnesValue())
987 return SCEV::getNegativeSCEV(LHS); // X /u -1 --> -x
989 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
990 Constant *LHSCV = LHSC->getValue();
991 Constant *RHSCV = RHSC->getValue();
992 if (LHSCV->getType()->isSigned())
993 LHSCV = ConstantExpr::getCast(LHSCV,
994 LHSCV->getType()->getUnsignedVersion());
995 if (RHSCV->getType()->isSigned())
996 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
997 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
1001 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1003 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
1004 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1009 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1010 /// specified loop. Simplify the expression as much as possible.
1011 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1012 const SCEVHandle &Step, const Loop *L) {
1013 std::vector<SCEVHandle> Operands;
1014 Operands.push_back(Start);
1015 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1016 if (StepChrec->getLoop() == L) {
1017 Operands.insert(Operands.end(), StepChrec->op_begin(),
1018 StepChrec->op_end());
1019 return get(Operands, L);
1022 Operands.push_back(Step);
1023 return get(Operands, L);
1026 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1027 /// specified loop. Simplify the expression as much as possible.
1028 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1030 if (Operands.size() == 1) return Operands[0];
1032 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1033 if (StepC->getValue()->isNullValue()) {
1034 Operands.pop_back();
1035 return get(Operands, L); // { X,+,0 } --> X
1038 SCEVAddRecExpr *&Result =
1039 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1041 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1045 SCEVHandle SCEVUnknown::get(Value *V) {
1046 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1047 return SCEVConstant::get(CI);
1048 SCEVUnknown *&Result = SCEVUnknowns[V];
1049 if (Result == 0) Result = new SCEVUnknown(V);
1054 //===----------------------------------------------------------------------===//
1055 // ScalarEvolutionsImpl Definition and Implementation
1056 //===----------------------------------------------------------------------===//
1058 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1062 struct ScalarEvolutionsImpl {
1063 /// F - The function we are analyzing.
1067 /// LI - The loop information for the function we are currently analyzing.
1071 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1073 SCEVHandle UnknownValue;
1075 /// Scalars - This is a cache of the scalars we have analyzed so far.
1077 std::map<Value*, SCEVHandle> Scalars;
1079 /// IterationCounts - Cache the iteration count of the loops for this
1080 /// function as they are computed.
1081 std::map<const Loop*, SCEVHandle> IterationCounts;
1083 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1084 /// the PHI instructions that we attempt to compute constant evolutions for.
1085 /// This allows us to avoid potentially expensive recomputation of these
1086 /// properties. An instruction maps to null if we are unable to compute its
1088 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1091 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1092 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1094 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1095 /// expression and create a new one.
1096 SCEVHandle getSCEV(Value *V);
1098 /// getSCEVAtScope - Compute the value of the specified expression within
1099 /// the indicated loop (which may be null to indicate in no loop). If the
1100 /// expression cannot be evaluated, return UnknownValue itself.
1101 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1104 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1105 /// an analyzable loop-invariant iteration count.
1106 bool hasLoopInvariantIterationCount(const Loop *L);
1108 /// getIterationCount - If the specified loop has a predictable iteration
1109 /// count, return it. Note that it is not valid to call this method on a
1110 /// loop without a loop-invariant iteration count.
1111 SCEVHandle getIterationCount(const Loop *L);
1113 /// deleteInstructionFromRecords - This method should be called by the
1114 /// client before it removes an instruction from the program, to make sure
1115 /// that no dangling references are left around.
1116 void deleteInstructionFromRecords(Instruction *I);
1119 /// createSCEV - We know that there is no SCEV for the specified value.
1120 /// Analyze the expression.
1121 SCEVHandle createSCEV(Value *V);
1122 SCEVHandle createNodeForCast(CastInst *CI);
1124 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1126 SCEVHandle createNodeForPHI(PHINode *PN);
1128 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1129 /// for the specified instruction and replaces any references to the
1130 /// symbolic value SymName with the specified value. This is used during
1132 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1133 const SCEVHandle &SymName,
1134 const SCEVHandle &NewVal);
1136 /// ComputeIterationCount - Compute the number of times the specified loop
1138 SCEVHandle ComputeIterationCount(const Loop *L);
1140 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1141 /// 'setcc load X, cst', try to se if we can compute the trip count.
1142 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1145 unsigned SetCCOpcode);
1147 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1148 /// constant number of times (the condition evolves only from constants),
1149 /// try to evaluate a few iterations of the loop until we get the exit
1150 /// condition gets a value of ExitWhen (true or false). If we cannot
1151 /// evaluate the trip count of the loop, return UnknownValue.
1152 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1155 /// HowFarToZero - Return the number of times a backedge comparing the
1156 /// specified value to zero will execute. If not computable, return
1158 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1160 /// HowFarToNonZero - Return the number of times a backedge checking the
1161 /// specified value for nonzero will execute. If not computable, return
1163 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1165 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1166 /// in the header of its containing loop, we know the loop executes a
1167 /// constant number of times, and the PHI node is just a recurrence
1168 /// involving constants, fold it.
1169 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1174 //===----------------------------------------------------------------------===//
1175 // Basic SCEV Analysis and PHI Idiom Recognition Code
1178 /// deleteInstructionFromRecords - This method should be called by the
1179 /// client before it removes an instruction from the program, to make sure
1180 /// that no dangling references are left around.
1181 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1183 if (PHINode *PN = dyn_cast<PHINode>(I))
1184 ConstantEvolutionLoopExitValue.erase(PN);
1188 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1189 /// expression and create a new one.
1190 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1191 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1193 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1194 if (I != Scalars.end()) return I->second;
1195 SCEVHandle S = createSCEV(V);
1196 Scalars.insert(std::make_pair(V, S));
1200 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1201 /// the specified instruction and replaces any references to the symbolic value
1202 /// SymName with the specified value. This is used during PHI resolution.
1203 void ScalarEvolutionsImpl::
1204 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1205 const SCEVHandle &NewVal) {
1206 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1207 if (SI == Scalars.end()) return;
1210 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1211 if (NV == SI->second) return; // No change.
1213 SI->second = NV; // Update the scalars map!
1215 // Any instruction values that use this instruction might also need to be
1217 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1219 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1222 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1223 /// a loop header, making it a potential recurrence, or it doesn't.
1225 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1226 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1227 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1228 if (L->getHeader() == PN->getParent()) {
1229 // If it lives in the loop header, it has two incoming values, one
1230 // from outside the loop, and one from inside.
1231 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1232 unsigned BackEdge = IncomingEdge^1;
1234 // While we are analyzing this PHI node, handle its value symbolically.
1235 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1236 assert(Scalars.find(PN) == Scalars.end() &&
1237 "PHI node already processed?");
1238 Scalars.insert(std::make_pair(PN, SymbolicName));
1240 // Using this symbolic name for the PHI, analyze the value coming around
1242 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1244 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1245 // has a special value for the first iteration of the loop.
1247 // If the value coming around the backedge is an add with the symbolic
1248 // value we just inserted, then we found a simple induction variable!
1249 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1250 // If there is a single occurrence of the symbolic value, replace it
1251 // with a recurrence.
1252 unsigned FoundIndex = Add->getNumOperands();
1253 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1254 if (Add->getOperand(i) == SymbolicName)
1255 if (FoundIndex == e) {
1260 if (FoundIndex != Add->getNumOperands()) {
1261 // Create an add with everything but the specified operand.
1262 std::vector<SCEVHandle> Ops;
1263 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1264 if (i != FoundIndex)
1265 Ops.push_back(Add->getOperand(i));
1266 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1268 // This is not a valid addrec if the step amount is varying each
1269 // loop iteration, but is not itself an addrec in this loop.
1270 if (Accum->isLoopInvariant(L) ||
1271 (isa<SCEVAddRecExpr>(Accum) &&
1272 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1273 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1274 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1276 // Okay, for the entire analysis of this edge we assumed the PHI
1277 // to be symbolic. We now need to go back and update all of the
1278 // entries for the scalars that use the PHI (except for the PHI
1279 // itself) to use the new analyzed value instead of the "symbolic"
1281 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1287 return SymbolicName;
1290 // If it's not a loop phi, we can't handle it yet.
1291 return SCEVUnknown::get(PN);
1294 /// createNodeForCast - Handle the various forms of casts that we support.
1296 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1297 const Type *SrcTy = CI->getOperand(0)->getType();
1298 const Type *DestTy = CI->getType();
1300 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1301 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1302 return getSCEV(CI->getOperand(0));
1304 if (SrcTy->isInteger() && DestTy->isInteger()) {
1305 // Otherwise, if this is a truncating integer cast, we can represent this
1307 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1308 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1309 CI->getType()->getUnsignedVersion());
1310 if (SrcTy->isUnsigned() &&
1311 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1312 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1313 CI->getType()->getUnsignedVersion());
1316 // If this is an sign or zero extending cast and we can prove that the value
1317 // will never overflow, we could do similar transformations.
1319 // Otherwise, we can't handle this cast!
1320 return SCEVUnknown::get(CI);
1324 /// createSCEV - We know that there is no SCEV for the specified value.
1325 /// Analyze the expression.
1327 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1328 if (Instruction *I = dyn_cast<Instruction>(V)) {
1329 switch (I->getOpcode()) {
1330 case Instruction::Add:
1331 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1332 getSCEV(I->getOperand(1)));
1333 case Instruction::Mul:
1334 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1335 getSCEV(I->getOperand(1)));
1336 case Instruction::Div:
1337 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1338 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1339 getSCEV(I->getOperand(1)));
1342 case Instruction::Sub:
1343 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1344 getSCEV(I->getOperand(1)));
1346 case Instruction::Shl:
1347 // Turn shift left of a constant amount into a multiply.
1348 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1349 Constant *X = ConstantInt::get(V->getType(), 1);
1350 X = ConstantExpr::getShl(X, SA);
1351 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1355 case Instruction::Shr:
1356 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1357 if (V->getType()->isUnsigned()) {
1358 Constant *X = ConstantInt::get(V->getType(), 1);
1359 X = ConstantExpr::getShl(X, SA);
1360 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1364 case Instruction::Cast:
1365 return createNodeForCast(cast<CastInst>(I));
1367 case Instruction::PHI:
1368 return createNodeForPHI(cast<PHINode>(I));
1370 default: // We cannot analyze this expression.
1375 return SCEVUnknown::get(V);
1380 //===----------------------------------------------------------------------===//
1381 // Iteration Count Computation Code
1384 /// getIterationCount - If the specified loop has a predictable iteration
1385 /// count, return it. Note that it is not valid to call this method on a
1386 /// loop without a loop-invariant iteration count.
1387 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1388 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1389 if (I == IterationCounts.end()) {
1390 SCEVHandle ItCount = ComputeIterationCount(L);
1391 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1392 if (ItCount != UnknownValue) {
1393 assert(ItCount->isLoopInvariant(L) &&
1394 "Computed trip count isn't loop invariant for loop!");
1395 ++NumTripCountsComputed;
1396 } else if (isa<PHINode>(L->getHeader()->begin())) {
1397 // Only count loops that have phi nodes as not being computable.
1398 ++NumTripCountsNotComputed;
1404 /// ComputeIterationCount - Compute the number of times the specified loop
1406 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1407 // If the loop has a non-one exit block count, we can't analyze it.
1408 std::vector<BasicBlock*> ExitBlocks;
1409 L->getExitBlocks(ExitBlocks);
1410 if (ExitBlocks.size() != 1) return UnknownValue;
1412 // Okay, there is one exit block. Try to find the condition that causes the
1413 // loop to be exited.
1414 BasicBlock *ExitBlock = ExitBlocks[0];
1416 BasicBlock *ExitingBlock = 0;
1417 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1419 if (L->contains(*PI)) {
1420 if (ExitingBlock == 0)
1423 return UnknownValue; // More than one block exiting!
1425 assert(ExitingBlock && "No exits from loop, something is broken!");
1427 // Okay, we've computed the exiting block. See what condition causes us to
1430 // FIXME: we should be able to handle switch instructions (with a single exit)
1431 // FIXME: We should handle cast of int to bool as well
1432 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1433 if (ExitBr == 0) return UnknownValue;
1434 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1435 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1436 if (ExitCond == 0) // Not a setcc
1437 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1438 ExitBr->getSuccessor(0) == ExitBlock);
1440 // If the condition was exit on true, convert the condition to exit on false.
1441 Instruction::BinaryOps Cond;
1442 if (ExitBr->getSuccessor(1) == ExitBlock)
1443 Cond = ExitCond->getOpcode();
1445 Cond = ExitCond->getInverseCondition();
1447 // Handle common loops like: for (X = "string"; *X; ++X)
1448 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1449 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1451 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1452 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1455 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1456 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1458 // Try to evaluate any dependencies out of the loop.
1459 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1460 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1461 Tmp = getSCEVAtScope(RHS, L);
1462 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1464 // At this point, we would like to compute how many iterations of the loop the
1465 // predicate will return true for these inputs.
1466 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1467 // If there is a constant, force it into the RHS.
1468 std::swap(LHS, RHS);
1469 Cond = SetCondInst::getSwappedCondition(Cond);
1472 // FIXME: think about handling pointer comparisons! i.e.:
1473 // while (P != P+100) ++P;
1475 // If we have a comparison of a chrec against a constant, try to use value
1476 // ranges to answer this query.
1477 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1478 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1479 if (AddRec->getLoop() == L) {
1480 // Form the comparison range using the constant of the correct type so
1481 // that the ConstantRange class knows to do a signed or unsigned
1483 ConstantInt *CompVal = RHSC->getValue();
1484 const Type *RealTy = ExitCond->getOperand(0)->getType();
1485 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1487 // Form the constant range.
1488 ConstantRange CompRange(Cond, CompVal);
1490 // Now that we have it, if it's signed, convert it to an unsigned
1492 if (CompRange.getLower()->getType()->isSigned()) {
1493 const Type *NewTy = RHSC->getValue()->getType();
1494 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1495 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1496 CompRange = ConstantRange(NewL, NewU);
1499 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1500 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1505 case Instruction::SetNE: // while (X != Y)
1506 // Convert to: while (X-Y != 0)
1507 if (LHS->getType()->isInteger()) {
1508 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1509 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1512 case Instruction::SetEQ:
1513 // Convert to: while (X-Y == 0) // while (X == Y)
1514 if (LHS->getType()->isInteger()) {
1515 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1516 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1521 std::cerr << "ComputeIterationCount ";
1522 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1523 std::cerr << "[unsigned] ";
1524 std::cerr << *LHS << " "
1525 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1530 return ComputeIterationCountExhaustively(L, ExitCond,
1531 ExitBr->getSuccessor(0) == ExitBlock);
1534 static ConstantInt *
1535 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1536 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1537 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1538 assert(isa<SCEVConstant>(Val) &&
1539 "Evaluation of SCEV at constant didn't fold correctly?");
1540 return cast<SCEVConstant>(Val)->getValue();
1543 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1544 /// and a GEP expression (missing the pointer index) indexing into it, return
1545 /// the addressed element of the initializer or null if the index expression is
1548 GetAddressedElementFromGlobal(GlobalVariable *GV,
1549 const std::vector<ConstantInt*> &Indices) {
1550 Constant *Init = GV->getInitializer();
1551 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1552 uint64_t Idx = Indices[i]->getRawValue();
1553 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1554 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1555 Init = cast<Constant>(CS->getOperand(Idx));
1556 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1557 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1558 Init = cast<Constant>(CA->getOperand(Idx));
1559 } else if (isa<ConstantAggregateZero>(Init)) {
1560 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1561 assert(Idx < STy->getNumElements() && "Bad struct index!");
1562 Init = Constant::getNullValue(STy->getElementType(Idx));
1563 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1564 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1565 Init = Constant::getNullValue(ATy->getElementType());
1567 assert(0 && "Unknown constant aggregate type!");
1571 return 0; // Unknown initializer type
1577 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1578 /// 'setcc load X, cst', try to se if we can compute the trip count.
1579 SCEVHandle ScalarEvolutionsImpl::
1580 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1581 const Loop *L, unsigned SetCCOpcode) {
1582 if (LI->isVolatile()) return UnknownValue;
1584 // Check to see if the loaded pointer is a getelementptr of a global.
1585 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1586 if (!GEP) return UnknownValue;
1588 // Make sure that it is really a constant global we are gepping, with an
1589 // initializer, and make sure the first IDX is really 0.
1590 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1591 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1592 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1593 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1594 return UnknownValue;
1596 // Okay, we allow one non-constant index into the GEP instruction.
1598 std::vector<ConstantInt*> Indexes;
1599 unsigned VarIdxNum = 0;
1600 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1601 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1602 Indexes.push_back(CI);
1603 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1604 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1605 VarIdx = GEP->getOperand(i);
1607 Indexes.push_back(0);
1610 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1611 // Check to see if X is a loop variant variable value now.
1612 SCEVHandle Idx = getSCEV(VarIdx);
1613 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1614 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1616 // We can only recognize very limited forms of loop index expressions, in
1617 // particular, only affine AddRec's like {C1,+,C2}.
1618 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1619 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1620 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1621 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1622 return UnknownValue;
1624 unsigned MaxSteps = MaxBruteForceIterations;
1625 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1626 ConstantUInt *ItCst =
1627 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1628 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1630 // Form the GEP offset.
1631 Indexes[VarIdxNum] = Val;
1633 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1634 if (Result == 0) break; // Cannot compute!
1636 // Evaluate the condition for this iteration.
1637 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1638 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1639 if (Result == ConstantBool::False) {
1641 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1642 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1645 ++NumArrayLenItCounts;
1646 return SCEVConstant::get(ItCst); // Found terminating iteration!
1649 return UnknownValue;
1653 /// CanConstantFold - Return true if we can constant fold an instruction of the
1654 /// specified type, assuming that all operands were constants.
1655 static bool CanConstantFold(const Instruction *I) {
1656 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1657 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1660 if (const CallInst *CI = dyn_cast<CallInst>(I))
1661 if (const Function *F = CI->getCalledFunction())
1662 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1666 /// ConstantFold - Constant fold an instruction of the specified type with the
1667 /// specified constant operands. This function may modify the operands vector.
1668 static Constant *ConstantFold(const Instruction *I,
1669 std::vector<Constant*> &Operands) {
1670 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1671 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1673 switch (I->getOpcode()) {
1674 case Instruction::Cast:
1675 return ConstantExpr::getCast(Operands[0], I->getType());
1676 case Instruction::Select:
1677 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1678 case Instruction::Call:
1679 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1680 Operands.erase(Operands.begin());
1681 return ConstantFoldCall(cast<Function>(GV), Operands);
1685 case Instruction::GetElementPtr:
1686 Constant *Base = Operands[0];
1687 Operands.erase(Operands.begin());
1688 return ConstantExpr::getGetElementPtr(Base, Operands);
1694 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1695 /// in the loop that V is derived from. We allow arbitrary operations along the
1696 /// way, but the operands of an operation must either be constants or a value
1697 /// derived from a constant PHI. If this expression does not fit with these
1698 /// constraints, return null.
1699 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1700 // If this is not an instruction, or if this is an instruction outside of the
1701 // loop, it can't be derived from a loop PHI.
1702 Instruction *I = dyn_cast<Instruction>(V);
1703 if (I == 0 || !L->contains(I->getParent())) return 0;
1705 if (PHINode *PN = dyn_cast<PHINode>(I))
1706 if (L->getHeader() == I->getParent())
1709 // We don't currently keep track of the control flow needed to evaluate
1710 // PHIs, so we cannot handle PHIs inside of loops.
1713 // If we won't be able to constant fold this expression even if the operands
1714 // are constants, return early.
1715 if (!CanConstantFold(I)) return 0;
1717 // Otherwise, we can evaluate this instruction if all of its operands are
1718 // constant or derived from a PHI node themselves.
1720 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1721 if (!(isa<Constant>(I->getOperand(Op)) ||
1722 isa<GlobalValue>(I->getOperand(Op)))) {
1723 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1724 if (P == 0) return 0; // Not evolving from PHI
1728 return 0; // Evolving from multiple different PHIs.
1731 // This is a expression evolving from a constant PHI!
1735 /// EvaluateExpression - Given an expression that passes the
1736 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1737 /// in the loop has the value PHIVal. If we can't fold this expression for some
1738 /// reason, return null.
1739 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1740 if (isa<PHINode>(V)) return PHIVal;
1741 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1743 if (Constant *C = dyn_cast<Constant>(V)) return C;
1744 Instruction *I = cast<Instruction>(V);
1746 std::vector<Constant*> Operands;
1747 Operands.resize(I->getNumOperands());
1749 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1750 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1751 if (Operands[i] == 0) return 0;
1754 return ConstantFold(I, Operands);
1757 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1758 /// in the header of its containing loop, we know the loop executes a
1759 /// constant number of times, and the PHI node is just a recurrence
1760 /// involving constants, fold it.
1761 Constant *ScalarEvolutionsImpl::
1762 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1763 std::map<PHINode*, Constant*>::iterator I =
1764 ConstantEvolutionLoopExitValue.find(PN);
1765 if (I != ConstantEvolutionLoopExitValue.end())
1768 if (Its > MaxBruteForceIterations)
1769 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1771 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1773 // Since the loop is canonicalized, the PHI node must have two entries. One
1774 // entry must be a constant (coming in from outside of the loop), and the
1775 // second must be derived from the same PHI.
1776 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1777 Constant *StartCST =
1778 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1780 return RetVal = 0; // Must be a constant.
1782 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1783 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1785 return RetVal = 0; // Not derived from same PHI.
1787 // Execute the loop symbolically to determine the exit value.
1788 unsigned IterationNum = 0;
1789 unsigned NumIterations = Its;
1790 if (NumIterations != Its)
1791 return RetVal = 0; // More than 2^32 iterations??
1793 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1794 if (IterationNum == NumIterations)
1795 return RetVal = PHIVal; // Got exit value!
1797 // Compute the value of the PHI node for the next iteration.
1798 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1799 if (NextPHI == PHIVal)
1800 return RetVal = NextPHI; // Stopped evolving!
1802 return 0; // Couldn't evaluate!
1807 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1808 /// constant number of times (the condition evolves only from constants),
1809 /// try to evaluate a few iterations of the loop until we get the exit
1810 /// condition gets a value of ExitWhen (true or false). If we cannot
1811 /// evaluate the trip count of the loop, return UnknownValue.
1812 SCEVHandle ScalarEvolutionsImpl::
1813 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1814 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1815 if (PN == 0) return UnknownValue;
1817 // Since the loop is canonicalized, the PHI node must have two entries. One
1818 // entry must be a constant (coming in from outside of the loop), and the
1819 // second must be derived from the same PHI.
1820 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1821 Constant *StartCST =
1822 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1823 if (StartCST == 0) return UnknownValue; // Must be a constant.
1825 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1826 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1827 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1829 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1830 // the loop symbolically to determine when the condition gets a value of
1832 unsigned IterationNum = 0;
1833 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1834 for (Constant *PHIVal = StartCST;
1835 IterationNum != MaxIterations; ++IterationNum) {
1836 ConstantBool *CondVal =
1837 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1838 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1840 if (CondVal->getValue() == ExitWhen) {
1841 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1842 ++NumBruteForceTripCountsComputed;
1843 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1846 // Compute the value of the PHI node for the next iteration.
1847 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1848 if (NextPHI == 0 || NextPHI == PHIVal)
1849 return UnknownValue; // Couldn't evaluate or not making progress...
1853 // Too many iterations were needed to evaluate.
1854 return UnknownValue;
1857 /// getSCEVAtScope - Compute the value of the specified expression within the
1858 /// indicated loop (which may be null to indicate in no loop). If the
1859 /// expression cannot be evaluated, return UnknownValue.
1860 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1861 // FIXME: this should be turned into a virtual method on SCEV!
1863 if (isa<SCEVConstant>(V)) return V;
1865 // If this instruction is evolves from a constant-evolving PHI, compute the
1866 // exit value from the loop without using SCEVs.
1867 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1868 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1869 const Loop *LI = this->LI[I->getParent()];
1870 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1871 if (PHINode *PN = dyn_cast<PHINode>(I))
1872 if (PN->getParent() == LI->getHeader()) {
1873 // Okay, there is no closed form solution for the PHI node. Check
1874 // to see if the loop that contains it has a known iteration count.
1875 // If so, we may be able to force computation of the exit value.
1876 SCEVHandle IterationCount = getIterationCount(LI);
1877 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1878 // Okay, we know how many times the containing loop executes. If
1879 // this is a constant evolving PHI node, get the final value at
1880 // the specified iteration number.
1881 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1882 ICC->getValue()->getRawValue(),
1884 if (RV) return SCEVUnknown::get(RV);
1888 // Okay, this is a some expression that we cannot symbolically evaluate
1889 // into a SCEV. Check to see if it's possible to symbolically evaluate
1890 // the arguments into constants, and if see, try to constant propagate the
1891 // result. This is particularly useful for computing loop exit values.
1892 if (CanConstantFold(I)) {
1893 std::vector<Constant*> Operands;
1894 Operands.reserve(I->getNumOperands());
1895 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1896 Value *Op = I->getOperand(i);
1897 if (Constant *C = dyn_cast<Constant>(Op)) {
1898 Operands.push_back(C);
1900 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1901 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1902 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1904 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1905 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1906 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1914 return SCEVUnknown::get(ConstantFold(I, Operands));
1918 // This is some other type of SCEVUnknown, just return it.
1922 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1923 // Avoid performing the look-up in the common case where the specified
1924 // expression has no loop-variant portions.
1925 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1926 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1927 if (OpAtScope != Comm->getOperand(i)) {
1928 if (OpAtScope == UnknownValue) return UnknownValue;
1929 // Okay, at least one of these operands is loop variant but might be
1930 // foldable. Build a new instance of the folded commutative expression.
1931 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1932 NewOps.push_back(OpAtScope);
1934 for (++i; i != e; ++i) {
1935 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1936 if (OpAtScope == UnknownValue) return UnknownValue;
1937 NewOps.push_back(OpAtScope);
1939 if (isa<SCEVAddExpr>(Comm))
1940 return SCEVAddExpr::get(NewOps);
1941 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1942 return SCEVMulExpr::get(NewOps);
1945 // If we got here, all operands are loop invariant.
1949 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1950 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1951 if (LHS == UnknownValue) return LHS;
1952 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1953 if (RHS == UnknownValue) return RHS;
1954 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1955 return UDiv; // must be loop invariant
1956 return SCEVUDivExpr::get(LHS, RHS);
1959 // If this is a loop recurrence for a loop that does not contain L, then we
1960 // are dealing with the final value computed by the loop.
1961 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1962 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1963 // To evaluate this recurrence, we need to know how many times the AddRec
1964 // loop iterates. Compute this now.
1965 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1966 if (IterationCount == UnknownValue) return UnknownValue;
1967 IterationCount = getTruncateOrZeroExtend(IterationCount,
1970 // If the value is affine, simplify the expression evaluation to just
1971 // Start + Step*IterationCount.
1972 if (AddRec->isAffine())
1973 return SCEVAddExpr::get(AddRec->getStart(),
1974 SCEVMulExpr::get(IterationCount,
1975 AddRec->getOperand(1)));
1977 // Otherwise, evaluate it the hard way.
1978 return AddRec->evaluateAtIteration(IterationCount);
1980 return UnknownValue;
1983 //assert(0 && "Unknown SCEV type!");
1984 return UnknownValue;
1988 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1989 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1990 /// might be the same) or two SCEVCouldNotCompute objects.
1992 static std::pair<SCEVHandle,SCEVHandle>
1993 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1994 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1995 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1996 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1997 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1999 // We currently can only solve this if the coefficients are constants.
2000 if (!L || !M || !N) {
2001 SCEV *CNC = new SCEVCouldNotCompute();
2002 return std::make_pair(CNC, CNC);
2005 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2007 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2008 Constant *C = L->getValue();
2009 // The B coefficient is M-N/2
2010 Constant *B = ConstantExpr::getSub(M->getValue(),
2011 ConstantExpr::getDiv(N->getValue(),
2013 // The A coefficient is N/2
2014 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2016 // Compute the B^2-4ac term.
2017 Constant *SqrtTerm =
2018 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2019 ConstantExpr::getMul(A, C));
2020 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2022 // Compute floor(sqrt(B^2-4ac))
2023 ConstantUInt *SqrtVal =
2024 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2025 SqrtTerm->getType()->getUnsignedVersion()));
2026 uint64_t SqrtValV = SqrtVal->getValue();
2027 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2028 // The square root might not be precise for arbitrary 64-bit integer
2029 // values. Do some sanity checks to ensure it's correct.
2030 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2031 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2032 SCEV *CNC = new SCEVCouldNotCompute();
2033 return std::make_pair(CNC, CNC);
2036 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2037 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2039 Constant *NegB = ConstantExpr::getNeg(B);
2040 Constant *TwoA = ConstantExpr::getMul(A, Two);
2042 // The divisions must be performed as signed divisions.
2043 const Type *SignedTy = NegB->getType()->getSignedVersion();
2044 NegB = ConstantExpr::getCast(NegB, SignedTy);
2045 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2046 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2048 Constant *Solution1 =
2049 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2050 Constant *Solution2 =
2051 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2052 return std::make_pair(SCEVUnknown::get(Solution1),
2053 SCEVUnknown::get(Solution2));
2056 /// HowFarToZero - Return the number of times a backedge comparing the specified
2057 /// value to zero will execute. If not computable, return UnknownValue
2058 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2059 // If the value is a constant
2060 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2061 // If the value is already zero, the branch will execute zero times.
2062 if (C->getValue()->isNullValue()) return C;
2063 return UnknownValue; // Otherwise it will loop infinitely.
2066 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2067 if (!AddRec || AddRec->getLoop() != L)
2068 return UnknownValue;
2070 if (AddRec->isAffine()) {
2071 // If this is an affine expression the execution count of this branch is
2074 // (0 - Start/Step) iff Start % Step == 0
2076 // Get the initial value for the loop.
2077 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2078 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2079 SCEVHandle Step = AddRec->getOperand(1);
2081 Step = getSCEVAtScope(Step, L->getParentLoop());
2083 // Figure out if Start % Step == 0.
2084 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2085 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2086 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2087 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
2088 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2089 return Start; // 0 - Start/-1 == Start
2091 // Check to see if Start is divisible by SC with no remainder.
2092 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2093 ConstantInt *StartCC = StartC->getValue();
2094 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2095 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2096 if (Rem->isNullValue()) {
2097 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2098 return SCEVUnknown::get(Result);
2102 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2103 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2104 // the quadratic equation to solve it.
2105 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2106 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2107 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2110 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2111 << " sol#2: " << *R2 << "\n";
2113 // Pick the smallest positive root value.
2114 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2115 if (ConstantBool *CB =
2116 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2118 if (CB != ConstantBool::True)
2119 std::swap(R1, R2); // R1 is the minimum root now.
2121 // We can only use this value if the chrec ends up with an exact zero
2122 // value at this index. When solving for "X*X != 5", for example, we
2123 // should not accept a root of 2.
2124 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2125 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2126 if (EvalVal->getValue()->isNullValue())
2127 return R1; // We found a quadratic root!
2132 return UnknownValue;
2135 /// HowFarToNonZero - Return the number of times a backedge checking the
2136 /// specified value for nonzero will execute. If not computable, return
2138 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2139 // Loops that look like: while (X == 0) are very strange indeed. We don't
2140 // handle them yet except for the trivial case. This could be expanded in the
2141 // future as needed.
2143 // If the value is a constant, check to see if it is known to be non-zero
2144 // already. If so, the backedge will execute zero times.
2145 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2146 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2147 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2148 if (NonZero == ConstantBool::True)
2149 return getSCEV(Zero);
2150 return UnknownValue; // Otherwise it will loop infinitely.
2153 // We could implement others, but I really doubt anyone writes loops like
2154 // this, and if they did, they would already be constant folded.
2155 return UnknownValue;
2158 /// getNumIterationsInRange - Return the number of iterations of this loop that
2159 /// produce values in the specified constant range. Another way of looking at
2160 /// this is that it returns the first iteration number where the value is not in
2161 /// the condition, thus computing the exit count. If the iteration count can't
2162 /// be computed, an instance of SCEVCouldNotCompute is returned.
2163 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2164 if (Range.isFullSet()) // Infinite loop.
2165 return new SCEVCouldNotCompute();
2167 // If the start is a non-zero constant, shift the range to simplify things.
2168 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2169 if (!SC->getValue()->isNullValue()) {
2170 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2171 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2172 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2173 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2174 return ShiftedAddRec->getNumIterationsInRange(
2175 Range.subtract(SC->getValue()));
2176 // This is strange and shouldn't happen.
2177 return new SCEVCouldNotCompute();
2180 // The only time we can solve this is when we have all constant indices.
2181 // Otherwise, we cannot determine the overflow conditions.
2182 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2183 if (!isa<SCEVConstant>(getOperand(i)))
2184 return new SCEVCouldNotCompute();
2187 // Okay at this point we know that all elements of the chrec are constants and
2188 // that the start element is zero.
2190 // First check to see if the range contains zero. If not, the first
2192 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2193 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2196 // If this is an affine expression then we have this situation:
2197 // Solve {0,+,A} in Range === Ax in Range
2199 // Since we know that zero is in the range, we know that the upper value of
2200 // the range must be the first possible exit value. Also note that we
2201 // already checked for a full range.
2202 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2203 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2204 ConstantInt *One = ConstantInt::get(getType(), 1);
2206 // The exit value should be (Upper+A-1)/A.
2207 Constant *ExitValue = Upper;
2209 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2210 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2212 assert(isa<ConstantInt>(ExitValue) &&
2213 "Constant folding of integers not implemented?");
2215 // Evaluate at the exit value. If we really did fall out of the valid
2216 // range, then we computed our trip count, otherwise wrap around or other
2217 // things must have happened.
2218 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2219 if (Range.contains(Val))
2220 return new SCEVCouldNotCompute(); // Something strange happened
2222 // Ensure that the previous value is in the range. This is a sanity check.
2223 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2224 ConstantExpr::getSub(ExitValue, One))) &&
2225 "Linear scev computation is off in a bad way!");
2226 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2227 } else if (isQuadratic()) {
2228 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2229 // quadratic equation to solve it. To do this, we must frame our problem in
2230 // terms of figuring out when zero is crossed, instead of when
2231 // Range.getUpper() is crossed.
2232 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2233 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2234 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2236 // Next, solve the constructed addrec
2237 std::pair<SCEVHandle,SCEVHandle> Roots =
2238 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2239 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2240 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2242 // Pick the smallest positive root value.
2243 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2244 if (ConstantBool *CB =
2245 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2247 if (CB != ConstantBool::True)
2248 std::swap(R1, R2); // R1 is the minimum root now.
2250 // Make sure the root is not off by one. The returned iteration should
2251 // not be in the range, but the previous one should be. When solving
2252 // for "X*X < 5", for example, we should not return a root of 2.
2253 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2255 if (Range.contains(R1Val)) {
2256 // The next iteration must be out of the range...
2258 ConstantExpr::getAdd(R1->getValue(),
2259 ConstantInt::get(R1->getType(), 1));
2261 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2262 if (!Range.contains(R1Val))
2263 return SCEVUnknown::get(NextVal);
2264 return new SCEVCouldNotCompute(); // Something strange happened
2267 // If R1 was not in the range, then it is a good return value. Make
2268 // sure that R1-1 WAS in the range though, just in case.
2270 ConstantExpr::getSub(R1->getValue(),
2271 ConstantInt::get(R1->getType(), 1));
2272 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2273 if (Range.contains(R1Val))
2275 return new SCEVCouldNotCompute(); // Something strange happened
2280 // Fallback, if this is a general polynomial, figure out the progression
2281 // through brute force: evaluate until we find an iteration that fails the
2282 // test. This is likely to be slow, but getting an accurate trip count is
2283 // incredibly important, we will be able to simplify the exit test a lot, and
2284 // we are almost guaranteed to get a trip count in this case.
2285 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2286 ConstantInt *One = ConstantInt::get(getType(), 1);
2287 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2289 ++NumBruteForceEvaluations;
2290 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2291 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2292 return new SCEVCouldNotCompute();
2294 // Check to see if we found the value!
2295 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2296 return SCEVConstant::get(TestVal);
2298 // Increment to test the next index.
2299 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2300 } while (TestVal != EndVal);
2302 return new SCEVCouldNotCompute();
2307 //===----------------------------------------------------------------------===//
2308 // ScalarEvolution Class Implementation
2309 //===----------------------------------------------------------------------===//
2311 bool ScalarEvolution::runOnFunction(Function &F) {
2312 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2316 void ScalarEvolution::releaseMemory() {
2317 delete (ScalarEvolutionsImpl*)Impl;
2321 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2322 AU.setPreservesAll();
2323 AU.addRequiredTransitive<LoopInfo>();
2326 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2327 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2330 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2331 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2334 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2335 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2338 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2339 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2342 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2343 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2346 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2348 // Print all inner loops first
2349 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2350 PrintLoopInfo(OS, SE, *I);
2352 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2354 std::vector<BasicBlock*> ExitBlocks;
2355 L->getExitBlocks(ExitBlocks);
2356 if (ExitBlocks.size() != 1)
2357 std::cerr << "<multiple exits> ";
2359 if (SE->hasLoopInvariantIterationCount(L)) {
2360 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2362 std::cerr << "Unpredictable iteration count. ";
2368 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2369 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2370 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2372 OS << "Classifying expressions for: " << F.getName() << "\n";
2373 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2374 if (I->getType()->isInteger()) {
2377 SCEVHandle SV = getSCEV(&*I);
2381 if ((*I).getType()->isIntegral()) {
2382 ConstantRange Bounds = SV->getValueRange();
2383 if (!Bounds.isFullSet())
2384 OS << "Bounds: " << Bounds << " ";
2387 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2389 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2390 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2391 OS << "<<Unknown>>";
2401 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2402 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2403 PrintLoopInfo(OS, this, *I);