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 static SCEVHandle 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 static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
494 return SCEVAddExpr::get(LHS, 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, 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 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 getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1345 case Instruction::Shl:
1346 // Turn shift left of a constant amount into a multiply.
1347 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1348 Constant *X = ConstantInt::get(V->getType(), 1);
1349 X = ConstantExpr::getShl(X, SA);
1350 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1354 case Instruction::Shr:
1355 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1356 if (V->getType()->isUnsigned()) {
1357 Constant *X = ConstantInt::get(V->getType(), 1);
1358 X = ConstantExpr::getShl(X, SA);
1359 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1363 case Instruction::Cast:
1364 return createNodeForCast(cast<CastInst>(I));
1366 case Instruction::PHI:
1367 return createNodeForPHI(cast<PHINode>(I));
1369 default: // We cannot analyze this expression.
1374 return SCEVUnknown::get(V);
1379 //===----------------------------------------------------------------------===//
1380 // Iteration Count Computation Code
1383 /// getIterationCount - If the specified loop has a predictable iteration
1384 /// count, return it. Note that it is not valid to call this method on a
1385 /// loop without a loop-invariant iteration count.
1386 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1387 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1388 if (I == IterationCounts.end()) {
1389 SCEVHandle ItCount = ComputeIterationCount(L);
1390 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1391 if (ItCount != UnknownValue) {
1392 assert(ItCount->isLoopInvariant(L) &&
1393 "Computed trip count isn't loop invariant for loop!");
1394 ++NumTripCountsComputed;
1395 } else if (isa<PHINode>(L->getHeader()->begin())) {
1396 // Only count loops that have phi nodes as not being computable.
1397 ++NumTripCountsNotComputed;
1403 /// ComputeIterationCount - Compute the number of times the specified loop
1405 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1406 // If the loop has a non-one exit block count, we can't analyze it.
1407 std::vector<BasicBlock*> ExitBlocks;
1408 L->getExitBlocks(ExitBlocks);
1409 if (ExitBlocks.size() != 1) return UnknownValue;
1411 // Okay, there is one exit block. Try to find the condition that causes the
1412 // loop to be exited.
1413 BasicBlock *ExitBlock = ExitBlocks[0];
1415 BasicBlock *ExitingBlock = 0;
1416 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1418 if (L->contains(*PI)) {
1419 if (ExitingBlock == 0)
1422 return UnknownValue; // More than one block exiting!
1424 assert(ExitingBlock && "No exits from loop, something is broken!");
1426 // Okay, we've computed the exiting block. See what condition causes us to
1429 // FIXME: we should be able to handle switch instructions (with a single exit)
1430 // FIXME: We should handle cast of int to bool as well
1431 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1432 if (ExitBr == 0) return UnknownValue;
1433 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1434 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1435 if (ExitCond == 0) // Not a setcc
1436 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1437 ExitBr->getSuccessor(0) == ExitBlock);
1439 // If the condition was exit on true, convert the condition to exit on false.
1440 Instruction::BinaryOps Cond;
1441 if (ExitBr->getSuccessor(1) == ExitBlock)
1442 Cond = ExitCond->getOpcode();
1444 Cond = ExitCond->getInverseCondition();
1446 // Handle common loops like: for (X = "string"; *X; ++X)
1447 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1448 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1450 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1451 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1454 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1455 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1457 // Try to evaluate any dependencies out of the loop.
1458 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1459 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1460 Tmp = getSCEVAtScope(RHS, L);
1461 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1463 // At this point, we would like to compute how many iterations of the loop the
1464 // predicate will return true for these inputs.
1465 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1466 // If there is a constant, force it into the RHS.
1467 std::swap(LHS, RHS);
1468 Cond = SetCondInst::getSwappedCondition(Cond);
1471 // FIXME: think about handling pointer comparisons! i.e.:
1472 // while (P != P+100) ++P;
1474 // If we have a comparison of a chrec against a constant, try to use value
1475 // ranges to answer this query.
1476 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1477 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1478 if (AddRec->getLoop() == L) {
1479 // Form the comparison range using the constant of the correct type so
1480 // that the ConstantRange class knows to do a signed or unsigned
1482 ConstantInt *CompVal = RHSC->getValue();
1483 const Type *RealTy = ExitCond->getOperand(0)->getType();
1484 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1486 // Form the constant range.
1487 ConstantRange CompRange(Cond, CompVal);
1489 // Now that we have it, if it's signed, convert it to an unsigned
1491 if (CompRange.getLower()->getType()->isSigned()) {
1492 const Type *NewTy = RHSC->getValue()->getType();
1493 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1494 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1495 CompRange = ConstantRange(NewL, NewU);
1498 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1499 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1504 case Instruction::SetNE: // while (X != Y)
1505 // Convert to: while (X-Y != 0)
1506 if (LHS->getType()->isInteger()) {
1507 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1508 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1511 case Instruction::SetEQ:
1512 // Convert to: while (X-Y == 0) // while (X == Y)
1513 if (LHS->getType()->isInteger()) {
1514 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1515 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1520 std::cerr << "ComputeIterationCount ";
1521 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1522 std::cerr << "[unsigned] ";
1523 std::cerr << *LHS << " "
1524 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1529 return ComputeIterationCountExhaustively(L, ExitCond,
1530 ExitBr->getSuccessor(0) == ExitBlock);
1533 static ConstantInt *
1534 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1535 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1536 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1537 assert(isa<SCEVConstant>(Val) &&
1538 "Evaluation of SCEV at constant didn't fold correctly?");
1539 return cast<SCEVConstant>(Val)->getValue();
1542 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1543 /// and a GEP expression (missing the pointer index) indexing into it, return
1544 /// the addressed element of the initializer or null if the index expression is
1547 GetAddressedElementFromGlobal(GlobalVariable *GV,
1548 const std::vector<ConstantInt*> &Indices) {
1549 Constant *Init = GV->getInitializer();
1550 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1551 uint64_t Idx = Indices[i]->getRawValue();
1552 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1553 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1554 Init = cast<Constant>(CS->getOperand(Idx));
1555 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1556 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1557 Init = cast<Constant>(CA->getOperand(Idx));
1558 } else if (isa<ConstantAggregateZero>(Init)) {
1559 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1560 assert(Idx < STy->getNumElements() && "Bad struct index!");
1561 Init = Constant::getNullValue(STy->getElementType(Idx));
1562 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1563 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1564 Init = Constant::getNullValue(ATy->getElementType());
1566 assert(0 && "Unknown constant aggregate type!");
1570 return 0; // Unknown initializer type
1576 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1577 /// 'setcc load X, cst', try to se if we can compute the trip count.
1578 SCEVHandle ScalarEvolutionsImpl::
1579 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1580 const Loop *L, unsigned SetCCOpcode) {
1581 if (LI->isVolatile()) return UnknownValue;
1583 // Check to see if the loaded pointer is a getelementptr of a global.
1584 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1585 if (!GEP) return UnknownValue;
1587 // Make sure that it is really a constant global we are gepping, with an
1588 // initializer, and make sure the first IDX is really 0.
1589 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1590 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1591 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1592 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1593 return UnknownValue;
1595 // Okay, we allow one non-constant index into the GEP instruction.
1597 std::vector<ConstantInt*> Indexes;
1598 unsigned VarIdxNum = 0;
1599 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1600 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1601 Indexes.push_back(CI);
1602 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1603 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1604 VarIdx = GEP->getOperand(i);
1606 Indexes.push_back(0);
1609 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1610 // Check to see if X is a loop variant variable value now.
1611 SCEVHandle Idx = getSCEV(VarIdx);
1612 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1613 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1615 // We can only recognize very limited forms of loop index expressions, in
1616 // particular, only affine AddRec's like {C1,+,C2}.
1617 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1618 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1619 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1620 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1621 return UnknownValue;
1623 unsigned MaxSteps = MaxBruteForceIterations;
1624 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1625 ConstantUInt *ItCst =
1626 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1627 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1629 // Form the GEP offset.
1630 Indexes[VarIdxNum] = Val;
1632 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1633 if (Result == 0) break; // Cannot compute!
1635 // Evaluate the condition for this iteration.
1636 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1637 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1638 if (Result == ConstantBool::False) {
1640 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1641 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1644 ++NumArrayLenItCounts;
1645 return SCEVConstant::get(ItCst); // Found terminating iteration!
1648 return UnknownValue;
1652 /// CanConstantFold - Return true if we can constant fold an instruction of the
1653 /// specified type, assuming that all operands were constants.
1654 static bool CanConstantFold(const Instruction *I) {
1655 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1656 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1659 if (const CallInst *CI = dyn_cast<CallInst>(I))
1660 if (const Function *F = CI->getCalledFunction())
1661 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1665 /// ConstantFold - Constant fold an instruction of the specified type with the
1666 /// specified constant operands. This function may modify the operands vector.
1667 static Constant *ConstantFold(const Instruction *I,
1668 std::vector<Constant*> &Operands) {
1669 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1670 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1672 switch (I->getOpcode()) {
1673 case Instruction::Cast:
1674 return ConstantExpr::getCast(Operands[0], I->getType());
1675 case Instruction::Select:
1676 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1677 case Instruction::Call:
1678 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1679 Operands.erase(Operands.begin());
1680 return ConstantFoldCall(cast<Function>(GV), Operands);
1684 case Instruction::GetElementPtr:
1685 Constant *Base = Operands[0];
1686 Operands.erase(Operands.begin());
1687 return ConstantExpr::getGetElementPtr(Base, Operands);
1693 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1694 /// in the loop that V is derived from. We allow arbitrary operations along the
1695 /// way, but the operands of an operation must either be constants or a value
1696 /// derived from a constant PHI. If this expression does not fit with these
1697 /// constraints, return null.
1698 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1699 // If this is not an instruction, or if this is an instruction outside of the
1700 // loop, it can't be derived from a loop PHI.
1701 Instruction *I = dyn_cast<Instruction>(V);
1702 if (I == 0 || !L->contains(I->getParent())) return 0;
1704 if (PHINode *PN = dyn_cast<PHINode>(I))
1705 if (L->getHeader() == I->getParent())
1708 // We don't currently keep track of the control flow needed to evaluate
1709 // PHIs, so we cannot handle PHIs inside of loops.
1712 // If we won't be able to constant fold this expression even if the operands
1713 // are constants, return early.
1714 if (!CanConstantFold(I)) return 0;
1716 // Otherwise, we can evaluate this instruction if all of its operands are
1717 // constant or derived from a PHI node themselves.
1719 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1720 if (!(isa<Constant>(I->getOperand(Op)) ||
1721 isa<GlobalValue>(I->getOperand(Op)))) {
1722 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1723 if (P == 0) return 0; // Not evolving from PHI
1727 return 0; // Evolving from multiple different PHIs.
1730 // This is a expression evolving from a constant PHI!
1734 /// EvaluateExpression - Given an expression that passes the
1735 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1736 /// in the loop has the value PHIVal. If we can't fold this expression for some
1737 /// reason, return null.
1738 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1739 if (isa<PHINode>(V)) return PHIVal;
1740 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1742 if (Constant *C = dyn_cast<Constant>(V)) return C;
1743 Instruction *I = cast<Instruction>(V);
1745 std::vector<Constant*> Operands;
1746 Operands.resize(I->getNumOperands());
1748 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1749 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1750 if (Operands[i] == 0) return 0;
1753 return ConstantFold(I, Operands);
1756 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1757 /// in the header of its containing loop, we know the loop executes a
1758 /// constant number of times, and the PHI node is just a recurrence
1759 /// involving constants, fold it.
1760 Constant *ScalarEvolutionsImpl::
1761 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1762 std::map<PHINode*, Constant*>::iterator I =
1763 ConstantEvolutionLoopExitValue.find(PN);
1764 if (I != ConstantEvolutionLoopExitValue.end())
1767 if (Its > MaxBruteForceIterations)
1768 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1770 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1772 // Since the loop is canonicalized, the PHI node must have two entries. One
1773 // entry must be a constant (coming in from outside of the loop), and the
1774 // second must be derived from the same PHI.
1775 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1776 Constant *StartCST =
1777 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1779 return RetVal = 0; // Must be a constant.
1781 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1782 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1784 return RetVal = 0; // Not derived from same PHI.
1786 // Execute the loop symbolically to determine the exit value.
1787 unsigned IterationNum = 0;
1788 unsigned NumIterations = Its;
1789 if (NumIterations != Its)
1790 return RetVal = 0; // More than 2^32 iterations??
1792 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1793 if (IterationNum == NumIterations)
1794 return RetVal = PHIVal; // Got exit value!
1796 // Compute the value of the PHI node for the next iteration.
1797 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1798 if (NextPHI == PHIVal)
1799 return RetVal = NextPHI; // Stopped evolving!
1801 return 0; // Couldn't evaluate!
1806 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1807 /// constant number of times (the condition evolves only from constants),
1808 /// try to evaluate a few iterations of the loop until we get the exit
1809 /// condition gets a value of ExitWhen (true or false). If we cannot
1810 /// evaluate the trip count of the loop, return UnknownValue.
1811 SCEVHandle ScalarEvolutionsImpl::
1812 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1813 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1814 if (PN == 0) return UnknownValue;
1816 // Since the loop is canonicalized, the PHI node must have two entries. One
1817 // entry must be a constant (coming in from outside of the loop), and the
1818 // second must be derived from the same PHI.
1819 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1820 Constant *StartCST =
1821 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1822 if (StartCST == 0) return UnknownValue; // Must be a constant.
1824 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1825 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1826 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1828 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1829 // the loop symbolically to determine when the condition gets a value of
1831 unsigned IterationNum = 0;
1832 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1833 for (Constant *PHIVal = StartCST;
1834 IterationNum != MaxIterations; ++IterationNum) {
1835 ConstantBool *CondVal =
1836 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1837 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1839 if (CondVal->getValue() == ExitWhen) {
1840 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1841 ++NumBruteForceTripCountsComputed;
1842 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1845 // Compute the value of the PHI node for the next iteration.
1846 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1847 if (NextPHI == 0 || NextPHI == PHIVal)
1848 return UnknownValue; // Couldn't evaluate or not making progress...
1852 // Too many iterations were needed to evaluate.
1853 return UnknownValue;
1856 /// getSCEVAtScope - Compute the value of the specified expression within the
1857 /// indicated loop (which may be null to indicate in no loop). If the
1858 /// expression cannot be evaluated, return UnknownValue.
1859 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1860 // FIXME: this should be turned into a virtual method on SCEV!
1862 if (isa<SCEVConstant>(V)) return V;
1864 // If this instruction is evolves from a constant-evolving PHI, compute the
1865 // exit value from the loop without using SCEVs.
1866 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1867 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1868 const Loop *LI = this->LI[I->getParent()];
1869 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1870 if (PHINode *PN = dyn_cast<PHINode>(I))
1871 if (PN->getParent() == LI->getHeader()) {
1872 // Okay, there is no closed form solution for the PHI node. Check
1873 // to see if the loop that contains it has a known iteration count.
1874 // If so, we may be able to force computation of the exit value.
1875 SCEVHandle IterationCount = getIterationCount(LI);
1876 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1877 // Okay, we know how many times the containing loop executes. If
1878 // this is a constant evolving PHI node, get the final value at
1879 // the specified iteration number.
1880 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1881 ICC->getValue()->getRawValue(),
1883 if (RV) return SCEVUnknown::get(RV);
1887 // Okay, this is a some expression that we cannot symbolically evaluate
1888 // into a SCEV. Check to see if it's possible to symbolically evaluate
1889 // the arguments into constants, and if see, try to constant propagate the
1890 // result. This is particularly useful for computing loop exit values.
1891 if (CanConstantFold(I)) {
1892 std::vector<Constant*> Operands;
1893 Operands.reserve(I->getNumOperands());
1894 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1895 Value *Op = I->getOperand(i);
1896 if (Constant *C = dyn_cast<Constant>(Op)) {
1897 Operands.push_back(C);
1899 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1900 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1901 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1903 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1904 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1905 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1913 return SCEVUnknown::get(ConstantFold(I, Operands));
1917 // This is some other type of SCEVUnknown, just return it.
1921 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1922 // Avoid performing the look-up in the common case where the specified
1923 // expression has no loop-variant portions.
1924 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1925 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1926 if (OpAtScope != Comm->getOperand(i)) {
1927 if (OpAtScope == UnknownValue) return UnknownValue;
1928 // Okay, at least one of these operands is loop variant but might be
1929 // foldable. Build a new instance of the folded commutative expression.
1930 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1931 NewOps.push_back(OpAtScope);
1933 for (++i; i != e; ++i) {
1934 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1935 if (OpAtScope == UnknownValue) return UnknownValue;
1936 NewOps.push_back(OpAtScope);
1938 if (isa<SCEVAddExpr>(Comm))
1939 return SCEVAddExpr::get(NewOps);
1940 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1941 return SCEVMulExpr::get(NewOps);
1944 // If we got here, all operands are loop invariant.
1948 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1949 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1950 if (LHS == UnknownValue) return LHS;
1951 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1952 if (RHS == UnknownValue) return RHS;
1953 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1954 return UDiv; // must be loop invariant
1955 return SCEVUDivExpr::get(LHS, RHS);
1958 // If this is a loop recurrence for a loop that does not contain L, then we
1959 // are dealing with the final value computed by the loop.
1960 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1961 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1962 // To evaluate this recurrence, we need to know how many times the AddRec
1963 // loop iterates. Compute this now.
1964 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1965 if (IterationCount == UnknownValue) return UnknownValue;
1966 IterationCount = getTruncateOrZeroExtend(IterationCount,
1969 // If the value is affine, simplify the expression evaluation to just
1970 // Start + Step*IterationCount.
1971 if (AddRec->isAffine())
1972 return SCEVAddExpr::get(AddRec->getStart(),
1973 SCEVMulExpr::get(IterationCount,
1974 AddRec->getOperand(1)));
1976 // Otherwise, evaluate it the hard way.
1977 return AddRec->evaluateAtIteration(IterationCount);
1979 return UnknownValue;
1982 //assert(0 && "Unknown SCEV type!");
1983 return UnknownValue;
1987 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1988 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1989 /// might be the same) or two SCEVCouldNotCompute objects.
1991 static std::pair<SCEVHandle,SCEVHandle>
1992 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1993 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1994 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1995 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1996 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1998 // We currently can only solve this if the coefficients are constants.
1999 if (!L || !M || !N) {
2000 SCEV *CNC = new SCEVCouldNotCompute();
2001 return std::make_pair(CNC, CNC);
2004 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2006 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2007 Constant *C = L->getValue();
2008 // The B coefficient is M-N/2
2009 Constant *B = ConstantExpr::getSub(M->getValue(),
2010 ConstantExpr::getDiv(N->getValue(),
2012 // The A coefficient is N/2
2013 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2015 // Compute the B^2-4ac term.
2016 Constant *SqrtTerm =
2017 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2018 ConstantExpr::getMul(A, C));
2019 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2021 // Compute floor(sqrt(B^2-4ac))
2022 ConstantUInt *SqrtVal =
2023 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2024 SqrtTerm->getType()->getUnsignedVersion()));
2025 uint64_t SqrtValV = SqrtVal->getValue();
2026 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2027 // The square root might not be precise for arbitrary 64-bit integer
2028 // values. Do some sanity checks to ensure it's correct.
2029 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2030 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2031 SCEV *CNC = new SCEVCouldNotCompute();
2032 return std::make_pair(CNC, CNC);
2035 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2036 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2038 Constant *NegB = ConstantExpr::getNeg(B);
2039 Constant *TwoA = ConstantExpr::getMul(A, Two);
2041 // The divisions must be performed as signed divisions.
2042 const Type *SignedTy = NegB->getType()->getSignedVersion();
2043 NegB = ConstantExpr::getCast(NegB, SignedTy);
2044 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2045 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2047 Constant *Solution1 =
2048 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2049 Constant *Solution2 =
2050 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2051 return std::make_pair(SCEVUnknown::get(Solution1),
2052 SCEVUnknown::get(Solution2));
2055 /// HowFarToZero - Return the number of times a backedge comparing the specified
2056 /// value to zero will execute. If not computable, return UnknownValue
2057 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2058 // If the value is a constant
2059 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2060 // If the value is already zero, the branch will execute zero times.
2061 if (C->getValue()->isNullValue()) return C;
2062 return UnknownValue; // Otherwise it will loop infinitely.
2065 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2066 if (!AddRec || AddRec->getLoop() != L)
2067 return UnknownValue;
2069 if (AddRec->isAffine()) {
2070 // If this is an affine expression the execution count of this branch is
2073 // (0 - Start/Step) iff Start % Step == 0
2075 // Get the initial value for the loop.
2076 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2077 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2078 SCEVHandle Step = AddRec->getOperand(1);
2080 Step = getSCEVAtScope(Step, L->getParentLoop());
2082 // Figure out if Start % Step == 0.
2083 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2084 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2085 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2086 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
2087 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2088 return Start; // 0 - Start/-1 == Start
2090 // Check to see if Start is divisible by SC with no remainder.
2091 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2092 ConstantInt *StartCC = StartC->getValue();
2093 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2094 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2095 if (Rem->isNullValue()) {
2096 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2097 return SCEVUnknown::get(Result);
2101 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2102 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2103 // the quadratic equation to solve it.
2104 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2105 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2106 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2109 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2110 << " sol#2: " << *R2 << "\n";
2112 // Pick the smallest positive root value.
2113 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2114 if (ConstantBool *CB =
2115 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2117 if (CB != ConstantBool::True)
2118 std::swap(R1, R2); // R1 is the minimum root now.
2120 // We can only use this value if the chrec ends up with an exact zero
2121 // value at this index. When solving for "X*X != 5", for example, we
2122 // should not accept a root of 2.
2123 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2124 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2125 if (EvalVal->getValue()->isNullValue())
2126 return R1; // We found a quadratic root!
2131 return UnknownValue;
2134 /// HowFarToNonZero - Return the number of times a backedge checking the
2135 /// specified value for nonzero will execute. If not computable, return
2137 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2138 // Loops that look like: while (X == 0) are very strange indeed. We don't
2139 // handle them yet except for the trivial case. This could be expanded in the
2140 // future as needed.
2142 // If the value is a constant, check to see if it is known to be non-zero
2143 // already. If so, the backedge will execute zero times.
2144 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2145 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2146 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2147 if (NonZero == ConstantBool::True)
2148 return getSCEV(Zero);
2149 return UnknownValue; // Otherwise it will loop infinitely.
2152 // We could implement others, but I really doubt anyone writes loops like
2153 // this, and if they did, they would already be constant folded.
2154 return UnknownValue;
2157 /// getNumIterationsInRange - Return the number of iterations of this loop that
2158 /// produce values in the specified constant range. Another way of looking at
2159 /// this is that it returns the first iteration number where the value is not in
2160 /// the condition, thus computing the exit count. If the iteration count can't
2161 /// be computed, an instance of SCEVCouldNotCompute is returned.
2162 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2163 if (Range.isFullSet()) // Infinite loop.
2164 return new SCEVCouldNotCompute();
2166 // If the start is a non-zero constant, shift the range to simplify things.
2167 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2168 if (!SC->getValue()->isNullValue()) {
2169 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2170 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2171 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2172 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2173 return ShiftedAddRec->getNumIterationsInRange(
2174 Range.subtract(SC->getValue()));
2175 // This is strange and shouldn't happen.
2176 return new SCEVCouldNotCompute();
2179 // The only time we can solve this is when we have all constant indices.
2180 // Otherwise, we cannot determine the overflow conditions.
2181 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2182 if (!isa<SCEVConstant>(getOperand(i)))
2183 return new SCEVCouldNotCompute();
2186 // Okay at this point we know that all elements of the chrec are constants and
2187 // that the start element is zero.
2189 // First check to see if the range contains zero. If not, the first
2191 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2192 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2195 // If this is an affine expression then we have this situation:
2196 // Solve {0,+,A} in Range === Ax in Range
2198 // Since we know that zero is in the range, we know that the upper value of
2199 // the range must be the first possible exit value. Also note that we
2200 // already checked for a full range.
2201 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2202 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2203 ConstantInt *One = ConstantInt::get(getType(), 1);
2205 // The exit value should be (Upper+A-1)/A.
2206 Constant *ExitValue = Upper;
2208 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2209 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2211 assert(isa<ConstantInt>(ExitValue) &&
2212 "Constant folding of integers not implemented?");
2214 // Evaluate at the exit value. If we really did fall out of the valid
2215 // range, then we computed our trip count, otherwise wrap around or other
2216 // things must have happened.
2217 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2218 if (Range.contains(Val))
2219 return new SCEVCouldNotCompute(); // Something strange happened
2221 // Ensure that the previous value is in the range. This is a sanity check.
2222 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2223 ConstantExpr::getSub(ExitValue, One))) &&
2224 "Linear scev computation is off in a bad way!");
2225 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2226 } else if (isQuadratic()) {
2227 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2228 // quadratic equation to solve it. To do this, we must frame our problem in
2229 // terms of figuring out when zero is crossed, instead of when
2230 // Range.getUpper() is crossed.
2231 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2232 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2233 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2235 // Next, solve the constructed addrec
2236 std::pair<SCEVHandle,SCEVHandle> Roots =
2237 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2238 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2239 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2241 // Pick the smallest positive root value.
2242 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2243 if (ConstantBool *CB =
2244 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2246 if (CB != ConstantBool::True)
2247 std::swap(R1, R2); // R1 is the minimum root now.
2249 // Make sure the root is not off by one. The returned iteration should
2250 // not be in the range, but the previous one should be. When solving
2251 // for "X*X < 5", for example, we should not return a root of 2.
2252 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2254 if (Range.contains(R1Val)) {
2255 // The next iteration must be out of the range...
2257 ConstantExpr::getAdd(R1->getValue(),
2258 ConstantInt::get(R1->getType(), 1));
2260 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2261 if (!Range.contains(R1Val))
2262 return SCEVUnknown::get(NextVal);
2263 return new SCEVCouldNotCompute(); // Something strange happened
2266 // If R1 was not in the range, then it is a good return value. Make
2267 // sure that R1-1 WAS in the range though, just in case.
2269 ConstantExpr::getSub(R1->getValue(),
2270 ConstantInt::get(R1->getType(), 1));
2271 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2272 if (Range.contains(R1Val))
2274 return new SCEVCouldNotCompute(); // Something strange happened
2279 // Fallback, if this is a general polynomial, figure out the progression
2280 // through brute force: evaluate until we find an iteration that fails the
2281 // test. This is likely to be slow, but getting an accurate trip count is
2282 // incredibly important, we will be able to simplify the exit test a lot, and
2283 // we are almost guaranteed to get a trip count in this case.
2284 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2285 ConstantInt *One = ConstantInt::get(getType(), 1);
2286 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2288 ++NumBruteForceEvaluations;
2289 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2290 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2291 return new SCEVCouldNotCompute();
2293 // Check to see if we found the value!
2294 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2295 return SCEVConstant::get(TestVal);
2297 // Increment to test the next index.
2298 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2299 } while (TestVal != EndVal);
2301 return new SCEVCouldNotCompute();
2306 //===----------------------------------------------------------------------===//
2307 // ScalarEvolution Class Implementation
2308 //===----------------------------------------------------------------------===//
2310 bool ScalarEvolution::runOnFunction(Function &F) {
2311 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2315 void ScalarEvolution::releaseMemory() {
2316 delete (ScalarEvolutionsImpl*)Impl;
2320 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2321 AU.setPreservesAll();
2322 AU.addRequiredID(LoopSimplifyID);
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);