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/ConstantRange.h"
73 #include "llvm/Support/InstIterator.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/ADT/Statistic.h"
82 RegisterAnalysis<ScalarEvolution>
83 R("scalar-evolution", "Scalar Evolution Analysis");
86 NumBruteForceEvaluations("scalar-evolution",
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
90 NumArrayLenItCounts("scalar-evolution",
91 "Number of trip counts computed with array length");
93 NumTripCountsComputed("scalar-evolution",
94 "Number of loops with predictable loop counts");
96 NumTripCountsNotComputed("scalar-evolution",
97 "Number of loops without predictable loop counts");
99 NumBruteForceTripCountsComputed("scalar-evolution",
100 "Number of loops with trip counts computed by force");
103 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
104 cl::desc("Maximum number of iterations SCEV will "
105 "symbolically execute a constant derived loop"),
109 //===----------------------------------------------------------------------===//
110 // SCEV class definitions
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
114 // Implementation of the SCEV class.
117 void SCEV::dump() const {
121 /// getValueRange - Return the tightest constant bounds that this value is
122 /// known to have. This method is only valid on integer SCEV objects.
123 ConstantRange SCEV::getValueRange() const {
124 const Type *Ty = getType();
125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
126 Ty = Ty->getUnsignedVersion();
127 // Default to a full range if no better information is available.
128 return ConstantRange(getType());
132 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
134 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 SCEVHandle SCEVCouldNotCompute::
150 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc) const {
155 void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
159 bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
164 // SCEVConstants - Only allow the creation of one SCEVConstant for any
165 // particular value. Don't use a SCEVHandle here, or else the object will
167 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
170 SCEVConstant::~SCEVConstant() {
171 SCEVConstants.erase(V);
174 SCEVHandle SCEVConstant::get(ConstantInt *V) {
175 // Make sure that SCEVConstant instances are all unsigned.
176 if (V->getType()->isSigned()) {
177 const Type *NewTy = V->getType()->getUnsignedVersion();
178 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
181 SCEVConstant *&R = SCEVConstants[V];
182 if (R == 0) R = new SCEVConstant(V);
186 ConstantRange SCEVConstant::getValueRange() const {
187 return ConstantRange(V);
190 const Type *SCEVConstant::getType() const { return V->getType(); }
192 void SCEVConstant::print(std::ostream &OS) const {
193 WriteAsOperand(OS, V, false);
196 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
197 // particular input. Don't use a SCEVHandle here, or else the object will
199 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
201 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
202 : SCEV(scTruncate), Op(op), Ty(ty) {
203 assert(Op->getType()->isInteger() && Ty->isInteger() &&
205 "Cannot truncate non-integer value!");
206 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
207 "This is not a truncating conversion!");
210 SCEVTruncateExpr::~SCEVTruncateExpr() {
211 SCEVTruncates.erase(std::make_pair(Op, Ty));
214 ConstantRange SCEVTruncateExpr::getValueRange() const {
215 return getOperand()->getValueRange().truncate(getType());
218 void SCEVTruncateExpr::print(std::ostream &OS) const {
219 OS << "(truncate " << *Op << " to " << *Ty << ")";
222 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223 // particular input. Don't use a SCEVHandle here, or else the object will never
225 static std::map<std::pair<SCEV*, const Type*>,
226 SCEVZeroExtendExpr*> SCEVZeroExtends;
228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
229 : SCEV(scTruncate), Op(op), Ty(ty) {
230 assert(Op->getType()->isInteger() && Ty->isInteger() &&
232 "Cannot zero extend non-integer value!");
233 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
234 "This is not an extending conversion!");
237 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
238 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
241 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
242 return getOperand()->getValueRange().zeroExtend(getType());
245 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
246 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
249 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
250 // particular input. Don't use a SCEVHandle here, or else the object will never
252 static std::map<std::pair<unsigned, std::vector<SCEV*> >,
253 SCEVCommutativeExpr*> SCEVCommExprs;
255 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
256 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
257 std::vector<SCEV*>(Operands.begin(),
261 void SCEVCommutativeExpr::print(std::ostream &OS) const {
262 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
263 const char *OpStr = getOperationStr();
264 OS << "(" << *Operands[0];
265 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
266 OS << OpStr << *Operands[i];
270 SCEVHandle SCEVCommutativeExpr::
271 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
272 const SCEVHandle &Conc) const {
273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
274 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
275 if (H != getOperand(i)) {
276 std::vector<SCEVHandle> NewOps;
277 NewOps.reserve(getNumOperands());
278 for (unsigned j = 0; j != i; ++j)
279 NewOps.push_back(getOperand(j));
281 for (++i; i != e; ++i)
282 NewOps.push_back(getOperand(i)->
283 replaceSymbolicValuesWithConcrete(Sym, Conc));
285 if (isa<SCEVAddExpr>(this))
286 return SCEVAddExpr::get(NewOps);
287 else if (isa<SCEVMulExpr>(this))
288 return SCEVMulExpr::get(NewOps);
290 assert(0 && "Unknown commutative expr!");
297 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
298 // input. Don't use a SCEVHandle here, or else the object will never be
300 static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
302 SCEVUDivExpr::~SCEVUDivExpr() {
303 SCEVUDivs.erase(std::make_pair(LHS, RHS));
306 void SCEVUDivExpr::print(std::ostream &OS) const {
307 OS << "(" << *LHS << " /u " << *RHS << ")";
310 const Type *SCEVUDivExpr::getType() const {
311 const Type *Ty = LHS->getType();
312 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
316 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
317 // particular input. Don't use a SCEVHandle here, or else the object will never
319 static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
320 SCEVAddRecExpr*> SCEVAddRecExprs;
322 SCEVAddRecExpr::~SCEVAddRecExpr() {
323 SCEVAddRecExprs.erase(std::make_pair(L,
324 std::vector<SCEV*>(Operands.begin(),
328 SCEVHandle SCEVAddRecExpr::
329 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
330 const SCEVHandle &Conc) const {
331 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
332 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
333 if (H != getOperand(i)) {
334 std::vector<SCEVHandle> NewOps;
335 NewOps.reserve(getNumOperands());
336 for (unsigned j = 0; j != i; ++j)
337 NewOps.push_back(getOperand(j));
339 for (++i; i != e; ++i)
340 NewOps.push_back(getOperand(i)->
341 replaceSymbolicValuesWithConcrete(Sym, Conc));
343 return get(NewOps, L);
350 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
351 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
352 // contain L and if the start is invariant.
353 return !QueryLoop->contains(L->getHeader()) &&
354 getOperand(0)->isLoopInvariant(QueryLoop);
358 void SCEVAddRecExpr::print(std::ostream &OS) const {
359 OS << "{" << *Operands[0];
360 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
361 OS << ",+," << *Operands[i];
362 OS << "}<" << L->getHeader()->getName() + ">";
365 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
366 // value. Don't use a SCEVHandle here, or else the object will never be
368 static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
370 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
372 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
373 // All non-instruction values are loop invariant. All instructions are loop
374 // invariant if they are not contained in the specified loop.
375 if (Instruction *I = dyn_cast<Instruction>(V))
376 return !L->contains(I->getParent());
380 const Type *SCEVUnknown::getType() const {
384 void SCEVUnknown::print(std::ostream &OS) const {
385 WriteAsOperand(OS, V, false);
388 //===----------------------------------------------------------------------===//
390 //===----------------------------------------------------------------------===//
393 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
394 /// than the complexity of the RHS. This comparator is used to canonicalize
396 struct SCEVComplexityCompare {
397 bool operator()(SCEV *LHS, SCEV *RHS) {
398 return LHS->getSCEVType() < RHS->getSCEVType();
403 /// GroupByComplexity - Given a list of SCEV objects, order them by their
404 /// complexity, and group objects of the same complexity together by value.
405 /// When this routine is finished, we know that any duplicates in the vector are
406 /// consecutive and that complexity is monotonically increasing.
408 /// Note that we go take special precautions to ensure that we get determinstic
409 /// results from this routine. In other words, we don't want the results of
410 /// this to depend on where the addresses of various SCEV objects happened to
413 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
414 if (Ops.size() < 2) return; // Noop
415 if (Ops.size() == 2) {
416 // This is the common case, which also happens to be trivially simple.
418 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
419 std::swap(Ops[0], Ops[1]);
423 // Do the rough sort by complexity.
424 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
426 // Now that we are sorted by complexity, group elements of the same
427 // complexity. Note that this is, at worst, N^2, but the vector is likely to
428 // be extremely short in practice. Note that we take this approach because we
429 // do not want to depend on the addresses of the objects we are grouping.
430 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
432 unsigned Complexity = S->getSCEVType();
434 // If there are any objects of the same complexity and same value as this
436 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
437 if (Ops[j] == S) { // Found a duplicate.
438 // Move it to immediately after i'th element.
439 std::swap(Ops[i+1], Ops[j]);
440 ++i; // no need to rescan it.
441 if (i == e-2) return; // Done!
449 //===----------------------------------------------------------------------===//
450 // Simple SCEV method implementations
451 //===----------------------------------------------------------------------===//
453 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
454 /// specified signed integer value and return a SCEV for the constant.
455 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
458 C = Constant::getNullValue(Ty);
459 else if (Ty->isFloatingPoint())
460 C = ConstantFP::get(Ty, Val);
461 else if (Ty->isSigned())
462 C = ConstantSInt::get(Ty, Val);
464 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
465 C = ConstantExpr::getCast(C, Ty);
467 return SCEVUnknown::get(C);
470 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
471 /// input value to the specified type. If the type must be extended, it is zero
473 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
474 const Type *SrcTy = V->getType();
475 assert(SrcTy->isInteger() && Ty->isInteger() &&
476 "Cannot truncate or zero extend with non-integer arguments!");
477 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
478 return V; // No conversion
479 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
480 return SCEVTruncateExpr::get(V, Ty);
481 return SCEVZeroExtendExpr::get(V, Ty);
484 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
486 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
487 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
488 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
490 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
493 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
495 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
497 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
501 /// PartialFact - Compute V!/(V-NumSteps)!
502 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
503 // Handle this case efficiently, it is common to have constant iteration
504 // counts while computing loop exit values.
505 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
506 uint64_t Val = SC->getValue()->getRawValue();
508 for (; NumSteps; --NumSteps)
509 Result *= Val-(NumSteps-1);
510 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
511 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
514 const Type *Ty = V->getType();
516 return SCEVUnknown::getIntegerSCEV(1, Ty);
518 SCEVHandle Result = V;
519 for (unsigned i = 1; i != NumSteps; ++i)
520 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
521 SCEVUnknown::getIntegerSCEV(i, Ty)));
526 /// evaluateAtIteration - Return the value of this chain of recurrences at
527 /// the specified iteration number. We can evaluate this recurrence by
528 /// multiplying each element in the chain by the binomial coefficient
529 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
531 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
533 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
534 /// Is the binomial equation safe using modular arithmetic??
536 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
537 SCEVHandle Result = getStart();
539 const Type *Ty = It->getType();
540 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
541 SCEVHandle BC = PartialFact(It, i);
543 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
544 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
545 Result = SCEVAddExpr::get(Result, Val);
551 //===----------------------------------------------------------------------===//
552 // SCEV Expression folder implementations
553 //===----------------------------------------------------------------------===//
555 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
556 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
557 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
559 // If the input value is a chrec scev made out of constants, truncate
560 // all of the constants.
561 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
562 std::vector<SCEVHandle> Operands;
563 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
564 // FIXME: This should allow truncation of other expression types!
565 if (isa<SCEVConstant>(AddRec->getOperand(i)))
566 Operands.push_back(get(AddRec->getOperand(i), Ty));
569 if (Operands.size() == AddRec->getNumOperands())
570 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
573 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
574 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
578 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
579 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
580 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
582 // FIXME: If the input value is a chrec scev, and we can prove that the value
583 // did not overflow the old, smaller, value, we can zero extend all of the
584 // operands (often constants). This would allow analysis of something like
585 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
587 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
588 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
592 // get - Get a canonical add expression, or something simpler if possible.
593 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
594 assert(!Ops.empty() && "Cannot get empty add!");
595 if (Ops.size() == 1) return Ops[0];
597 // Sort by complexity, this groups all similar expression types together.
598 GroupByComplexity(Ops);
600 // If there are any constants, fold them together.
602 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
604 assert(Idx < Ops.size());
605 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
606 // We found two constants, fold them together!
607 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
609 Ops[0] = SCEVConstant::get(CI);
610 Ops.erase(Ops.begin()+1); // Erase the folded element
611 if (Ops.size() == 1) return Ops[0];
612 LHSC = cast<SCEVConstant>(Ops[0]);
614 // If we couldn't fold the expression, move to the next constant. Note
615 // that this is impossible to happen in practice because we always
616 // constant fold constant ints to constant ints.
621 // If we are left with a constant zero being added, strip it off.
622 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
623 Ops.erase(Ops.begin());
628 if (Ops.size() == 1) return Ops[0];
630 // Okay, check to see if the same value occurs in the operand list twice. If
631 // so, merge them together into an multiply expression. Since we sorted the
632 // list, these values are required to be adjacent.
633 const Type *Ty = Ops[0]->getType();
634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
636 // Found a match, merge the two values into a multiply, and add any
637 // remaining values to the result.
638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
644 return SCEVAddExpr::get(Ops);
647 // Okay, now we know the first non-constant operand. If there are add
648 // operands they would be next.
649 if (Idx < Ops.size()) {
650 bool DeletedAdd = false;
651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
652 // If we have an add, expand the add operands onto the end of the operands
654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
655 Ops.erase(Ops.begin()+Idx);
659 // If we deleted at least one add, we added operands to the end of the list,
660 // and they are not necessarily sorted. Recurse to resort and resimplify
661 // any operands we just aquired.
666 // Skip over the add expression until we get to a multiply.
667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
670 // If we are adding something to a multiply expression, make sure the
671 // something is not already an operand of the multiply. If so, merge it into
673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
676 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
681 if (Mul->getNumOperands() != 2) {
682 // If the multiply has more than two operands, we must get the
684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
685 MulOps.erase(MulOps.begin()+MulOp);
686 InnerMul = SCEVMulExpr::get(MulOps);
688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
691 if (Ops.size() == 2) return OuterMul;
693 Ops.erase(Ops.begin()+AddOp);
694 Ops.erase(Ops.begin()+Idx-1);
696 Ops.erase(Ops.begin()+Idx);
697 Ops.erase(Ops.begin()+AddOp-1);
699 Ops.push_back(OuterMul);
700 return SCEVAddExpr::get(Ops);
703 // Check this multiply against other multiplies being added together.
704 for (unsigned OtherMulIdx = Idx+1;
705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
708 // If MulOp occurs in OtherMul, we can fold the two multiplies
710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
711 OMulOp != e; ++OMulOp)
712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
715 if (Mul->getNumOperands() != 2) {
716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
717 MulOps.erase(MulOps.begin()+MulOp);
718 InnerMul1 = SCEVMulExpr::get(MulOps);
720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
721 if (OtherMul->getNumOperands() != 2) {
722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
724 MulOps.erase(MulOps.begin()+OMulOp);
725 InnerMul2 = SCEVMulExpr::get(MulOps);
727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
729 if (Ops.size() == 2) return OuterMul;
730 Ops.erase(Ops.begin()+Idx);
731 Ops.erase(Ops.begin()+OtherMulIdx-1);
732 Ops.push_back(OuterMul);
733 return SCEVAddExpr::get(Ops);
739 // If there are any add recurrences in the operands list, see if any other
740 // added values are loop invariant. If so, we can fold them into the
742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
745 // Scan over all recurrences, trying to fold loop invariants into them.
746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
747 // Scan all of the other operands to this add and add them to the vector if
748 // they are loop invariant w.r.t. the recurrence.
749 std::vector<SCEVHandle> LIOps;
750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
751 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
753 LIOps.push_back(Ops[i]);
754 Ops.erase(Ops.begin()+i);
758 // If we found some loop invariants, fold them into the recurrence.
759 if (!LIOps.empty()) {
760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
761 LIOps.push_back(AddRec->getStart());
763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
764 AddRecOps[0] = SCEVAddExpr::get(LIOps);
766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
767 // If all of the other operands were loop invariant, we are done.
768 if (Ops.size() == 1) return NewRec;
770 // Otherwise, add the folded AddRec by the non-liv parts.
771 for (unsigned i = 0;; ++i)
772 if (Ops[i] == AddRec) {
776 return SCEVAddExpr::get(Ops);
779 // Okay, if there weren't any loop invariants to be folded, check to see if
780 // there are multiple AddRec's with the same loop induction variable being
781 // added together. If so, we can fold them.
782 for (unsigned OtherIdx = Idx+1;
783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
784 if (OtherIdx != Idx) {
785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
790 if (i >= NewOps.size()) {
791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
792 OtherAddRec->op_end());
795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
799 if (Ops.size() == 2) return NewAddRec;
801 Ops.erase(Ops.begin()+Idx);
802 Ops.erase(Ops.begin()+OtherIdx-1);
803 Ops.push_back(NewAddRec);
804 return SCEVAddExpr::get(Ops);
808 // Otherwise couldn't fold anything into this recurrence. Move onto the
812 // Okay, it looks like we really DO need an add expr. Check to see if we
813 // already have one, otherwise create a new one.
814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
815 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
817 if (Result == 0) Result = new SCEVAddExpr(Ops);
822 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
823 assert(!Ops.empty() && "Cannot get empty mul!");
825 // Sort by complexity, this groups all similar expression types together.
826 GroupByComplexity(Ops);
828 // If there are any constants, fold them together.
830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
832 // C1*(C2+V) -> C1*C2 + C1*V
834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
835 if (Add->getNumOperands() == 2 &&
836 isa<SCEVConstant>(Add->getOperand(0)))
837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
838 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
843 // We found two constants, fold them together!
844 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
845 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
846 Ops[0] = SCEVConstant::get(CI);
847 Ops.erase(Ops.begin()+1); // Erase the folded element
848 if (Ops.size() == 1) return Ops[0];
849 LHSC = cast<SCEVConstant>(Ops[0]);
851 // If we couldn't fold the expression, move to the next constant. Note
852 // that this is impossible to happen in practice because we always
853 // constant fold constant ints to constant ints.
858 // If we are left with a constant one being multiplied, strip it off.
859 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
860 Ops.erase(Ops.begin());
862 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
863 // If we have a multiply of zero, it will always be zero.
868 // Skip over the add expression until we get to a multiply.
869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
875 // If there are mul operands inline them all into this expression.
876 if (Idx < Ops.size()) {
877 bool DeletedMul = false;
878 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
879 // If we have an mul, expand the mul operands onto the end of the operands
881 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
882 Ops.erase(Ops.begin()+Idx);
886 // If we deleted at least one mul, we added operands to the end of the list,
887 // and they are not necessarily sorted. Recurse to resort and resimplify
888 // any operands we just aquired.
893 // If there are any add recurrences in the operands list, see if any other
894 // added values are loop invariant. If so, we can fold them into the
896 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
899 // Scan over all recurrences, trying to fold loop invariants into them.
900 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
901 // Scan all of the other operands to this mul and add them to the vector if
902 // they are loop invariant w.r.t. the recurrence.
903 std::vector<SCEVHandle> LIOps;
904 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
905 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
906 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
907 LIOps.push_back(Ops[i]);
908 Ops.erase(Ops.begin()+i);
912 // If we found some loop invariants, fold them into the recurrence.
913 if (!LIOps.empty()) {
914 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
915 std::vector<SCEVHandle> NewOps;
916 NewOps.reserve(AddRec->getNumOperands());
917 if (LIOps.size() == 1) {
918 SCEV *Scale = LIOps[0];
919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
920 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
923 std::vector<SCEVHandle> MulOps(LIOps);
924 MulOps.push_back(AddRec->getOperand(i));
925 NewOps.push_back(SCEVMulExpr::get(MulOps));
929 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
931 // If all of the other operands were loop invariant, we are done.
932 if (Ops.size() == 1) return NewRec;
934 // Otherwise, multiply the folded AddRec by the non-liv parts.
935 for (unsigned i = 0;; ++i)
936 if (Ops[i] == AddRec) {
940 return SCEVMulExpr::get(Ops);
943 // Okay, if there weren't any loop invariants to be folded, check to see if
944 // there are multiple AddRec's with the same loop induction variable being
945 // multiplied together. If so, we can fold them.
946 for (unsigned OtherIdx = Idx+1;
947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
948 if (OtherIdx != Idx) {
949 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
950 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
951 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
952 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
953 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
955 SCEVHandle B = F->getStepRecurrence();
956 SCEVHandle D = G->getStepRecurrence();
957 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
958 SCEVMulExpr::get(G, B),
959 SCEVMulExpr::get(B, D));
960 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
962 if (Ops.size() == 2) return NewAddRec;
964 Ops.erase(Ops.begin()+Idx);
965 Ops.erase(Ops.begin()+OtherIdx-1);
966 Ops.push_back(NewAddRec);
967 return SCEVMulExpr::get(Ops);
971 // Otherwise couldn't fold anything into this recurrence. Move onto the
975 // Okay, it looks like we really DO need an mul expr. Check to see if we
976 // already have one, otherwise create a new one.
977 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
978 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
981 Result = new SCEVMulExpr(Ops);
985 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
987 if (RHSC->getValue()->equalsInt(1))
988 return LHS; // X /u 1 --> x
989 if (RHSC->getValue()->isAllOnesValue())
990 return SCEV::getNegativeSCEV(LHS); // X /u -1 --> -x
992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
993 Constant *LHSCV = LHSC->getValue();
994 Constant *RHSCV = RHSC->getValue();
995 if (LHSCV->getType()->isSigned())
996 LHSCV = ConstantExpr::getCast(LHSCV,
997 LHSCV->getType()->getUnsignedVersion());
998 if (RHSCV->getType()->isSigned())
999 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
1000 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
1004 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1006 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
1007 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1012 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1013 /// specified loop. Simplify the expression as much as possible.
1014 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1015 const SCEVHandle &Step, const Loop *L) {
1016 std::vector<SCEVHandle> Operands;
1017 Operands.push_back(Start);
1018 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1019 if (StepChrec->getLoop() == L) {
1020 Operands.insert(Operands.end(), StepChrec->op_begin(),
1021 StepChrec->op_end());
1022 return get(Operands, L);
1025 Operands.push_back(Step);
1026 return get(Operands, L);
1029 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1030 /// specified loop. Simplify the expression as much as possible.
1031 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1033 if (Operands.size() == 1) return Operands[0];
1035 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1036 if (StepC->getValue()->isNullValue()) {
1037 Operands.pop_back();
1038 return get(Operands, L); // { X,+,0 } --> X
1041 SCEVAddRecExpr *&Result =
1042 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1044 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1048 SCEVHandle SCEVUnknown::get(Value *V) {
1049 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1050 return SCEVConstant::get(CI);
1051 SCEVUnknown *&Result = SCEVUnknowns[V];
1052 if (Result == 0) Result = new SCEVUnknown(V);
1057 //===----------------------------------------------------------------------===//
1058 // ScalarEvolutionsImpl Definition and Implementation
1059 //===----------------------------------------------------------------------===//
1061 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1065 struct ScalarEvolutionsImpl {
1066 /// F - The function we are analyzing.
1070 /// LI - The loop information for the function we are currently analyzing.
1074 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1076 SCEVHandle UnknownValue;
1078 /// Scalars - This is a cache of the scalars we have analyzed so far.
1080 std::map<Value*, SCEVHandle> Scalars;
1082 /// IterationCounts - Cache the iteration count of the loops for this
1083 /// function as they are computed.
1084 std::map<const Loop*, SCEVHandle> IterationCounts;
1086 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1087 /// the PHI instructions that we attempt to compute constant evolutions for.
1088 /// This allows us to avoid potentially expensive recomputation of these
1089 /// properties. An instruction maps to null if we are unable to compute its
1091 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1094 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1095 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1097 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1098 /// expression and create a new one.
1099 SCEVHandle getSCEV(Value *V);
1101 /// hasSCEV - Return true if the SCEV for this value has already been
1103 bool hasSCEV(Value *V) const {
1104 return Scalars.count(V);
1107 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1108 /// the specified value.
1109 void setSCEV(Value *V, const SCEVHandle &H) {
1110 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1111 assert(isNew && "This entry already existed!");
1115 /// getSCEVAtScope - Compute the value of the specified expression within
1116 /// the indicated loop (which may be null to indicate in no loop). If the
1117 /// expression cannot be evaluated, return UnknownValue itself.
1118 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1121 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1122 /// an analyzable loop-invariant iteration count.
1123 bool hasLoopInvariantIterationCount(const Loop *L);
1125 /// getIterationCount - If the specified loop has a predictable iteration
1126 /// count, return it. Note that it is not valid to call this method on a
1127 /// loop without a loop-invariant iteration count.
1128 SCEVHandle getIterationCount(const Loop *L);
1130 /// deleteInstructionFromRecords - This method should be called by the
1131 /// client before it removes an instruction from the program, to make sure
1132 /// that no dangling references are left around.
1133 void deleteInstructionFromRecords(Instruction *I);
1136 /// createSCEV - We know that there is no SCEV for the specified value.
1137 /// Analyze the expression.
1138 SCEVHandle createSCEV(Value *V);
1139 SCEVHandle createNodeForCast(CastInst *CI);
1141 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1143 SCEVHandle createNodeForPHI(PHINode *PN);
1145 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1146 /// for the specified instruction and replaces any references to the
1147 /// symbolic value SymName with the specified value. This is used during
1149 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1150 const SCEVHandle &SymName,
1151 const SCEVHandle &NewVal);
1153 /// ComputeIterationCount - Compute the number of times the specified loop
1155 SCEVHandle ComputeIterationCount(const Loop *L);
1157 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1158 /// 'setcc load X, cst', try to se if we can compute the trip count.
1159 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1162 unsigned SetCCOpcode);
1164 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1165 /// constant number of times (the condition evolves only from constants),
1166 /// try to evaluate a few iterations of the loop until we get the exit
1167 /// condition gets a value of ExitWhen (true or false). If we cannot
1168 /// evaluate the trip count of the loop, return UnknownValue.
1169 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1172 /// HowFarToZero - Return the number of times a backedge comparing the
1173 /// specified value to zero will execute. If not computable, return
1175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1177 /// HowFarToNonZero - Return the number of times a backedge checking the
1178 /// specified value for nonzero will execute. If not computable, return
1180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1182 /// HowManyLessThans - Return the number of times a backedge containing the
1183 /// specified less-than comparison will execute. If not computable, return
1185 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1187 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1188 /// in the header of its containing loop, we know the loop executes a
1189 /// constant number of times, and the PHI node is just a recurrence
1190 /// involving constants, fold it.
1191 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1196 //===----------------------------------------------------------------------===//
1197 // Basic SCEV Analysis and PHI Idiom Recognition Code
1200 /// deleteInstructionFromRecords - This method should be called by the
1201 /// client before it removes an instruction from the program, to make sure
1202 /// that no dangling references are left around.
1203 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1205 if (PHINode *PN = dyn_cast<PHINode>(I))
1206 ConstantEvolutionLoopExitValue.erase(PN);
1210 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1211 /// expression and create a new one.
1212 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1213 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1215 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1216 if (I != Scalars.end()) return I->second;
1217 SCEVHandle S = createSCEV(V);
1218 Scalars.insert(std::make_pair(V, S));
1222 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1223 /// the specified instruction and replaces any references to the symbolic value
1224 /// SymName with the specified value. This is used during PHI resolution.
1225 void ScalarEvolutionsImpl::
1226 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1227 const SCEVHandle &NewVal) {
1228 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1229 if (SI == Scalars.end()) return;
1232 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1233 if (NV == SI->second) return; // No change.
1235 SI->second = NV; // Update the scalars map!
1237 // Any instruction values that use this instruction might also need to be
1239 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1241 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1244 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1245 /// a loop header, making it a potential recurrence, or it doesn't.
1247 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1248 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1249 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1250 if (L->getHeader() == PN->getParent()) {
1251 // If it lives in the loop header, it has two incoming values, one
1252 // from outside the loop, and one from inside.
1253 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1254 unsigned BackEdge = IncomingEdge^1;
1256 // While we are analyzing this PHI node, handle its value symbolically.
1257 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1258 assert(Scalars.find(PN) == Scalars.end() &&
1259 "PHI node already processed?");
1260 Scalars.insert(std::make_pair(PN, SymbolicName));
1262 // Using this symbolic name for the PHI, analyze the value coming around
1264 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1266 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1267 // has a special value for the first iteration of the loop.
1269 // If the value coming around the backedge is an add with the symbolic
1270 // value we just inserted, then we found a simple induction variable!
1271 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1272 // If there is a single occurrence of the symbolic value, replace it
1273 // with a recurrence.
1274 unsigned FoundIndex = Add->getNumOperands();
1275 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1276 if (Add->getOperand(i) == SymbolicName)
1277 if (FoundIndex == e) {
1282 if (FoundIndex != Add->getNumOperands()) {
1283 // Create an add with everything but the specified operand.
1284 std::vector<SCEVHandle> Ops;
1285 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1286 if (i != FoundIndex)
1287 Ops.push_back(Add->getOperand(i));
1288 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1290 // This is not a valid addrec if the step amount is varying each
1291 // loop iteration, but is not itself an addrec in this loop.
1292 if (Accum->isLoopInvariant(L) ||
1293 (isa<SCEVAddRecExpr>(Accum) &&
1294 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1295 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1296 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1298 // Okay, for the entire analysis of this edge we assumed the PHI
1299 // to be symbolic. We now need to go back and update all of the
1300 // entries for the scalars that use the PHI (except for the PHI
1301 // itself) to use the new analyzed value instead of the "symbolic"
1303 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1309 return SymbolicName;
1312 // If it's not a loop phi, we can't handle it yet.
1313 return SCEVUnknown::get(PN);
1316 /// createNodeForCast - Handle the various forms of casts that we support.
1318 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1319 const Type *SrcTy = CI->getOperand(0)->getType();
1320 const Type *DestTy = CI->getType();
1322 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1323 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1324 return getSCEV(CI->getOperand(0));
1326 if (SrcTy->isInteger() && DestTy->isInteger()) {
1327 // Otherwise, if this is a truncating integer cast, we can represent this
1329 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1330 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1331 CI->getType()->getUnsignedVersion());
1332 if (SrcTy->isUnsigned() &&
1333 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1334 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1335 CI->getType()->getUnsignedVersion());
1338 // If this is an sign or zero extending cast and we can prove that the value
1339 // will never overflow, we could do similar transformations.
1341 // Otherwise, we can't handle this cast!
1342 return SCEVUnknown::get(CI);
1346 /// createSCEV - We know that there is no SCEV for the specified value.
1347 /// Analyze the expression.
1349 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1350 if (Instruction *I = dyn_cast<Instruction>(V)) {
1351 switch (I->getOpcode()) {
1352 case Instruction::Add:
1353 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1354 getSCEV(I->getOperand(1)));
1355 case Instruction::Mul:
1356 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1357 getSCEV(I->getOperand(1)));
1358 case Instruction::Div:
1359 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1360 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1361 getSCEV(I->getOperand(1)));
1364 case Instruction::Sub:
1365 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1366 getSCEV(I->getOperand(1)));
1368 case Instruction::Shl:
1369 // Turn shift left of a constant amount into a multiply.
1370 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1371 Constant *X = ConstantInt::get(V->getType(), 1);
1372 X = ConstantExpr::getShl(X, SA);
1373 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1377 case Instruction::Shr:
1378 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1379 if (V->getType()->isUnsigned()) {
1380 Constant *X = ConstantInt::get(V->getType(), 1);
1381 X = ConstantExpr::getShl(X, SA);
1382 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1386 case Instruction::Cast:
1387 return createNodeForCast(cast<CastInst>(I));
1389 case Instruction::PHI:
1390 return createNodeForPHI(cast<PHINode>(I));
1392 default: // We cannot analyze this expression.
1397 return SCEVUnknown::get(V);
1402 //===----------------------------------------------------------------------===//
1403 // Iteration Count Computation Code
1406 /// getIterationCount - If the specified loop has a predictable iteration
1407 /// count, return it. Note that it is not valid to call this method on a
1408 /// loop without a loop-invariant iteration count.
1409 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1410 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1411 if (I == IterationCounts.end()) {
1412 SCEVHandle ItCount = ComputeIterationCount(L);
1413 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1414 if (ItCount != UnknownValue) {
1415 assert(ItCount->isLoopInvariant(L) &&
1416 "Computed trip count isn't loop invariant for loop!");
1417 ++NumTripCountsComputed;
1418 } else if (isa<PHINode>(L->getHeader()->begin())) {
1419 // Only count loops that have phi nodes as not being computable.
1420 ++NumTripCountsNotComputed;
1426 /// ComputeIterationCount - Compute the number of times the specified loop
1428 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1429 // If the loop has a non-one exit block count, we can't analyze it.
1430 std::vector<BasicBlock*> ExitBlocks;
1431 L->getExitBlocks(ExitBlocks);
1432 if (ExitBlocks.size() != 1) return UnknownValue;
1434 // Okay, there is one exit block. Try to find the condition that causes the
1435 // loop to be exited.
1436 BasicBlock *ExitBlock = ExitBlocks[0];
1438 BasicBlock *ExitingBlock = 0;
1439 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1441 if (L->contains(*PI)) {
1442 if (ExitingBlock == 0)
1445 return UnknownValue; // More than one block exiting!
1447 assert(ExitingBlock && "No exits from loop, something is broken!");
1449 // Okay, we've computed the exiting block. See what condition causes us to
1452 // FIXME: we should be able to handle switch instructions (with a single exit)
1453 // FIXME: We should handle cast of int to bool as well
1454 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1455 if (ExitBr == 0) return UnknownValue;
1456 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1457 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1458 if (ExitCond == 0) // Not a setcc
1459 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1460 ExitBr->getSuccessor(0) == ExitBlock);
1462 // If the condition was exit on true, convert the condition to exit on false.
1463 Instruction::BinaryOps Cond;
1464 if (ExitBr->getSuccessor(1) == ExitBlock)
1465 Cond = ExitCond->getOpcode();
1467 Cond = ExitCond->getInverseCondition();
1469 // Handle common loops like: for (X = "string"; *X; ++X)
1470 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1471 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1473 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1474 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1477 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1478 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1480 // Try to evaluate any dependencies out of the loop.
1481 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1482 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1483 Tmp = getSCEVAtScope(RHS, L);
1484 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1486 // At this point, we would like to compute how many iterations of the loop the
1487 // predicate will return true for these inputs.
1488 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1489 // If there is a constant, force it into the RHS.
1490 std::swap(LHS, RHS);
1491 Cond = SetCondInst::getSwappedCondition(Cond);
1494 // FIXME: think about handling pointer comparisons! i.e.:
1495 // while (P != P+100) ++P;
1497 // If we have a comparison of a chrec against a constant, try to use value
1498 // ranges to answer this query.
1499 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1500 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1501 if (AddRec->getLoop() == L) {
1502 // Form the comparison range using the constant of the correct type so
1503 // that the ConstantRange class knows to do a signed or unsigned
1505 ConstantInt *CompVal = RHSC->getValue();
1506 const Type *RealTy = ExitCond->getOperand(0)->getType();
1507 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1509 // Form the constant range.
1510 ConstantRange CompRange(Cond, CompVal);
1512 // Now that we have it, if it's signed, convert it to an unsigned
1514 if (CompRange.getLower()->getType()->isSigned()) {
1515 const Type *NewTy = RHSC->getValue()->getType();
1516 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1517 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1518 CompRange = ConstantRange(NewL, NewU);
1521 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1522 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1527 case Instruction::SetNE: // while (X != Y)
1528 // Convert to: while (X-Y != 0)
1529 if (LHS->getType()->isInteger()) {
1530 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1531 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1534 case Instruction::SetEQ:
1535 // Convert to: while (X-Y == 0) // while (X == Y)
1536 if (LHS->getType()->isInteger()) {
1537 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1538 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1541 case Instruction::SetLT:
1542 if (LHS->getType()->isInteger() &&
1543 ExitCond->getOperand(0)->getType()->isSigned()) {
1544 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1545 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1548 case Instruction::SetGT:
1549 if (LHS->getType()->isInteger() &&
1550 ExitCond->getOperand(0)->getType()->isSigned()) {
1551 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1552 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1557 std::cerr << "ComputeIterationCount ";
1558 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1559 std::cerr << "[unsigned] ";
1560 std::cerr << *LHS << " "
1561 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1566 return ComputeIterationCountExhaustively(L, ExitCond,
1567 ExitBr->getSuccessor(0) == ExitBlock);
1570 static ConstantInt *
1571 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1572 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1573 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1574 assert(isa<SCEVConstant>(Val) &&
1575 "Evaluation of SCEV at constant didn't fold correctly?");
1576 return cast<SCEVConstant>(Val)->getValue();
1579 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1580 /// and a GEP expression (missing the pointer index) indexing into it, return
1581 /// the addressed element of the initializer or null if the index expression is
1584 GetAddressedElementFromGlobal(GlobalVariable *GV,
1585 const std::vector<ConstantInt*> &Indices) {
1586 Constant *Init = GV->getInitializer();
1587 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1588 uint64_t Idx = Indices[i]->getRawValue();
1589 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1590 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1591 Init = cast<Constant>(CS->getOperand(Idx));
1592 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1593 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1594 Init = cast<Constant>(CA->getOperand(Idx));
1595 } else if (isa<ConstantAggregateZero>(Init)) {
1596 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1597 assert(Idx < STy->getNumElements() && "Bad struct index!");
1598 Init = Constant::getNullValue(STy->getElementType(Idx));
1599 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1600 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1601 Init = Constant::getNullValue(ATy->getElementType());
1603 assert(0 && "Unknown constant aggregate type!");
1607 return 0; // Unknown initializer type
1613 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1614 /// 'setcc load X, cst', try to se if we can compute the trip count.
1615 SCEVHandle ScalarEvolutionsImpl::
1616 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1617 const Loop *L, unsigned SetCCOpcode) {
1618 if (LI->isVolatile()) return UnknownValue;
1620 // Check to see if the loaded pointer is a getelementptr of a global.
1621 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1622 if (!GEP) return UnknownValue;
1624 // Make sure that it is really a constant global we are gepping, with an
1625 // initializer, and make sure the first IDX is really 0.
1626 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1627 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1628 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1629 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1630 return UnknownValue;
1632 // Okay, we allow one non-constant index into the GEP instruction.
1634 std::vector<ConstantInt*> Indexes;
1635 unsigned VarIdxNum = 0;
1636 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1637 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1638 Indexes.push_back(CI);
1639 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1640 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1641 VarIdx = GEP->getOperand(i);
1643 Indexes.push_back(0);
1646 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1647 // Check to see if X is a loop variant variable value now.
1648 SCEVHandle Idx = getSCEV(VarIdx);
1649 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1650 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1652 // We can only recognize very limited forms of loop index expressions, in
1653 // particular, only affine AddRec's like {C1,+,C2}.
1654 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1655 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1656 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1657 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1658 return UnknownValue;
1660 unsigned MaxSteps = MaxBruteForceIterations;
1661 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1662 ConstantUInt *ItCst =
1663 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1664 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1666 // Form the GEP offset.
1667 Indexes[VarIdxNum] = Val;
1669 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1670 if (Result == 0) break; // Cannot compute!
1672 // Evaluate the condition for this iteration.
1673 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1674 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1675 if (Result == ConstantBool::False) {
1677 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1678 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1681 ++NumArrayLenItCounts;
1682 return SCEVConstant::get(ItCst); // Found terminating iteration!
1685 return UnknownValue;
1689 /// CanConstantFold - Return true if we can constant fold an instruction of the
1690 /// specified type, assuming that all operands were constants.
1691 static bool CanConstantFold(const Instruction *I) {
1692 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1693 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1696 if (const CallInst *CI = dyn_cast<CallInst>(I))
1697 if (const Function *F = CI->getCalledFunction())
1698 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1702 /// ConstantFold - Constant fold an instruction of the specified type with the
1703 /// specified constant operands. This function may modify the operands vector.
1704 static Constant *ConstantFold(const Instruction *I,
1705 std::vector<Constant*> &Operands) {
1706 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1707 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1709 switch (I->getOpcode()) {
1710 case Instruction::Cast:
1711 return ConstantExpr::getCast(Operands[0], I->getType());
1712 case Instruction::Select:
1713 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1714 case Instruction::Call:
1715 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1716 Operands.erase(Operands.begin());
1717 return ConstantFoldCall(cast<Function>(GV), Operands);
1721 case Instruction::GetElementPtr:
1722 Constant *Base = Operands[0];
1723 Operands.erase(Operands.begin());
1724 return ConstantExpr::getGetElementPtr(Base, Operands);
1730 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1731 /// in the loop that V is derived from. We allow arbitrary operations along the
1732 /// way, but the operands of an operation must either be constants or a value
1733 /// derived from a constant PHI. If this expression does not fit with these
1734 /// constraints, return null.
1735 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1736 // If this is not an instruction, or if this is an instruction outside of the
1737 // loop, it can't be derived from a loop PHI.
1738 Instruction *I = dyn_cast<Instruction>(V);
1739 if (I == 0 || !L->contains(I->getParent())) return 0;
1741 if (PHINode *PN = dyn_cast<PHINode>(I))
1742 if (L->getHeader() == I->getParent())
1745 // We don't currently keep track of the control flow needed to evaluate
1746 // PHIs, so we cannot handle PHIs inside of loops.
1749 // If we won't be able to constant fold this expression even if the operands
1750 // are constants, return early.
1751 if (!CanConstantFold(I)) return 0;
1753 // Otherwise, we can evaluate this instruction if all of its operands are
1754 // constant or derived from a PHI node themselves.
1756 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1757 if (!(isa<Constant>(I->getOperand(Op)) ||
1758 isa<GlobalValue>(I->getOperand(Op)))) {
1759 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1760 if (P == 0) return 0; // Not evolving from PHI
1764 return 0; // Evolving from multiple different PHIs.
1767 // This is a expression evolving from a constant PHI!
1771 /// EvaluateExpression - Given an expression that passes the
1772 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1773 /// in the loop has the value PHIVal. If we can't fold this expression for some
1774 /// reason, return null.
1775 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1776 if (isa<PHINode>(V)) return PHIVal;
1777 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1779 if (Constant *C = dyn_cast<Constant>(V)) return C;
1780 Instruction *I = cast<Instruction>(V);
1782 std::vector<Constant*> Operands;
1783 Operands.resize(I->getNumOperands());
1785 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1786 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1787 if (Operands[i] == 0) return 0;
1790 return ConstantFold(I, Operands);
1793 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1794 /// in the header of its containing loop, we know the loop executes a
1795 /// constant number of times, and the PHI node is just a recurrence
1796 /// involving constants, fold it.
1797 Constant *ScalarEvolutionsImpl::
1798 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1799 std::map<PHINode*, Constant*>::iterator I =
1800 ConstantEvolutionLoopExitValue.find(PN);
1801 if (I != ConstantEvolutionLoopExitValue.end())
1804 if (Its > MaxBruteForceIterations)
1805 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1807 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1809 // Since the loop is canonicalized, the PHI node must have two entries. One
1810 // entry must be a constant (coming in from outside of the loop), and the
1811 // second must be derived from the same PHI.
1812 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1813 Constant *StartCST =
1814 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1816 return RetVal = 0; // Must be a constant.
1818 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1819 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1821 return RetVal = 0; // Not derived from same PHI.
1823 // Execute the loop symbolically to determine the exit value.
1824 unsigned IterationNum = 0;
1825 unsigned NumIterations = Its;
1826 if (NumIterations != Its)
1827 return RetVal = 0; // More than 2^32 iterations??
1829 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1830 if (IterationNum == NumIterations)
1831 return RetVal = PHIVal; // Got exit value!
1833 // Compute the value of the PHI node for the next iteration.
1834 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1835 if (NextPHI == PHIVal)
1836 return RetVal = NextPHI; // Stopped evolving!
1838 return 0; // Couldn't evaluate!
1843 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1844 /// constant number of times (the condition evolves only from constants),
1845 /// try to evaluate a few iterations of the loop until we get the exit
1846 /// condition gets a value of ExitWhen (true or false). If we cannot
1847 /// evaluate the trip count of the loop, return UnknownValue.
1848 SCEVHandle ScalarEvolutionsImpl::
1849 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1850 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1851 if (PN == 0) return UnknownValue;
1853 // Since the loop is canonicalized, the PHI node must have two entries. One
1854 // entry must be a constant (coming in from outside of the loop), and the
1855 // second must be derived from the same PHI.
1856 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1857 Constant *StartCST =
1858 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1859 if (StartCST == 0) return UnknownValue; // Must be a constant.
1861 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1862 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1863 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1865 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1866 // the loop symbolically to determine when the condition gets a value of
1868 unsigned IterationNum = 0;
1869 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1870 for (Constant *PHIVal = StartCST;
1871 IterationNum != MaxIterations; ++IterationNum) {
1872 ConstantBool *CondVal =
1873 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1874 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1876 if (CondVal->getValue() == ExitWhen) {
1877 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1878 ++NumBruteForceTripCountsComputed;
1879 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1882 // Compute the value of the PHI node for the next iteration.
1883 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1884 if (NextPHI == 0 || NextPHI == PHIVal)
1885 return UnknownValue; // Couldn't evaluate or not making progress...
1889 // Too many iterations were needed to evaluate.
1890 return UnknownValue;
1893 /// getSCEVAtScope - Compute the value of the specified expression within the
1894 /// indicated loop (which may be null to indicate in no loop). If the
1895 /// expression cannot be evaluated, return UnknownValue.
1896 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1897 // FIXME: this should be turned into a virtual method on SCEV!
1899 if (isa<SCEVConstant>(V)) return V;
1901 // If this instruction is evolves from a constant-evolving PHI, compute the
1902 // exit value from the loop without using SCEVs.
1903 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1904 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1905 const Loop *LI = this->LI[I->getParent()];
1906 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1907 if (PHINode *PN = dyn_cast<PHINode>(I))
1908 if (PN->getParent() == LI->getHeader()) {
1909 // Okay, there is no closed form solution for the PHI node. Check
1910 // to see if the loop that contains it has a known iteration count.
1911 // If so, we may be able to force computation of the exit value.
1912 SCEVHandle IterationCount = getIterationCount(LI);
1913 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1914 // Okay, we know how many times the containing loop executes. If
1915 // this is a constant evolving PHI node, get the final value at
1916 // the specified iteration number.
1917 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1918 ICC->getValue()->getRawValue(),
1920 if (RV) return SCEVUnknown::get(RV);
1924 // Okay, this is a some expression that we cannot symbolically evaluate
1925 // into a SCEV. Check to see if it's possible to symbolically evaluate
1926 // the arguments into constants, and if see, try to constant propagate the
1927 // result. This is particularly useful for computing loop exit values.
1928 if (CanConstantFold(I)) {
1929 std::vector<Constant*> Operands;
1930 Operands.reserve(I->getNumOperands());
1931 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1932 Value *Op = I->getOperand(i);
1933 if (Constant *C = dyn_cast<Constant>(Op)) {
1934 Operands.push_back(C);
1936 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1937 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1938 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1940 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1941 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1942 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1950 return SCEVUnknown::get(ConstantFold(I, Operands));
1954 // This is some other type of SCEVUnknown, just return it.
1958 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1959 // Avoid performing the look-up in the common case where the specified
1960 // expression has no loop-variant portions.
1961 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1962 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1963 if (OpAtScope != Comm->getOperand(i)) {
1964 if (OpAtScope == UnknownValue) return UnknownValue;
1965 // Okay, at least one of these operands is loop variant but might be
1966 // foldable. Build a new instance of the folded commutative expression.
1967 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1968 NewOps.push_back(OpAtScope);
1970 for (++i; i != e; ++i) {
1971 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1972 if (OpAtScope == UnknownValue) return UnknownValue;
1973 NewOps.push_back(OpAtScope);
1975 if (isa<SCEVAddExpr>(Comm))
1976 return SCEVAddExpr::get(NewOps);
1977 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1978 return SCEVMulExpr::get(NewOps);
1981 // If we got here, all operands are loop invariant.
1985 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1986 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1987 if (LHS == UnknownValue) return LHS;
1988 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1989 if (RHS == UnknownValue) return RHS;
1990 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1991 return UDiv; // must be loop invariant
1992 return SCEVUDivExpr::get(LHS, RHS);
1995 // If this is a loop recurrence for a loop that does not contain L, then we
1996 // are dealing with the final value computed by the loop.
1997 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1998 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1999 // To evaluate this recurrence, we need to know how many times the AddRec
2000 // loop iterates. Compute this now.
2001 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2002 if (IterationCount == UnknownValue) return UnknownValue;
2003 IterationCount = getTruncateOrZeroExtend(IterationCount,
2006 // If the value is affine, simplify the expression evaluation to just
2007 // Start + Step*IterationCount.
2008 if (AddRec->isAffine())
2009 return SCEVAddExpr::get(AddRec->getStart(),
2010 SCEVMulExpr::get(IterationCount,
2011 AddRec->getOperand(1)));
2013 // Otherwise, evaluate it the hard way.
2014 return AddRec->evaluateAtIteration(IterationCount);
2016 return UnknownValue;
2019 //assert(0 && "Unknown SCEV type!");
2020 return UnknownValue;
2024 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2025 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2026 /// might be the same) or two SCEVCouldNotCompute objects.
2028 static std::pair<SCEVHandle,SCEVHandle>
2029 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2030 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2031 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2032 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2033 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2035 // We currently can only solve this if the coefficients are constants.
2036 if (!L || !M || !N) {
2037 SCEV *CNC = new SCEVCouldNotCompute();
2038 return std::make_pair(CNC, CNC);
2041 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2043 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2044 Constant *C = L->getValue();
2045 // The B coefficient is M-N/2
2046 Constant *B = ConstantExpr::getSub(M->getValue(),
2047 ConstantExpr::getDiv(N->getValue(),
2049 // The A coefficient is N/2
2050 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2052 // Compute the B^2-4ac term.
2053 Constant *SqrtTerm =
2054 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2055 ConstantExpr::getMul(A, C));
2056 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2058 // Compute floor(sqrt(B^2-4ac))
2059 ConstantUInt *SqrtVal =
2060 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2061 SqrtTerm->getType()->getUnsignedVersion()));
2062 uint64_t SqrtValV = SqrtVal->getValue();
2063 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2064 // The square root might not be precise for arbitrary 64-bit integer
2065 // values. Do some sanity checks to ensure it's correct.
2066 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2067 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2068 SCEV *CNC = new SCEVCouldNotCompute();
2069 return std::make_pair(CNC, CNC);
2072 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2073 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2075 Constant *NegB = ConstantExpr::getNeg(B);
2076 Constant *TwoA = ConstantExpr::getMul(A, Two);
2078 // The divisions must be performed as signed divisions.
2079 const Type *SignedTy = NegB->getType()->getSignedVersion();
2080 NegB = ConstantExpr::getCast(NegB, SignedTy);
2081 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2082 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2084 Constant *Solution1 =
2085 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2086 Constant *Solution2 =
2087 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2088 return std::make_pair(SCEVUnknown::get(Solution1),
2089 SCEVUnknown::get(Solution2));
2092 /// HowFarToZero - Return the number of times a backedge comparing the specified
2093 /// value to zero will execute. If not computable, return UnknownValue
2094 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2095 // If the value is a constant
2096 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2097 // If the value is already zero, the branch will execute zero times.
2098 if (C->getValue()->isNullValue()) return C;
2099 return UnknownValue; // Otherwise it will loop infinitely.
2102 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2103 if (!AddRec || AddRec->getLoop() != L)
2104 return UnknownValue;
2106 if (AddRec->isAffine()) {
2107 // If this is an affine expression the execution count of this branch is
2110 // (0 - Start/Step) iff Start % Step == 0
2112 // Get the initial value for the loop.
2113 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2114 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2115 SCEVHandle Step = AddRec->getOperand(1);
2117 Step = getSCEVAtScope(Step, L->getParentLoop());
2119 // Figure out if Start % Step == 0.
2120 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2121 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2122 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2123 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
2124 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2125 return Start; // 0 - Start/-1 == Start
2127 // Check to see if Start is divisible by SC with no remainder.
2128 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2129 ConstantInt *StartCC = StartC->getValue();
2130 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2131 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2132 if (Rem->isNullValue()) {
2133 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2134 return SCEVUnknown::get(Result);
2138 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2139 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2140 // the quadratic equation to solve it.
2141 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2142 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2143 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2146 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2147 << " sol#2: " << *R2 << "\n";
2149 // Pick the smallest positive root value.
2150 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2151 if (ConstantBool *CB =
2152 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2154 if (CB != ConstantBool::True)
2155 std::swap(R1, R2); // R1 is the minimum root now.
2157 // We can only use this value if the chrec ends up with an exact zero
2158 // value at this index. When solving for "X*X != 5", for example, we
2159 // should not accept a root of 2.
2160 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2161 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2162 if (EvalVal->getValue()->isNullValue())
2163 return R1; // We found a quadratic root!
2168 return UnknownValue;
2171 /// HowFarToNonZero - Return the number of times a backedge checking the
2172 /// specified value for nonzero will execute. If not computable, return
2174 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2175 // Loops that look like: while (X == 0) are very strange indeed. We don't
2176 // handle them yet except for the trivial case. This could be expanded in the
2177 // future as needed.
2179 // If the value is a constant, check to see if it is known to be non-zero
2180 // already. If so, the backedge will execute zero times.
2181 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2182 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2183 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2184 if (NonZero == ConstantBool::True)
2185 return getSCEV(Zero);
2186 return UnknownValue; // Otherwise it will loop infinitely.
2189 // We could implement others, but I really doubt anyone writes loops like
2190 // this, and if they did, they would already be constant folded.
2191 return UnknownValue;
2194 /// HowManyLessThans - Return the number of times a backedge containing the
2195 /// specified less-than comparison will execute. If not computable, return
2197 SCEVHandle ScalarEvolutionsImpl::
2198 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2199 // Only handle: "ADDREC < LoopInvariant".
2200 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2202 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2203 if (!AddRec || AddRec->getLoop() != L)
2204 return UnknownValue;
2206 if (AddRec->isAffine()) {
2207 // FORNOW: We only support unit strides.
2208 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2209 if (AddRec->getOperand(1) != One)
2210 return UnknownValue;
2212 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2213 // know that m is >= n on input to the loop. If it is, the condition return
2214 // true zero times. What we really should return, for full generality, is
2215 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2216 // canonical loop form: most do-loops will have a check that dominates the
2217 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2218 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2220 // Search for the check.
2221 BasicBlock *Preheader = L->getLoopPreheader();
2222 BasicBlock *PreheaderDest = L->getHeader();
2223 if (Preheader == 0) return UnknownValue;
2225 BranchInst *LoopEntryPredicate =
2226 dyn_cast<BranchInst>(Preheader->getTerminator());
2227 if (!LoopEntryPredicate) return UnknownValue;
2229 // This might be a critical edge broken out. If the loop preheader ends in
2230 // an unconditional branch to the loop, check to see if the preheader has a
2231 // single predecessor, and if so, look for its terminator.
2232 while (LoopEntryPredicate->isUnconditional()) {
2233 PreheaderDest = Preheader;
2234 Preheader = Preheader->getSinglePredecessor();
2235 if (!Preheader) return UnknownValue; // Multiple preds.
2237 LoopEntryPredicate =
2238 dyn_cast<BranchInst>(Preheader->getTerminator());
2239 if (!LoopEntryPredicate) return UnknownValue;
2242 // Now that we found a conditional branch that dominates the loop, check to
2243 // see if it is the comparison we are looking for.
2244 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2245 if (!SCI) return UnknownValue;
2246 Value *PreCondLHS = SCI->getOperand(0);
2247 Value *PreCondRHS = SCI->getOperand(1);
2248 Instruction::BinaryOps Cond;
2249 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2250 Cond = SCI->getOpcode();
2252 Cond = SCI->getInverseCondition();
2255 case Instruction::SetGT:
2256 std::swap(PreCondLHS, PreCondRHS);
2257 Cond = Instruction::SetLT;
2259 case Instruction::SetLT:
2260 if (PreCondLHS->getType()->isInteger() &&
2261 PreCondLHS->getType()->isSigned()) {
2262 if (RHS != getSCEV(PreCondRHS))
2263 return UnknownValue; // Not a comparison against 'm'.
2265 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2266 != getSCEV(PreCondLHS))
2267 return UnknownValue; // Not a comparison against 'n-1'.
2270 return UnknownValue;
2275 //std::cerr << "Computed Loop Trip Count as: " <<
2276 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2277 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2280 return UnknownValue;
2283 /// getNumIterationsInRange - Return the number of iterations of this loop that
2284 /// produce values in the specified constant range. Another way of looking at
2285 /// this is that it returns the first iteration number where the value is not in
2286 /// the condition, thus computing the exit count. If the iteration count can't
2287 /// be computed, an instance of SCEVCouldNotCompute is returned.
2288 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2289 if (Range.isFullSet()) // Infinite loop.
2290 return new SCEVCouldNotCompute();
2292 // If the start is a non-zero constant, shift the range to simplify things.
2293 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2294 if (!SC->getValue()->isNullValue()) {
2295 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2296 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2297 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2298 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2299 return ShiftedAddRec->getNumIterationsInRange(
2300 Range.subtract(SC->getValue()));
2301 // This is strange and shouldn't happen.
2302 return new SCEVCouldNotCompute();
2305 // The only time we can solve this is when we have all constant indices.
2306 // Otherwise, we cannot determine the overflow conditions.
2307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2308 if (!isa<SCEVConstant>(getOperand(i)))
2309 return new SCEVCouldNotCompute();
2312 // Okay at this point we know that all elements of the chrec are constants and
2313 // that the start element is zero.
2315 // First check to see if the range contains zero. If not, the first
2317 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2318 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2321 // If this is an affine expression then we have this situation:
2322 // Solve {0,+,A} in Range === Ax in Range
2324 // Since we know that zero is in the range, we know that the upper value of
2325 // the range must be the first possible exit value. Also note that we
2326 // already checked for a full range.
2327 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2328 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2329 ConstantInt *One = ConstantInt::get(getType(), 1);
2331 // The exit value should be (Upper+A-1)/A.
2332 Constant *ExitValue = Upper;
2334 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2335 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2337 assert(isa<ConstantInt>(ExitValue) &&
2338 "Constant folding of integers not implemented?");
2340 // Evaluate at the exit value. If we really did fall out of the valid
2341 // range, then we computed our trip count, otherwise wrap around or other
2342 // things must have happened.
2343 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2344 if (Range.contains(Val))
2345 return new SCEVCouldNotCompute(); // Something strange happened
2347 // Ensure that the previous value is in the range. This is a sanity check.
2348 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2349 ConstantExpr::getSub(ExitValue, One))) &&
2350 "Linear scev computation is off in a bad way!");
2351 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2352 } else if (isQuadratic()) {
2353 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2354 // quadratic equation to solve it. To do this, we must frame our problem in
2355 // terms of figuring out when zero is crossed, instead of when
2356 // Range.getUpper() is crossed.
2357 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2358 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2359 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2361 // Next, solve the constructed addrec
2362 std::pair<SCEVHandle,SCEVHandle> Roots =
2363 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2364 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2365 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2367 // Pick the smallest positive root value.
2368 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2369 if (ConstantBool *CB =
2370 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2372 if (CB != ConstantBool::True)
2373 std::swap(R1, R2); // R1 is the minimum root now.
2375 // Make sure the root is not off by one. The returned iteration should
2376 // not be in the range, but the previous one should be. When solving
2377 // for "X*X < 5", for example, we should not return a root of 2.
2378 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2380 if (Range.contains(R1Val)) {
2381 // The next iteration must be out of the range...
2383 ConstantExpr::getAdd(R1->getValue(),
2384 ConstantInt::get(R1->getType(), 1));
2386 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2387 if (!Range.contains(R1Val))
2388 return SCEVUnknown::get(NextVal);
2389 return new SCEVCouldNotCompute(); // Something strange happened
2392 // If R1 was not in the range, then it is a good return value. Make
2393 // sure that R1-1 WAS in the range though, just in case.
2395 ConstantExpr::getSub(R1->getValue(),
2396 ConstantInt::get(R1->getType(), 1));
2397 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2398 if (Range.contains(R1Val))
2400 return new SCEVCouldNotCompute(); // Something strange happened
2405 // Fallback, if this is a general polynomial, figure out the progression
2406 // through brute force: evaluate until we find an iteration that fails the
2407 // test. This is likely to be slow, but getting an accurate trip count is
2408 // incredibly important, we will be able to simplify the exit test a lot, and
2409 // we are almost guaranteed to get a trip count in this case.
2410 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2411 ConstantInt *One = ConstantInt::get(getType(), 1);
2412 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2414 ++NumBruteForceEvaluations;
2415 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2416 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2417 return new SCEVCouldNotCompute();
2419 // Check to see if we found the value!
2420 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2421 return SCEVConstant::get(TestVal);
2423 // Increment to test the next index.
2424 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2425 } while (TestVal != EndVal);
2427 return new SCEVCouldNotCompute();
2432 //===----------------------------------------------------------------------===//
2433 // ScalarEvolution Class Implementation
2434 //===----------------------------------------------------------------------===//
2436 bool ScalarEvolution::runOnFunction(Function &F) {
2437 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2441 void ScalarEvolution::releaseMemory() {
2442 delete (ScalarEvolutionsImpl*)Impl;
2446 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2447 AU.setPreservesAll();
2448 AU.addRequiredTransitive<LoopInfo>();
2451 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2452 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2455 /// hasSCEV - Return true if the SCEV for this value has already been
2457 bool ScalarEvolution::hasSCEV(Value *V) const {
2458 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2462 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2463 /// the specified value.
2464 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2465 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2469 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2470 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2473 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2474 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2477 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2478 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2481 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2482 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2485 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2487 // Print all inner loops first
2488 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2489 PrintLoopInfo(OS, SE, *I);
2491 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2493 std::vector<BasicBlock*> ExitBlocks;
2494 L->getExitBlocks(ExitBlocks);
2495 if (ExitBlocks.size() != 1)
2496 std::cerr << "<multiple exits> ";
2498 if (SE->hasLoopInvariantIterationCount(L)) {
2499 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2501 std::cerr << "Unpredictable iteration count. ";
2507 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2508 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2509 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2511 OS << "Classifying expressions for: " << F.getName() << "\n";
2512 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2513 if (I->getType()->isInteger()) {
2516 SCEVHandle SV = getSCEV(&*I);
2520 if ((*I).getType()->isIntegral()) {
2521 ConstantRange Bounds = SV->getValueRange();
2522 if (!Bounds.isFullSet())
2523 OS << "Bounds: " << Bounds << " ";
2526 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2528 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2529 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2530 OS << "<<Unknown>>";
2540 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2541 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2542 PrintLoopInfo(OS, this, *I);