1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/Instructions.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Assembly/Writer.h"
70 #include "llvm/Transforms/Scalar.h"
71 #include "llvm/Support/CFG.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ConstantRange.h"
75 #include "llvm/Support/InstIterator.h"
76 #include "llvm/Support/ManagedStatic.h"
77 #include "llvm/ADT/Statistic.h"
83 RegisterPass<ScalarEvolution>
84 R("scalar-evolution", "Scalar Evolution Analysis");
87 NumBruteForceEvaluations("scalar-evolution",
88 "Number of brute force evaluations needed to "
89 "calculate high-order polynomial exit values");
91 NumArrayLenItCounts("scalar-evolution",
92 "Number of trip counts computed with array length");
94 NumTripCountsComputed("scalar-evolution",
95 "Number of loops with predictable loop counts");
97 NumTripCountsNotComputed("scalar-evolution",
98 "Number of loops without predictable loop counts");
100 NumBruteForceTripCountsComputed("scalar-evolution",
101 "Number of loops with trip counts computed by force");
104 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
105 cl::desc("Maximum number of iterations SCEV will "
106 "symbolically execute a constant derived loop"),
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 Ty = Ty->getUnsignedVersion();
128 // Default to a full range if no better information is available.
129 return ConstantRange(getType());
133 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 SCEVHandle SCEVCouldNotCompute::
151 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
152 const SCEVHandle &Conc) const {
156 void SCEVCouldNotCompute::print(std::ostream &OS) const {
157 OS << "***COULDNOTCOMPUTE***";
160 bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
165 // SCEVConstants - Only allow the creation of one SCEVConstant for any
166 // particular value. Don't use a SCEVHandle here, or else the object will
168 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
171 SCEVConstant::~SCEVConstant() {
172 SCEVConstants->erase(V);
175 SCEVHandle SCEVConstant::get(ConstantInt *V) {
176 // Make sure that SCEVConstant instances are all unsigned.
177 if (V->getType()->isSigned()) {
178 const Type *NewTy = V->getType()->getUnsignedVersion();
179 V = cast<ConstantInt>(ConstantExpr::getCast(V, NewTy));
182 SCEVConstant *&R = (*SCEVConstants)[V];
183 if (R == 0) R = new SCEVConstant(V);
187 ConstantRange SCEVConstant::getValueRange() const {
188 return ConstantRange(V);
191 const Type *SCEVConstant::getType() const { return V->getType(); }
193 void SCEVConstant::print(std::ostream &OS) const {
194 WriteAsOperand(OS, V, false);
197 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
198 // particular input. Don't use a SCEVHandle here, or else the object will
200 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
201 SCEVTruncateExpr*> > SCEVTruncates;
203 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
204 : SCEV(scTruncate), Op(op), Ty(ty) {
205 assert(Op->getType()->isInteger() && Ty->isInteger() &&
207 "Cannot truncate non-integer value!");
208 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
209 "This is not a truncating conversion!");
212 SCEVTruncateExpr::~SCEVTruncateExpr() {
213 SCEVTruncates->erase(std::make_pair(Op, Ty));
216 ConstantRange SCEVTruncateExpr::getValueRange() const {
217 return getOperand()->getValueRange().truncate(getType());
220 void SCEVTruncateExpr::print(std::ostream &OS) const {
221 OS << "(truncate " << *Op << " to " << *Ty << ")";
224 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
225 // particular input. Don't use a SCEVHandle here, or else the object will never
227 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
228 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
231 : SCEV(scZeroExtend), Op(op), Ty(ty) {
232 assert(Op->getType()->isInteger() && Ty->isInteger() &&
234 "Cannot zero extend non-integer value!");
235 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
236 "This is not an extending conversion!");
239 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
243 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
244 return getOperand()->getValueRange().zeroExtend(getType());
247 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
248 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
252 // particular input. Don't use a SCEVHandle here, or else the object will never
254 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
255 SCEVCommutativeExpr*> > SCEVCommExprs;
257 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
258 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
259 std::vector<SCEV*>(Operands.begin(),
263 void SCEVCommutativeExpr::print(std::ostream &OS) const {
264 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
265 const char *OpStr = getOperationStr();
266 OS << "(" << *Operands[0];
267 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
268 OS << OpStr << *Operands[i];
272 SCEVHandle SCEVCommutativeExpr::
273 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
274 const SCEVHandle &Conc) const {
275 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
276 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
277 if (H != getOperand(i)) {
278 std::vector<SCEVHandle> NewOps;
279 NewOps.reserve(getNumOperands());
280 for (unsigned j = 0; j != i; ++j)
281 NewOps.push_back(getOperand(j));
283 for (++i; i != e; ++i)
284 NewOps.push_back(getOperand(i)->
285 replaceSymbolicValuesWithConcrete(Sym, Conc));
287 if (isa<SCEVAddExpr>(this))
288 return SCEVAddExpr::get(NewOps);
289 else if (isa<SCEVMulExpr>(this))
290 return SCEVMulExpr::get(NewOps);
292 assert(0 && "Unknown commutative expr!");
299 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
300 // input. Don't use a SCEVHandle here, or else the object will never be
302 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
303 SCEVSDivExpr*> > SCEVSDivs;
305 SCEVSDivExpr::~SCEVSDivExpr() {
306 SCEVSDivs->erase(std::make_pair(LHS, RHS));
309 void SCEVSDivExpr::print(std::ostream &OS) const {
310 OS << "(" << *LHS << " /s " << *RHS << ")";
313 const Type *SCEVSDivExpr::getType() const {
314 const Type *Ty = LHS->getType();
315 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
319 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
320 // particular input. Don't use a SCEVHandle here, or else the object will never
322 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
323 SCEVAddRecExpr*> > SCEVAddRecExprs;
325 SCEVAddRecExpr::~SCEVAddRecExpr() {
326 SCEVAddRecExprs->erase(std::make_pair(L,
327 std::vector<SCEV*>(Operands.begin(),
331 SCEVHandle SCEVAddRecExpr::
332 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
333 const SCEVHandle &Conc) const {
334 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
335 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
336 if (H != getOperand(i)) {
337 std::vector<SCEVHandle> NewOps;
338 NewOps.reserve(getNumOperands());
339 for (unsigned j = 0; j != i; ++j)
340 NewOps.push_back(getOperand(j));
342 for (++i; i != e; ++i)
343 NewOps.push_back(getOperand(i)->
344 replaceSymbolicValuesWithConcrete(Sym, Conc));
346 return get(NewOps, L);
353 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
354 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
355 // contain L and if the start is invariant.
356 return !QueryLoop->contains(L->getHeader()) &&
357 getOperand(0)->isLoopInvariant(QueryLoop);
361 void SCEVAddRecExpr::print(std::ostream &OS) const {
362 OS << "{" << *Operands[0];
363 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
364 OS << ",+," << *Operands[i];
365 OS << "}<" << L->getHeader()->getName() + ">";
368 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
369 // value. Don't use a SCEVHandle here, or else the object will never be
371 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
373 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
375 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
376 // All non-instruction values are loop invariant. All instructions are loop
377 // invariant if they are not contained in the specified loop.
378 if (Instruction *I = dyn_cast<Instruction>(V))
379 return !L->contains(I->getParent());
383 const Type *SCEVUnknown::getType() const {
387 void SCEVUnknown::print(std::ostream &OS) const {
388 WriteAsOperand(OS, V, false);
391 //===----------------------------------------------------------------------===//
393 //===----------------------------------------------------------------------===//
396 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
397 /// than the complexity of the RHS. This comparator is used to canonicalize
399 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
400 bool operator()(SCEV *LHS, SCEV *RHS) {
401 return LHS->getSCEVType() < RHS->getSCEVType();
406 /// GroupByComplexity - Given a list of SCEV objects, order them by their
407 /// complexity, and group objects of the same complexity together by value.
408 /// When this routine is finished, we know that any duplicates in the vector are
409 /// consecutive and that complexity is monotonically increasing.
411 /// Note that we go take special precautions to ensure that we get determinstic
412 /// results from this routine. In other words, we don't want the results of
413 /// this to depend on where the addresses of various SCEV objects happened to
416 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
417 if (Ops.size() < 2) return; // Noop
418 if (Ops.size() == 2) {
419 // This is the common case, which also happens to be trivially simple.
421 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
422 std::swap(Ops[0], Ops[1]);
426 // Do the rough sort by complexity.
427 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
429 // Now that we are sorted by complexity, group elements of the same
430 // complexity. Note that this is, at worst, N^2, but the vector is likely to
431 // be extremely short in practice. Note that we take this approach because we
432 // do not want to depend on the addresses of the objects we are grouping.
433 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
435 unsigned Complexity = S->getSCEVType();
437 // If there are any objects of the same complexity and same value as this
439 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
440 if (Ops[j] == S) { // Found a duplicate.
441 // Move it to immediately after i'th element.
442 std::swap(Ops[i+1], Ops[j]);
443 ++i; // no need to rescan it.
444 if (i == e-2) return; // Done!
452 //===----------------------------------------------------------------------===//
453 // Simple SCEV method implementations
454 //===----------------------------------------------------------------------===//
456 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
457 /// specified signed integer value and return a SCEV for the constant.
458 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
461 C = Constant::getNullValue(Ty);
462 else if (Ty->isFloatingPoint())
463 C = ConstantFP::get(Ty, Val);
464 else if (Ty->isSigned())
465 C = ConstantInt::get(Ty, Val);
467 C = ConstantInt::get(Ty->getSignedVersion(), Val);
468 C = ConstantExpr::getCast(C, Ty);
470 return SCEVUnknown::get(C);
473 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
474 /// input value to the specified type. If the type must be extended, it is zero
476 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
477 const Type *SrcTy = V->getType();
478 assert(SrcTy->isInteger() && Ty->isInteger() &&
479 "Cannot truncate or zero extend with non-integer arguments!");
480 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
481 return V; // No conversion
482 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
483 return SCEVTruncateExpr::get(V, Ty);
484 return SCEVZeroExtendExpr::get(V, Ty);
487 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
489 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
490 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
491 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
493 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
496 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
498 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
500 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
504 /// PartialFact - Compute V!/(V-NumSteps)!
505 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
506 // Handle this case efficiently, it is common to have constant iteration
507 // counts while computing loop exit values.
508 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
509 uint64_t Val = SC->getValue()->getZExtValue();
511 for (; NumSteps; --NumSteps)
512 Result *= Val-(NumSteps-1);
513 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
514 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
517 const Type *Ty = V->getType();
519 return SCEVUnknown::getIntegerSCEV(1, Ty);
521 SCEVHandle Result = V;
522 for (unsigned i = 1; i != NumSteps; ++i)
523 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
524 SCEVUnknown::getIntegerSCEV(i, Ty)));
529 /// evaluateAtIteration - Return the value of this chain of recurrences at
530 /// the specified iteration number. We can evaluate this recurrence by
531 /// multiplying each element in the chain by the binomial coefficient
532 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
534 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
536 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
537 /// Is the binomial equation safe using modular arithmetic??
539 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
540 SCEVHandle Result = getStart();
542 const Type *Ty = It->getType();
543 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
544 SCEVHandle BC = PartialFact(It, i);
546 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
547 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
548 Result = SCEVAddExpr::get(Result, Val);
554 //===----------------------------------------------------------------------===//
555 // SCEV Expression folder implementations
556 //===----------------------------------------------------------------------===//
558 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
559 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
560 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
562 // If the input value is a chrec scev made out of constants, truncate
563 // all of the constants.
564 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
565 std::vector<SCEVHandle> Operands;
566 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
567 // FIXME: This should allow truncation of other expression types!
568 if (isa<SCEVConstant>(AddRec->getOperand(i)))
569 Operands.push_back(get(AddRec->getOperand(i), Ty));
572 if (Operands.size() == AddRec->getNumOperands())
573 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
576 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
577 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
581 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
582 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
583 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
585 // FIXME: If the input value is a chrec scev, and we can prove that the value
586 // did not overflow the old, smaller, value, we can zero extend all of the
587 // operands (often constants). This would allow analysis of something like
588 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
590 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
591 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
595 // get - Get a canonical add expression, or something simpler if possible.
596 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
597 assert(!Ops.empty() && "Cannot get empty add!");
598 if (Ops.size() == 1) return Ops[0];
600 // Sort by complexity, this groups all similar expression types together.
601 GroupByComplexity(Ops);
603 // If there are any constants, fold them together.
605 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
607 assert(Idx < Ops.size());
608 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
609 // We found two constants, fold them together!
610 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
612 Ops[0] = SCEVConstant::get(CI);
613 Ops.erase(Ops.begin()+1); // Erase the folded element
614 if (Ops.size() == 1) return Ops[0];
615 LHSC = cast<SCEVConstant>(Ops[0]);
617 // If we couldn't fold the expression, move to the next constant. Note
618 // that this is impossible to happen in practice because we always
619 // constant fold constant ints to constant ints.
624 // If we are left with a constant zero being added, strip it off.
625 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
626 Ops.erase(Ops.begin());
631 if (Ops.size() == 1) return Ops[0];
633 // Okay, check to see if the same value occurs in the operand list twice. If
634 // so, merge them together into an multiply expression. Since we sorted the
635 // list, these values are required to be adjacent.
636 const Type *Ty = Ops[0]->getType();
637 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
638 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
639 // Found a match, merge the two values into a multiply, and add any
640 // remaining values to the result.
641 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
642 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
645 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
647 return SCEVAddExpr::get(Ops);
650 // Okay, now we know the first non-constant operand. If there are add
651 // operands they would be next.
652 if (Idx < Ops.size()) {
653 bool DeletedAdd = false;
654 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
655 // If we have an add, expand the add operands onto the end of the operands
657 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
658 Ops.erase(Ops.begin()+Idx);
662 // If we deleted at least one add, we added operands to the end of the list,
663 // and they are not necessarily sorted. Recurse to resort and resimplify
664 // any operands we just aquired.
669 // Skip over the add expression until we get to a multiply.
670 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
673 // If we are adding something to a multiply expression, make sure the
674 // something is not already an operand of the multiply. If so, merge it into
676 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
677 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
678 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
679 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
680 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
681 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
682 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
683 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
684 if (Mul->getNumOperands() != 2) {
685 // If the multiply has more than two operands, we must get the
687 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
688 MulOps.erase(MulOps.begin()+MulOp);
689 InnerMul = SCEVMulExpr::get(MulOps);
691 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
692 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
693 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
694 if (Ops.size() == 2) return OuterMul;
696 Ops.erase(Ops.begin()+AddOp);
697 Ops.erase(Ops.begin()+Idx-1);
699 Ops.erase(Ops.begin()+Idx);
700 Ops.erase(Ops.begin()+AddOp-1);
702 Ops.push_back(OuterMul);
703 return SCEVAddExpr::get(Ops);
706 // Check this multiply against other multiplies being added together.
707 for (unsigned OtherMulIdx = Idx+1;
708 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
710 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
711 // If MulOp occurs in OtherMul, we can fold the two multiplies
713 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
714 OMulOp != e; ++OMulOp)
715 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
716 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
717 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
718 if (Mul->getNumOperands() != 2) {
719 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
720 MulOps.erase(MulOps.begin()+MulOp);
721 InnerMul1 = SCEVMulExpr::get(MulOps);
723 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
724 if (OtherMul->getNumOperands() != 2) {
725 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
727 MulOps.erase(MulOps.begin()+OMulOp);
728 InnerMul2 = SCEVMulExpr::get(MulOps);
730 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
731 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
732 if (Ops.size() == 2) return OuterMul;
733 Ops.erase(Ops.begin()+Idx);
734 Ops.erase(Ops.begin()+OtherMulIdx-1);
735 Ops.push_back(OuterMul);
736 return SCEVAddExpr::get(Ops);
742 // If there are any add recurrences in the operands list, see if any other
743 // added values are loop invariant. If so, we can fold them into the
745 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
748 // Scan over all recurrences, trying to fold loop invariants into them.
749 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
750 // Scan all of the other operands to this add and add them to the vector if
751 // they are loop invariant w.r.t. the recurrence.
752 std::vector<SCEVHandle> LIOps;
753 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
754 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
755 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
756 LIOps.push_back(Ops[i]);
757 Ops.erase(Ops.begin()+i);
761 // If we found some loop invariants, fold them into the recurrence.
762 if (!LIOps.empty()) {
763 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
764 LIOps.push_back(AddRec->getStart());
766 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
767 AddRecOps[0] = SCEVAddExpr::get(LIOps);
769 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
770 // If all of the other operands were loop invariant, we are done.
771 if (Ops.size() == 1) return NewRec;
773 // Otherwise, add the folded AddRec by the non-liv parts.
774 for (unsigned i = 0;; ++i)
775 if (Ops[i] == AddRec) {
779 return SCEVAddExpr::get(Ops);
782 // Okay, if there weren't any loop invariants to be folded, check to see if
783 // there are multiple AddRec's with the same loop induction variable being
784 // added together. If so, we can fold them.
785 for (unsigned OtherIdx = Idx+1;
786 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
787 if (OtherIdx != Idx) {
788 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
789 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
790 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
791 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
792 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
793 if (i >= NewOps.size()) {
794 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
795 OtherAddRec->op_end());
798 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
800 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
802 if (Ops.size() == 2) return NewAddRec;
804 Ops.erase(Ops.begin()+Idx);
805 Ops.erase(Ops.begin()+OtherIdx-1);
806 Ops.push_back(NewAddRec);
807 return SCEVAddExpr::get(Ops);
811 // Otherwise couldn't fold anything into this recurrence. Move onto the
815 // Okay, it looks like we really DO need an add expr. Check to see if we
816 // already have one, otherwise create a new one.
817 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
818 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
820 if (Result == 0) Result = new SCEVAddExpr(Ops);
825 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
826 assert(!Ops.empty() && "Cannot get empty mul!");
828 // Sort by complexity, this groups all similar expression types together.
829 GroupByComplexity(Ops);
831 // If there are any constants, fold them together.
833 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
835 // C1*(C2+V) -> C1*C2 + C1*V
837 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
838 if (Add->getNumOperands() == 2 &&
839 isa<SCEVConstant>(Add->getOperand(0)))
840 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
841 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
845 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
846 // We found two constants, fold them together!
847 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
849 Ops[0] = SCEVConstant::get(CI);
850 Ops.erase(Ops.begin()+1); // Erase the folded element
851 if (Ops.size() == 1) return Ops[0];
852 LHSC = cast<SCEVConstant>(Ops[0]);
854 // If we couldn't fold the expression, move to the next constant. Note
855 // that this is impossible to happen in practice because we always
856 // constant fold constant ints to constant ints.
861 // If we are left with a constant one being multiplied, strip it off.
862 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
863 Ops.erase(Ops.begin());
865 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
866 // If we have a multiply of zero, it will always be zero.
871 // Skip over the add expression until we get to a multiply.
872 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
878 // If there are mul operands inline them all into this expression.
879 if (Idx < Ops.size()) {
880 bool DeletedMul = false;
881 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
882 // If we have an mul, expand the mul operands onto the end of the operands
884 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
885 Ops.erase(Ops.begin()+Idx);
889 // If we deleted at least one mul, we added operands to the end of the list,
890 // and they are not necessarily sorted. Recurse to resort and resimplify
891 // any operands we just aquired.
896 // If there are any add recurrences in the operands list, see if any other
897 // added values are loop invariant. If so, we can fold them into the
899 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
902 // Scan over all recurrences, trying to fold loop invariants into them.
903 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
904 // Scan all of the other operands to this mul and add them to the vector if
905 // they are loop invariant w.r.t. the recurrence.
906 std::vector<SCEVHandle> LIOps;
907 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
908 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
909 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
910 LIOps.push_back(Ops[i]);
911 Ops.erase(Ops.begin()+i);
915 // If we found some loop invariants, fold them into the recurrence.
916 if (!LIOps.empty()) {
917 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
918 std::vector<SCEVHandle> NewOps;
919 NewOps.reserve(AddRec->getNumOperands());
920 if (LIOps.size() == 1) {
921 SCEV *Scale = LIOps[0];
922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
923 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
925 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
926 std::vector<SCEVHandle> MulOps(LIOps);
927 MulOps.push_back(AddRec->getOperand(i));
928 NewOps.push_back(SCEVMulExpr::get(MulOps));
932 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
934 // If all of the other operands were loop invariant, we are done.
935 if (Ops.size() == 1) return NewRec;
937 // Otherwise, multiply the folded AddRec by the non-liv parts.
938 for (unsigned i = 0;; ++i)
939 if (Ops[i] == AddRec) {
943 return SCEVMulExpr::get(Ops);
946 // Okay, if there weren't any loop invariants to be folded, check to see if
947 // there are multiple AddRec's with the same loop induction variable being
948 // multiplied together. If so, we can fold them.
949 for (unsigned OtherIdx = Idx+1;
950 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
951 if (OtherIdx != Idx) {
952 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
953 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
954 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
955 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
956 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
958 SCEVHandle B = F->getStepRecurrence();
959 SCEVHandle D = G->getStepRecurrence();
960 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
961 SCEVMulExpr::get(G, B),
962 SCEVMulExpr::get(B, D));
963 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
965 if (Ops.size() == 2) return NewAddRec;
967 Ops.erase(Ops.begin()+Idx);
968 Ops.erase(Ops.begin()+OtherIdx-1);
969 Ops.push_back(NewAddRec);
970 return SCEVMulExpr::get(Ops);
974 // Otherwise couldn't fold anything into this recurrence. Move onto the
978 // Okay, it looks like we really DO need an mul expr. Check to see if we
979 // already have one, otherwise create a new one.
980 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
981 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
984 Result = new SCEVMulExpr(Ops);
988 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
989 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
990 if (RHSC->getValue()->equalsInt(1))
991 return LHS; // X sdiv 1 --> x
992 if (RHSC->getValue()->isAllOnesValue())
993 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
995 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
996 Constant *LHSCV = LHSC->getValue();
997 Constant *RHSCV = RHSC->getValue();
998 if (LHSCV->getType()->isUnsigned())
999 LHSCV = ConstantExpr::getCast(LHSCV,
1000 LHSCV->getType()->getSignedVersion());
1001 if (RHSCV->getType()->isUnsigned())
1002 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
1003 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
1007 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1009 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1010 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1015 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1016 /// specified loop. Simplify the expression as much as possible.
1017 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1018 const SCEVHandle &Step, const Loop *L) {
1019 std::vector<SCEVHandle> Operands;
1020 Operands.push_back(Start);
1021 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1022 if (StepChrec->getLoop() == L) {
1023 Operands.insert(Operands.end(), StepChrec->op_begin(),
1024 StepChrec->op_end());
1025 return get(Operands, L);
1028 Operands.push_back(Step);
1029 return get(Operands, L);
1032 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1033 /// specified loop. Simplify the expression as much as possible.
1034 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1036 if (Operands.size() == 1) return Operands[0];
1038 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1039 if (StepC->getValue()->isNullValue()) {
1040 Operands.pop_back();
1041 return get(Operands, L); // { X,+,0 } --> X
1044 SCEVAddRecExpr *&Result =
1045 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1047 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1051 SCEVHandle SCEVUnknown::get(Value *V) {
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1053 return SCEVConstant::get(CI);
1054 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1055 if (Result == 0) Result = new SCEVUnknown(V);
1060 //===----------------------------------------------------------------------===//
1061 // ScalarEvolutionsImpl Definition and Implementation
1062 //===----------------------------------------------------------------------===//
1064 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1068 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1069 /// F - The function we are analyzing.
1073 /// LI - The loop information for the function we are currently analyzing.
1077 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1079 SCEVHandle UnknownValue;
1081 /// Scalars - This is a cache of the scalars we have analyzed so far.
1083 std::map<Value*, SCEVHandle> Scalars;
1085 /// IterationCounts - Cache the iteration count of the loops for this
1086 /// function as they are computed.
1087 std::map<const Loop*, SCEVHandle> IterationCounts;
1089 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1090 /// the PHI instructions that we attempt to compute constant evolutions for.
1091 /// This allows us to avoid potentially expensive recomputation of these
1092 /// properties. An instruction maps to null if we are unable to compute its
1094 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1097 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1098 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1100 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1101 /// expression and create a new one.
1102 SCEVHandle getSCEV(Value *V);
1104 /// hasSCEV - Return true if the SCEV for this value has already been
1106 bool hasSCEV(Value *V) const {
1107 return Scalars.count(V);
1110 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1111 /// the specified value.
1112 void setSCEV(Value *V, const SCEVHandle &H) {
1113 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1114 assert(isNew && "This entry already existed!");
1118 /// getSCEVAtScope - Compute the value of the specified expression within
1119 /// the indicated loop (which may be null to indicate in no loop). If the
1120 /// expression cannot be evaluated, return UnknownValue itself.
1121 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1124 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1125 /// an analyzable loop-invariant iteration count.
1126 bool hasLoopInvariantIterationCount(const Loop *L);
1128 /// getIterationCount - If the specified loop has a predictable iteration
1129 /// count, return it. Note that it is not valid to call this method on a
1130 /// loop without a loop-invariant iteration count.
1131 SCEVHandle getIterationCount(const Loop *L);
1133 /// deleteInstructionFromRecords - This method should be called by the
1134 /// client before it removes an instruction from the program, to make sure
1135 /// that no dangling references are left around.
1136 void deleteInstructionFromRecords(Instruction *I);
1139 /// createSCEV - We know that there is no SCEV for the specified value.
1140 /// Analyze the expression.
1141 SCEVHandle createSCEV(Value *V);
1142 SCEVHandle createNodeForCast(CastInst *CI);
1144 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1146 SCEVHandle createNodeForPHI(PHINode *PN);
1148 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1149 /// for the specified instruction and replaces any references to the
1150 /// symbolic value SymName with the specified value. This is used during
1152 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1153 const SCEVHandle &SymName,
1154 const SCEVHandle &NewVal);
1156 /// ComputeIterationCount - Compute the number of times the specified loop
1158 SCEVHandle ComputeIterationCount(const Loop *L);
1160 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1161 /// 'setcc load X, cst', try to se if we can compute the trip count.
1162 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1165 unsigned SetCCOpcode);
1167 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1168 /// constant number of times (the condition evolves only from constants),
1169 /// try to evaluate a few iterations of the loop until we get the exit
1170 /// condition gets a value of ExitWhen (true or false). If we cannot
1171 /// evaluate the trip count of the loop, return UnknownValue.
1172 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1175 /// HowFarToZero - Return the number of times a backedge comparing the
1176 /// specified value to zero will execute. If not computable, return
1178 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1180 /// HowFarToNonZero - Return the number of times a backedge checking the
1181 /// specified value for nonzero will execute. If not computable, return
1183 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1185 /// HowManyLessThans - Return the number of times a backedge containing the
1186 /// specified less-than comparison will execute. If not computable, return
1188 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1190 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1191 /// in the header of its containing loop, we know the loop executes a
1192 /// constant number of times, and the PHI node is just a recurrence
1193 /// involving constants, fold it.
1194 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1199 //===----------------------------------------------------------------------===//
1200 // Basic SCEV Analysis and PHI Idiom Recognition Code
1203 /// deleteInstructionFromRecords - This method should be called by the
1204 /// client before it removes an instruction from the program, to make sure
1205 /// that no dangling references are left around.
1206 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1208 if (PHINode *PN = dyn_cast<PHINode>(I))
1209 ConstantEvolutionLoopExitValue.erase(PN);
1213 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1214 /// expression and create a new one.
1215 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1216 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1218 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1219 if (I != Scalars.end()) return I->second;
1220 SCEVHandle S = createSCEV(V);
1221 Scalars.insert(std::make_pair(V, S));
1225 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1226 /// the specified instruction and replaces any references to the symbolic value
1227 /// SymName with the specified value. This is used during PHI resolution.
1228 void ScalarEvolutionsImpl::
1229 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1230 const SCEVHandle &NewVal) {
1231 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1232 if (SI == Scalars.end()) return;
1235 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1236 if (NV == SI->second) return; // No change.
1238 SI->second = NV; // Update the scalars map!
1240 // Any instruction values that use this instruction might also need to be
1242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1244 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1247 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1248 /// a loop header, making it a potential recurrence, or it doesn't.
1250 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1251 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1252 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1253 if (L->getHeader() == PN->getParent()) {
1254 // If it lives in the loop header, it has two incoming values, one
1255 // from outside the loop, and one from inside.
1256 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1257 unsigned BackEdge = IncomingEdge^1;
1259 // While we are analyzing this PHI node, handle its value symbolically.
1260 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1261 assert(Scalars.find(PN) == Scalars.end() &&
1262 "PHI node already processed?");
1263 Scalars.insert(std::make_pair(PN, SymbolicName));
1265 // Using this symbolic name for the PHI, analyze the value coming around
1267 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1269 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1270 // has a special value for the first iteration of the loop.
1272 // If the value coming around the backedge is an add with the symbolic
1273 // value we just inserted, then we found a simple induction variable!
1274 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1275 // If there is a single occurrence of the symbolic value, replace it
1276 // with a recurrence.
1277 unsigned FoundIndex = Add->getNumOperands();
1278 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1279 if (Add->getOperand(i) == SymbolicName)
1280 if (FoundIndex == e) {
1285 if (FoundIndex != Add->getNumOperands()) {
1286 // Create an add with everything but the specified operand.
1287 std::vector<SCEVHandle> Ops;
1288 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1289 if (i != FoundIndex)
1290 Ops.push_back(Add->getOperand(i));
1291 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1293 // This is not a valid addrec if the step amount is varying each
1294 // loop iteration, but is not itself an addrec in this loop.
1295 if (Accum->isLoopInvariant(L) ||
1296 (isa<SCEVAddRecExpr>(Accum) &&
1297 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1298 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1299 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1301 // Okay, for the entire analysis of this edge we assumed the PHI
1302 // to be symbolic. We now need to go back and update all of the
1303 // entries for the scalars that use the PHI (except for the PHI
1304 // itself) to use the new analyzed value instead of the "symbolic"
1306 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1310 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1311 // Otherwise, this could be a loop like this:
1312 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1313 // In this case, j = {1,+,1} and BEValue is j.
1314 // Because the other in-value of i (0) fits the evolution of BEValue
1315 // i really is an addrec evolution.
1316 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1317 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1319 // If StartVal = j.start - j.stride, we can use StartVal as the
1320 // initial step of the addrec evolution.
1321 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1322 AddRec->getOperand(1))) {
1323 SCEVHandle PHISCEV =
1324 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1326 // Okay, for the entire analysis of this edge we assumed the PHI
1327 // to be symbolic. We now need to go back and update all of the
1328 // entries for the scalars that use the PHI (except for the PHI
1329 // itself) to use the new analyzed value instead of the "symbolic"
1331 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1337 return SymbolicName;
1340 // If it's not a loop phi, we can't handle it yet.
1341 return SCEVUnknown::get(PN);
1344 /// createNodeForCast - Handle the various forms of casts that we support.
1346 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1347 const Type *SrcTy = CI->getOperand(0)->getType();
1348 const Type *DestTy = CI->getType();
1350 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1351 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1352 return getSCEV(CI->getOperand(0));
1354 if (SrcTy->isInteger() && DestTy->isInteger()) {
1355 // Otherwise, if this is a truncating integer cast, we can represent this
1357 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1358 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1359 CI->getType()->getUnsignedVersion());
1360 if (SrcTy->isUnsigned() &&
1361 SrcTy->getPrimitiveSize() <= DestTy->getPrimitiveSize())
1362 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1363 CI->getType()->getUnsignedVersion());
1366 // If this is an sign or zero extending cast and we can prove that the value
1367 // will never overflow, we could do similar transformations.
1369 // Otherwise, we can't handle this cast!
1370 return SCEVUnknown::get(CI);
1374 /// createSCEV - We know that there is no SCEV for the specified value.
1375 /// Analyze the expression.
1377 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1378 if (Instruction *I = dyn_cast<Instruction>(V)) {
1379 switch (I->getOpcode()) {
1380 case Instruction::Add:
1381 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1382 getSCEV(I->getOperand(1)));
1383 case Instruction::Mul:
1384 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1385 getSCEV(I->getOperand(1)));
1386 case Instruction::SDiv:
1387 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1388 getSCEV(I->getOperand(1)));
1391 case Instruction::Sub:
1392 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1393 getSCEV(I->getOperand(1)));
1395 case Instruction::Shl:
1396 // Turn shift left of a constant amount into a multiply.
1397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1398 Constant *X = ConstantInt::get(V->getType(), 1);
1399 X = ConstantExpr::getShl(X, SA);
1400 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1404 case Instruction::Cast:
1405 return createNodeForCast(cast<CastInst>(I));
1407 case Instruction::PHI:
1408 return createNodeForPHI(cast<PHINode>(I));
1410 default: // We cannot analyze this expression.
1415 return SCEVUnknown::get(V);
1420 //===----------------------------------------------------------------------===//
1421 // Iteration Count Computation Code
1424 /// getIterationCount - If the specified loop has a predictable iteration
1425 /// count, return it. Note that it is not valid to call this method on a
1426 /// loop without a loop-invariant iteration count.
1427 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1428 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1429 if (I == IterationCounts.end()) {
1430 SCEVHandle ItCount = ComputeIterationCount(L);
1431 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1432 if (ItCount != UnknownValue) {
1433 assert(ItCount->isLoopInvariant(L) &&
1434 "Computed trip count isn't loop invariant for loop!");
1435 ++NumTripCountsComputed;
1436 } else if (isa<PHINode>(L->getHeader()->begin())) {
1437 // Only count loops that have phi nodes as not being computable.
1438 ++NumTripCountsNotComputed;
1444 /// ComputeIterationCount - Compute the number of times the specified loop
1446 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1447 // If the loop has a non-one exit block count, we can't analyze it.
1448 std::vector<BasicBlock*> ExitBlocks;
1449 L->getExitBlocks(ExitBlocks);
1450 if (ExitBlocks.size() != 1) return UnknownValue;
1452 // Okay, there is one exit block. Try to find the condition that causes the
1453 // loop to be exited.
1454 BasicBlock *ExitBlock = ExitBlocks[0];
1456 BasicBlock *ExitingBlock = 0;
1457 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1459 if (L->contains(*PI)) {
1460 if (ExitingBlock == 0)
1463 return UnknownValue; // More than one block exiting!
1465 assert(ExitingBlock && "No exits from loop, something is broken!");
1467 // Okay, we've computed the exiting block. See what condition causes us to
1470 // FIXME: we should be able to handle switch instructions (with a single exit)
1471 // FIXME: We should handle cast of int to bool as well
1472 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1473 if (ExitBr == 0) return UnknownValue;
1474 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1475 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1476 if (ExitCond == 0) // Not a setcc
1477 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1478 ExitBr->getSuccessor(0) == ExitBlock);
1480 // If the condition was exit on true, convert the condition to exit on false.
1481 Instruction::BinaryOps Cond;
1482 if (ExitBr->getSuccessor(1) == ExitBlock)
1483 Cond = ExitCond->getOpcode();
1485 Cond = ExitCond->getInverseCondition();
1487 // Handle common loops like: for (X = "string"; *X; ++X)
1488 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1489 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1491 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1492 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1495 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1496 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1498 // Try to evaluate any dependencies out of the loop.
1499 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1500 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1501 Tmp = getSCEVAtScope(RHS, L);
1502 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1504 // At this point, we would like to compute how many iterations of the loop the
1505 // predicate will return true for these inputs.
1506 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1507 // If there is a constant, force it into the RHS.
1508 std::swap(LHS, RHS);
1509 Cond = SetCondInst::getSwappedCondition(Cond);
1512 // FIXME: think about handling pointer comparisons! i.e.:
1513 // while (P != P+100) ++P;
1515 // If we have a comparison of a chrec against a constant, try to use value
1516 // ranges to answer this query.
1517 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1518 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1519 if (AddRec->getLoop() == L) {
1520 // Form the comparison range using the constant of the correct type so
1521 // that the ConstantRange class knows to do a signed or unsigned
1523 ConstantInt *CompVal = RHSC->getValue();
1524 const Type *RealTy = ExitCond->getOperand(0)->getType();
1525 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1527 // Form the constant range.
1528 ConstantRange CompRange(Cond, CompVal);
1530 // Now that we have it, if it's signed, convert it to an unsigned
1532 if (CompRange.getLower()->getType()->isSigned()) {
1533 const Type *NewTy = RHSC->getValue()->getType();
1534 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1535 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1536 CompRange = ConstantRange(NewL, NewU);
1539 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1540 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1545 case Instruction::SetNE: // while (X != Y)
1546 // Convert to: while (X-Y != 0)
1547 if (LHS->getType()->isInteger()) {
1548 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1549 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1552 case Instruction::SetEQ:
1553 // Convert to: while (X-Y == 0) // while (X == Y)
1554 if (LHS->getType()->isInteger()) {
1555 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1556 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1559 case Instruction::SetLT:
1560 if (LHS->getType()->isInteger() &&
1561 ExitCond->getOperand(0)->getType()->isSigned()) {
1562 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1563 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1566 case Instruction::SetGT:
1567 if (LHS->getType()->isInteger() &&
1568 ExitCond->getOperand(0)->getType()->isSigned()) {
1569 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1570 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1575 std::cerr << "ComputeIterationCount ";
1576 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1577 std::cerr << "[unsigned] ";
1578 std::cerr << *LHS << " "
1579 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1584 return ComputeIterationCountExhaustively(L, ExitCond,
1585 ExitBr->getSuccessor(0) == ExitBlock);
1588 static ConstantInt *
1589 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1590 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1591 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1592 assert(isa<SCEVConstant>(Val) &&
1593 "Evaluation of SCEV at constant didn't fold correctly?");
1594 return cast<SCEVConstant>(Val)->getValue();
1597 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1598 /// and a GEP expression (missing the pointer index) indexing into it, return
1599 /// the addressed element of the initializer or null if the index expression is
1602 GetAddressedElementFromGlobal(GlobalVariable *GV,
1603 const std::vector<ConstantInt*> &Indices) {
1604 Constant *Init = GV->getInitializer();
1605 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1606 uint64_t Idx = Indices[i]->getZExtValue();
1607 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1608 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1609 Init = cast<Constant>(CS->getOperand(Idx));
1610 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1611 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1612 Init = cast<Constant>(CA->getOperand(Idx));
1613 } else if (isa<ConstantAggregateZero>(Init)) {
1614 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1615 assert(Idx < STy->getNumElements() && "Bad struct index!");
1616 Init = Constant::getNullValue(STy->getElementType(Idx));
1617 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1618 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1619 Init = Constant::getNullValue(ATy->getElementType());
1621 assert(0 && "Unknown constant aggregate type!");
1625 return 0; // Unknown initializer type
1631 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1632 /// 'setcc load X, cst', try to se if we can compute the trip count.
1633 SCEVHandle ScalarEvolutionsImpl::
1634 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1635 const Loop *L, unsigned SetCCOpcode) {
1636 if (LI->isVolatile()) return UnknownValue;
1638 // Check to see if the loaded pointer is a getelementptr of a global.
1639 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1640 if (!GEP) return UnknownValue;
1642 // Make sure that it is really a constant global we are gepping, with an
1643 // initializer, and make sure the first IDX is really 0.
1644 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1645 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1646 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1647 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1648 return UnknownValue;
1650 // Okay, we allow one non-constant index into the GEP instruction.
1652 std::vector<ConstantInt*> Indexes;
1653 unsigned VarIdxNum = 0;
1654 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1655 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1656 Indexes.push_back(CI);
1657 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1658 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1659 VarIdx = GEP->getOperand(i);
1661 Indexes.push_back(0);
1664 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1665 // Check to see if X is a loop variant variable value now.
1666 SCEVHandle Idx = getSCEV(VarIdx);
1667 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1668 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1670 // We can only recognize very limited forms of loop index expressions, in
1671 // particular, only affine AddRec's like {C1,+,C2}.
1672 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1673 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1674 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1675 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1676 return UnknownValue;
1678 unsigned MaxSteps = MaxBruteForceIterations;
1679 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1680 ConstantInt *ItCst =
1681 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1682 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1684 // Form the GEP offset.
1685 Indexes[VarIdxNum] = Val;
1687 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1688 if (Result == 0) break; // Cannot compute!
1690 // Evaluate the condition for this iteration.
1691 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1692 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1693 if (cast<ConstantBool>(Result)->getValue() == false) {
1695 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1696 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1699 ++NumArrayLenItCounts;
1700 return SCEVConstant::get(ItCst); // Found terminating iteration!
1703 return UnknownValue;
1707 /// CanConstantFold - Return true if we can constant fold an instruction of the
1708 /// specified type, assuming that all operands were constants.
1709 static bool CanConstantFold(const Instruction *I) {
1710 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1711 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1714 if (const CallInst *CI = dyn_cast<CallInst>(I))
1715 if (const Function *F = CI->getCalledFunction())
1716 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1720 /// ConstantFold - Constant fold an instruction of the specified type with the
1721 /// specified constant operands. This function may modify the operands vector.
1722 static Constant *ConstantFold(const Instruction *I,
1723 std::vector<Constant*> &Operands) {
1724 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1725 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1727 switch (I->getOpcode()) {
1728 case Instruction::Cast:
1729 return ConstantExpr::getCast(Operands[0], I->getType());
1730 case Instruction::Select:
1731 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1732 case Instruction::Call:
1733 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1734 Operands.erase(Operands.begin());
1735 return ConstantFoldCall(cast<Function>(GV), Operands);
1739 case Instruction::GetElementPtr:
1740 Constant *Base = Operands[0];
1741 Operands.erase(Operands.begin());
1742 return ConstantExpr::getGetElementPtr(Base, Operands);
1748 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1749 /// in the loop that V is derived from. We allow arbitrary operations along the
1750 /// way, but the operands of an operation must either be constants or a value
1751 /// derived from a constant PHI. If this expression does not fit with these
1752 /// constraints, return null.
1753 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1754 // If this is not an instruction, or if this is an instruction outside of the
1755 // loop, it can't be derived from a loop PHI.
1756 Instruction *I = dyn_cast<Instruction>(V);
1757 if (I == 0 || !L->contains(I->getParent())) return 0;
1759 if (PHINode *PN = dyn_cast<PHINode>(I))
1760 if (L->getHeader() == I->getParent())
1763 // We don't currently keep track of the control flow needed to evaluate
1764 // PHIs, so we cannot handle PHIs inside of loops.
1767 // If we won't be able to constant fold this expression even if the operands
1768 // are constants, return early.
1769 if (!CanConstantFold(I)) return 0;
1771 // Otherwise, we can evaluate this instruction if all of its operands are
1772 // constant or derived from a PHI node themselves.
1774 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1775 if (!(isa<Constant>(I->getOperand(Op)) ||
1776 isa<GlobalValue>(I->getOperand(Op)))) {
1777 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1778 if (P == 0) return 0; // Not evolving from PHI
1782 return 0; // Evolving from multiple different PHIs.
1785 // This is a expression evolving from a constant PHI!
1789 /// EvaluateExpression - Given an expression that passes the
1790 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1791 /// in the loop has the value PHIVal. If we can't fold this expression for some
1792 /// reason, return null.
1793 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1794 if (isa<PHINode>(V)) return PHIVal;
1795 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1797 if (Constant *C = dyn_cast<Constant>(V)) return C;
1798 Instruction *I = cast<Instruction>(V);
1800 std::vector<Constant*> Operands;
1801 Operands.resize(I->getNumOperands());
1803 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1804 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1805 if (Operands[i] == 0) return 0;
1808 return ConstantFold(I, Operands);
1811 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1812 /// in the header of its containing loop, we know the loop executes a
1813 /// constant number of times, and the PHI node is just a recurrence
1814 /// involving constants, fold it.
1815 Constant *ScalarEvolutionsImpl::
1816 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1817 std::map<PHINode*, Constant*>::iterator I =
1818 ConstantEvolutionLoopExitValue.find(PN);
1819 if (I != ConstantEvolutionLoopExitValue.end())
1822 if (Its > MaxBruteForceIterations)
1823 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1825 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1827 // Since the loop is canonicalized, the PHI node must have two entries. One
1828 // entry must be a constant (coming in from outside of the loop), and the
1829 // second must be derived from the same PHI.
1830 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1831 Constant *StartCST =
1832 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1834 return RetVal = 0; // Must be a constant.
1836 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1837 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1839 return RetVal = 0; // Not derived from same PHI.
1841 // Execute the loop symbolically to determine the exit value.
1842 unsigned IterationNum = 0;
1843 unsigned NumIterations = Its;
1844 if (NumIterations != Its)
1845 return RetVal = 0; // More than 2^32 iterations??
1847 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1848 if (IterationNum == NumIterations)
1849 return RetVal = PHIVal; // Got exit value!
1851 // Compute the value of the PHI node for the next iteration.
1852 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1853 if (NextPHI == PHIVal)
1854 return RetVal = NextPHI; // Stopped evolving!
1856 return 0; // Couldn't evaluate!
1861 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1862 /// constant number of times (the condition evolves only from constants),
1863 /// try to evaluate a few iterations of the loop until we get the exit
1864 /// condition gets a value of ExitWhen (true or false). If we cannot
1865 /// evaluate the trip count of the loop, return UnknownValue.
1866 SCEVHandle ScalarEvolutionsImpl::
1867 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1868 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1869 if (PN == 0) return UnknownValue;
1871 // Since the loop is canonicalized, the PHI node must have two entries. One
1872 // entry must be a constant (coming in from outside of the loop), and the
1873 // second must be derived from the same PHI.
1874 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1875 Constant *StartCST =
1876 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1877 if (StartCST == 0) return UnknownValue; // Must be a constant.
1879 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1880 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1881 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1883 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1884 // the loop symbolically to determine when the condition gets a value of
1886 unsigned IterationNum = 0;
1887 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1888 for (Constant *PHIVal = StartCST;
1889 IterationNum != MaxIterations; ++IterationNum) {
1890 ConstantBool *CondVal =
1891 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1892 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1894 if (CondVal->getValue() == ExitWhen) {
1895 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1896 ++NumBruteForceTripCountsComputed;
1897 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
1900 // Compute the value of the PHI node for the next iteration.
1901 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1902 if (NextPHI == 0 || NextPHI == PHIVal)
1903 return UnknownValue; // Couldn't evaluate or not making progress...
1907 // Too many iterations were needed to evaluate.
1908 return UnknownValue;
1911 /// getSCEVAtScope - Compute the value of the specified expression within the
1912 /// indicated loop (which may be null to indicate in no loop). If the
1913 /// expression cannot be evaluated, return UnknownValue.
1914 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1915 // FIXME: this should be turned into a virtual method on SCEV!
1917 if (isa<SCEVConstant>(V)) return V;
1919 // If this instruction is evolves from a constant-evolving PHI, compute the
1920 // exit value from the loop without using SCEVs.
1921 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1922 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1923 const Loop *LI = this->LI[I->getParent()];
1924 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1925 if (PHINode *PN = dyn_cast<PHINode>(I))
1926 if (PN->getParent() == LI->getHeader()) {
1927 // Okay, there is no closed form solution for the PHI node. Check
1928 // to see if the loop that contains it has a known iteration count.
1929 // If so, we may be able to force computation of the exit value.
1930 SCEVHandle IterationCount = getIterationCount(LI);
1931 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1932 // Okay, we know how many times the containing loop executes. If
1933 // this is a constant evolving PHI node, get the final value at
1934 // the specified iteration number.
1935 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1936 ICC->getValue()->getZExtValue(),
1938 if (RV) return SCEVUnknown::get(RV);
1942 // Okay, this is a some expression that we cannot symbolically evaluate
1943 // into a SCEV. Check to see if it's possible to symbolically evaluate
1944 // the arguments into constants, and if see, try to constant propagate the
1945 // result. This is particularly useful for computing loop exit values.
1946 if (CanConstantFold(I)) {
1947 std::vector<Constant*> Operands;
1948 Operands.reserve(I->getNumOperands());
1949 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1950 Value *Op = I->getOperand(i);
1951 if (Constant *C = dyn_cast<Constant>(Op)) {
1952 Operands.push_back(C);
1954 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1955 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1956 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1958 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1959 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1960 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1968 return SCEVUnknown::get(ConstantFold(I, Operands));
1972 // This is some other type of SCEVUnknown, just return it.
1976 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1977 // Avoid performing the look-up in the common case where the specified
1978 // expression has no loop-variant portions.
1979 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1980 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1981 if (OpAtScope != Comm->getOperand(i)) {
1982 if (OpAtScope == UnknownValue) return UnknownValue;
1983 // Okay, at least one of these operands is loop variant but might be
1984 // foldable. Build a new instance of the folded commutative expression.
1985 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1986 NewOps.push_back(OpAtScope);
1988 for (++i; i != e; ++i) {
1989 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1990 if (OpAtScope == UnknownValue) return UnknownValue;
1991 NewOps.push_back(OpAtScope);
1993 if (isa<SCEVAddExpr>(Comm))
1994 return SCEVAddExpr::get(NewOps);
1995 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1996 return SCEVMulExpr::get(NewOps);
1999 // If we got here, all operands are loop invariant.
2003 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2004 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2005 if (LHS == UnknownValue) return LHS;
2006 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2007 if (RHS == UnknownValue) return RHS;
2008 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2009 return Div; // must be loop invariant
2010 return SCEVSDivExpr::get(LHS, RHS);
2013 // If this is a loop recurrence for a loop that does not contain L, then we
2014 // are dealing with the final value computed by the loop.
2015 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2016 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2017 // To evaluate this recurrence, we need to know how many times the AddRec
2018 // loop iterates. Compute this now.
2019 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2020 if (IterationCount == UnknownValue) return UnknownValue;
2021 IterationCount = getTruncateOrZeroExtend(IterationCount,
2024 // If the value is affine, simplify the expression evaluation to just
2025 // Start + Step*IterationCount.
2026 if (AddRec->isAffine())
2027 return SCEVAddExpr::get(AddRec->getStart(),
2028 SCEVMulExpr::get(IterationCount,
2029 AddRec->getOperand(1)));
2031 // Otherwise, evaluate it the hard way.
2032 return AddRec->evaluateAtIteration(IterationCount);
2034 return UnknownValue;
2037 //assert(0 && "Unknown SCEV type!");
2038 return UnknownValue;
2042 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2043 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2044 /// might be the same) or two SCEVCouldNotCompute objects.
2046 static std::pair<SCEVHandle,SCEVHandle>
2047 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2048 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2049 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2050 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2051 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2053 // We currently can only solve this if the coefficients are constants.
2054 if (!L || !M || !N) {
2055 SCEV *CNC = new SCEVCouldNotCompute();
2056 return std::make_pair(CNC, CNC);
2059 Constant *C = L->getValue();
2060 Constant *Two = ConstantInt::get(C->getType(), 2);
2062 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2063 // The B coefficient is M-N/2
2064 Constant *B = ConstantExpr::getSub(M->getValue(),
2065 ConstantExpr::getSDiv(N->getValue(),
2067 // The A coefficient is N/2
2068 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
2070 // Compute the B^2-4ac term.
2071 Constant *SqrtTerm =
2072 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2073 ConstantExpr::getMul(A, C));
2074 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2076 // Compute floor(sqrt(B^2-4ac))
2077 ConstantInt *SqrtVal =
2078 cast<ConstantInt>(ConstantExpr::getCast(SqrtTerm,
2079 SqrtTerm->getType()->getUnsignedVersion()));
2080 uint64_t SqrtValV = SqrtVal->getZExtValue();
2081 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2082 // The square root might not be precise for arbitrary 64-bit integer
2083 // values. Do some sanity checks to ensure it's correct.
2084 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2085 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2086 SCEV *CNC = new SCEVCouldNotCompute();
2087 return std::make_pair(CNC, CNC);
2090 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
2091 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2093 Constant *NegB = ConstantExpr::getNeg(B);
2094 Constant *TwoA = ConstantExpr::getMul(A, Two);
2096 // The divisions must be performed as signed divisions.
2097 const Type *SignedTy = NegB->getType()->getSignedVersion();
2098 NegB = ConstantExpr::getCast(NegB, SignedTy);
2099 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2100 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2102 Constant *Solution1 =
2103 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2104 Constant *Solution2 =
2105 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2106 return std::make_pair(SCEVUnknown::get(Solution1),
2107 SCEVUnknown::get(Solution2));
2110 /// HowFarToZero - Return the number of times a backedge comparing the specified
2111 /// value to zero will execute. If not computable, return UnknownValue
2112 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2113 // If the value is a constant
2114 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2115 // If the value is already zero, the branch will execute zero times.
2116 if (C->getValue()->isNullValue()) return C;
2117 return UnknownValue; // Otherwise it will loop infinitely.
2120 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2121 if (!AddRec || AddRec->getLoop() != L)
2122 return UnknownValue;
2124 if (AddRec->isAffine()) {
2125 // If this is an affine expression the execution count of this branch is
2128 // (0 - Start/Step) iff Start % Step == 0
2130 // Get the initial value for the loop.
2131 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2132 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2133 SCEVHandle Step = AddRec->getOperand(1);
2135 Step = getSCEVAtScope(Step, L->getParentLoop());
2137 // Figure out if Start % Step == 0.
2138 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2139 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2140 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2141 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
2142 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2143 return Start; // 0 - Start/-1 == Start
2145 // Check to see if Start is divisible by SC with no remainder.
2146 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2147 ConstantInt *StartCC = StartC->getValue();
2148 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2149 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2150 if (Rem->isNullValue()) {
2151 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2152 return SCEVUnknown::get(Result);
2156 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2157 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2158 // the quadratic equation to solve it.
2159 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2160 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2161 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2164 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2165 << " sol#2: " << *R2 << "\n";
2167 // Pick the smallest positive root value.
2168 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2169 if (ConstantBool *CB =
2170 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2172 if (CB->getValue() == false)
2173 std::swap(R1, R2); // R1 is the minimum root now.
2175 // We can only use this value if the chrec ends up with an exact zero
2176 // value at this index. When solving for "X*X != 5", for example, we
2177 // should not accept a root of 2.
2178 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2179 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2180 if (EvalVal->getValue()->isNullValue())
2181 return R1; // We found a quadratic root!
2186 return UnknownValue;
2189 /// HowFarToNonZero - Return the number of times a backedge checking the
2190 /// specified value for nonzero will execute. If not computable, return
2192 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2193 // Loops that look like: while (X == 0) are very strange indeed. We don't
2194 // handle them yet except for the trivial case. This could be expanded in the
2195 // future as needed.
2197 // If the value is a constant, check to see if it is known to be non-zero
2198 // already. If so, the backedge will execute zero times.
2199 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2200 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2201 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2202 if (NonZero == ConstantBool::getTrue())
2203 return getSCEV(Zero);
2204 return UnknownValue; // Otherwise it will loop infinitely.
2207 // We could implement others, but I really doubt anyone writes loops like
2208 // this, and if they did, they would already be constant folded.
2209 return UnknownValue;
2212 /// HowManyLessThans - Return the number of times a backedge containing the
2213 /// specified less-than comparison will execute. If not computable, return
2215 SCEVHandle ScalarEvolutionsImpl::
2216 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2217 // Only handle: "ADDREC < LoopInvariant".
2218 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2220 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2221 if (!AddRec || AddRec->getLoop() != L)
2222 return UnknownValue;
2224 if (AddRec->isAffine()) {
2225 // FORNOW: We only support unit strides.
2226 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2227 if (AddRec->getOperand(1) != One)
2228 return UnknownValue;
2230 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2231 // know that m is >= n on input to the loop. If it is, the condition return
2232 // true zero times. What we really should return, for full generality, is
2233 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2234 // canonical loop form: most do-loops will have a check that dominates the
2235 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2236 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2238 // Search for the check.
2239 BasicBlock *Preheader = L->getLoopPreheader();
2240 BasicBlock *PreheaderDest = L->getHeader();
2241 if (Preheader == 0) return UnknownValue;
2243 BranchInst *LoopEntryPredicate =
2244 dyn_cast<BranchInst>(Preheader->getTerminator());
2245 if (!LoopEntryPredicate) return UnknownValue;
2247 // This might be a critical edge broken out. If the loop preheader ends in
2248 // an unconditional branch to the loop, check to see if the preheader has a
2249 // single predecessor, and if so, look for its terminator.
2250 while (LoopEntryPredicate->isUnconditional()) {
2251 PreheaderDest = Preheader;
2252 Preheader = Preheader->getSinglePredecessor();
2253 if (!Preheader) return UnknownValue; // Multiple preds.
2255 LoopEntryPredicate =
2256 dyn_cast<BranchInst>(Preheader->getTerminator());
2257 if (!LoopEntryPredicate) return UnknownValue;
2260 // Now that we found a conditional branch that dominates the loop, check to
2261 // see if it is the comparison we are looking for.
2262 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2263 if (!SCI) return UnknownValue;
2264 Value *PreCondLHS = SCI->getOperand(0);
2265 Value *PreCondRHS = SCI->getOperand(1);
2266 Instruction::BinaryOps Cond;
2267 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2268 Cond = SCI->getOpcode();
2270 Cond = SCI->getInverseCondition();
2273 case Instruction::SetGT:
2274 std::swap(PreCondLHS, PreCondRHS);
2275 Cond = Instruction::SetLT;
2277 case Instruction::SetLT:
2278 if (PreCondLHS->getType()->isInteger() &&
2279 PreCondLHS->getType()->isSigned()) {
2280 if (RHS != getSCEV(PreCondRHS))
2281 return UnknownValue; // Not a comparison against 'm'.
2283 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2284 != getSCEV(PreCondLHS))
2285 return UnknownValue; // Not a comparison against 'n-1'.
2288 return UnknownValue;
2293 //std::cerr << "Computed Loop Trip Count as: " <<
2294 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2295 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2298 return UnknownValue;
2301 /// getNumIterationsInRange - Return the number of iterations of this loop that
2302 /// produce values in the specified constant range. Another way of looking at
2303 /// this is that it returns the first iteration number where the value is not in
2304 /// the condition, thus computing the exit count. If the iteration count can't
2305 /// be computed, an instance of SCEVCouldNotCompute is returned.
2306 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2307 if (Range.isFullSet()) // Infinite loop.
2308 return new SCEVCouldNotCompute();
2310 // If the start is a non-zero constant, shift the range to simplify things.
2311 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2312 if (!SC->getValue()->isNullValue()) {
2313 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2314 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2315 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2316 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2317 return ShiftedAddRec->getNumIterationsInRange(
2318 Range.subtract(SC->getValue()));
2319 // This is strange and shouldn't happen.
2320 return new SCEVCouldNotCompute();
2323 // The only time we can solve this is when we have all constant indices.
2324 // Otherwise, we cannot determine the overflow conditions.
2325 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2326 if (!isa<SCEVConstant>(getOperand(i)))
2327 return new SCEVCouldNotCompute();
2330 // Okay at this point we know that all elements of the chrec are constants and
2331 // that the start element is zero.
2333 // First check to see if the range contains zero. If not, the first
2335 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2336 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2339 // If this is an affine expression then we have this situation:
2340 // Solve {0,+,A} in Range === Ax in Range
2342 // Since we know that zero is in the range, we know that the upper value of
2343 // the range must be the first possible exit value. Also note that we
2344 // already checked for a full range.
2345 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2346 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2347 ConstantInt *One = ConstantInt::get(getType(), 1);
2349 // The exit value should be (Upper+A-1)/A.
2350 Constant *ExitValue = Upper;
2352 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2353 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
2355 assert(isa<ConstantInt>(ExitValue) &&
2356 "Constant folding of integers not implemented?");
2358 // Evaluate at the exit value. If we really did fall out of the valid
2359 // range, then we computed our trip count, otherwise wrap around or other
2360 // things must have happened.
2361 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2362 if (Range.contains(Val))
2363 return new SCEVCouldNotCompute(); // Something strange happened
2365 // Ensure that the previous value is in the range. This is a sanity check.
2366 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2367 ConstantExpr::getSub(ExitValue, One))) &&
2368 "Linear scev computation is off in a bad way!");
2369 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2370 } else if (isQuadratic()) {
2371 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2372 // quadratic equation to solve it. To do this, we must frame our problem in
2373 // terms of figuring out when zero is crossed, instead of when
2374 // Range.getUpper() is crossed.
2375 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2376 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2377 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2379 // Next, solve the constructed addrec
2380 std::pair<SCEVHandle,SCEVHandle> Roots =
2381 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2382 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2383 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2385 // Pick the smallest positive root value.
2386 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2387 if (ConstantBool *CB =
2388 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2390 if (CB->getValue() == false)
2391 std::swap(R1, R2); // R1 is the minimum root now.
2393 // Make sure the root is not off by one. The returned iteration should
2394 // not be in the range, but the previous one should be. When solving
2395 // for "X*X < 5", for example, we should not return a root of 2.
2396 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2398 if (Range.contains(R1Val)) {
2399 // The next iteration must be out of the range...
2401 ConstantExpr::getAdd(R1->getValue(),
2402 ConstantInt::get(R1->getType(), 1));
2404 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2405 if (!Range.contains(R1Val))
2406 return SCEVUnknown::get(NextVal);
2407 return new SCEVCouldNotCompute(); // Something strange happened
2410 // If R1 was not in the range, then it is a good return value. Make
2411 // sure that R1-1 WAS in the range though, just in case.
2413 ConstantExpr::getSub(R1->getValue(),
2414 ConstantInt::get(R1->getType(), 1));
2415 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2416 if (Range.contains(R1Val))
2418 return new SCEVCouldNotCompute(); // Something strange happened
2423 // Fallback, if this is a general polynomial, figure out the progression
2424 // through brute force: evaluate until we find an iteration that fails the
2425 // test. This is likely to be slow, but getting an accurate trip count is
2426 // incredibly important, we will be able to simplify the exit test a lot, and
2427 // we are almost guaranteed to get a trip count in this case.
2428 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2429 ConstantInt *One = ConstantInt::get(getType(), 1);
2430 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2432 ++NumBruteForceEvaluations;
2433 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2434 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2435 return new SCEVCouldNotCompute();
2437 // Check to see if we found the value!
2438 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2439 return SCEVConstant::get(TestVal);
2441 // Increment to test the next index.
2442 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2443 } while (TestVal != EndVal);
2445 return new SCEVCouldNotCompute();
2450 //===----------------------------------------------------------------------===//
2451 // ScalarEvolution Class Implementation
2452 //===----------------------------------------------------------------------===//
2454 bool ScalarEvolution::runOnFunction(Function &F) {
2455 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2459 void ScalarEvolution::releaseMemory() {
2460 delete (ScalarEvolutionsImpl*)Impl;
2464 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2465 AU.setPreservesAll();
2466 AU.addRequiredTransitive<LoopInfo>();
2469 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2470 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2473 /// hasSCEV - Return true if the SCEV for this value has already been
2475 bool ScalarEvolution::hasSCEV(Value *V) const {
2476 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2480 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2481 /// the specified value.
2482 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2483 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2487 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2488 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2491 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2492 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2495 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2496 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2499 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2500 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2503 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2505 // Print all inner loops first
2506 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2507 PrintLoopInfo(OS, SE, *I);
2509 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2511 std::vector<BasicBlock*> ExitBlocks;
2512 L->getExitBlocks(ExitBlocks);
2513 if (ExitBlocks.size() != 1)
2514 std::cerr << "<multiple exits> ";
2516 if (SE->hasLoopInvariantIterationCount(L)) {
2517 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2519 std::cerr << "Unpredictable iteration count. ";
2525 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2526 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2527 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2529 OS << "Classifying expressions for: " << F.getName() << "\n";
2530 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2531 if (I->getType()->isInteger()) {
2534 SCEVHandle SV = getSCEV(&*I);
2538 if ((*I).getType()->isIntegral()) {
2539 ConstantRange Bounds = SV->getValueRange();
2540 if (!Bounds.isFullSet())
2541 OS << "Bounds: " << Bounds << " ";
2544 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2546 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2547 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2548 OS << "<<Unknown>>";
2558 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2559 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2560 PrintLoopInfo(OS, this, *I);