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 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
86 STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
105 RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis");
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
118 void SCEV::dump() const {
122 /// getValueRange - Return the tightest constant bounds that this value is
123 /// known to have. This method is only valid on integer SCEV objects.
124 ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127 // Default to a full range if no better information is available.
128 return ConstantRange(getBitWidth());
131 uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
138 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
140 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
155 SCEVHandle SCEVCouldNotCompute::
156 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc) const {
161 void SCEVCouldNotCompute::print(std::ostream &OS) const {
162 OS << "***COULDNOTCOMPUTE***";
165 bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
170 // SCEVConstants - Only allow the creation of one SCEVConstant for any
171 // particular value. Don't use a SCEVHandle here, or else the object will
173 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
176 SCEVConstant::~SCEVConstant() {
177 SCEVConstants->erase(V);
180 SCEVHandle SCEVConstant::get(ConstantInt *V) {
181 SCEVConstant *&R = (*SCEVConstants)[V];
182 if (R == 0) R = new SCEVConstant(V);
186 ConstantRange SCEVConstant::getValueRange() const {
187 return ConstantRange(V->getValue());
190 const Type *SCEVConstant::getType() const { return V->getType(); }
192 void SCEVConstant::print(std::ostream &OS) const {
193 WriteAsOperand(OS, V, false);
196 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
197 // particular input. Don't use a SCEVHandle here, or else the object will
199 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
200 SCEVTruncateExpr*> > SCEVTruncates;
202 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
203 : SCEV(scTruncate), Op(op), Ty(ty) {
204 assert(Op->getType()->isInteger() && Ty->isInteger() &&
205 "Cannot truncate non-integer value!");
206 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
207 && "This is not a truncating conversion!");
210 SCEVTruncateExpr::~SCEVTruncateExpr() {
211 SCEVTruncates->erase(std::make_pair(Op, Ty));
214 ConstantRange SCEVTruncateExpr::getValueRange() const {
215 return getOperand()->getValueRange().truncate(getBitWidth());
218 void SCEVTruncateExpr::print(std::ostream &OS) const {
219 OS << "(truncate " << *Op << " to " << *Ty << ")";
222 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223 // particular input. Don't use a SCEVHandle here, or else the object will never
225 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
229 : SCEV(scZeroExtend), Op(op), Ty(ty) {
230 assert(Op->getType()->isInteger() && Ty->isInteger() &&
231 "Cannot zero extend non-integer value!");
232 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
233 && "This is not an extending conversion!");
236 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
237 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
241 return getOperand()->getValueRange().zeroExtend(getBitWidth());
244 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
245 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
248 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
249 // particular input. Don't use a SCEVHandle here, or else the object will never
251 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
252 SCEVCommutativeExpr*> > SCEVCommExprs;
254 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
255 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
256 std::vector<SCEV*>(Operands.begin(),
260 void SCEVCommutativeExpr::print(std::ostream &OS) const {
261 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
262 const char *OpStr = getOperationStr();
263 OS << "(" << *Operands[0];
264 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
265 OS << OpStr << *Operands[i];
269 SCEVHandle SCEVCommutativeExpr::
270 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
271 const SCEVHandle &Conc) const {
272 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
273 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
274 if (H != getOperand(i)) {
275 std::vector<SCEVHandle> NewOps;
276 NewOps.reserve(getNumOperands());
277 for (unsigned j = 0; j != i; ++j)
278 NewOps.push_back(getOperand(j));
280 for (++i; i != e; ++i)
281 NewOps.push_back(getOperand(i)->
282 replaceSymbolicValuesWithConcrete(Sym, Conc));
284 if (isa<SCEVAddExpr>(this))
285 return SCEVAddExpr::get(NewOps);
286 else if (isa<SCEVMulExpr>(this))
287 return SCEVMulExpr::get(NewOps);
289 assert(0 && "Unknown commutative expr!");
296 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
297 // input. Don't use a SCEVHandle here, or else the object will never be
299 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
300 SCEVSDivExpr*> > SCEVSDivs;
302 SCEVSDivExpr::~SCEVSDivExpr() {
303 SCEVSDivs->erase(std::make_pair(LHS, RHS));
306 void SCEVSDivExpr::print(std::ostream &OS) const {
307 OS << "(" << *LHS << " /s " << *RHS << ")";
310 const Type *SCEVSDivExpr::getType() const {
311 return LHS->getType();
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 ManagedStatic<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
350 // contain L and if the start is invariant.
351 return !QueryLoop->contains(L->getHeader()) &&
352 getOperand(0)->isLoopInvariant(QueryLoop);
356 void SCEVAddRecExpr::print(std::ostream &OS) const {
357 OS << "{" << *Operands[0];
358 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
359 OS << ",+," << *Operands[i];
360 OS << "}<" << L->getHeader()->getName() + ">";
363 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
364 // value. Don't use a SCEVHandle here, or else the object will never be
366 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
368 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
370 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
371 // All non-instruction values are loop invariant. All instructions are loop
372 // invariant if they are not contained in the specified loop.
373 if (Instruction *I = dyn_cast<Instruction>(V))
374 return !L->contains(I->getParent());
378 const Type *SCEVUnknown::getType() const {
382 void SCEVUnknown::print(std::ostream &OS) const {
383 WriteAsOperand(OS, V, false);
386 //===----------------------------------------------------------------------===//
388 //===----------------------------------------------------------------------===//
391 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
392 /// than the complexity of the RHS. This comparator is used to canonicalize
394 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
395 bool operator()(SCEV *LHS, SCEV *RHS) {
396 return LHS->getSCEVType() < RHS->getSCEVType();
401 /// GroupByComplexity - Given a list of SCEV objects, order them by their
402 /// complexity, and group objects of the same complexity together by value.
403 /// When this routine is finished, we know that any duplicates in the vector are
404 /// consecutive and that complexity is monotonically increasing.
406 /// Note that we go take special precautions to ensure that we get determinstic
407 /// results from this routine. In other words, we don't want the results of
408 /// this to depend on where the addresses of various SCEV objects happened to
411 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
412 if (Ops.size() < 2) return; // Noop
413 if (Ops.size() == 2) {
414 // This is the common case, which also happens to be trivially simple.
416 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
417 std::swap(Ops[0], Ops[1]);
421 // Do the rough sort by complexity.
422 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
424 // Now that we are sorted by complexity, group elements of the same
425 // complexity. Note that this is, at worst, N^2, but the vector is likely to
426 // be extremely short in practice. Note that we take this approach because we
427 // do not want to depend on the addresses of the objects we are grouping.
428 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
430 unsigned Complexity = S->getSCEVType();
432 // If there are any objects of the same complexity and same value as this
434 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
435 if (Ops[j] == S) { // Found a duplicate.
436 // Move it to immediately after i'th element.
437 std::swap(Ops[i+1], Ops[j]);
438 ++i; // no need to rescan it.
439 if (i == e-2) return; // Done!
447 //===----------------------------------------------------------------------===//
448 // Simple SCEV method implementations
449 //===----------------------------------------------------------------------===//
451 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
452 /// specified signed integer value and return a SCEV for the constant.
453 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
456 C = Constant::getNullValue(Ty);
457 else if (Ty->isFloatingPoint())
458 C = ConstantFP::get(Ty, Val);
460 C = ConstantInt::get(Ty, Val);
461 return SCEVUnknown::get(C);
464 SCEVHandle SCEVUnknown::getIntegerSCEV(const APInt& Val) {
465 return SCEVUnknown::get(ConstantInt::get(Val));
468 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
469 /// input value to the specified type. If the type must be extended, it is zero
471 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
472 const Type *SrcTy = V->getType();
473 assert(SrcTy->isInteger() && Ty->isInteger() &&
474 "Cannot truncate or zero extend with non-integer arguments!");
475 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
476 return V; // No conversion
477 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
478 return SCEVTruncateExpr::get(V, Ty);
479 return SCEVZeroExtendExpr::get(V, Ty);
482 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
484 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
485 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
486 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
488 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
491 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
493 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
495 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
499 /// PartialFact - Compute V!/(V-NumSteps)!
500 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
501 // Handle this case efficiently, it is common to have constant iteration
502 // counts while computing loop exit values.
503 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
504 const APInt& Val = SC->getValue()->getValue();
505 APInt Result(Val.getBitWidth(), 1);
506 for (; NumSteps; --NumSteps)
507 Result *= Val-(NumSteps-1);
508 return SCEVUnknown::get(ConstantInt::get(Result));
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 = SCEVSDivExpr::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(
555 ConstantExpr::getTrunc(SC->getValue(), Ty));
557 // If the input value is a chrec scev made out of constants, truncate
558 // all of the constants.
559 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
560 std::vector<SCEVHandle> Operands;
561 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
562 // FIXME: This should allow truncation of other expression types!
563 if (isa<SCEVConstant>(AddRec->getOperand(i)))
564 Operands.push_back(get(AddRec->getOperand(i), Ty));
567 if (Operands.size() == AddRec->getNumOperands())
568 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
571 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
572 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
576 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
577 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
578 return SCEVUnknown::get(
579 ConstantExpr::getZExt(SC->getValue(), Ty));
581 // FIXME: If the input value is a chrec scev, and we can prove that the value
582 // did not overflow the old, smaller, value, we can zero extend all of the
583 // operands (often constants). This would allow analysis of something like
584 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
586 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
587 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
591 // get - Get a canonical add expression, or something simpler if possible.
592 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
593 assert(!Ops.empty() && "Cannot get empty add!");
594 if (Ops.size() == 1) return Ops[0];
596 // Sort by complexity, this groups all similar expression types together.
597 GroupByComplexity(Ops);
599 // If there are any constants, fold them together.
601 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
603 assert(Idx < Ops.size());
604 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
605 // We found two constants, fold them together!
606 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
607 RHSC->getValue()->getValue());
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
609 Ops[0] = SCEVConstant::get(CI);
610 Ops.erase(Ops.begin()+1); // Erase the folded element
611 if (Ops.size() == 1) return Ops[0];
612 LHSC = cast<SCEVConstant>(Ops[0]);
614 // If we couldn't fold the expression, move to the next constant. Note
615 // that this is impossible to happen in practice because we always
616 // constant fold constant ints to constant ints.
621 // If we are left with a constant zero being added, strip it off.
622 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
623 Ops.erase(Ops.begin());
628 if (Ops.size() == 1) return Ops[0];
630 // Okay, check to see if the same value occurs in the operand list twice. If
631 // so, merge them together into an multiply expression. Since we sorted the
632 // list, these values are required to be adjacent.
633 const Type *Ty = Ops[0]->getType();
634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
636 // Found a match, merge the two values into a multiply, and add any
637 // remaining values to the result.
638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
644 return SCEVAddExpr::get(Ops);
647 // Okay, now we know the first non-constant operand. If there are add
648 // operands they would be next.
649 if (Idx < Ops.size()) {
650 bool DeletedAdd = false;
651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
652 // If we have an add, expand the add operands onto the end of the operands
654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
655 Ops.erase(Ops.begin()+Idx);
659 // If we deleted at least one add, we added operands to the end of the list,
660 // and they are not necessarily sorted. Recurse to resort and resimplify
661 // any operands we just aquired.
666 // Skip over the add expression until we get to a multiply.
667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
670 // If we are adding something to a multiply expression, make sure the
671 // something is not already an operand of the multiply. If so, merge it into
673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
676 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
681 if (Mul->getNumOperands() != 2) {
682 // If the multiply has more than two operands, we must get the
684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
685 MulOps.erase(MulOps.begin()+MulOp);
686 InnerMul = SCEVMulExpr::get(MulOps);
688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
691 if (Ops.size() == 2) return OuterMul;
693 Ops.erase(Ops.begin()+AddOp);
694 Ops.erase(Ops.begin()+Idx-1);
696 Ops.erase(Ops.begin()+Idx);
697 Ops.erase(Ops.begin()+AddOp-1);
699 Ops.push_back(OuterMul);
700 return SCEVAddExpr::get(Ops);
703 // Check this multiply against other multiplies being added together.
704 for (unsigned OtherMulIdx = Idx+1;
705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
708 // If MulOp occurs in OtherMul, we can fold the two multiplies
710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
711 OMulOp != e; ++OMulOp)
712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
715 if (Mul->getNumOperands() != 2) {
716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
717 MulOps.erase(MulOps.begin()+MulOp);
718 InnerMul1 = SCEVMulExpr::get(MulOps);
720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
721 if (OtherMul->getNumOperands() != 2) {
722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
724 MulOps.erase(MulOps.begin()+OMulOp);
725 InnerMul2 = SCEVMulExpr::get(MulOps);
727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
729 if (Ops.size() == 2) return OuterMul;
730 Ops.erase(Ops.begin()+Idx);
731 Ops.erase(Ops.begin()+OtherMulIdx-1);
732 Ops.push_back(OuterMul);
733 return SCEVAddExpr::get(Ops);
739 // If there are any add recurrences in the operands list, see if any other
740 // added values are loop invariant. If so, we can fold them into the
742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
745 // Scan over all recurrences, trying to fold loop invariants into them.
746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
747 // Scan all of the other operands to this add and add them to the vector if
748 // they are loop invariant w.r.t. the recurrence.
749 std::vector<SCEVHandle> LIOps;
750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
751 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
753 LIOps.push_back(Ops[i]);
754 Ops.erase(Ops.begin()+i);
758 // If we found some loop invariants, fold them into the recurrence.
759 if (!LIOps.empty()) {
760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
761 LIOps.push_back(AddRec->getStart());
763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
764 AddRecOps[0] = SCEVAddExpr::get(LIOps);
766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
767 // If all of the other operands were loop invariant, we are done.
768 if (Ops.size() == 1) return NewRec;
770 // Otherwise, add the folded AddRec by the non-liv parts.
771 for (unsigned i = 0;; ++i)
772 if (Ops[i] == AddRec) {
776 return SCEVAddExpr::get(Ops);
779 // Okay, if there weren't any loop invariants to be folded, check to see if
780 // there are multiple AddRec's with the same loop induction variable being
781 // added together. If so, we can fold them.
782 for (unsigned OtherIdx = Idx+1;
783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
784 if (OtherIdx != Idx) {
785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
790 if (i >= NewOps.size()) {
791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
792 OtherAddRec->op_end());
795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
799 if (Ops.size() == 2) return NewAddRec;
801 Ops.erase(Ops.begin()+Idx);
802 Ops.erase(Ops.begin()+OtherIdx-1);
803 Ops.push_back(NewAddRec);
804 return SCEVAddExpr::get(Ops);
808 // Otherwise couldn't fold anything into this recurrence. Move onto the
812 // Okay, it looks like we really DO need an add expr. Check to see if we
813 // already have one, otherwise create a new one.
814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
815 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
817 if (Result == 0) Result = new SCEVAddExpr(Ops);
822 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
823 assert(!Ops.empty() && "Cannot get empty mul!");
825 // Sort by complexity, this groups all similar expression types together.
826 GroupByComplexity(Ops);
828 // If there are any constants, fold them together.
830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
832 // C1*(C2+V) -> C1*C2 + C1*V
834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
835 if (Add->getNumOperands() == 2 &&
836 isa<SCEVConstant>(Add->getOperand(0)))
837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
838 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
843 // We found two constants, fold them together!
844 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
845 RHSC->getValue()->getValue());
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
847 Ops[0] = SCEVConstant::get(CI);
848 Ops.erase(Ops.begin()+1); // Erase the folded element
849 if (Ops.size() == 1) return Ops[0];
850 LHSC = cast<SCEVConstant>(Ops[0]);
852 // If we couldn't fold the expression, move to the next constant. Note
853 // that this is impossible to happen in practice because we always
854 // constant fold constant ints to constant ints.
859 // If we are left with a constant one being multiplied, strip it off.
860 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
861 Ops.erase(Ops.begin());
863 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
864 // If we have a multiply of zero, it will always be zero.
869 // Skip over the add expression until we get to a multiply.
870 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
876 // If there are mul operands inline them all into this expression.
877 if (Idx < Ops.size()) {
878 bool DeletedMul = false;
879 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
880 // If we have an mul, expand the mul operands onto the end of the operands
882 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
883 Ops.erase(Ops.begin()+Idx);
887 // If we deleted at least one mul, we added operands to the end of the list,
888 // and they are not necessarily sorted. Recurse to resort and resimplify
889 // any operands we just aquired.
894 // If there are any add recurrences in the operands list, see if any other
895 // added values are loop invariant. If so, we can fold them into the
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
900 // Scan over all recurrences, trying to fold loop invariants into them.
901 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
902 // Scan all of the other operands to this mul and add them to the vector if
903 // they are loop invariant w.r.t. the recurrence.
904 std::vector<SCEVHandle> LIOps;
905 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
906 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
907 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
908 LIOps.push_back(Ops[i]);
909 Ops.erase(Ops.begin()+i);
913 // If we found some loop invariants, fold them into the recurrence.
914 if (!LIOps.empty()) {
915 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
916 std::vector<SCEVHandle> NewOps;
917 NewOps.reserve(AddRec->getNumOperands());
918 if (LIOps.size() == 1) {
919 SCEV *Scale = LIOps[0];
920 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
921 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
923 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
924 std::vector<SCEVHandle> MulOps(LIOps);
925 MulOps.push_back(AddRec->getOperand(i));
926 NewOps.push_back(SCEVMulExpr::get(MulOps));
930 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
932 // If all of the other operands were loop invariant, we are done.
933 if (Ops.size() == 1) return NewRec;
935 // Otherwise, multiply the folded AddRec by the non-liv parts.
936 for (unsigned i = 0;; ++i)
937 if (Ops[i] == AddRec) {
941 return SCEVMulExpr::get(Ops);
944 // Okay, if there weren't any loop invariants to be folded, check to see if
945 // there are multiple AddRec's with the same loop induction variable being
946 // multiplied together. If so, we can fold them.
947 for (unsigned OtherIdx = Idx+1;
948 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
949 if (OtherIdx != Idx) {
950 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
951 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
952 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
953 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
954 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
956 SCEVHandle B = F->getStepRecurrence();
957 SCEVHandle D = G->getStepRecurrence();
958 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
959 SCEVMulExpr::get(G, B),
960 SCEVMulExpr::get(B, D));
961 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
963 if (Ops.size() == 2) return NewAddRec;
965 Ops.erase(Ops.begin()+Idx);
966 Ops.erase(Ops.begin()+OtherIdx-1);
967 Ops.push_back(NewAddRec);
968 return SCEVMulExpr::get(Ops);
972 // Otherwise couldn't fold anything into this recurrence. Move onto the
976 // Okay, it looks like we really DO need an mul expr. Check to see if we
977 // already have one, otherwise create a new one.
978 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
979 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
982 Result = new SCEVMulExpr(Ops);
986 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
987 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
988 if (RHSC->getValue()->equalsInt(1))
989 return LHS; // X sdiv 1 --> x
990 if (RHSC->getValue()->isAllOnesValue())
991 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
993 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
994 Constant *LHSCV = LHSC->getValue();
995 Constant *RHSCV = RHSC->getValue();
996 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
1000 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1002 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1003 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1008 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1009 /// specified loop. Simplify the expression as much as possible.
1010 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1011 const SCEVHandle &Step, const Loop *L) {
1012 std::vector<SCEVHandle> Operands;
1013 Operands.push_back(Start);
1014 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1015 if (StepChrec->getLoop() == L) {
1016 Operands.insert(Operands.end(), StepChrec->op_begin(),
1017 StepChrec->op_end());
1018 return get(Operands, L);
1021 Operands.push_back(Step);
1022 return get(Operands, L);
1025 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1026 /// specified loop. Simplify the expression as much as possible.
1027 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1029 if (Operands.size() == 1) return Operands[0];
1031 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1032 if (StepC->getValue()->isZero()) {
1033 Operands.pop_back();
1034 return get(Operands, L); // { X,+,0 } --> X
1037 SCEVAddRecExpr *&Result =
1038 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1040 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1044 SCEVHandle SCEVUnknown::get(Value *V) {
1045 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1046 return SCEVConstant::get(CI);
1047 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1048 if (Result == 0) Result = new SCEVUnknown(V);
1053 //===----------------------------------------------------------------------===//
1054 // ScalarEvolutionsImpl Definition and Implementation
1055 //===----------------------------------------------------------------------===//
1057 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1061 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1062 /// F - The function we are analyzing.
1066 /// LI - The loop information for the function we are currently analyzing.
1070 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1072 SCEVHandle UnknownValue;
1074 /// Scalars - This is a cache of the scalars we have analyzed so far.
1076 std::map<Value*, SCEVHandle> Scalars;
1078 /// IterationCounts - Cache the iteration count of the loops for this
1079 /// function as they are computed.
1080 std::map<const Loop*, SCEVHandle> IterationCounts;
1082 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1083 /// the PHI instructions that we attempt to compute constant evolutions for.
1084 /// This allows us to avoid potentially expensive recomputation of these
1085 /// properties. An instruction maps to null if we are unable to compute its
1087 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1090 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1091 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1093 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1094 /// expression and create a new one.
1095 SCEVHandle getSCEV(Value *V);
1097 /// hasSCEV - Return true if the SCEV for this value has already been
1099 bool hasSCEV(Value *V) const {
1100 return Scalars.count(V);
1103 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1104 /// the specified value.
1105 void setSCEV(Value *V, const SCEVHandle &H) {
1106 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1107 assert(isNew && "This entry already existed!");
1111 /// getSCEVAtScope - Compute the value of the specified expression within
1112 /// the indicated loop (which may be null to indicate in no loop). If the
1113 /// expression cannot be evaluated, return UnknownValue itself.
1114 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1117 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1118 /// an analyzable loop-invariant iteration count.
1119 bool hasLoopInvariantIterationCount(const Loop *L);
1121 /// getIterationCount - If the specified loop has a predictable iteration
1122 /// count, return it. Note that it is not valid to call this method on a
1123 /// loop without a loop-invariant iteration count.
1124 SCEVHandle getIterationCount(const Loop *L);
1126 /// deleteInstructionFromRecords - This method should be called by the
1127 /// client before it removes an instruction from the program, to make sure
1128 /// that no dangling references are left around.
1129 void deleteInstructionFromRecords(Instruction *I);
1132 /// createSCEV - We know that there is no SCEV for the specified value.
1133 /// Analyze the expression.
1134 SCEVHandle createSCEV(Value *V);
1136 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1138 SCEVHandle createNodeForPHI(PHINode *PN);
1140 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1141 /// for the specified instruction and replaces any references to the
1142 /// symbolic value SymName with the specified value. This is used during
1144 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1145 const SCEVHandle &SymName,
1146 const SCEVHandle &NewVal);
1148 /// ComputeIterationCount - Compute the number of times the specified loop
1150 SCEVHandle ComputeIterationCount(const Loop *L);
1152 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1153 /// 'setcc load X, cst', try to see if we can compute the trip count.
1154 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1157 ICmpInst::Predicate p);
1159 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1160 /// constant number of times (the condition evolves only from constants),
1161 /// try to evaluate a few iterations of the loop until we get the exit
1162 /// condition gets a value of ExitWhen (true or false). If we cannot
1163 /// evaluate the trip count of the loop, return UnknownValue.
1164 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1167 /// HowFarToZero - Return the number of times a backedge comparing the
1168 /// specified value to zero will execute. If not computable, return
1170 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1172 /// HowFarToNonZero - Return the number of times a backedge checking the
1173 /// specified value for nonzero will execute. If not computable, return
1175 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1177 /// HowManyLessThans - Return the number of times a backedge containing the
1178 /// specified less-than comparison will execute. If not computable, return
1180 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1182 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1183 /// in the header of its containing loop, we know the loop executes a
1184 /// constant number of times, and the PHI node is just a recurrence
1185 /// involving constants, fold it.
1186 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1191 //===----------------------------------------------------------------------===//
1192 // Basic SCEV Analysis and PHI Idiom Recognition Code
1195 /// deleteInstructionFromRecords - This method should be called by the
1196 /// client before it removes an instruction from the program, to make sure
1197 /// that no dangling references are left around.
1198 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1199 SmallVector<Instruction *, 16> Worklist;
1201 if (Scalars.erase(I)) {
1202 if (PHINode *PN = dyn_cast<PHINode>(I))
1203 ConstantEvolutionLoopExitValue.erase(PN);
1204 Worklist.push_back(I);
1207 while (!Worklist.empty()) {
1208 Instruction *II = Worklist.back();
1209 Worklist.pop_back();
1211 for (Instruction::use_iterator UI = II->use_begin(), UE = II->use_end();
1213 Instruction *Inst = cast<Instruction>(*UI);
1214 if (Scalars.erase(Inst)) {
1215 if (PHINode *PN = dyn_cast<PHINode>(II))
1216 ConstantEvolutionLoopExitValue.erase(PN);
1217 Worklist.push_back(Inst);
1224 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1225 /// expression and create a new one.
1226 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1227 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1229 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1230 if (I != Scalars.end()) return I->second;
1231 SCEVHandle S = createSCEV(V);
1232 Scalars.insert(std::make_pair(V, S));
1236 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1237 /// the specified instruction and replaces any references to the symbolic value
1238 /// SymName with the specified value. This is used during PHI resolution.
1239 void ScalarEvolutionsImpl::
1240 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1241 const SCEVHandle &NewVal) {
1242 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1243 if (SI == Scalars.end()) return;
1246 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1247 if (NV == SI->second) return; // No change.
1249 SI->second = NV; // Update the scalars map!
1251 // Any instruction values that use this instruction might also need to be
1253 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1255 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1258 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1259 /// a loop header, making it a potential recurrence, or it doesn't.
1261 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1262 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1263 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1264 if (L->getHeader() == PN->getParent()) {
1265 // If it lives in the loop header, it has two incoming values, one
1266 // from outside the loop, and one from inside.
1267 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1268 unsigned BackEdge = IncomingEdge^1;
1270 // While we are analyzing this PHI node, handle its value symbolically.
1271 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1272 assert(Scalars.find(PN) == Scalars.end() &&
1273 "PHI node already processed?");
1274 Scalars.insert(std::make_pair(PN, SymbolicName));
1276 // Using this symbolic name for the PHI, analyze the value coming around
1278 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1280 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1281 // has a special value for the first iteration of the loop.
1283 // If the value coming around the backedge is an add with the symbolic
1284 // value we just inserted, then we found a simple induction variable!
1285 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1286 // If there is a single occurrence of the symbolic value, replace it
1287 // with a recurrence.
1288 unsigned FoundIndex = Add->getNumOperands();
1289 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1290 if (Add->getOperand(i) == SymbolicName)
1291 if (FoundIndex == e) {
1296 if (FoundIndex != Add->getNumOperands()) {
1297 // Create an add with everything but the specified operand.
1298 std::vector<SCEVHandle> Ops;
1299 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1300 if (i != FoundIndex)
1301 Ops.push_back(Add->getOperand(i));
1302 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1304 // This is not a valid addrec if the step amount is varying each
1305 // loop iteration, but is not itself an addrec in this loop.
1306 if (Accum->isLoopInvariant(L) ||
1307 (isa<SCEVAddRecExpr>(Accum) &&
1308 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1309 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1310 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1312 // Okay, for the entire analysis of this edge we assumed the PHI
1313 // to be symbolic. We now need to go back and update all of the
1314 // entries for the scalars that use the PHI (except for the PHI
1315 // itself) to use the new analyzed value instead of the "symbolic"
1317 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1321 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1322 // Otherwise, this could be a loop like this:
1323 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1324 // In this case, j = {1,+,1} and BEValue is j.
1325 // Because the other in-value of i (0) fits the evolution of BEValue
1326 // i really is an addrec evolution.
1327 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1328 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1330 // If StartVal = j.start - j.stride, we can use StartVal as the
1331 // initial step of the addrec evolution.
1332 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1333 AddRec->getOperand(1))) {
1334 SCEVHandle PHISCEV =
1335 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1337 // Okay, for the entire analysis of this edge we assumed the PHI
1338 // to be symbolic. We now need to go back and update all of the
1339 // entries for the scalars that use the PHI (except for the PHI
1340 // itself) to use the new analyzed value instead of the "symbolic"
1342 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1348 return SymbolicName;
1351 // If it's not a loop phi, we can't handle it yet.
1352 return SCEVUnknown::get(PN);
1355 /// GetConstantFactor - Determine the largest constant factor that S has. For
1356 /// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1357 static APInt GetConstantFactor(SCEVHandle S) {
1358 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1359 const APInt& V = C->getValue()->getValue();
1360 if (!V.isMinValue())
1362 else // Zero is a multiple of everything.
1363 return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
1366 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
1367 return GetConstantFactor(T->getOperand()).trunc(
1368 cast<IntegerType>(T->getType())->getBitWidth());
1370 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1371 return GetConstantFactor(E->getOperand()).zext(
1372 cast<IntegerType>(E->getType())->getBitWidth());
1374 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1375 // The result is the min of all operands.
1376 APInt Res(GetConstantFactor(A->getOperand(0)));
1377 for (unsigned i = 1, e = A->getNumOperands();
1378 i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1379 APInt Tmp(GetConstantFactor(A->getOperand(i)));
1380 Res = APIntOps::umin(Res, Tmp);
1385 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1386 // The result is the product of all the operands.
1387 APInt Res(GetConstantFactor(M->getOperand(0)));
1388 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1389 APInt Tmp(GetConstantFactor(M->getOperand(i)));
1395 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1396 // For now, we just handle linear expressions.
1397 if (A->getNumOperands() == 2) {
1398 // We want the GCD between the start and the stride value.
1399 APInt Start(GetConstantFactor(A->getOperand(0)));
1402 APInt Stride(GetConstantFactor(A->getOperand(1)));
1403 return APIntOps::GreatestCommonDivisor(Start, Stride);
1407 // SCEVSDivExpr, SCEVUnknown.
1408 return APInt(S->getBitWidth(), 1);
1411 /// createSCEV - We know that there is no SCEV for the specified value.
1412 /// Analyze the expression.
1414 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1415 if (Instruction *I = dyn_cast<Instruction>(V)) {
1416 switch (I->getOpcode()) {
1417 case Instruction::Add:
1418 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1419 getSCEV(I->getOperand(1)));
1420 case Instruction::Mul:
1421 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1422 getSCEV(I->getOperand(1)));
1423 case Instruction::SDiv:
1424 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1425 getSCEV(I->getOperand(1)));
1428 case Instruction::Sub:
1429 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1430 getSCEV(I->getOperand(1)));
1431 case Instruction::Or:
1432 // If the RHS of the Or is a constant, we may have something like:
1433 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1434 // optimizations will transparently handle this case.
1435 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1436 SCEVHandle LHS = getSCEV(I->getOperand(0));
1437 APInt CommonFact(GetConstantFactor(LHS));
1438 assert(!CommonFact.isMinValue() &&
1439 "Common factor should at least be 1!");
1440 if (CommonFact.ugt(CI->getValue())) {
1441 // If the LHS is a multiple that is larger than the RHS, use +.
1442 return SCEVAddExpr::get(LHS,
1443 getSCEV(I->getOperand(1)));
1447 case Instruction::Xor:
1448 // If the RHS of the xor is a signbit, then this is just an add.
1449 // Instcombine turns add of signbit into xor as a strength reduction step.
1450 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1451 if (CI->getValue().isSignBit())
1452 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1453 getSCEV(I->getOperand(1)));
1457 case Instruction::Shl:
1458 // Turn shift left of a constant amount into a multiply.
1459 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1460 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1461 Constant *X = ConstantInt::get(
1462 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1463 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1467 case Instruction::Trunc:
1468 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
1470 case Instruction::ZExt:
1471 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
1473 case Instruction::BitCast:
1474 // BitCasts are no-op casts so we just eliminate the cast.
1475 if (I->getType()->isInteger() &&
1476 I->getOperand(0)->getType()->isInteger())
1477 return getSCEV(I->getOperand(0));
1480 case Instruction::PHI:
1481 return createNodeForPHI(cast<PHINode>(I));
1483 default: // We cannot analyze this expression.
1488 return SCEVUnknown::get(V);
1493 //===----------------------------------------------------------------------===//
1494 // Iteration Count Computation Code
1497 /// getIterationCount - If the specified loop has a predictable iteration
1498 /// count, return it. Note that it is not valid to call this method on a
1499 /// loop without a loop-invariant iteration count.
1500 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1501 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1502 if (I == IterationCounts.end()) {
1503 SCEVHandle ItCount = ComputeIterationCount(L);
1504 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1505 if (ItCount != UnknownValue) {
1506 assert(ItCount->isLoopInvariant(L) &&
1507 "Computed trip count isn't loop invariant for loop!");
1508 ++NumTripCountsComputed;
1509 } else if (isa<PHINode>(L->getHeader()->begin())) {
1510 // Only count loops that have phi nodes as not being computable.
1511 ++NumTripCountsNotComputed;
1517 /// ComputeIterationCount - Compute the number of times the specified loop
1519 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1520 // If the loop has a non-one exit block count, we can't analyze it.
1521 std::vector<BasicBlock*> ExitBlocks;
1522 L->getExitBlocks(ExitBlocks);
1523 if (ExitBlocks.size() != 1) return UnknownValue;
1525 // Okay, there is one exit block. Try to find the condition that causes the
1526 // loop to be exited.
1527 BasicBlock *ExitBlock = ExitBlocks[0];
1529 BasicBlock *ExitingBlock = 0;
1530 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1532 if (L->contains(*PI)) {
1533 if (ExitingBlock == 0)
1536 return UnknownValue; // More than one block exiting!
1538 assert(ExitingBlock && "No exits from loop, something is broken!");
1540 // Okay, we've computed the exiting block. See what condition causes us to
1543 // FIXME: we should be able to handle switch instructions (with a single exit)
1544 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1545 if (ExitBr == 0) return UnknownValue;
1546 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1548 // At this point, we know we have a conditional branch that determines whether
1549 // the loop is exited. However, we don't know if the branch is executed each
1550 // time through the loop. If not, then the execution count of the branch will
1551 // not be equal to the trip count of the loop.
1553 // Currently we check for this by checking to see if the Exit branch goes to
1554 // the loop header. If so, we know it will always execute the same number of
1555 // times as the loop. We also handle the case where the exit block *is* the
1556 // loop header. This is common for un-rotated loops. More extensive analysis
1557 // could be done to handle more cases here.
1558 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1559 ExitBr->getSuccessor(1) != L->getHeader() &&
1560 ExitBr->getParent() != L->getHeader())
1561 return UnknownValue;
1563 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1565 // If its not an integer comparison then compute it the hard way.
1566 // Note that ICmpInst deals with pointer comparisons too so we must check
1567 // the type of the operand.
1568 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1569 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1570 ExitBr->getSuccessor(0) == ExitBlock);
1572 // If the condition was exit on true, convert the condition to exit on false
1573 ICmpInst::Predicate Cond;
1574 if (ExitBr->getSuccessor(1) == ExitBlock)
1575 Cond = ExitCond->getPredicate();
1577 Cond = ExitCond->getInversePredicate();
1579 // Handle common loops like: for (X = "string"; *X; ++X)
1580 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1581 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1583 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1584 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1587 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1588 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1590 // Try to evaluate any dependencies out of the loop.
1591 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1592 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1593 Tmp = getSCEVAtScope(RHS, L);
1594 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1596 // At this point, we would like to compute how many iterations of the
1597 // loop the predicate will return true for these inputs.
1598 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1599 // If there is a constant, force it into the RHS.
1600 std::swap(LHS, RHS);
1601 Cond = ICmpInst::getSwappedPredicate(Cond);
1604 // FIXME: think about handling pointer comparisons! i.e.:
1605 // while (P != P+100) ++P;
1607 // If we have a comparison of a chrec against a constant, try to use value
1608 // ranges to answer this query.
1609 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1610 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1611 if (AddRec->getLoop() == L) {
1612 // Form the comparison range using the constant of the correct type so
1613 // that the ConstantRange class knows to do a signed or unsigned
1615 ConstantInt *CompVal = RHSC->getValue();
1616 const Type *RealTy = ExitCond->getOperand(0)->getType();
1617 CompVal = dyn_cast<ConstantInt>(
1618 ConstantExpr::getBitCast(CompVal, RealTy));
1620 // Form the constant range.
1621 ConstantRange CompRange(
1622 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1624 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange,
1625 false /*Always treat as unsigned range*/);
1626 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1631 case ICmpInst::ICMP_NE: { // while (X != Y)
1632 // Convert to: while (X-Y != 0)
1633 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1634 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1637 case ICmpInst::ICMP_EQ: {
1638 // Convert to: while (X-Y == 0) // while (X == Y)
1639 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1640 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1643 case ICmpInst::ICMP_SLT: {
1644 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1645 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1648 case ICmpInst::ICMP_SGT: {
1649 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1650 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1655 cerr << "ComputeIterationCount ";
1656 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1657 cerr << "[unsigned] ";
1659 << Instruction::getOpcodeName(Instruction::ICmp)
1660 << " " << *RHS << "\n";
1664 return ComputeIterationCountExhaustively(L, ExitCond,
1665 ExitBr->getSuccessor(0) == ExitBlock);
1668 static ConstantInt *
1669 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1670 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1671 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1672 assert(isa<SCEVConstant>(Val) &&
1673 "Evaluation of SCEV at constant didn't fold correctly?");
1674 return cast<SCEVConstant>(Val)->getValue();
1677 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1678 /// and a GEP expression (missing the pointer index) indexing into it, return
1679 /// the addressed element of the initializer or null if the index expression is
1682 GetAddressedElementFromGlobal(GlobalVariable *GV,
1683 const std::vector<ConstantInt*> &Indices) {
1684 Constant *Init = GV->getInitializer();
1685 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1686 uint64_t Idx = Indices[i]->getZExtValue();
1687 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1688 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1689 Init = cast<Constant>(CS->getOperand(Idx));
1690 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1691 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1692 Init = cast<Constant>(CA->getOperand(Idx));
1693 } else if (isa<ConstantAggregateZero>(Init)) {
1694 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1695 assert(Idx < STy->getNumElements() && "Bad struct index!");
1696 Init = Constant::getNullValue(STy->getElementType(Idx));
1697 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1698 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1699 Init = Constant::getNullValue(ATy->getElementType());
1701 assert(0 && "Unknown constant aggregate type!");
1705 return 0; // Unknown initializer type
1711 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1712 /// 'setcc load X, cst', try to se if we can compute the trip count.
1713 SCEVHandle ScalarEvolutionsImpl::
1714 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1716 ICmpInst::Predicate predicate) {
1717 if (LI->isVolatile()) return UnknownValue;
1719 // Check to see if the loaded pointer is a getelementptr of a global.
1720 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1721 if (!GEP) return UnknownValue;
1723 // Make sure that it is really a constant global we are gepping, with an
1724 // initializer, and make sure the first IDX is really 0.
1725 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1726 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1727 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1728 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1729 return UnknownValue;
1731 // Okay, we allow one non-constant index into the GEP instruction.
1733 std::vector<ConstantInt*> Indexes;
1734 unsigned VarIdxNum = 0;
1735 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1736 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1737 Indexes.push_back(CI);
1738 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1739 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1740 VarIdx = GEP->getOperand(i);
1742 Indexes.push_back(0);
1745 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1746 // Check to see if X is a loop variant variable value now.
1747 SCEVHandle Idx = getSCEV(VarIdx);
1748 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1749 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1751 // We can only recognize very limited forms of loop index expressions, in
1752 // particular, only affine AddRec's like {C1,+,C2}.
1753 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1754 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1755 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1756 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1757 return UnknownValue;
1759 unsigned MaxSteps = MaxBruteForceIterations;
1760 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1761 ConstantInt *ItCst =
1762 ConstantInt::get(IdxExpr->getType(), IterationNum);
1763 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1765 // Form the GEP offset.
1766 Indexes[VarIdxNum] = Val;
1768 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1769 if (Result == 0) break; // Cannot compute!
1771 // Evaluate the condition for this iteration.
1772 Result = ConstantExpr::getICmp(predicate, Result, RHS);
1773 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
1774 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
1776 cerr << "\n***\n*** Computed loop count " << *ItCst
1777 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1780 ++NumArrayLenItCounts;
1781 return SCEVConstant::get(ItCst); // Found terminating iteration!
1784 return UnknownValue;
1788 /// CanConstantFold - Return true if we can constant fold an instruction of the
1789 /// specified type, assuming that all operands were constants.
1790 static bool CanConstantFold(const Instruction *I) {
1791 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1792 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1795 if (const CallInst *CI = dyn_cast<CallInst>(I))
1796 if (const Function *F = CI->getCalledFunction())
1797 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1801 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1802 /// in the loop that V is derived from. We allow arbitrary operations along the
1803 /// way, but the operands of an operation must either be constants or a value
1804 /// derived from a constant PHI. If this expression does not fit with these
1805 /// constraints, return null.
1806 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1807 // If this is not an instruction, or if this is an instruction outside of the
1808 // loop, it can't be derived from a loop PHI.
1809 Instruction *I = dyn_cast<Instruction>(V);
1810 if (I == 0 || !L->contains(I->getParent())) return 0;
1812 if (PHINode *PN = dyn_cast<PHINode>(I))
1813 if (L->getHeader() == I->getParent())
1816 // We don't currently keep track of the control flow needed to evaluate
1817 // PHIs, so we cannot handle PHIs inside of loops.
1820 // If we won't be able to constant fold this expression even if the operands
1821 // are constants, return early.
1822 if (!CanConstantFold(I)) return 0;
1824 // Otherwise, we can evaluate this instruction if all of its operands are
1825 // constant or derived from a PHI node themselves.
1827 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1828 if (!(isa<Constant>(I->getOperand(Op)) ||
1829 isa<GlobalValue>(I->getOperand(Op)))) {
1830 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1831 if (P == 0) return 0; // Not evolving from PHI
1835 return 0; // Evolving from multiple different PHIs.
1838 // This is a expression evolving from a constant PHI!
1842 /// EvaluateExpression - Given an expression that passes the
1843 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1844 /// in the loop has the value PHIVal. If we can't fold this expression for some
1845 /// reason, return null.
1846 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1847 if (isa<PHINode>(V)) return PHIVal;
1848 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1850 if (Constant *C = dyn_cast<Constant>(V)) return C;
1851 Instruction *I = cast<Instruction>(V);
1853 std::vector<Constant*> Operands;
1854 Operands.resize(I->getNumOperands());
1856 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1857 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1858 if (Operands[i] == 0) return 0;
1861 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
1864 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1865 /// in the header of its containing loop, we know the loop executes a
1866 /// constant number of times, and the PHI node is just a recurrence
1867 /// involving constants, fold it.
1868 Constant *ScalarEvolutionsImpl::
1869 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
1870 std::map<PHINode*, Constant*>::iterator I =
1871 ConstantEvolutionLoopExitValue.find(PN);
1872 if (I != ConstantEvolutionLoopExitValue.end())
1875 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
1876 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1878 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1880 // Since the loop is canonicalized, the PHI node must have two entries. One
1881 // entry must be a constant (coming in from outside of the loop), and the
1882 // second must be derived from the same PHI.
1883 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1884 Constant *StartCST =
1885 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1887 return RetVal = 0; // Must be a constant.
1889 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1890 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1892 return RetVal = 0; // Not derived from same PHI.
1894 // Execute the loop symbolically to determine the exit value.
1895 if (Its.getActiveBits() >= 32)
1896 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
1898 unsigned NumIterations = Its.getZExtValue(); // must be in range
1899 unsigned IterationNum = 0;
1900 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1901 if (IterationNum == NumIterations)
1902 return RetVal = PHIVal; // Got exit value!
1904 // Compute the value of the PHI node for the next iteration.
1905 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1906 if (NextPHI == PHIVal)
1907 return RetVal = NextPHI; // Stopped evolving!
1909 return 0; // Couldn't evaluate!
1914 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1915 /// constant number of times (the condition evolves only from constants),
1916 /// try to evaluate a few iterations of the loop until we get the exit
1917 /// condition gets a value of ExitWhen (true or false). If we cannot
1918 /// evaluate the trip count of the loop, return UnknownValue.
1919 SCEVHandle ScalarEvolutionsImpl::
1920 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1921 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1922 if (PN == 0) return UnknownValue;
1924 // Since the loop is canonicalized, the PHI node must have two entries. One
1925 // entry must be a constant (coming in from outside of the loop), and the
1926 // second must be derived from the same PHI.
1927 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1928 Constant *StartCST =
1929 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1930 if (StartCST == 0) return UnknownValue; // Must be a constant.
1932 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1933 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1934 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1936 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1937 // the loop symbolically to determine when the condition gets a value of
1939 unsigned IterationNum = 0;
1940 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1941 for (Constant *PHIVal = StartCST;
1942 IterationNum != MaxIterations; ++IterationNum) {
1943 ConstantInt *CondVal =
1944 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
1946 // Couldn't symbolically evaluate.
1947 if (!CondVal) return UnknownValue;
1949 if (CondVal->getValue() == uint64_t(ExitWhen)) {
1950 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1951 ++NumBruteForceTripCountsComputed;
1952 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
1955 // Compute the value of the PHI node for the next iteration.
1956 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1957 if (NextPHI == 0 || NextPHI == PHIVal)
1958 return UnknownValue; // Couldn't evaluate or not making progress...
1962 // Too many iterations were needed to evaluate.
1963 return UnknownValue;
1966 /// getSCEVAtScope - Compute the value of the specified expression within the
1967 /// indicated loop (which may be null to indicate in no loop). If the
1968 /// expression cannot be evaluated, return UnknownValue.
1969 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1970 // FIXME: this should be turned into a virtual method on SCEV!
1972 if (isa<SCEVConstant>(V)) return V;
1974 // If this instruction is evolves from a constant-evolving PHI, compute the
1975 // exit value from the loop without using SCEVs.
1976 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1977 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1978 const Loop *LI = this->LI[I->getParent()];
1979 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1980 if (PHINode *PN = dyn_cast<PHINode>(I))
1981 if (PN->getParent() == LI->getHeader()) {
1982 // Okay, there is no closed form solution for the PHI node. Check
1983 // to see if the loop that contains it has a known iteration count.
1984 // If so, we may be able to force computation of the exit value.
1985 SCEVHandle IterationCount = getIterationCount(LI);
1986 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1987 // Okay, we know how many times the containing loop executes. If
1988 // this is a constant evolving PHI node, get the final value at
1989 // the specified iteration number.
1990 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1991 ICC->getValue()->getValue(),
1993 if (RV) return SCEVUnknown::get(RV);
1997 // Okay, this is an expression that we cannot symbolically evaluate
1998 // into a SCEV. Check to see if it's possible to symbolically evaluate
1999 // the arguments into constants, and if so, try to constant propagate the
2000 // result. This is particularly useful for computing loop exit values.
2001 if (CanConstantFold(I)) {
2002 std::vector<Constant*> Operands;
2003 Operands.reserve(I->getNumOperands());
2004 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2005 Value *Op = I->getOperand(i);
2006 if (Constant *C = dyn_cast<Constant>(Op)) {
2007 Operands.push_back(C);
2009 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2010 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2011 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2014 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2015 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2016 Operands.push_back(ConstantExpr::getIntegerCast(C,
2026 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
2027 return SCEVUnknown::get(C);
2031 // This is some other type of SCEVUnknown, just return it.
2035 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2036 // Avoid performing the look-up in the common case where the specified
2037 // expression has no loop-variant portions.
2038 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2039 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2040 if (OpAtScope != Comm->getOperand(i)) {
2041 if (OpAtScope == UnknownValue) return UnknownValue;
2042 // Okay, at least one of these operands is loop variant but might be
2043 // foldable. Build a new instance of the folded commutative expression.
2044 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2045 NewOps.push_back(OpAtScope);
2047 for (++i; i != e; ++i) {
2048 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2049 if (OpAtScope == UnknownValue) return UnknownValue;
2050 NewOps.push_back(OpAtScope);
2052 if (isa<SCEVAddExpr>(Comm))
2053 return SCEVAddExpr::get(NewOps);
2054 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2055 return SCEVMulExpr::get(NewOps);
2058 // If we got here, all operands are loop invariant.
2062 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2063 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2064 if (LHS == UnknownValue) return LHS;
2065 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2066 if (RHS == UnknownValue) return RHS;
2067 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2068 return Div; // must be loop invariant
2069 return SCEVSDivExpr::get(LHS, RHS);
2072 // If this is a loop recurrence for a loop that does not contain L, then we
2073 // are dealing with the final value computed by the loop.
2074 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2075 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2076 // To evaluate this recurrence, we need to know how many times the AddRec
2077 // loop iterates. Compute this now.
2078 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2079 if (IterationCount == UnknownValue) return UnknownValue;
2080 IterationCount = getTruncateOrZeroExtend(IterationCount,
2083 // If the value is affine, simplify the expression evaluation to just
2084 // Start + Step*IterationCount.
2085 if (AddRec->isAffine())
2086 return SCEVAddExpr::get(AddRec->getStart(),
2087 SCEVMulExpr::get(IterationCount,
2088 AddRec->getOperand(1)));
2090 // Otherwise, evaluate it the hard way.
2091 return AddRec->evaluateAtIteration(IterationCount);
2093 return UnknownValue;
2096 //assert(0 && "Unknown SCEV type!");
2097 return UnknownValue;
2101 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2102 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2103 /// might be the same) or two SCEVCouldNotCompute objects.
2105 static std::pair<SCEVHandle,SCEVHandle>
2106 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2107 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2108 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2109 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2110 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2112 // We currently can only solve this if the coefficients are constants.
2113 if (!LC || !MC || !NC) {
2114 SCEV *CNC = new SCEVCouldNotCompute();
2115 return std::make_pair(CNC, CNC);
2118 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2119 const APInt &L = LC->getValue()->getValue();
2120 const APInt &M = MC->getValue()->getValue();
2121 const APInt &N = NC->getValue()->getValue();
2122 APInt Two(BitWidth, 2);
2123 APInt Four(BitWidth, 4);
2126 using namespace APIntOps;
2128 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2129 // The B coefficient is M-N/2
2133 // The A coefficient is N/2
2134 APInt A(N.sdiv(Two));
2136 // Compute the B^2-4ac term.
2139 SqrtTerm -= Four * (A * C);
2141 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2142 // integer value or else APInt::sqrt() will assert.
2143 APInt SqrtVal(SqrtTerm.sqrt());
2145 // Compute the two solutions for the quadratic formula.
2146 // The divisions must be performed as signed divisions.
2148 APInt TwoA( A << 1 );
2149 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2150 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2152 return std::make_pair(SCEVUnknown::get(Solution1),
2153 SCEVUnknown::get(Solution2));
2154 } // end APIntOps namespace
2157 /// HowFarToZero - Return the number of times a backedge comparing the specified
2158 /// value to zero will execute. If not computable, return UnknownValue
2159 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2160 // If the value is a constant
2161 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2162 // If the value is already zero, the branch will execute zero times.
2163 if (C->getValue()->isZero()) return C;
2164 return UnknownValue; // Otherwise it will loop infinitely.
2167 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2168 if (!AddRec || AddRec->getLoop() != L)
2169 return UnknownValue;
2171 if (AddRec->isAffine()) {
2172 // If this is an affine expression the execution count of this branch is
2175 // (0 - Start/Step) iff Start % Step == 0
2177 // Get the initial value for the loop.
2178 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2179 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2180 SCEVHandle Step = AddRec->getOperand(1);
2182 Step = getSCEVAtScope(Step, L->getParentLoop());
2184 // Figure out if Start % Step == 0.
2185 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2186 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2187 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2188 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
2189 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2190 return Start; // 0 - Start/-1 == Start
2192 // Check to see if Start is divisible by SC with no remainder.
2193 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2194 ConstantInt *StartCC = StartC->getValue();
2195 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2196 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2197 if (Rem->isNullValue()) {
2198 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2199 return SCEVUnknown::get(Result);
2203 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2204 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2205 // the quadratic equation to solve it.
2206 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2207 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2208 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2211 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2212 << " sol#2: " << *R2 << "\n";
2214 // Pick the smallest positive root value.
2215 if (ConstantInt *CB =
2216 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2217 R1->getValue(), R2->getValue()))) {
2218 if (CB->getZExtValue() == false)
2219 std::swap(R1, R2); // R1 is the minimum root now.
2221 // We can only use this value if the chrec ends up with an exact zero
2222 // value at this index. When solving for "X*X != 5", for example, we
2223 // should not accept a root of 2.
2224 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2225 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2226 if (EvalVal->getValue()->isZero())
2227 return R1; // We found a quadratic root!
2232 return UnknownValue;
2235 /// HowFarToNonZero - Return the number of times a backedge checking the
2236 /// specified value for nonzero will execute. If not computable, return
2238 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2239 // Loops that look like: while (X == 0) are very strange indeed. We don't
2240 // handle them yet except for the trivial case. This could be expanded in the
2241 // future as needed.
2243 // If the value is a constant, check to see if it is known to be non-zero
2244 // already. If so, the backedge will execute zero times.
2245 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2246 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2248 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2249 if (NonZero == ConstantInt::getTrue())
2250 return getSCEV(Zero);
2251 return UnknownValue; // Otherwise it will loop infinitely.
2254 // We could implement others, but I really doubt anyone writes loops like
2255 // this, and if they did, they would already be constant folded.
2256 return UnknownValue;
2259 /// HowManyLessThans - Return the number of times a backedge containing the
2260 /// specified less-than comparison will execute. If not computable, return
2262 SCEVHandle ScalarEvolutionsImpl::
2263 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2264 // Only handle: "ADDREC < LoopInvariant".
2265 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2267 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2268 if (!AddRec || AddRec->getLoop() != L)
2269 return UnknownValue;
2271 if (AddRec->isAffine()) {
2272 // FORNOW: We only support unit strides.
2273 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2274 if (AddRec->getOperand(1) != One)
2275 return UnknownValue;
2277 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2278 // know that m is >= n on input to the loop. If it is, the condition return
2279 // true zero times. What we really should return, for full generality, is
2280 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2281 // canonical loop form: most do-loops will have a check that dominates the
2282 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2283 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2285 // Search for the check.
2286 BasicBlock *Preheader = L->getLoopPreheader();
2287 BasicBlock *PreheaderDest = L->getHeader();
2288 if (Preheader == 0) return UnknownValue;
2290 BranchInst *LoopEntryPredicate =
2291 dyn_cast<BranchInst>(Preheader->getTerminator());
2292 if (!LoopEntryPredicate) return UnknownValue;
2294 // This might be a critical edge broken out. If the loop preheader ends in
2295 // an unconditional branch to the loop, check to see if the preheader has a
2296 // single predecessor, and if so, look for its terminator.
2297 while (LoopEntryPredicate->isUnconditional()) {
2298 PreheaderDest = Preheader;
2299 Preheader = Preheader->getSinglePredecessor();
2300 if (!Preheader) return UnknownValue; // Multiple preds.
2302 LoopEntryPredicate =
2303 dyn_cast<BranchInst>(Preheader->getTerminator());
2304 if (!LoopEntryPredicate) return UnknownValue;
2307 // Now that we found a conditional branch that dominates the loop, check to
2308 // see if it is the comparison we are looking for.
2309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2310 Value *PreCondLHS = ICI->getOperand(0);
2311 Value *PreCondRHS = ICI->getOperand(1);
2312 ICmpInst::Predicate Cond;
2313 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2314 Cond = ICI->getPredicate();
2316 Cond = ICI->getInversePredicate();
2319 case ICmpInst::ICMP_UGT:
2320 std::swap(PreCondLHS, PreCondRHS);
2321 Cond = ICmpInst::ICMP_ULT;
2323 case ICmpInst::ICMP_SGT:
2324 std::swap(PreCondLHS, PreCondRHS);
2325 Cond = ICmpInst::ICMP_SLT;
2330 if (Cond == ICmpInst::ICMP_SLT) {
2331 if (PreCondLHS->getType()->isInteger()) {
2332 if (RHS != getSCEV(PreCondRHS))
2333 return UnknownValue; // Not a comparison against 'm'.
2335 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2336 != getSCEV(PreCondLHS))
2337 return UnknownValue; // Not a comparison against 'n-1'.
2339 else return UnknownValue;
2340 } else if (Cond == ICmpInst::ICMP_ULT)
2341 return UnknownValue;
2343 // cerr << "Computed Loop Trip Count as: "
2344 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2345 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2348 return UnknownValue;
2351 return UnknownValue;
2354 /// getNumIterationsInRange - Return the number of iterations of this loop that
2355 /// produce values in the specified constant range. Another way of looking at
2356 /// this is that it returns the first iteration number where the value is not in
2357 /// the condition, thus computing the exit count. If the iteration count can't
2358 /// be computed, an instance of SCEVCouldNotCompute is returned.
2359 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2360 bool isSigned) const {
2361 if (Range.isFullSet()) // Infinite loop.
2362 return new SCEVCouldNotCompute();
2364 // If the start is a non-zero constant, shift the range to simplify things.
2365 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2366 if (!SC->getValue()->isZero()) {
2367 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2368 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2369 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2370 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2371 return ShiftedAddRec->getNumIterationsInRange(
2372 Range.subtract(SC->getValue()->getValue()),isSigned);
2373 // This is strange and shouldn't happen.
2374 return new SCEVCouldNotCompute();
2377 // The only time we can solve this is when we have all constant indices.
2378 // Otherwise, we cannot determine the overflow conditions.
2379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2380 if (!isa<SCEVConstant>(getOperand(i)))
2381 return new SCEVCouldNotCompute();
2384 // Okay at this point we know that all elements of the chrec are constants and
2385 // that the start element is zero.
2387 // First check to see if the range contains zero. If not, the first
2389 if (!Range.contains(APInt(getBitWidth(),0)))
2390 return SCEVConstant::get(ConstantInt::get(getType(),0));
2393 // If this is an affine expression then we have this situation:
2394 // Solve {0,+,A} in Range === Ax in Range
2396 // Since we know that zero is in the range, we know that the upper value of
2397 // the range must be the first possible exit value. Also note that we
2398 // already checked for a full range.
2399 const APInt &Upper = Range.getUpper();
2400 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2401 APInt One(getBitWidth(),1);
2403 // The exit value should be (Upper+A-1)/A.
2404 APInt ExitVal(Upper);
2406 ExitVal = (Upper + A - One).sdiv(A);
2407 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2409 // Evaluate at the exit value. If we really did fall out of the valid
2410 // range, then we computed our trip count, otherwise wrap around or other
2411 // things must have happened.
2412 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2413 if (Range.contains(Val->getValue()))
2414 return new SCEVCouldNotCompute(); // Something strange happened
2416 // Ensure that the previous value is in the range. This is a sanity check.
2417 assert(Range.contains(
2418 EvaluateConstantChrecAtConstant(this,
2419 ConstantInt::get(ExitVal - One))->getValue()) &&
2420 "Linear scev computation is off in a bad way!");
2421 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2422 } else if (isQuadratic()) {
2423 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2424 // quadratic equation to solve it. To do this, we must frame our problem in
2425 // terms of figuring out when zero is crossed, instead of when
2426 // Range.getUpper() is crossed.
2427 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2428 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(
2429 ConstantInt::get(Range.getUpper())));
2430 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2432 // Next, solve the constructed addrec
2433 std::pair<SCEVHandle,SCEVHandle> Roots =
2434 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2435 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2436 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2438 // Pick the smallest positive root value.
2439 if (ConstantInt *CB =
2440 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2441 R1->getValue(), R2->getValue()))) {
2442 if (CB->getZExtValue() == false)
2443 std::swap(R1, R2); // R1 is the minimum root now.
2445 // Make sure the root is not off by one. The returned iteration should
2446 // not be in the range, but the previous one should be. When solving
2447 // for "X*X < 5", for example, we should not return a root of 2.
2448 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2450 if (Range.contains(R1Val->getValue())) {
2451 // The next iteration must be out of the range...
2452 Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2454 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2455 if (!Range.contains(R1Val->getValue()))
2456 return SCEVUnknown::get(NextVal);
2457 return new SCEVCouldNotCompute(); // Something strange happened
2460 // If R1 was not in the range, then it is a good return value. Make
2461 // sure that R1-1 WAS in the range though, just in case.
2462 Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2463 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2464 if (Range.contains(R1Val->getValue()))
2466 return new SCEVCouldNotCompute(); // Something strange happened
2471 // Fallback, if this is a general polynomial, figure out the progression
2472 // through brute force: evaluate until we find an iteration that fails the
2473 // test. This is likely to be slow, but getting an accurate trip count is
2474 // incredibly important, we will be able to simplify the exit test a lot, and
2475 // we are almost guaranteed to get a trip count in this case.
2476 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2477 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2479 ++NumBruteForceEvaluations;
2480 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2481 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2482 return new SCEVCouldNotCompute();
2484 // Check to see if we found the value!
2485 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2486 return SCEVConstant::get(TestVal);
2488 // Increment to test the next index.
2489 TestVal = ConstantInt::get(TestVal->getValue()+1);
2490 } while (TestVal != EndVal);
2492 return new SCEVCouldNotCompute();
2497 //===----------------------------------------------------------------------===//
2498 // ScalarEvolution Class Implementation
2499 //===----------------------------------------------------------------------===//
2501 bool ScalarEvolution::runOnFunction(Function &F) {
2502 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2506 void ScalarEvolution::releaseMemory() {
2507 delete (ScalarEvolutionsImpl*)Impl;
2511 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2512 AU.setPreservesAll();
2513 AU.addRequiredTransitive<LoopInfo>();
2516 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2517 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2520 /// hasSCEV - Return true if the SCEV for this value has already been
2522 bool ScalarEvolution::hasSCEV(Value *V) const {
2523 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2527 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2528 /// the specified value.
2529 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2530 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2534 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2535 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2538 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2539 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2542 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2543 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2546 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2547 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2550 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2552 // Print all inner loops first
2553 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2554 PrintLoopInfo(OS, SE, *I);
2556 cerr << "Loop " << L->getHeader()->getName() << ": ";
2558 std::vector<BasicBlock*> ExitBlocks;
2559 L->getExitBlocks(ExitBlocks);
2560 if (ExitBlocks.size() != 1)
2561 cerr << "<multiple exits> ";
2563 if (SE->hasLoopInvariantIterationCount(L)) {
2564 cerr << *SE->getIterationCount(L) << " iterations! ";
2566 cerr << "Unpredictable iteration count. ";
2572 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2573 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2574 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2576 OS << "Classifying expressions for: " << F.getName() << "\n";
2577 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2578 if (I->getType()->isInteger()) {
2581 SCEVHandle SV = getSCEV(&*I);
2585 if ((*I).getType()->isInteger()) {
2586 ConstantRange Bounds = SV->getValueRange();
2587 if (!Bounds.isFullSet())
2588 OS << "Bounds: " << Bounds << " ";
2591 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2593 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2594 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2595 OS << "<<Unknown>>";
2605 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2606 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2607 PrintLoopInfo(OS, this, *I);