1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/Instructions.h"
67 #include "llvm/Analysis/LoopInfo.h"
68 #include "llvm/Assembly/Writer.h"
69 #include "llvm/Transforms/Scalar.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include "llvm/Support/CFG.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/InstIterator.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/ADT/Statistic.h"
81 RegisterAnalysis<ScalarEvolution>
82 R("scalar-evolution", "Scalar Evolution Analysis");
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to "
87 "calculate high-order polynomial exit values");
89 NumArrayLenItCounts("scalar-evolution",
90 "Number of trip counts computed with array length");
92 NumTripCountsComputed("scalar-evolution",
93 "Number of loops with predictable loop counts");
95 NumTripCountsNotComputed("scalar-evolution",
96 "Number of loops without predictable loop counts");
98 NumBruteForceTripCountsComputed("scalar-evolution",
99 "Number of loops with trip counts computed by force");
102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
103 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
107 //===----------------------------------------------------------------------===//
108 // SCEV class definitions
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
112 // Implementation of the SCEV class.
115 void SCEV::dump() const {
119 /// getValueRange - Return the tightest constant bounds that this value is
120 /// known to have. This method is only valid on integer SCEV objects.
121 ConstantRange SCEV::getValueRange() const {
122 const Type *Ty = getType();
123 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
124 Ty = Ty->getUnsignedVersion();
125 // Default to a full range if no better information is available.
126 return ConstantRange(getType());
130 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
137 const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 void SCEVCouldNotCompute::print(std::ostream &OS) const {
148 OS << "***COULDNOTCOMPUTE***";
151 bool SCEVCouldNotCompute::classof(const SCEV *S) {
152 return S->getSCEVType() == scCouldNotCompute;
156 // SCEVConstants - Only allow the creation of one SCEVConstant for any
157 // particular value. Don't use a SCEVHandle here, or else the object will
159 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
162 SCEVConstant::~SCEVConstant() {
163 SCEVConstants.erase(V);
166 SCEVHandle SCEVConstant::get(ConstantInt *V) {
167 // Make sure that SCEVConstant instances are all unsigned.
168 if (V->getType()->isSigned()) {
169 const Type *NewTy = V->getType()->getUnsignedVersion();
170 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
173 SCEVConstant *&R = SCEVConstants[V];
174 if (R == 0) R = new SCEVConstant(V);
178 ConstantRange SCEVConstant::getValueRange() const {
179 return ConstantRange(V);
182 const Type *SCEVConstant::getType() const { return V->getType(); }
184 void SCEVConstant::print(std::ostream &OS) const {
185 WriteAsOperand(OS, V, false);
188 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
189 // particular input. Don't use a SCEVHandle here, or else the object will
191 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
193 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
194 : SCEV(scTruncate), Op(op), Ty(ty) {
195 assert(Op->getType()->isInteger() && Ty->isInteger() &&
197 "Cannot truncate non-integer value!");
198 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
199 "This is not a truncating conversion!");
202 SCEVTruncateExpr::~SCEVTruncateExpr() {
203 SCEVTruncates.erase(std::make_pair(Op, Ty));
206 ConstantRange SCEVTruncateExpr::getValueRange() const {
207 return getOperand()->getValueRange().truncate(getType());
210 void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
214 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215 // particular input. Don't use a SCEVHandle here, or else the object will never
217 static std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> SCEVZeroExtends;
220 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
221 : SCEV(scTruncate), Op(Op), Ty(ty) {
222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
224 "Cannot zero extend non-integer value!");
225 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
226 "This is not an extending conversion!");
229 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
230 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
233 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
234 return getOperand()->getValueRange().zeroExtend(getType());
237 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
238 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
241 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
242 // particular input. Don't use a SCEVHandle here, or else the object will never
244 static std::map<std::pair<unsigned, std::vector<SCEV*> >,
245 SCEVCommutativeExpr*> SCEVCommExprs;
247 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
248 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
249 std::vector<SCEV*>(Operands.begin(),
253 void SCEVCommutativeExpr::print(std::ostream &OS) const {
254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
262 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
263 // input. Don't use a SCEVHandle here, or else the object will never be
265 static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
267 SCEVUDivExpr::~SCEVUDivExpr() {
268 SCEVUDivs.erase(std::make_pair(LHS, RHS));
271 void SCEVUDivExpr::print(std::ostream &OS) const {
272 OS << "(" << *LHS << " /u " << *RHS << ")";
275 const Type *SCEVUDivExpr::getType() const {
276 const Type *Ty = LHS->getType();
277 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
281 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
282 // particular input. Don't use a SCEVHandle here, or else the object will never
284 static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
285 SCEVAddRecExpr*> SCEVAddRecExprs;
287 SCEVAddRecExpr::~SCEVAddRecExpr() {
288 SCEVAddRecExprs.erase(std::make_pair(L,
289 std::vector<SCEV*>(Operands.begin(),
293 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
294 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
296 return !QueryLoop->contains(L->getHeader());
300 void SCEVAddRecExpr::print(std::ostream &OS) const {
301 OS << "{" << *Operands[0];
302 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
303 OS << ",+," << *Operands[i];
304 OS << "}<" << L->getHeader()->getName() + ">";
307 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
308 // value. Don't use a SCEVHandle here, or else the object will never be
310 static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
312 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
314 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
315 // All non-instruction values are loop invariant. All instructions are loop
316 // invariant if they are not contained in the specified loop.
317 if (Instruction *I = dyn_cast<Instruction>(V))
318 return !L->contains(I->getParent());
322 const Type *SCEVUnknown::getType() const {
326 void SCEVUnknown::print(std::ostream &OS) const {
327 WriteAsOperand(OS, V, false);
330 //===----------------------------------------------------------------------===//
332 //===----------------------------------------------------------------------===//
335 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
336 /// than the complexity of the RHS. This comparator is used to canonicalize
338 struct SCEVComplexityCompare {
339 bool operator()(SCEV *LHS, SCEV *RHS) {
340 return LHS->getSCEVType() < RHS->getSCEVType();
345 /// GroupByComplexity - Given a list of SCEV objects, order them by their
346 /// complexity, and group objects of the same complexity together by value.
347 /// When this routine is finished, we know that any duplicates in the vector are
348 /// consecutive and that complexity is monotonically increasing.
350 /// Note that we go take special precautions to ensure that we get determinstic
351 /// results from this routine. In other words, we don't want the results of
352 /// this to depend on where the addresses of various SCEV objects happened to
355 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
356 if (Ops.size() < 2) return; // Noop
357 if (Ops.size() == 2) {
358 // This is the common case, which also happens to be trivially simple.
360 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
361 std::swap(Ops[0], Ops[1]);
365 // Do the rough sort by complexity.
366 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
368 // Now that we are sorted by complexity, group elements of the same
369 // complexity. Note that this is, at worst, N^2, but the vector is likely to
370 // be extremely short in practice. Note that we take this approach because we
371 // do not want to depend on the addresses of the objects we are grouping.
372 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
374 unsigned Complexity = S->getSCEVType();
376 // If there are any objects of the same complexity and same value as this
378 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
379 if (Ops[j] == S) { // Found a duplicate.
380 // Move it to immediately after i'th element.
381 std::swap(Ops[i+1], Ops[j]);
382 ++i; // no need to rescan it.
383 if (i == e-2) return; // Done!
391 //===----------------------------------------------------------------------===//
392 // Simple SCEV method implementations
393 //===----------------------------------------------------------------------===//
395 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
396 /// specified signed integer value and return a SCEV for the constant.
397 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
400 C = Constant::getNullValue(Ty);
401 else if (Ty->isFloatingPoint())
402 C = ConstantFP::get(Ty, Val);
403 else if (Ty->isSigned())
404 C = ConstantSInt::get(Ty, Val);
406 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
407 C = ConstantExpr::getCast(C, Ty);
409 return SCEVUnknown::get(C);
412 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
413 /// input value to the specified type. If the type must be extended, it is zero
415 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
416 const Type *SrcTy = V->getType();
417 assert(SrcTy->isInteger() && Ty->isInteger() &&
418 "Cannot truncate or zero extend with non-integer arguments!");
419 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
420 return V; // No conversion
421 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
422 return SCEVTruncateExpr::get(V, Ty);
423 return SCEVZeroExtendExpr::get(V, Ty);
426 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
428 static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
429 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
430 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
432 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
435 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
437 static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
439 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
443 /// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
444 /// often very small, so we try to reduce the number of N! terms we need to
445 /// evaluate by evaluating this as (N!/(N-M)!)/M!
446 static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
447 uint64_t NVal = N->getRawValue();
448 uint64_t FirstTerm = 1;
449 for (unsigned i = 0; i != M; ++i)
452 unsigned MFactorial = 1;
456 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
457 Result = ConstantExpr::getCast(Result, N->getType());
458 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
459 return cast<ConstantInt>(Result);
462 /// PartialFact - Compute V!/(V-NumSteps)!
463 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
464 // Handle this case efficiently, it is common to have constant iteration
465 // counts while computing loop exit values.
466 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
467 uint64_t Val = SC->getValue()->getRawValue();
469 for (; NumSteps; --NumSteps)
470 Result *= Val-(NumSteps-1);
471 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
472 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
475 const Type *Ty = V->getType();
477 return SCEVUnknown::getIntegerSCEV(1, Ty);
479 SCEVHandle Result = V;
480 for (unsigned i = 1; i != NumSteps; ++i)
481 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
482 SCEVUnknown::getIntegerSCEV(i, Ty)));
487 /// evaluateAtIteration - Return the value of this chain of recurrences at
488 /// the specified iteration number. We can evaluate this recurrence by
489 /// multiplying each element in the chain by the binomial coefficient
490 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
492 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
494 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
495 /// Is the binomial equation safe using modular arithmetic??
497 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
498 SCEVHandle Result = getStart();
500 const Type *Ty = It->getType();
501 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
502 SCEVHandle BC = PartialFact(It, i);
504 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
505 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
506 Result = SCEVAddExpr::get(Result, Val);
512 //===----------------------------------------------------------------------===//
513 // SCEV Expression folder implementations
514 //===----------------------------------------------------------------------===//
516 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
517 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
518 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
520 // If the input value is a chrec scev made out of constants, truncate
521 // all of the constants.
522 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
523 std::vector<SCEVHandle> Operands;
524 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
525 // FIXME: This should allow truncation of other expression types!
526 if (isa<SCEVConstant>(AddRec->getOperand(i)))
527 Operands.push_back(get(AddRec->getOperand(i), Ty));
530 if (Operands.size() == AddRec->getNumOperands())
531 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
534 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
535 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
539 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
540 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
541 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
543 // FIXME: If the input value is a chrec scev, and we can prove that the value
544 // did not overflow the old, smaller, value, we can zero extend all of the
545 // operands (often constants). This would allow analysis of something like
546 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
548 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
549 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
553 // get - Get a canonical add expression, or something simpler if possible.
554 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
555 assert(!Ops.empty() && "Cannot get empty add!");
556 if (Ops.size() == 1) return Ops[0];
558 // Sort by complexity, this groups all similar expression types together.
559 GroupByComplexity(Ops);
561 // If there are any constants, fold them together.
563 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
565 assert(Idx < Ops.size());
566 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
567 // We found two constants, fold them together!
568 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
569 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
570 Ops[0] = SCEVConstant::get(CI);
571 Ops.erase(Ops.begin()+1); // Erase the folded element
572 if (Ops.size() == 1) return Ops[0];
574 // If we couldn't fold the expression, move to the next constant. Note
575 // that this is impossible to happen in practice because we always
576 // constant fold constant ints to constant ints.
581 // If we are left with a constant zero being added, strip it off.
582 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
583 Ops.erase(Ops.begin());
588 if (Ops.size() == 1) return Ops[0];
590 // Okay, check to see if the same value occurs in the operand list twice. If
591 // so, merge them together into an multiply expression. Since we sorted the
592 // list, these values are required to be adjacent.
593 const Type *Ty = Ops[0]->getType();
594 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
595 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
596 // Found a match, merge the two values into a multiply, and add any
597 // remaining values to the result.
598 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
599 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
602 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
604 return SCEVAddExpr::get(Ops);
607 // Okay, now we know the first non-constant operand. If there are add
608 // operands they would be next.
609 if (Idx < Ops.size()) {
610 bool DeletedAdd = false;
611 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
612 // If we have an add, expand the add operands onto the end of the operands
614 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
615 Ops.erase(Ops.begin()+Idx);
619 // If we deleted at least one add, we added operands to the end of the list,
620 // and they are not necessarily sorted. Recurse to resort and resimplify
621 // any operands we just aquired.
626 // Skip over the add expression until we get to a multiply.
627 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
630 // If we are adding something to a multiply expression, make sure the
631 // something is not already an operand of the multiply. If so, merge it into
633 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
634 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
635 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
636 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
637 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
638 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
639 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
640 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
641 if (Mul->getNumOperands() != 2) {
642 // If the multiply has more than two operands, we must get the
644 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
645 MulOps.erase(MulOps.begin()+MulOp);
646 InnerMul = SCEVMulExpr::get(MulOps);
648 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
649 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
650 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
651 if (Ops.size() == 2) return OuterMul;
653 Ops.erase(Ops.begin()+AddOp);
654 Ops.erase(Ops.begin()+Idx-1);
656 Ops.erase(Ops.begin()+Idx);
657 Ops.erase(Ops.begin()+AddOp-1);
659 Ops.push_back(OuterMul);
660 return SCEVAddExpr::get(Ops);
663 // Check this multiply against other multiplies being added together.
664 for (unsigned OtherMulIdx = Idx+1;
665 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
667 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
668 // If MulOp occurs in OtherMul, we can fold the two multiplies
670 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
671 OMulOp != e; ++OMulOp)
672 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
673 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
674 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
675 if (Mul->getNumOperands() != 2) {
676 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
677 MulOps.erase(MulOps.begin()+MulOp);
678 InnerMul1 = SCEVMulExpr::get(MulOps);
680 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
681 if (OtherMul->getNumOperands() != 2) {
682 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
684 MulOps.erase(MulOps.begin()+OMulOp);
685 InnerMul2 = SCEVMulExpr::get(MulOps);
687 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
688 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
689 if (Ops.size() == 2) return OuterMul;
690 Ops.erase(Ops.begin()+Idx);
691 Ops.erase(Ops.begin()+OtherMulIdx-1);
692 Ops.push_back(OuterMul);
693 return SCEVAddExpr::get(Ops);
699 // If there are any add recurrences in the operands list, see if any other
700 // added values are loop invariant. If so, we can fold them into the
702 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
705 // Scan over all recurrences, trying to fold loop invariants into them.
706 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
707 // Scan all of the other operands to this add and add them to the vector if
708 // they are loop invariant w.r.t. the recurrence.
709 std::vector<SCEVHandle> LIOps;
710 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
711 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
712 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
713 LIOps.push_back(Ops[i]);
714 Ops.erase(Ops.begin()+i);
718 // If we found some loop invariants, fold them into the recurrence.
719 if (!LIOps.empty()) {
720 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
721 LIOps.push_back(AddRec->getStart());
723 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
724 AddRecOps[0] = SCEVAddExpr::get(LIOps);
726 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
727 // If all of the other operands were loop invariant, we are done.
728 if (Ops.size() == 1) return NewRec;
730 // Otherwise, add the folded AddRec by the non-liv parts.
731 for (unsigned i = 0;; ++i)
732 if (Ops[i] == AddRec) {
736 return SCEVAddExpr::get(Ops);
739 // Okay, if there weren't any loop invariants to be folded, check to see if
740 // there are multiple AddRec's with the same loop induction variable being
741 // added together. If so, we can fold them.
742 for (unsigned OtherIdx = Idx+1;
743 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
744 if (OtherIdx != Idx) {
745 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
746 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
747 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
748 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
749 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
750 if (i >= NewOps.size()) {
751 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
752 OtherAddRec->op_end());
755 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
757 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
759 if (Ops.size() == 2) return NewAddRec;
761 Ops.erase(Ops.begin()+Idx);
762 Ops.erase(Ops.begin()+OtherIdx-1);
763 Ops.push_back(NewAddRec);
764 return SCEVAddExpr::get(Ops);
768 // Otherwise couldn't fold anything into this recurrence. Move onto the
772 // Okay, it looks like we really DO need an add expr. Check to see if we
773 // already have one, otherwise create a new one.
774 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
775 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
777 if (Result == 0) Result = new SCEVAddExpr(Ops);
782 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
783 assert(!Ops.empty() && "Cannot get empty mul!");
785 // Sort by complexity, this groups all similar expression types together.
786 GroupByComplexity(Ops);
788 // If there are any constants, fold them together.
790 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
792 // C1*(C2+V) -> C1*C2 + C1*V
794 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
795 if (Add->getNumOperands() == 2 &&
796 isa<SCEVConstant>(Add->getOperand(0)))
797 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
798 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
802 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
803 // We found two constants, fold them together!
804 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
805 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
806 Ops[0] = SCEVConstant::get(CI);
807 Ops.erase(Ops.begin()+1); // Erase the folded element
808 if (Ops.size() == 1) return Ops[0];
810 // If we couldn't fold the expression, move to the next constant. Note
811 // that this is impossible to happen in practice because we always
812 // constant fold constant ints to constant ints.
817 // If we are left with a constant one being multiplied, strip it off.
818 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
819 Ops.erase(Ops.begin());
821 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
822 // If we have a multiply of zero, it will always be zero.
827 // Skip over the add expression until we get to a multiply.
828 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
834 // If there are mul operands inline them all into this expression.
835 if (Idx < Ops.size()) {
836 bool DeletedMul = false;
837 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
838 // If we have an mul, expand the mul operands onto the end of the operands
840 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
841 Ops.erase(Ops.begin()+Idx);
845 // If we deleted at least one mul, we added operands to the end of the list,
846 // and they are not necessarily sorted. Recurse to resort and resimplify
847 // any operands we just aquired.
852 // If there are any add recurrences in the operands list, see if any other
853 // added values are loop invariant. If so, we can fold them into the
855 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
858 // Scan over all recurrences, trying to fold loop invariants into them.
859 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
860 // Scan all of the other operands to this mul and add them to the vector if
861 // they are loop invariant w.r.t. the recurrence.
862 std::vector<SCEVHandle> LIOps;
863 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
864 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
865 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
866 LIOps.push_back(Ops[i]);
867 Ops.erase(Ops.begin()+i);
871 // If we found some loop invariants, fold them into the recurrence.
872 if (!LIOps.empty()) {
873 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
874 std::vector<SCEVHandle> NewOps;
875 NewOps.reserve(AddRec->getNumOperands());
876 if (LIOps.size() == 1) {
877 SCEV *Scale = LIOps[0];
878 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
879 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
881 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
882 std::vector<SCEVHandle> MulOps(LIOps);
883 MulOps.push_back(AddRec->getOperand(i));
884 NewOps.push_back(SCEVMulExpr::get(MulOps));
888 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
893 // Otherwise, multiply the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
899 return SCEVMulExpr::get(Ops);
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // multiplied together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
911 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
912 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
914 SCEVHandle B = F->getStepRecurrence();
915 SCEVHandle D = G->getStepRecurrence();
916 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
917 SCEVMulExpr::get(G, B),
918 SCEVMulExpr::get(B, D));
919 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
921 if (Ops.size() == 2) return NewAddRec;
923 Ops.erase(Ops.begin()+Idx);
924 Ops.erase(Ops.begin()+OtherIdx-1);
925 Ops.push_back(NewAddRec);
926 return SCEVMulExpr::get(Ops);
930 // Otherwise couldn't fold anything into this recurrence. Move onto the
934 // Okay, it looks like we really DO need an mul expr. Check to see if we
935 // already have one, otherwise create a new one.
936 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
937 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
940 Result = new SCEVMulExpr(Ops);
944 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
945 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
946 if (RHSC->getValue()->equalsInt(1))
947 return LHS; // X /u 1 --> x
948 if (RHSC->getValue()->isAllOnesValue())
949 return getNegativeSCEV(LHS); // X /u -1 --> -x
951 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
952 Constant *LHSCV = LHSC->getValue();
953 Constant *RHSCV = RHSC->getValue();
954 if (LHSCV->getType()->isSigned())
955 LHSCV = ConstantExpr::getCast(LHSCV,
956 LHSCV->getType()->getUnsignedVersion());
957 if (RHSCV->getType()->isSigned())
958 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
959 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
963 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
965 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
966 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
971 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
972 /// specified loop. Simplify the expression as much as possible.
973 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
974 const SCEVHandle &Step, const Loop *L) {
975 std::vector<SCEVHandle> Operands;
976 Operands.push_back(Start);
977 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
978 if (StepChrec->getLoop() == L) {
979 Operands.insert(Operands.end(), StepChrec->op_begin(),
980 StepChrec->op_end());
981 return get(Operands, L);
984 Operands.push_back(Step);
985 return get(Operands, L);
988 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
989 /// specified loop. Simplify the expression as much as possible.
990 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
992 if (Operands.size() == 1) return Operands[0];
994 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
995 if (StepC->getValue()->isNullValue()) {
997 return get(Operands, L); // { X,+,0 } --> X
1000 SCEVAddRecExpr *&Result =
1001 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1003 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1007 SCEVHandle SCEVUnknown::get(Value *V) {
1008 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1009 return SCEVConstant::get(CI);
1010 SCEVUnknown *&Result = SCEVUnknowns[V];
1011 if (Result == 0) Result = new SCEVUnknown(V);
1016 //===----------------------------------------------------------------------===//
1017 // ScalarEvolutionsImpl Definition and Implementation
1018 //===----------------------------------------------------------------------===//
1020 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1024 struct ScalarEvolutionsImpl {
1025 /// F - The function we are analyzing.
1029 /// LI - The loop information for the function we are currently analyzing.
1033 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1035 SCEVHandle UnknownValue;
1037 /// Scalars - This is a cache of the scalars we have analyzed so far.
1039 std::map<Value*, SCEVHandle> Scalars;
1041 /// IterationCounts - Cache the iteration count of the loops for this
1042 /// function as they are computed.
1043 std::map<const Loop*, SCEVHandle> IterationCounts;
1045 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1046 /// the PHI instructions that we attempt to compute constant evolutions for.
1047 /// This allows us to avoid potentially expensive recomputation of these
1048 /// properties. An instruction maps to null if we are unable to compute its
1050 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1053 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1054 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1056 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1057 /// expression and create a new one.
1058 SCEVHandle getSCEV(Value *V);
1060 /// getSCEVAtScope - Compute the value of the specified expression within
1061 /// the indicated loop (which may be null to indicate in no loop). If the
1062 /// expression cannot be evaluated, return UnknownValue itself.
1063 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1066 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1067 /// an analyzable loop-invariant iteration count.
1068 bool hasLoopInvariantIterationCount(const Loop *L);
1070 /// getIterationCount - If the specified loop has a predictable iteration
1071 /// count, return it. Note that it is not valid to call this method on a
1072 /// loop without a loop-invariant iteration count.
1073 SCEVHandle getIterationCount(const Loop *L);
1075 /// deleteInstructionFromRecords - This method should be called by the
1076 /// client before it removes an instruction from the program, to make sure
1077 /// that no dangling references are left around.
1078 void deleteInstructionFromRecords(Instruction *I);
1081 /// createSCEV - We know that there is no SCEV for the specified value.
1082 /// Analyze the expression.
1083 SCEVHandle createSCEV(Value *V);
1084 SCEVHandle createNodeForCast(CastInst *CI);
1086 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1088 SCEVHandle createNodeForPHI(PHINode *PN);
1089 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1090 std::set<Instruction*> &UpdatedInsts);
1092 /// ComputeIterationCount - Compute the number of times the specified loop
1094 SCEVHandle ComputeIterationCount(const Loop *L);
1096 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1097 /// 'setcc load X, cst', try to se if we can compute the trip count.
1098 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1101 unsigned SetCCOpcode);
1103 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1104 /// constant number of times (the condition evolves only from constants),
1105 /// try to evaluate a few iterations of the loop until we get the exit
1106 /// condition gets a value of ExitWhen (true or false). If we cannot
1107 /// evaluate the trip count of the loop, return UnknownValue.
1108 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1111 /// HowFarToZero - Return the number of times a backedge comparing the
1112 /// specified value to zero will execute. If not computable, return
1114 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1116 /// HowFarToNonZero - Return the number of times a backedge checking the
1117 /// specified value for nonzero will execute. If not computable, return
1119 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1121 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1122 /// in the header of its containing loop, we know the loop executes a
1123 /// constant number of times, and the PHI node is just a recurrence
1124 /// involving constants, fold it.
1125 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1130 //===----------------------------------------------------------------------===//
1131 // Basic SCEV Analysis and PHI Idiom Recognition Code
1134 /// deleteInstructionFromRecords - This method should be called by the
1135 /// client before it removes an instruction from the program, to make sure
1136 /// that no dangling references are left around.
1137 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1139 if (PHINode *PN = dyn_cast<PHINode>(I))
1140 ConstantEvolutionLoopExitValue.erase(PN);
1144 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1145 /// expression and create a new one.
1146 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1147 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1149 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1150 if (I != Scalars.end()) return I->second;
1151 SCEVHandle S = createSCEV(V);
1152 Scalars.insert(std::make_pair(V, S));
1157 /// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1158 /// entries in the scalar map that refer to the "symbolic" PHI value instead of
1159 /// the recurrence value. After we resolve the PHI we must loop over all of the
1160 /// using instructions that have scalar map entries and update them.
1161 void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1163 std::set<Instruction*> &UpdatedInsts) {
1164 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1165 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1166 if (UpdatedInsts.insert(I).second) {
1167 Scalars.erase(SI); // Remove the old entry
1168 getSCEV(I); // Calculate the new entry
1170 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1172 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1177 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1178 /// a loop header, making it a potential recurrence, or it doesn't.
1180 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1181 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1182 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1183 if (L->getHeader() == PN->getParent()) {
1184 // If it lives in the loop header, it has two incoming values, one
1185 // from outside the loop, and one from inside.
1186 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1187 unsigned BackEdge = IncomingEdge^1;
1189 // While we are analyzing this PHI node, handle its value symbolically.
1190 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1191 assert(Scalars.find(PN) == Scalars.end() &&
1192 "PHI node already processed?");
1193 Scalars.insert(std::make_pair(PN, SymbolicName));
1195 // Using this symbolic name for the PHI, analyze the value coming around
1197 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1199 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1200 // has a special value for the first iteration of the loop.
1202 // If the value coming around the backedge is an add with the symbolic
1203 // value we just inserted, then we found a simple induction variable!
1204 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1205 // If there is a single occurrence of the symbolic value, replace it
1206 // with a recurrence.
1207 unsigned FoundIndex = Add->getNumOperands();
1208 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1209 if (Add->getOperand(i) == SymbolicName)
1210 if (FoundIndex == e) {
1215 if (FoundIndex != Add->getNumOperands()) {
1216 // Create an add with everything but the specified operand.
1217 std::vector<SCEVHandle> Ops;
1218 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1219 if (i != FoundIndex)
1220 Ops.push_back(Add->getOperand(i));
1221 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1223 // This is not a valid addrec if the step amount is varying each
1224 // loop iteration, but is not itself an addrec in this loop.
1225 if (Accum->isLoopInvariant(L) ||
1226 (isa<SCEVAddRecExpr>(Accum) &&
1227 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1228 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1229 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1231 // Okay, for the entire analysis of this edge we assumed the PHI
1232 // to be symbolic. We now need to go back and update all of the
1233 // entries for the scalars that use the PHI (except for the PHI
1234 // itself) to use the new analyzed value instead of the "symbolic"
1236 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1237 std::set<Instruction*> UpdatedInsts;
1238 UpdatedInsts.insert(PN);
1239 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1241 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1248 return SymbolicName;
1251 // If it's not a loop phi, we can't handle it yet.
1252 return SCEVUnknown::get(PN);
1255 /// createNodeForCast - Handle the various forms of casts that we support.
1257 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1258 const Type *SrcTy = CI->getOperand(0)->getType();
1259 const Type *DestTy = CI->getType();
1261 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1262 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1263 return getSCEV(CI->getOperand(0));
1265 if (SrcTy->isInteger() && DestTy->isInteger()) {
1266 // Otherwise, if this is a truncating integer cast, we can represent this
1268 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1269 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1270 CI->getType()->getUnsignedVersion());
1271 if (SrcTy->isUnsigned() &&
1272 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1273 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1274 CI->getType()->getUnsignedVersion());
1277 // If this is an sign or zero extending cast and we can prove that the value
1278 // will never overflow, we could do similar transformations.
1280 // Otherwise, we can't handle this cast!
1281 return SCEVUnknown::get(CI);
1285 /// createSCEV - We know that there is no SCEV for the specified value.
1286 /// Analyze the expression.
1288 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1289 if (Instruction *I = dyn_cast<Instruction>(V)) {
1290 switch (I->getOpcode()) {
1291 case Instruction::Add:
1292 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1293 getSCEV(I->getOperand(1)));
1294 case Instruction::Mul:
1295 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1296 getSCEV(I->getOperand(1)));
1297 case Instruction::Div:
1298 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1299 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1300 getSCEV(I->getOperand(1)));
1303 case Instruction::Sub:
1304 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1306 case Instruction::Shl:
1307 // Turn shift left of a constant amount into a multiply.
1308 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1309 Constant *X = ConstantInt::get(V->getType(), 1);
1310 X = ConstantExpr::getShl(X, SA);
1311 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1315 case Instruction::Shr:
1316 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1317 if (V->getType()->isUnsigned()) {
1318 Constant *X = ConstantInt::get(V->getType(), 1);
1319 X = ConstantExpr::getShl(X, SA);
1320 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1324 case Instruction::Cast:
1325 return createNodeForCast(cast<CastInst>(I));
1327 case Instruction::PHI:
1328 return createNodeForPHI(cast<PHINode>(I));
1330 default: // We cannot analyze this expression.
1335 return SCEVUnknown::get(V);
1340 //===----------------------------------------------------------------------===//
1341 // Iteration Count Computation Code
1344 /// getIterationCount - If the specified loop has a predictable iteration
1345 /// count, return it. Note that it is not valid to call this method on a
1346 /// loop without a loop-invariant iteration count.
1347 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1348 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1349 if (I == IterationCounts.end()) {
1350 SCEVHandle ItCount = ComputeIterationCount(L);
1351 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1352 if (ItCount != UnknownValue) {
1353 assert(ItCount->isLoopInvariant(L) &&
1354 "Computed trip count isn't loop invariant for loop!");
1355 ++NumTripCountsComputed;
1356 } else if (isa<PHINode>(L->getHeader()->begin())) {
1357 // Only count loops that have phi nodes as not being computable.
1358 ++NumTripCountsNotComputed;
1364 /// ComputeIterationCount - Compute the number of times the specified loop
1366 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1367 // If the loop has a non-one exit block count, we can't analyze it.
1368 std::vector<BasicBlock*> ExitBlocks;
1369 L->getExitBlocks(ExitBlocks);
1370 if (ExitBlocks.size() != 1) return UnknownValue;
1372 // Okay, there is one exit block. Try to find the condition that causes the
1373 // loop to be exited.
1374 BasicBlock *ExitBlock = ExitBlocks[0];
1376 BasicBlock *ExitingBlock = 0;
1377 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1379 if (L->contains(*PI)) {
1380 if (ExitingBlock == 0)
1383 return UnknownValue; // More than one block exiting!
1385 assert(ExitingBlock && "No exits from loop, something is broken!");
1387 // Okay, we've computed the exiting block. See what condition causes us to
1390 // FIXME: we should be able to handle switch instructions (with a single exit)
1391 // FIXME: We should handle cast of int to bool as well
1392 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1393 if (ExitBr == 0) return UnknownValue;
1394 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1395 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1396 if (ExitCond == 0) // Not a setcc
1397 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1398 ExitBr->getSuccessor(0) == ExitBlock);
1400 // If the condition was exit on true, convert the condition to exit on false.
1401 Instruction::BinaryOps Cond;
1402 if (ExitBr->getSuccessor(1) == ExitBlock)
1403 Cond = ExitCond->getOpcode();
1405 Cond = ExitCond->getInverseCondition();
1407 // Handle common loops like: for (X = "string"; *X; ++X)
1408 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1409 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1411 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1412 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1415 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1416 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1418 // Try to evaluate any dependencies out of the loop.
1419 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1420 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1421 Tmp = getSCEVAtScope(RHS, L);
1422 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1424 // At this point, we would like to compute how many iterations of the loop the
1425 // predicate will return true for these inputs.
1426 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1427 // If there is a constant, force it into the RHS.
1428 std::swap(LHS, RHS);
1429 Cond = SetCondInst::getSwappedCondition(Cond);
1432 // FIXME: think about handling pointer comparisons! i.e.:
1433 // while (P != P+100) ++P;
1435 // If we have a comparison of a chrec against a constant, try to use value
1436 // ranges to answer this query.
1437 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1438 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1439 if (AddRec->getLoop() == L) {
1440 // Form the comparison range using the constant of the correct type so
1441 // that the ConstantRange class knows to do a signed or unsigned
1443 ConstantInt *CompVal = RHSC->getValue();
1444 const Type *RealTy = ExitCond->getOperand(0)->getType();
1445 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1447 // Form the constant range.
1448 ConstantRange CompRange(Cond, CompVal);
1450 // Now that we have it, if it's signed, convert it to an unsigned
1452 if (CompRange.getLower()->getType()->isSigned()) {
1453 const Type *NewTy = RHSC->getValue()->getType();
1454 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1455 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1456 CompRange = ConstantRange(NewL, NewU);
1459 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1460 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1465 case Instruction::SetNE: // while (X != Y)
1466 // Convert to: while (X-Y != 0)
1467 if (LHS->getType()->isInteger()) {
1468 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1469 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1472 case Instruction::SetEQ:
1473 // Convert to: while (X-Y == 0) // while (X == Y)
1474 if (LHS->getType()->isInteger()) {
1475 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1476 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1481 std::cerr << "ComputeIterationCount ";
1482 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1483 std::cerr << "[unsigned] ";
1484 std::cerr << *LHS << " "
1485 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1490 return ComputeIterationCountExhaustively(L, ExitCond,
1491 ExitBr->getSuccessor(0) == ExitBlock);
1494 static ConstantInt *
1495 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1496 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1497 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1498 assert(isa<SCEVConstant>(Val) &&
1499 "Evaluation of SCEV at constant didn't fold correctly?");
1500 return cast<SCEVConstant>(Val)->getValue();
1503 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1504 /// and a GEP expression (missing the pointer index) indexing into it, return
1505 /// the addressed element of the initializer or null if the index expression is
1508 GetAddressedElementFromGlobal(GlobalVariable *GV,
1509 const std::vector<ConstantInt*> &Indices) {
1510 Constant *Init = GV->getInitializer();
1511 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1512 uint64_t Idx = Indices[i]->getRawValue();
1513 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1514 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1515 Init = cast<Constant>(CS->getOperand(Idx));
1516 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1517 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1518 Init = cast<Constant>(CA->getOperand(Idx));
1519 } else if (isa<ConstantAggregateZero>(Init)) {
1520 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1521 assert(Idx < STy->getNumElements() && "Bad struct index!");
1522 Init = Constant::getNullValue(STy->getElementType(Idx));
1523 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1524 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1525 Init = Constant::getNullValue(ATy->getElementType());
1527 assert(0 && "Unknown constant aggregate type!");
1531 return 0; // Unknown initializer type
1537 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1538 /// 'setcc load X, cst', try to se if we can compute the trip count.
1539 SCEVHandle ScalarEvolutionsImpl::
1540 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1541 const Loop *L, unsigned SetCCOpcode) {
1542 if (LI->isVolatile()) return UnknownValue;
1544 // Check to see if the loaded pointer is a getelementptr of a global.
1545 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1546 if (!GEP) return UnknownValue;
1548 // Make sure that it is really a constant global we are gepping, with an
1549 // initializer, and make sure the first IDX is really 0.
1550 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1551 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1552 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1553 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1554 return UnknownValue;
1556 // Okay, we allow one non-constant index into the GEP instruction.
1558 std::vector<ConstantInt*> Indexes;
1559 unsigned VarIdxNum = 0;
1560 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1561 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1562 Indexes.push_back(CI);
1563 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1564 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1565 VarIdx = GEP->getOperand(i);
1567 Indexes.push_back(0);
1570 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1571 // Check to see if X is a loop variant variable value now.
1572 SCEVHandle Idx = getSCEV(VarIdx);
1573 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1574 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1576 // We can only recognize very limited forms of loop index expressions, in
1577 // particular, only affine AddRec's like {C1,+,C2}.
1578 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1579 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1580 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1581 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1582 return UnknownValue;
1584 unsigned MaxSteps = MaxBruteForceIterations;
1585 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1586 ConstantUInt *ItCst =
1587 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1588 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1590 // Form the GEP offset.
1591 Indexes[VarIdxNum] = Val;
1593 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1594 if (Result == 0) break; // Cannot compute!
1596 // Evaluate the condition for this iteration.
1597 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1598 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1599 if (Result == ConstantBool::False) {
1601 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1602 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1605 ++NumArrayLenItCounts;
1606 return SCEVConstant::get(ItCst); // Found terminating iteration!
1609 return UnknownValue;
1613 /// CanConstantFold - Return true if we can constant fold an instruction of the
1614 /// specified type, assuming that all operands were constants.
1615 static bool CanConstantFold(const Instruction *I) {
1616 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1617 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1620 if (const CallInst *CI = dyn_cast<CallInst>(I))
1621 if (const Function *F = CI->getCalledFunction())
1622 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1626 /// ConstantFold - Constant fold an instruction of the specified type with the
1627 /// specified constant operands. This function may modify the operands vector.
1628 static Constant *ConstantFold(const Instruction *I,
1629 std::vector<Constant*> &Operands) {
1630 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1631 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1633 switch (I->getOpcode()) {
1634 case Instruction::Cast:
1635 return ConstantExpr::getCast(Operands[0], I->getType());
1636 case Instruction::Select:
1637 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1638 case Instruction::Call:
1639 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1640 Operands.erase(Operands.begin());
1641 return ConstantFoldCall(cast<Function>(GV), Operands);
1645 case Instruction::GetElementPtr:
1646 Constant *Base = Operands[0];
1647 Operands.erase(Operands.begin());
1648 return ConstantExpr::getGetElementPtr(Base, Operands);
1654 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1655 /// in the loop that V is derived from. We allow arbitrary operations along the
1656 /// way, but the operands of an operation must either be constants or a value
1657 /// derived from a constant PHI. If this expression does not fit with these
1658 /// constraints, return null.
1659 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1660 // If this is not an instruction, or if this is an instruction outside of the
1661 // loop, it can't be derived from a loop PHI.
1662 Instruction *I = dyn_cast<Instruction>(V);
1663 if (I == 0 || !L->contains(I->getParent())) return 0;
1665 if (PHINode *PN = dyn_cast<PHINode>(I))
1666 if (L->getHeader() == I->getParent())
1669 // We don't currently keep track of the control flow needed to evaluate
1670 // PHIs, so we cannot handle PHIs inside of loops.
1673 // If we won't be able to constant fold this expression even if the operands
1674 // are constants, return early.
1675 if (!CanConstantFold(I)) return 0;
1677 // Otherwise, we can evaluate this instruction if all of its operands are
1678 // constant or derived from a PHI node themselves.
1680 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1681 if (!(isa<Constant>(I->getOperand(Op)) ||
1682 isa<GlobalValue>(I->getOperand(Op)))) {
1683 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1684 if (P == 0) return 0; // Not evolving from PHI
1688 return 0; // Evolving from multiple different PHIs.
1691 // This is a expression evolving from a constant PHI!
1695 /// EvaluateExpression - Given an expression that passes the
1696 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1697 /// in the loop has the value PHIVal. If we can't fold this expression for some
1698 /// reason, return null.
1699 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1700 if (isa<PHINode>(V)) return PHIVal;
1701 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1703 if (Constant *C = dyn_cast<Constant>(V)) return C;
1704 Instruction *I = cast<Instruction>(V);
1706 std::vector<Constant*> Operands;
1707 Operands.resize(I->getNumOperands());
1709 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1710 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1711 if (Operands[i] == 0) return 0;
1714 return ConstantFold(I, Operands);
1717 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1718 /// in the header of its containing loop, we know the loop executes a
1719 /// constant number of times, and the PHI node is just a recurrence
1720 /// involving constants, fold it.
1721 Constant *ScalarEvolutionsImpl::
1722 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1723 std::map<PHINode*, Constant*>::iterator I =
1724 ConstantEvolutionLoopExitValue.find(PN);
1725 if (I != ConstantEvolutionLoopExitValue.end())
1728 if (Its > MaxBruteForceIterations)
1729 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1731 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1733 // Since the loop is canonicalized, the PHI node must have two entries. One
1734 // entry must be a constant (coming in from outside of the loop), and the
1735 // second must be derived from the same PHI.
1736 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1737 Constant *StartCST =
1738 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1740 return RetVal = 0; // Must be a constant.
1742 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1743 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1745 return RetVal = 0; // Not derived from same PHI.
1747 // Execute the loop symbolically to determine the exit value.
1748 unsigned IterationNum = 0;
1749 unsigned NumIterations = Its;
1750 if (NumIterations != Its)
1751 return RetVal = 0; // More than 2^32 iterations??
1753 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1754 if (IterationNum == NumIterations)
1755 return RetVal = PHIVal; // Got exit value!
1757 // Compute the value of the PHI node for the next iteration.
1758 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1759 if (NextPHI == PHIVal)
1760 return RetVal = NextPHI; // Stopped evolving!
1762 return 0; // Couldn't evaluate!
1767 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1768 /// constant number of times (the condition evolves only from constants),
1769 /// try to evaluate a few iterations of the loop until we get the exit
1770 /// condition gets a value of ExitWhen (true or false). If we cannot
1771 /// evaluate the trip count of the loop, return UnknownValue.
1772 SCEVHandle ScalarEvolutionsImpl::
1773 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1774 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1775 if (PN == 0) return UnknownValue;
1777 // Since the loop is canonicalized, the PHI node must have two entries. One
1778 // entry must be a constant (coming in from outside of the loop), and the
1779 // second must be derived from the same PHI.
1780 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1781 Constant *StartCST =
1782 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1783 if (StartCST == 0) return UnknownValue; // Must be a constant.
1785 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1786 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1787 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1789 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1790 // the loop symbolically to determine when the condition gets a value of
1792 unsigned IterationNum = 0;
1793 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1794 for (Constant *PHIVal = StartCST;
1795 IterationNum != MaxIterations; ++IterationNum) {
1796 ConstantBool *CondVal =
1797 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1798 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1800 if (CondVal->getValue() == ExitWhen) {
1801 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1802 ++NumBruteForceTripCountsComputed;
1803 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1806 // Compute the value of the PHI node for the next iteration.
1807 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1808 if (NextPHI == 0 || NextPHI == PHIVal)
1809 return UnknownValue; // Couldn't evaluate or not making progress...
1813 // Too many iterations were needed to evaluate.
1814 return UnknownValue;
1817 /// getSCEVAtScope - Compute the value of the specified expression within the
1818 /// indicated loop (which may be null to indicate in no loop). If the
1819 /// expression cannot be evaluated, return UnknownValue.
1820 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1821 // FIXME: this should be turned into a virtual method on SCEV!
1823 if (isa<SCEVConstant>(V)) return V;
1825 // If this instruction is evolves from a constant-evolving PHI, compute the
1826 // exit value from the loop without using SCEVs.
1827 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1828 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1829 const Loop *LI = this->LI[I->getParent()];
1830 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1831 if (PHINode *PN = dyn_cast<PHINode>(I))
1832 if (PN->getParent() == LI->getHeader()) {
1833 // Okay, there is no closed form solution for the PHI node. Check
1834 // to see if the loop that contains it has a known iteration count.
1835 // If so, we may be able to force computation of the exit value.
1836 SCEVHandle IterationCount = getIterationCount(LI);
1837 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1838 // Okay, we know how many times the containing loop executes. If
1839 // this is a constant evolving PHI node, get the final value at
1840 // the specified iteration number.
1841 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1842 ICC->getValue()->getRawValue(),
1844 if (RV) return SCEVUnknown::get(RV);
1848 // Okay, this is a some expression that we cannot symbolically evaluate
1849 // into a SCEV. Check to see if it's possible to symbolically evaluate
1850 // the arguments into constants, and if see, try to constant propagate the
1851 // result. This is particularly useful for computing loop exit values.
1852 if (CanConstantFold(I)) {
1853 std::vector<Constant*> Operands;
1854 Operands.reserve(I->getNumOperands());
1855 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1856 Value *Op = I->getOperand(i);
1857 if (Constant *C = dyn_cast<Constant>(Op)) {
1858 Operands.push_back(C);
1860 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1861 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1862 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1864 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1865 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1866 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1874 return SCEVUnknown::get(ConstantFold(I, Operands));
1878 // This is some other type of SCEVUnknown, just return it.
1882 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1883 // Avoid performing the look-up in the common case where the specified
1884 // expression has no loop-variant portions.
1885 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1886 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1887 if (OpAtScope != Comm->getOperand(i)) {
1888 if (OpAtScope == UnknownValue) return UnknownValue;
1889 // Okay, at least one of these operands is loop variant but might be
1890 // foldable. Build a new instance of the folded commutative expression.
1891 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1892 NewOps.push_back(OpAtScope);
1894 for (++i; i != e; ++i) {
1895 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1896 if (OpAtScope == UnknownValue) return UnknownValue;
1897 NewOps.push_back(OpAtScope);
1899 if (isa<SCEVAddExpr>(Comm))
1900 return SCEVAddExpr::get(NewOps);
1901 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1902 return SCEVMulExpr::get(NewOps);
1905 // If we got here, all operands are loop invariant.
1909 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1910 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1911 if (LHS == UnknownValue) return LHS;
1912 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1913 if (RHS == UnknownValue) return RHS;
1914 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1915 return UDiv; // must be loop invariant
1916 return SCEVUDivExpr::get(LHS, RHS);
1919 // If this is a loop recurrence for a loop that does not contain L, then we
1920 // are dealing with the final value computed by the loop.
1921 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1922 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1923 // To evaluate this recurrence, we need to know how many times the AddRec
1924 // loop iterates. Compute this now.
1925 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1926 if (IterationCount == UnknownValue) return UnknownValue;
1927 IterationCount = getTruncateOrZeroExtend(IterationCount,
1930 // If the value is affine, simplify the expression evaluation to just
1931 // Start + Step*IterationCount.
1932 if (AddRec->isAffine())
1933 return SCEVAddExpr::get(AddRec->getStart(),
1934 SCEVMulExpr::get(IterationCount,
1935 AddRec->getOperand(1)));
1937 // Otherwise, evaluate it the hard way.
1938 return AddRec->evaluateAtIteration(IterationCount);
1940 return UnknownValue;
1943 //assert(0 && "Unknown SCEV type!");
1944 return UnknownValue;
1948 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1949 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1950 /// might be the same) or two SCEVCouldNotCompute objects.
1952 static std::pair<SCEVHandle,SCEVHandle>
1953 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1954 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1955 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1956 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1957 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1959 // We currently can only solve this if the coefficients are constants.
1960 if (!L || !M || !N) {
1961 SCEV *CNC = new SCEVCouldNotCompute();
1962 return std::make_pair(CNC, CNC);
1965 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1967 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1968 Constant *C = L->getValue();
1969 // The B coefficient is M-N/2
1970 Constant *B = ConstantExpr::getSub(M->getValue(),
1971 ConstantExpr::getDiv(N->getValue(),
1973 // The A coefficient is N/2
1974 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1976 // Compute the B^2-4ac term.
1977 Constant *SqrtTerm =
1978 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1979 ConstantExpr::getMul(A, C));
1980 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1982 // Compute floor(sqrt(B^2-4ac))
1983 ConstantUInt *SqrtVal =
1984 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1985 SqrtTerm->getType()->getUnsignedVersion()));
1986 uint64_t SqrtValV = SqrtVal->getValue();
1987 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
1988 // The square root might not be precise for arbitrary 64-bit integer
1989 // values. Do some sanity checks to ensure it's correct.
1990 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1991 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1992 SCEV *CNC = new SCEVCouldNotCompute();
1993 return std::make_pair(CNC, CNC);
1996 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1997 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1999 Constant *NegB = ConstantExpr::getNeg(B);
2000 Constant *TwoA = ConstantExpr::getMul(A, Two);
2002 // The divisions must be performed as signed divisions.
2003 const Type *SignedTy = NegB->getType()->getSignedVersion();
2004 NegB = ConstantExpr::getCast(NegB, SignedTy);
2005 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2006 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2008 Constant *Solution1 =
2009 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2010 Constant *Solution2 =
2011 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2012 return std::make_pair(SCEVUnknown::get(Solution1),
2013 SCEVUnknown::get(Solution2));
2016 /// HowFarToZero - Return the number of times a backedge comparing the specified
2017 /// value to zero will execute. If not computable, return UnknownValue
2018 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2019 // If the value is a constant
2020 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2021 // If the value is already zero, the branch will execute zero times.
2022 if (C->getValue()->isNullValue()) return C;
2023 return UnknownValue; // Otherwise it will loop infinitely.
2026 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2027 if (!AddRec || AddRec->getLoop() != L)
2028 return UnknownValue;
2030 if (AddRec->isAffine()) {
2031 // If this is an affine expression the execution count of this branch is
2034 // (0 - Start/Step) iff Start % Step == 0
2036 // Get the initial value for the loop.
2037 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2038 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2039 SCEVHandle Step = AddRec->getOperand(1);
2041 Step = getSCEVAtScope(Step, L->getParentLoop());
2043 // Figure out if Start % Step == 0.
2044 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2045 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2046 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2047 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
2048 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2049 return Start; // 0 - Start/-1 == Start
2051 // Check to see if Start is divisible by SC with no remainder.
2052 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2053 ConstantInt *StartCC = StartC->getValue();
2054 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2055 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2056 if (Rem->isNullValue()) {
2057 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2058 return SCEVUnknown::get(Result);
2062 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2063 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2064 // the quadratic equation to solve it.
2065 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2066 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2067 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2070 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2071 << " sol#2: " << *R2 << "\n";
2073 // Pick the smallest positive root value.
2074 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2075 if (ConstantBool *CB =
2076 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2078 if (CB != ConstantBool::True)
2079 std::swap(R1, R2); // R1 is the minimum root now.
2081 // We can only use this value if the chrec ends up with an exact zero
2082 // value at this index. When solving for "X*X != 5", for example, we
2083 // should not accept a root of 2.
2084 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2085 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2086 if (EvalVal->getValue()->isNullValue())
2087 return R1; // We found a quadratic root!
2092 return UnknownValue;
2095 /// HowFarToNonZero - Return the number of times a backedge checking the
2096 /// specified value for nonzero will execute. If not computable, return
2098 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2099 // Loops that look like: while (X == 0) are very strange indeed. We don't
2100 // handle them yet except for the trivial case. This could be expanded in the
2101 // future as needed.
2103 // If the value is a constant, check to see if it is known to be non-zero
2104 // already. If so, the backedge will execute zero times.
2105 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2106 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2107 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2108 if (NonZero == ConstantBool::True)
2109 return getSCEV(Zero);
2110 return UnknownValue; // Otherwise it will loop infinitely.
2113 // We could implement others, but I really doubt anyone writes loops like
2114 // this, and if they did, they would already be constant folded.
2115 return UnknownValue;
2118 /// getNumIterationsInRange - Return the number of iterations of this loop that
2119 /// produce values in the specified constant range. Another way of looking at
2120 /// this is that it returns the first iteration number where the value is not in
2121 /// the condition, thus computing the exit count. If the iteration count can't
2122 /// be computed, an instance of SCEVCouldNotCompute is returned.
2123 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2124 if (Range.isFullSet()) // Infinite loop.
2125 return new SCEVCouldNotCompute();
2127 // If the start is a non-zero constant, shift the range to simplify things.
2128 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2129 if (!SC->getValue()->isNullValue()) {
2130 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2131 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2132 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2133 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2134 return ShiftedAddRec->getNumIterationsInRange(
2135 Range.subtract(SC->getValue()));
2136 // This is strange and shouldn't happen.
2137 return new SCEVCouldNotCompute();
2140 // The only time we can solve this is when we have all constant indices.
2141 // Otherwise, we cannot determine the overflow conditions.
2142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2143 if (!isa<SCEVConstant>(getOperand(i)))
2144 return new SCEVCouldNotCompute();
2147 // Okay at this point we know that all elements of the chrec are constants and
2148 // that the start element is zero.
2150 // First check to see if the range contains zero. If not, the first
2152 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2153 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2156 // If this is an affine expression then we have this situation:
2157 // Solve {0,+,A} in Range === Ax in Range
2159 // Since we know that zero is in the range, we know that the upper value of
2160 // the range must be the first possible exit value. Also note that we
2161 // already checked for a full range.
2162 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2163 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2164 ConstantInt *One = ConstantInt::get(getType(), 1);
2166 // The exit value should be (Upper+A-1)/A.
2167 Constant *ExitValue = Upper;
2169 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2170 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2172 assert(isa<ConstantInt>(ExitValue) &&
2173 "Constant folding of integers not implemented?");
2175 // Evaluate at the exit value. If we really did fall out of the valid
2176 // range, then we computed our trip count, otherwise wrap around or other
2177 // things must have happened.
2178 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2179 if (Range.contains(Val))
2180 return new SCEVCouldNotCompute(); // Something strange happened
2182 // Ensure that the previous value is in the range. This is a sanity check.
2183 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2184 ConstantExpr::getSub(ExitValue, One))) &&
2185 "Linear scev computation is off in a bad way!");
2186 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2187 } else if (isQuadratic()) {
2188 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2189 // quadratic equation to solve it. To do this, we must frame our problem in
2190 // terms of figuring out when zero is crossed, instead of when
2191 // Range.getUpper() is crossed.
2192 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2193 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2194 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2196 // Next, solve the constructed addrec
2197 std::pair<SCEVHandle,SCEVHandle> Roots =
2198 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2199 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2200 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2202 // Pick the smallest positive root value.
2203 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2204 if (ConstantBool *CB =
2205 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2207 if (CB != ConstantBool::True)
2208 std::swap(R1, R2); // R1 is the minimum root now.
2210 // Make sure the root is not off by one. The returned iteration should
2211 // not be in the range, but the previous one should be. When solving
2212 // for "X*X < 5", for example, we should not return a root of 2.
2213 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2215 if (Range.contains(R1Val)) {
2216 // The next iteration must be out of the range...
2218 ConstantExpr::getAdd(R1->getValue(),
2219 ConstantInt::get(R1->getType(), 1));
2221 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2222 if (!Range.contains(R1Val))
2223 return SCEVUnknown::get(NextVal);
2224 return new SCEVCouldNotCompute(); // Something strange happened
2227 // If R1 was not in the range, then it is a good return value. Make
2228 // sure that R1-1 WAS in the range though, just in case.
2230 ConstantExpr::getSub(R1->getValue(),
2231 ConstantInt::get(R1->getType(), 1));
2232 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2233 if (Range.contains(R1Val))
2235 return new SCEVCouldNotCompute(); // Something strange happened
2240 // Fallback, if this is a general polynomial, figure out the progression
2241 // through brute force: evaluate until we find an iteration that fails the
2242 // test. This is likely to be slow, but getting an accurate trip count is
2243 // incredibly important, we will be able to simplify the exit test a lot, and
2244 // we are almost guaranteed to get a trip count in this case.
2245 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2246 ConstantInt *One = ConstantInt::get(getType(), 1);
2247 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2249 ++NumBruteForceEvaluations;
2250 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2251 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2252 return new SCEVCouldNotCompute();
2254 // Check to see if we found the value!
2255 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2256 return SCEVConstant::get(TestVal);
2258 // Increment to test the next index.
2259 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2260 } while (TestVal != EndVal);
2262 return new SCEVCouldNotCompute();
2267 //===----------------------------------------------------------------------===//
2268 // ScalarEvolution Class Implementation
2269 //===----------------------------------------------------------------------===//
2271 bool ScalarEvolution::runOnFunction(Function &F) {
2272 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2276 void ScalarEvolution::releaseMemory() {
2277 delete (ScalarEvolutionsImpl*)Impl;
2281 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2282 AU.setPreservesAll();
2283 AU.addRequiredID(LoopSimplifyID);
2284 AU.addRequiredTransitive<LoopInfo>();
2287 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2288 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2291 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2292 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2295 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2296 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2299 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2300 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2303 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2304 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2307 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2309 // Print all inner loops first
2310 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2311 PrintLoopInfo(OS, SE, *I);
2313 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2315 std::vector<BasicBlock*> ExitBlocks;
2316 L->getExitBlocks(ExitBlocks);
2317 if (ExitBlocks.size() != 1)
2318 std::cerr << "<multiple exits> ";
2320 if (SE->hasLoopInvariantIterationCount(L)) {
2321 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2323 std::cerr << "Unpredictable iteration count. ";
2329 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2330 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2331 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2333 OS << "Classifying expressions for: " << F.getName() << "\n";
2334 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2335 if (I->getType()->isInteger()) {
2338 SCEVHandle SV = getSCEV(&*I);
2342 if ((*I).getType()->isIntegral()) {
2343 ConstantRange Bounds = SV->getValueRange();
2344 if (!Bounds.isFullSet())
2345 OS << "Bounds: " << Bounds << " ";
2348 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2350 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2351 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2352 OS << "<<Unknown>>";
2362 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2363 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2364 PrintLoopInfo(OS, this, *I);