1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Assembly/Writer.h"
72 #include "llvm/Target/TargetData.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/GetElementPtrTypeIterator.h"
77 #include "llvm/Support/InstIterator.h"
78 #include "llvm/Support/ManagedStatic.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include "llvm/ADT/Statistic.h"
82 #include "llvm/ADT/STLExtras.h"
86 STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88 STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90 STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92 STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
95 static cl::opt<unsigned>
96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
101 static RegisterPass<ScalarEvolution>
102 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
103 char ScalarEvolution::ID = 0;
105 //===----------------------------------------------------------------------===//
106 // SCEV class definitions
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
110 // Implementation of the SCEV class.
113 void SCEV::dump() const {
118 void SCEV::print(std::ostream &o) const {
119 raw_os_ostream OS(o);
123 bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
129 bool SCEV::isOne() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isOne();
135 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
136 SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
138 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143 const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
148 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
153 SCEVHandle SCEVCouldNotCompute::
154 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
155 const SCEVHandle &Conc,
156 ScalarEvolution &SE) const {
160 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
161 OS << "***COULDNOTCOMPUTE***";
164 bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
169 // SCEVConstants - Only allow the creation of one SCEVConstant for any
170 // particular value. Don't use a SCEVHandle here, or else the object will
172 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
175 SCEVConstant::~SCEVConstant() {
176 SCEVConstants->erase(V);
179 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
180 SCEVConstant *&R = (*SCEVConstants)[V];
181 if (R == 0) R = new SCEVConstant(V);
185 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(Val));
190 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
191 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
194 const Type *SCEVConstant::getType() const { return V->getType(); }
196 void SCEVConstant::print(raw_ostream &OS) const {
197 WriteAsOperand(OS, V, false);
200 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
201 const SCEVHandle &op, const Type *ty)
202 : SCEV(SCEVTy), Op(op), Ty(ty) {}
204 SCEVCastExpr::~SCEVCastExpr() {}
206 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
210 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
211 // particular input. Don't use a SCEVHandle here, or else the object will
213 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
214 SCEVTruncateExpr*> > SCEVTruncates;
216 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
217 : SCEVCastExpr(scTruncate, op, ty) {
218 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
219 (Ty->isInteger() || isa<PointerType>(Ty)) &&
220 "Cannot truncate non-integer value!");
223 SCEVTruncateExpr::~SCEVTruncateExpr() {
224 SCEVTruncates->erase(std::make_pair(Op, Ty));
227 void SCEVTruncateExpr::print(raw_ostream &OS) const {
228 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
231 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
232 // particular input. Don't use a SCEVHandle here, or else the object will never
234 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
235 SCEVZeroExtendExpr*> > SCEVZeroExtends;
237 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
238 : SCEVCastExpr(scZeroExtend, op, ty) {
239 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
240 (Ty->isInteger() || isa<PointerType>(Ty)) &&
241 "Cannot zero extend non-integer value!");
244 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
245 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
248 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
249 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
252 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
253 // particular input. Don't use a SCEVHandle here, or else the object will never
255 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
256 SCEVSignExtendExpr*> > SCEVSignExtends;
258 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
259 : SCEVCastExpr(scSignExtend, op, ty) {
260 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
261 (Ty->isInteger() || isa<PointerType>(Ty)) &&
262 "Cannot sign extend non-integer value!");
265 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
266 SCEVSignExtends->erase(std::make_pair(Op, Ty));
269 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
270 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
273 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
274 // particular input. Don't use a SCEVHandle here, or else the object will never
276 static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
277 SCEVCommutativeExpr*> > SCEVCommExprs;
279 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
280 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
281 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
284 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
285 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
286 const char *OpStr = getOperationStr();
287 OS << "(" << *Operands[0];
288 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
289 OS << OpStr << *Operands[i];
293 SCEVHandle SCEVCommutativeExpr::
294 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
295 const SCEVHandle &Conc,
296 ScalarEvolution &SE) const {
297 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
299 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
300 if (H != getOperand(i)) {
301 SmallVector<SCEVHandle, 8> NewOps;
302 NewOps.reserve(getNumOperands());
303 for (unsigned j = 0; j != i; ++j)
304 NewOps.push_back(getOperand(j));
306 for (++i; i != e; ++i)
307 NewOps.push_back(getOperand(i)->
308 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
310 if (isa<SCEVAddExpr>(this))
311 return SE.getAddExpr(NewOps);
312 else if (isa<SCEVMulExpr>(this))
313 return SE.getMulExpr(NewOps);
314 else if (isa<SCEVSMaxExpr>(this))
315 return SE.getSMaxExpr(NewOps);
316 else if (isa<SCEVUMaxExpr>(this))
317 return SE.getUMaxExpr(NewOps);
319 assert(0 && "Unknown commutative expr!");
325 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
327 if (!getOperand(i)->dominates(BB, DT))
334 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
335 // input. Don't use a SCEVHandle here, or else the object will never be
337 static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
338 SCEVUDivExpr*> > SCEVUDivs;
340 SCEVUDivExpr::~SCEVUDivExpr() {
341 SCEVUDivs->erase(std::make_pair(LHS, RHS));
344 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
345 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
348 void SCEVUDivExpr::print(raw_ostream &OS) const {
349 OS << "(" << *LHS << " /u " << *RHS << ")";
352 const Type *SCEVUDivExpr::getType() const {
353 // In most cases the types of LHS and RHS will be the same, but in some
354 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
355 // depend on the type for correctness, but handling types carefully can
356 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
357 // a pointer type than the RHS, so use the RHS' type here.
358 return RHS->getType();
361 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
362 // particular input. Don't use a SCEVHandle here, or else the object will never
364 static ManagedStatic<std::map<std::pair<const Loop *,
365 std::vector<const SCEV*> >,
366 SCEVAddRecExpr*> > SCEVAddRecExprs;
368 SCEVAddRecExpr::~SCEVAddRecExpr() {
369 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
370 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
373 SCEVHandle SCEVAddRecExpr::
374 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
375 const SCEVHandle &Conc,
376 ScalarEvolution &SE) const {
377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
379 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
380 if (H != getOperand(i)) {
381 SmallVector<SCEVHandle, 8> NewOps;
382 NewOps.reserve(getNumOperands());
383 for (unsigned j = 0; j != i; ++j)
384 NewOps.push_back(getOperand(j));
386 for (++i; i != e; ++i)
387 NewOps.push_back(getOperand(i)->
388 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
390 return SE.getAddRecExpr(NewOps, L);
397 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
398 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
399 // contain L and if the start is invariant.
400 // Add recurrences are never invariant in the function-body (null loop).
402 !QueryLoop->contains(L->getHeader()) &&
403 getOperand(0)->isLoopInvariant(QueryLoop);
407 void SCEVAddRecExpr::print(raw_ostream &OS) const {
408 OS << "{" << *Operands[0];
409 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
410 OS << ",+," << *Operands[i];
411 OS << "}<" << L->getHeader()->getName() + ">";
414 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
415 // value. Don't use a SCEVHandle here, or else the object will never be
417 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
419 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
421 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
422 // All non-instruction values are loop invariant. All instructions are loop
423 // invariant if they are not contained in the specified loop.
424 // Instructions are never considered invariant in the function body
425 // (null loop) because they are defined within the "loop".
426 if (Instruction *I = dyn_cast<Instruction>(V))
427 return L && !L->contains(I->getParent());
431 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
432 if (Instruction *I = dyn_cast<Instruction>(getValue()))
433 return DT->dominates(I->getParent(), BB);
437 const Type *SCEVUnknown::getType() const {
441 void SCEVUnknown::print(raw_ostream &OS) const {
442 WriteAsOperand(OS, V, false);
445 //===----------------------------------------------------------------------===//
447 //===----------------------------------------------------------------------===//
450 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
451 /// than the complexity of the RHS. This comparator is used to canonicalize
453 class VISIBILITY_HIDDEN SCEVComplexityCompare {
456 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
458 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
459 // Primarily, sort the SCEVs by their getSCEVType().
460 if (LHS->getSCEVType() != RHS->getSCEVType())
461 return LHS->getSCEVType() < RHS->getSCEVType();
463 // Aside from the getSCEVType() ordering, the particular ordering
464 // isn't very important except that it's beneficial to be consistent,
465 // so that (a + b) and (b + a) don't end up as different expressions.
467 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
468 // not as complete as it could be.
469 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
470 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
472 // Order pointer values after integer values. This helps SCEVExpander
474 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
476 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
479 // Compare getValueID values.
480 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
481 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
483 // Sort arguments by their position.
484 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
485 const Argument *RA = cast<Argument>(RU->getValue());
486 return LA->getArgNo() < RA->getArgNo();
489 // For instructions, compare their loop depth, and their opcode.
490 // This is pretty loose.
491 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
492 Instruction *RV = cast<Instruction>(RU->getValue());
494 // Compare loop depths.
495 if (LI->getLoopDepth(LV->getParent()) !=
496 LI->getLoopDepth(RV->getParent()))
497 return LI->getLoopDepth(LV->getParent()) <
498 LI->getLoopDepth(RV->getParent());
501 if (LV->getOpcode() != RV->getOpcode())
502 return LV->getOpcode() < RV->getOpcode();
504 // Compare the number of operands.
505 if (LV->getNumOperands() != RV->getNumOperands())
506 return LV->getNumOperands() < RV->getNumOperands();
512 // Compare constant values.
513 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
514 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
515 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
518 // Compare addrec loop depths.
519 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
520 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
521 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
522 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
525 // Lexicographically compare n-ary expressions.
526 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
527 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
528 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
529 if (i >= RC->getNumOperands())
531 if (operator()(LC->getOperand(i), RC->getOperand(i)))
533 if (operator()(RC->getOperand(i), LC->getOperand(i)))
536 return LC->getNumOperands() < RC->getNumOperands();
539 // Lexicographically compare udiv expressions.
540 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
541 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
542 if (operator()(LC->getLHS(), RC->getLHS()))
544 if (operator()(RC->getLHS(), LC->getLHS()))
546 if (operator()(LC->getRHS(), RC->getRHS()))
548 if (operator()(RC->getRHS(), LC->getRHS()))
553 // Compare cast expressions by operand.
554 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
555 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
556 return operator()(LC->getOperand(), RC->getOperand());
559 assert(0 && "Unknown SCEV kind!");
565 /// GroupByComplexity - Given a list of SCEV objects, order them by their
566 /// complexity, and group objects of the same complexity together by value.
567 /// When this routine is finished, we know that any duplicates in the vector are
568 /// consecutive and that complexity is monotonically increasing.
570 /// Note that we go take special precautions to ensure that we get determinstic
571 /// results from this routine. In other words, we don't want the results of
572 /// this to depend on where the addresses of various SCEV objects happened to
575 static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
577 if (Ops.size() < 2) return; // Noop
578 if (Ops.size() == 2) {
579 // This is the common case, which also happens to be trivially simple.
581 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
582 std::swap(Ops[0], Ops[1]);
586 // Do the rough sort by complexity.
587 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
589 // Now that we are sorted by complexity, group elements of the same
590 // complexity. Note that this is, at worst, N^2, but the vector is likely to
591 // be extremely short in practice. Note that we take this approach because we
592 // do not want to depend on the addresses of the objects we are grouping.
593 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
594 const SCEV *S = Ops[i];
595 unsigned Complexity = S->getSCEVType();
597 // If there are any objects of the same complexity and same value as this
599 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
600 if (Ops[j] == S) { // Found a duplicate.
601 // Move it to immediately after i'th element.
602 std::swap(Ops[i+1], Ops[j]);
603 ++i; // no need to rescan it.
604 if (i == e-2) return; // Done!
612 //===----------------------------------------------------------------------===//
613 // Simple SCEV method implementations
614 //===----------------------------------------------------------------------===//
616 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
618 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
620 const Type* ResultTy) {
621 // Handle the simplest case efficiently.
623 return SE.getTruncateOrZeroExtend(It, ResultTy);
625 // We are using the following formula for BC(It, K):
627 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
629 // Suppose, W is the bitwidth of the return value. We must be prepared for
630 // overflow. Hence, we must assure that the result of our computation is
631 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
632 // safe in modular arithmetic.
634 // However, this code doesn't use exactly that formula; the formula it uses
635 // is something like the following, where T is the number of factors of 2 in
636 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
639 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
641 // This formula is trivially equivalent to the previous formula. However,
642 // this formula can be implemented much more efficiently. The trick is that
643 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
644 // arithmetic. To do exact division in modular arithmetic, all we have
645 // to do is multiply by the inverse. Therefore, this step can be done at
648 // The next issue is how to safely do the division by 2^T. The way this
649 // is done is by doing the multiplication step at a width of at least W + T
650 // bits. This way, the bottom W+T bits of the product are accurate. Then,
651 // when we perform the division by 2^T (which is equivalent to a right shift
652 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
653 // truncated out after the division by 2^T.
655 // In comparison to just directly using the first formula, this technique
656 // is much more efficient; using the first formula requires W * K bits,
657 // but this formula less than W + K bits. Also, the first formula requires
658 // a division step, whereas this formula only requires multiplies and shifts.
660 // It doesn't matter whether the subtraction step is done in the calculation
661 // width or the input iteration count's width; if the subtraction overflows,
662 // the result must be zero anyway. We prefer here to do it in the width of
663 // the induction variable because it helps a lot for certain cases; CodeGen
664 // isn't smart enough to ignore the overflow, which leads to much less
665 // efficient code if the width of the subtraction is wider than the native
668 // (It's possible to not widen at all by pulling out factors of 2 before
669 // the multiplication; for example, K=2 can be calculated as
670 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
671 // extra arithmetic, so it's not an obvious win, and it gets
672 // much more complicated for K > 3.)
674 // Protection from insane SCEVs; this bound is conservative,
675 // but it probably doesn't matter.
677 return SE.getCouldNotCompute();
679 unsigned W = SE.getTypeSizeInBits(ResultTy);
681 // Calculate K! / 2^T and T; we divide out the factors of two before
682 // multiplying for calculating K! / 2^T to avoid overflow.
683 // Other overflow doesn't matter because we only care about the bottom
684 // W bits of the result.
685 APInt OddFactorial(W, 1);
687 for (unsigned i = 3; i <= K; ++i) {
689 unsigned TwoFactors = Mult.countTrailingZeros();
691 Mult = Mult.lshr(TwoFactors);
692 OddFactorial *= Mult;
695 // We need at least W + T bits for the multiplication step
696 unsigned CalculationBits = W + T;
698 // Calcuate 2^T, at width T+W.
699 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
701 // Calculate the multiplicative inverse of K! / 2^T;
702 // this multiplication factor will perform the exact division by
704 APInt Mod = APInt::getSignedMinValue(W+1);
705 APInt MultiplyFactor = OddFactorial.zext(W+1);
706 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
707 MultiplyFactor = MultiplyFactor.trunc(W);
709 // Calculate the product, at width T+W
710 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
711 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
712 for (unsigned i = 1; i != K; ++i) {
713 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
714 Dividend = SE.getMulExpr(Dividend,
715 SE.getTruncateOrZeroExtend(S, CalculationTy));
719 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
721 // Truncate the result, and divide by K! / 2^T.
723 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
724 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
727 /// evaluateAtIteration - Return the value of this chain of recurrences at
728 /// the specified iteration number. We can evaluate this recurrence by
729 /// multiplying each element in the chain by the binomial coefficient
730 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
732 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
734 /// where BC(It, k) stands for binomial coefficient.
736 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
737 ScalarEvolution &SE) const {
738 SCEVHandle Result = getStart();
739 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
740 // The computation is correct in the face of overflow provided that the
741 // multiplication is performed _after_ the evaluation of the binomial
743 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
744 if (isa<SCEVCouldNotCompute>(Coeff))
747 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
752 //===----------------------------------------------------------------------===//
753 // SCEV Expression folder implementations
754 //===----------------------------------------------------------------------===//
756 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
758 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
759 "This is not a truncating conversion!");
760 assert(isSCEVable(Ty) &&
761 "This is not a conversion to a SCEVable type!");
762 Ty = getEffectiveSCEVType(Ty);
764 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
766 ConstantExpr::getTrunc(SC->getValue(), Ty));
768 // trunc(trunc(x)) --> trunc(x)
769 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
770 return getTruncateExpr(ST->getOperand(), Ty);
772 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
773 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
774 return getTruncateOrSignExtend(SS->getOperand(), Ty);
776 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
777 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
778 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
780 // If the input value is a chrec scev made out of constants, truncate
781 // all of the constants.
782 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
783 SmallVector<SCEVHandle, 4> Operands;
784 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
785 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
786 return getAddRecExpr(Operands, AddRec->getLoop());
789 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
790 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
794 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
796 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
797 "This is not an extending conversion!");
798 assert(isSCEVable(Ty) &&
799 "This is not a conversion to a SCEVable type!");
800 Ty = getEffectiveSCEVType(Ty);
802 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
803 const Type *IntTy = getEffectiveSCEVType(Ty);
804 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
805 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
806 return getUnknown(C);
809 // zext(zext(x)) --> zext(x)
810 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
811 return getZeroExtendExpr(SZ->getOperand(), Ty);
813 // If the input value is a chrec scev, and we can prove that the value
814 // did not overflow the old, smaller, value, we can zero extend all of the
815 // operands (often constants). This allows analysis of something like
816 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
817 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
818 if (AR->isAffine()) {
819 // Check whether the backedge-taken count is SCEVCouldNotCompute.
820 // Note that this serves two purposes: It filters out loops that are
821 // simply not analyzable, and it covers the case where this code is
822 // being called from within backedge-taken count analysis, such that
823 // attempting to ask for the backedge-taken count would likely result
824 // in infinite recursion. In the later case, the analysis code will
825 // cope with a conservative value, and it will take care to purge
826 // that value once it has finished.
827 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
828 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
829 // Manually compute the final value for AR, checking for
831 SCEVHandle Start = AR->getStart();
832 SCEVHandle Step = AR->getStepRecurrence(*this);
834 // Check whether the backedge-taken count can be losslessly casted to
835 // the addrec's type. The count is always unsigned.
836 SCEVHandle CastedMaxBECount =
837 getTruncateOrZeroExtend(MaxBECount, Start->getType());
838 SCEVHandle RecastedMaxBECount =
839 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
840 if (MaxBECount == RecastedMaxBECount) {
842 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
843 // Check whether Start+Step*MaxBECount has no unsigned overflow.
845 getMulExpr(CastedMaxBECount,
846 getTruncateOrZeroExtend(Step, Start->getType()));
847 SCEVHandle Add = getAddExpr(Start, ZMul);
848 SCEVHandle OperandExtendedAdd =
849 getAddExpr(getZeroExtendExpr(Start, WideTy),
850 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
851 getZeroExtendExpr(Step, WideTy)));
852 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
853 // Return the expression with the addrec on the outside.
854 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
855 getZeroExtendExpr(Step, Ty),
858 // Similar to above, only this time treat the step value as signed.
859 // This covers loops that count down.
861 getMulExpr(CastedMaxBECount,
862 getTruncateOrSignExtend(Step, Start->getType()));
863 Add = getAddExpr(Start, SMul);
865 getAddExpr(getZeroExtendExpr(Start, WideTy),
866 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
867 getSignExtendExpr(Step, WideTy)));
868 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
869 // Return the expression with the addrec on the outside.
870 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
871 getSignExtendExpr(Step, Ty),
877 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
878 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
882 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
885 "This is not an extending conversion!");
886 assert(isSCEVable(Ty) &&
887 "This is not a conversion to a SCEVable type!");
888 Ty = getEffectiveSCEVType(Ty);
890 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
891 const Type *IntTy = getEffectiveSCEVType(Ty);
892 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
893 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
894 return getUnknown(C);
897 // sext(sext(x)) --> sext(x)
898 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
899 return getSignExtendExpr(SS->getOperand(), Ty);
901 // If the input value is a chrec scev, and we can prove that the value
902 // did not overflow the old, smaller, value, we can sign extend all of the
903 // operands (often constants). This allows analysis of something like
904 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
905 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
906 if (AR->isAffine()) {
907 // Check whether the backedge-taken count is SCEVCouldNotCompute.
908 // Note that this serves two purposes: It filters out loops that are
909 // simply not analyzable, and it covers the case where this code is
910 // being called from within backedge-taken count analysis, such that
911 // attempting to ask for the backedge-taken count would likely result
912 // in infinite recursion. In the later case, the analysis code will
913 // cope with a conservative value, and it will take care to purge
914 // that value once it has finished.
915 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
916 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
917 // Manually compute the final value for AR, checking for
919 SCEVHandle Start = AR->getStart();
920 SCEVHandle Step = AR->getStepRecurrence(*this);
922 // Check whether the backedge-taken count can be losslessly casted to
923 // the addrec's type. The count is always unsigned.
924 SCEVHandle CastedMaxBECount =
925 getTruncateOrZeroExtend(MaxBECount, Start->getType());
926 SCEVHandle RecastedMaxBECount =
927 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
928 if (MaxBECount == RecastedMaxBECount) {
930 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
931 // Check whether Start+Step*MaxBECount has no signed overflow.
933 getMulExpr(CastedMaxBECount,
934 getTruncateOrSignExtend(Step, Start->getType()));
935 SCEVHandle Add = getAddExpr(Start, SMul);
936 SCEVHandle OperandExtendedAdd =
937 getAddExpr(getSignExtendExpr(Start, WideTy),
938 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
939 getSignExtendExpr(Step, WideTy)));
940 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
941 // Return the expression with the addrec on the outside.
942 return getAddRecExpr(getSignExtendExpr(Start, Ty),
943 getSignExtendExpr(Step, Ty),
949 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
950 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
954 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
955 /// unspecified bits out to the given type.
957 SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
959 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
960 "This is not an extending conversion!");
961 assert(isSCEVable(Ty) &&
962 "This is not a conversion to a SCEVable type!");
963 Ty = getEffectiveSCEVType(Ty);
965 // Sign-extend negative constants.
966 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
967 if (SC->getValue()->getValue().isNegative())
968 return getSignExtendExpr(Op, Ty);
970 // Peel off a truncate cast.
971 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
972 SCEVHandle NewOp = T->getOperand();
973 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
974 return getAnyExtendExpr(NewOp, Ty);
975 return getTruncateOrNoop(NewOp, Ty);
978 // Next try a zext cast. If the cast is folded, use it.
979 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
980 if (!isa<SCEVZeroExtendExpr>(ZExt))
983 // Next try a sext cast. If the cast is folded, use it.
984 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
985 if (!isa<SCEVSignExtendExpr>(SExt))
988 // If the expression is obviously signed, use the sext cast value.
989 if (isa<SCEVSMaxExpr>(Op))
992 // Absent any other information, use the zext cast value.
996 /// CollectAddOperandsWithScales - Process the given Ops list, which is
997 /// a list of operands to be added under the given scale, update the given
998 /// map. This is a helper function for getAddRecExpr. As an example of
999 /// what it does, given a sequence of operands that would form an add
1000 /// expression like this:
1002 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1004 /// where A and B are constants, update the map with these values:
1006 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1008 /// and add 13 + A*B*29 to AccumulatedConstant.
1009 /// This will allow getAddRecExpr to produce this:
1011 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1013 /// This form often exposes folding opportunities that are hidden in
1014 /// the original operand list.
1016 /// Return true iff it appears that any interesting folding opportunities
1017 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1018 /// the common case where no interesting opportunities are present, and
1019 /// is also used as a check to avoid infinite recursion.
1022 CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1023 SmallVector<SCEVHandle, 8> &NewOps,
1024 APInt &AccumulatedConstant,
1025 const SmallVectorImpl<SCEVHandle> &Ops,
1027 ScalarEvolution &SE) {
1028 bool Interesting = false;
1030 // Iterate over the add operands.
1031 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1032 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1033 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1035 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1036 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1037 // A multiplication of a constant with another add; recurse.
1039 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1040 cast<SCEVAddExpr>(Mul->getOperand(1))
1044 // A multiplication of a constant with some other value. Update
1046 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1047 SCEVHandle Key = SE.getMulExpr(MulOps);
1048 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1049 M.insert(std::make_pair(Key, APInt()));
1051 Pair.first->second = NewScale;
1052 NewOps.push_back(Pair.first->first);
1054 Pair.first->second += NewScale;
1055 // The map already had an entry for this value, which may indicate
1056 // a folding opportunity.
1060 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1061 // Pull a buried constant out to the outside.
1062 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1064 AccumulatedConstant += Scale * C->getValue()->getValue();
1066 // An ordinary operand. Update the map.
1067 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1068 M.insert(std::make_pair(Ops[i], APInt()));
1070 Pair.first->second = Scale;
1071 NewOps.push_back(Pair.first->first);
1073 Pair.first->second += Scale;
1074 // The map already had an entry for this value, which may indicate
1075 // a folding opportunity.
1085 struct APIntCompare {
1086 bool operator()(const APInt &LHS, const APInt &RHS) const {
1087 return LHS.ult(RHS);
1092 /// getAddExpr - Get a canonical add expression, or something simpler if
1094 SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1095 assert(!Ops.empty() && "Cannot get empty add!");
1096 if (Ops.size() == 1) return Ops[0];
1098 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1099 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1100 getEffectiveSCEVType(Ops[0]->getType()) &&
1101 "SCEVAddExpr operand types don't match!");
1104 // Sort by complexity, this groups all similar expression types together.
1105 GroupByComplexity(Ops, LI);
1107 // If there are any constants, fold them together.
1109 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1111 assert(Idx < Ops.size());
1112 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1113 // We found two constants, fold them together!
1114 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1115 RHSC->getValue()->getValue());
1116 if (Ops.size() == 2) return Ops[0];
1117 Ops.erase(Ops.begin()+1); // Erase the folded element
1118 LHSC = cast<SCEVConstant>(Ops[0]);
1121 // If we are left with a constant zero being added, strip it off.
1122 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1123 Ops.erase(Ops.begin());
1128 if (Ops.size() == 1) return Ops[0];
1130 // Okay, check to see if the same value occurs in the operand list twice. If
1131 // so, merge them together into an multiply expression. Since we sorted the
1132 // list, these values are required to be adjacent.
1133 const Type *Ty = Ops[0]->getType();
1134 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1135 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1136 // Found a match, merge the two values into a multiply, and add any
1137 // remaining values to the result.
1138 SCEVHandle Two = getIntegerSCEV(2, Ty);
1139 SCEVHandle Mul = getMulExpr(Ops[i], Two);
1140 if (Ops.size() == 2)
1142 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1144 return getAddExpr(Ops);
1147 // Check for truncates. If all the operands are truncated from the same
1148 // type, see if factoring out the truncate would permit the result to be
1149 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1150 // if the contents of the resulting outer trunc fold to something simple.
1151 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1152 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1153 const Type *DstType = Trunc->getType();
1154 const Type *SrcType = Trunc->getOperand()->getType();
1155 SmallVector<SCEVHandle, 8> LargeOps;
1157 // Check all the operands to see if they can be represented in the
1158 // source type of the truncate.
1159 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1161 if (T->getOperand()->getType() != SrcType) {
1165 LargeOps.push_back(T->getOperand());
1166 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1167 // This could be either sign or zero extension, but sign extension
1168 // is much more likely to be foldable here.
1169 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1170 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1171 SmallVector<SCEVHandle, 8> LargeMulOps;
1172 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1173 if (const SCEVTruncateExpr *T =
1174 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1175 if (T->getOperand()->getType() != SrcType) {
1179 LargeMulOps.push_back(T->getOperand());
1180 } else if (const SCEVConstant *C =
1181 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1182 // This could be either sign or zero extension, but sign extension
1183 // is much more likely to be foldable here.
1184 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1191 LargeOps.push_back(getMulExpr(LargeMulOps));
1198 // Evaluate the expression in the larger type.
1199 SCEVHandle Fold = getAddExpr(LargeOps);
1200 // If it folds to something simple, use it. Otherwise, don't.
1201 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1202 return getTruncateExpr(Fold, DstType);
1206 // Skip past any other cast SCEVs.
1207 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1210 // If there are add operands they would be next.
1211 if (Idx < Ops.size()) {
1212 bool DeletedAdd = false;
1213 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1214 // If we have an add, expand the add operands onto the end of the operands
1216 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1217 Ops.erase(Ops.begin()+Idx);
1221 // If we deleted at least one add, we added operands to the end of the list,
1222 // and they are not necessarily sorted. Recurse to resort and resimplify
1223 // any operands we just aquired.
1225 return getAddExpr(Ops);
1228 // Skip over the add expression until we get to a multiply.
1229 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1232 // Check to see if there are any folding opportunities present with
1233 // operands multiplied by constant values.
1234 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1235 uint64_t BitWidth = getTypeSizeInBits(Ty);
1236 DenseMap<SCEVHandle, APInt> M;
1237 SmallVector<SCEVHandle, 8> NewOps;
1238 APInt AccumulatedConstant(BitWidth, 0);
1239 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1240 Ops, APInt(BitWidth, 1), *this)) {
1241 // Some interesting folding opportunity is present, so its worthwhile to
1242 // re-generate the operands list. Group the operands by constant scale,
1243 // to avoid multiplying by the same constant scale multiple times.
1244 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1245 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1246 E = NewOps.end(); I != E; ++I)
1247 MulOpLists[M.find(*I)->second].push_back(*I);
1248 // Re-generate the operands list.
1250 if (AccumulatedConstant != 0)
1251 Ops.push_back(getConstant(AccumulatedConstant));
1252 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1253 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1255 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1257 return getIntegerSCEV(0, Ty);
1258 if (Ops.size() == 1)
1260 return getAddExpr(Ops);
1264 // If we are adding something to a multiply expression, make sure the
1265 // something is not already an operand of the multiply. If so, merge it into
1267 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1268 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1269 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1270 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1271 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1272 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1273 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1274 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1275 if (Mul->getNumOperands() != 2) {
1276 // If the multiply has more than two operands, we must get the
1278 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1279 MulOps.erase(MulOps.begin()+MulOp);
1280 InnerMul = getMulExpr(MulOps);
1282 SCEVHandle One = getIntegerSCEV(1, Ty);
1283 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1284 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1285 if (Ops.size() == 2) return OuterMul;
1287 Ops.erase(Ops.begin()+AddOp);
1288 Ops.erase(Ops.begin()+Idx-1);
1290 Ops.erase(Ops.begin()+Idx);
1291 Ops.erase(Ops.begin()+AddOp-1);
1293 Ops.push_back(OuterMul);
1294 return getAddExpr(Ops);
1297 // Check this multiply against other multiplies being added together.
1298 for (unsigned OtherMulIdx = Idx+1;
1299 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1301 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1302 // If MulOp occurs in OtherMul, we can fold the two multiplies
1304 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1305 OMulOp != e; ++OMulOp)
1306 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1307 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1308 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1309 if (Mul->getNumOperands() != 2) {
1310 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1311 MulOps.erase(MulOps.begin()+MulOp);
1312 InnerMul1 = getMulExpr(MulOps);
1314 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1315 if (OtherMul->getNumOperands() != 2) {
1316 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
1317 OtherMul->op_end());
1318 MulOps.erase(MulOps.begin()+OMulOp);
1319 InnerMul2 = getMulExpr(MulOps);
1321 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1322 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1323 if (Ops.size() == 2) return OuterMul;
1324 Ops.erase(Ops.begin()+Idx);
1325 Ops.erase(Ops.begin()+OtherMulIdx-1);
1326 Ops.push_back(OuterMul);
1327 return getAddExpr(Ops);
1333 // If there are any add recurrences in the operands list, see if any other
1334 // added values are loop invariant. If so, we can fold them into the
1336 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1339 // Scan over all recurrences, trying to fold loop invariants into them.
1340 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1341 // Scan all of the other operands to this add and add them to the vector if
1342 // they are loop invariant w.r.t. the recurrence.
1343 SmallVector<SCEVHandle, 8> LIOps;
1344 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1345 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1346 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1347 LIOps.push_back(Ops[i]);
1348 Ops.erase(Ops.begin()+i);
1352 // If we found some loop invariants, fold them into the recurrence.
1353 if (!LIOps.empty()) {
1354 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1355 LIOps.push_back(AddRec->getStart());
1357 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1359 AddRecOps[0] = getAddExpr(LIOps);
1361 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1362 // If all of the other operands were loop invariant, we are done.
1363 if (Ops.size() == 1) return NewRec;
1365 // Otherwise, add the folded AddRec by the non-liv parts.
1366 for (unsigned i = 0;; ++i)
1367 if (Ops[i] == AddRec) {
1371 return getAddExpr(Ops);
1374 // Okay, if there weren't any loop invariants to be folded, check to see if
1375 // there are multiple AddRec's with the same loop induction variable being
1376 // added together. If so, we can fold them.
1377 for (unsigned OtherIdx = Idx+1;
1378 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1379 if (OtherIdx != Idx) {
1380 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1381 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1382 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1383 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
1384 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1385 if (i >= NewOps.size()) {
1386 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1387 OtherAddRec->op_end());
1390 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1392 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1394 if (Ops.size() == 2) return NewAddRec;
1396 Ops.erase(Ops.begin()+Idx);
1397 Ops.erase(Ops.begin()+OtherIdx-1);
1398 Ops.push_back(NewAddRec);
1399 return getAddExpr(Ops);
1403 // Otherwise couldn't fold anything into this recurrence. Move onto the
1407 // Okay, it looks like we really DO need an add expr. Check to see if we
1408 // already have one, otherwise create a new one.
1409 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1410 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1412 if (Result == 0) Result = new SCEVAddExpr(Ops);
1417 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1419 SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1420 assert(!Ops.empty() && "Cannot get empty mul!");
1422 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1423 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1424 getEffectiveSCEVType(Ops[0]->getType()) &&
1425 "SCEVMulExpr operand types don't match!");
1428 // Sort by complexity, this groups all similar expression types together.
1429 GroupByComplexity(Ops, LI);
1431 // If there are any constants, fold them together.
1433 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1435 // C1*(C2+V) -> C1*C2 + C1*V
1436 if (Ops.size() == 2)
1437 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1438 if (Add->getNumOperands() == 2 &&
1439 isa<SCEVConstant>(Add->getOperand(0)))
1440 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1441 getMulExpr(LHSC, Add->getOperand(1)));
1445 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1446 // We found two constants, fold them together!
1447 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1448 RHSC->getValue()->getValue());
1449 Ops[0] = getConstant(Fold);
1450 Ops.erase(Ops.begin()+1); // Erase the folded element
1451 if (Ops.size() == 1) return Ops[0];
1452 LHSC = cast<SCEVConstant>(Ops[0]);
1455 // If we are left with a constant one being multiplied, strip it off.
1456 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1457 Ops.erase(Ops.begin());
1459 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1460 // If we have a multiply of zero, it will always be zero.
1465 // Skip over the add expression until we get to a multiply.
1466 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1469 if (Ops.size() == 1)
1472 // If there are mul operands inline them all into this expression.
1473 if (Idx < Ops.size()) {
1474 bool DeletedMul = false;
1475 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1476 // If we have an mul, expand the mul operands onto the end of the operands
1478 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1479 Ops.erase(Ops.begin()+Idx);
1483 // If we deleted at least one mul, we added operands to the end of the list,
1484 // and they are not necessarily sorted. Recurse to resort and resimplify
1485 // any operands we just aquired.
1487 return getMulExpr(Ops);
1490 // If there are any add recurrences in the operands list, see if any other
1491 // added values are loop invariant. If so, we can fold them into the
1493 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1496 // Scan over all recurrences, trying to fold loop invariants into them.
1497 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1498 // Scan all of the other operands to this mul and add them to the vector if
1499 // they are loop invariant w.r.t. the recurrence.
1500 SmallVector<SCEVHandle, 8> LIOps;
1501 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1502 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1503 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1504 LIOps.push_back(Ops[i]);
1505 Ops.erase(Ops.begin()+i);
1509 // If we found some loop invariants, fold them into the recurrence.
1510 if (!LIOps.empty()) {
1511 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1512 SmallVector<SCEVHandle, 4> NewOps;
1513 NewOps.reserve(AddRec->getNumOperands());
1514 if (LIOps.size() == 1) {
1515 const SCEV *Scale = LIOps[0];
1516 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1517 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1519 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1520 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
1521 MulOps.push_back(AddRec->getOperand(i));
1522 NewOps.push_back(getMulExpr(MulOps));
1526 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1528 // If all of the other operands were loop invariant, we are done.
1529 if (Ops.size() == 1) return NewRec;
1531 // Otherwise, multiply the folded AddRec by the non-liv parts.
1532 for (unsigned i = 0;; ++i)
1533 if (Ops[i] == AddRec) {
1537 return getMulExpr(Ops);
1540 // Okay, if there weren't any loop invariants to be folded, check to see if
1541 // there are multiple AddRec's with the same loop induction variable being
1542 // multiplied together. If so, we can fold them.
1543 for (unsigned OtherIdx = Idx+1;
1544 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1545 if (OtherIdx != Idx) {
1546 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1547 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1548 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1549 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1550 SCEVHandle NewStart = getMulExpr(F->getStart(),
1552 SCEVHandle B = F->getStepRecurrence(*this);
1553 SCEVHandle D = G->getStepRecurrence(*this);
1554 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1557 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1559 if (Ops.size() == 2) return NewAddRec;
1561 Ops.erase(Ops.begin()+Idx);
1562 Ops.erase(Ops.begin()+OtherIdx-1);
1563 Ops.push_back(NewAddRec);
1564 return getMulExpr(Ops);
1568 // Otherwise couldn't fold anything into this recurrence. Move onto the
1572 // Okay, it looks like we really DO need an mul expr. Check to see if we
1573 // already have one, otherwise create a new one.
1574 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1575 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1578 Result = new SCEVMulExpr(Ops);
1582 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1584 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1585 const SCEVHandle &RHS) {
1586 assert(getEffectiveSCEVType(LHS->getType()) ==
1587 getEffectiveSCEVType(RHS->getType()) &&
1588 "SCEVUDivExpr operand types don't match!");
1590 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1591 if (RHSC->getValue()->equalsInt(1))
1592 return LHS; // X udiv 1 --> x
1594 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1596 // Determine if the division can be folded into the operands of
1598 // TODO: Generalize this to non-constants by using known-bits information.
1599 const Type *Ty = LHS->getType();
1600 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1601 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1602 // For non-power-of-two values, effectively round the value up to the
1603 // nearest power of two.
1604 if (!RHSC->getValue()->getValue().isPowerOf2())
1606 const IntegerType *ExtTy =
1607 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1608 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1609 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1610 if (const SCEVConstant *Step =
1611 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1612 if (!Step->getValue()->getValue()
1613 .urem(RHSC->getValue()->getValue()) &&
1614 getZeroExtendExpr(AR, ExtTy) ==
1615 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1616 getZeroExtendExpr(Step, ExtTy),
1618 SmallVector<SCEVHandle, 4> Operands;
1619 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1620 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1621 return getAddRecExpr(Operands, AR->getLoop());
1623 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1624 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1625 SmallVector<SCEVHandle, 4> Operands;
1626 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1627 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1628 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1629 // Find an operand that's safely divisible.
1630 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1631 SCEVHandle Op = M->getOperand(i);
1632 SCEVHandle Div = getUDivExpr(Op, RHSC);
1633 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1634 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1635 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1638 return getMulExpr(Operands);
1642 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1643 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1644 SmallVector<SCEVHandle, 4> Operands;
1645 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1646 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1647 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1649 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1650 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1651 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1653 Operands.push_back(Op);
1655 if (Operands.size() == A->getNumOperands())
1656 return getAddExpr(Operands);
1660 // Fold if both operands are constant.
1661 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1662 Constant *LHSCV = LHSC->getValue();
1663 Constant *RHSCV = RHSC->getValue();
1664 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1668 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1669 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1674 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1675 /// Simplify the expression as much as possible.
1676 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1677 const SCEVHandle &Step, const Loop *L) {
1678 SmallVector<SCEVHandle, 4> Operands;
1679 Operands.push_back(Start);
1680 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1681 if (StepChrec->getLoop() == L) {
1682 Operands.insert(Operands.end(), StepChrec->op_begin(),
1683 StepChrec->op_end());
1684 return getAddRecExpr(Operands, L);
1687 Operands.push_back(Step);
1688 return getAddRecExpr(Operands, L);
1691 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1692 /// Simplify the expression as much as possible.
1693 SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
1695 if (Operands.size() == 1) return Operands[0];
1697 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1698 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1699 getEffectiveSCEVType(Operands[0]->getType()) &&
1700 "SCEVAddRecExpr operand types don't match!");
1703 if (Operands.back()->isZero()) {
1704 Operands.pop_back();
1705 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1708 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1709 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1710 const Loop* NestedLoop = NestedAR->getLoop();
1711 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1712 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1713 NestedAR->op_end());
1714 SCEVHandle NestedARHandle(NestedAR);
1715 Operands[0] = NestedAR->getStart();
1716 NestedOperands[0] = getAddRecExpr(Operands, L);
1717 return getAddRecExpr(NestedOperands, NestedLoop);
1721 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1722 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1723 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1727 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1728 const SCEVHandle &RHS) {
1729 SmallVector<SCEVHandle, 2> Ops;
1732 return getSMaxExpr(Ops);
1736 ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1737 assert(!Ops.empty() && "Cannot get empty smax!");
1738 if (Ops.size() == 1) return Ops[0];
1740 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1741 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1742 getEffectiveSCEVType(Ops[0]->getType()) &&
1743 "SCEVSMaxExpr operand types don't match!");
1746 // Sort by complexity, this groups all similar expression types together.
1747 GroupByComplexity(Ops, LI);
1749 // If there are any constants, fold them together.
1751 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1753 assert(Idx < Ops.size());
1754 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1755 // We found two constants, fold them together!
1756 ConstantInt *Fold = ConstantInt::get(
1757 APIntOps::smax(LHSC->getValue()->getValue(),
1758 RHSC->getValue()->getValue()));
1759 Ops[0] = getConstant(Fold);
1760 Ops.erase(Ops.begin()+1); // Erase the folded element
1761 if (Ops.size() == 1) return Ops[0];
1762 LHSC = cast<SCEVConstant>(Ops[0]);
1765 // If we are left with a constant -inf, strip it off.
1766 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1767 Ops.erase(Ops.begin());
1772 if (Ops.size() == 1) return Ops[0];
1774 // Find the first SMax
1775 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1778 // Check to see if one of the operands is an SMax. If so, expand its operands
1779 // onto our operand list, and recurse to simplify.
1780 if (Idx < Ops.size()) {
1781 bool DeletedSMax = false;
1782 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1783 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1784 Ops.erase(Ops.begin()+Idx);
1789 return getSMaxExpr(Ops);
1792 // Okay, check to see if the same value occurs in the operand list twice. If
1793 // so, delete one. Since we sorted the list, these values are required to
1795 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1796 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1797 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1801 if (Ops.size() == 1) return Ops[0];
1803 assert(!Ops.empty() && "Reduced smax down to nothing!");
1805 // Okay, it looks like we really DO need an smax expr. Check to see if we
1806 // already have one, otherwise create a new one.
1807 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1808 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1810 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1814 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1815 const SCEVHandle &RHS) {
1816 SmallVector<SCEVHandle, 2> Ops;
1819 return getUMaxExpr(Ops);
1823 ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1824 assert(!Ops.empty() && "Cannot get empty umax!");
1825 if (Ops.size() == 1) return Ops[0];
1827 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1828 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1829 getEffectiveSCEVType(Ops[0]->getType()) &&
1830 "SCEVUMaxExpr operand types don't match!");
1833 // Sort by complexity, this groups all similar expression types together.
1834 GroupByComplexity(Ops, LI);
1836 // If there are any constants, fold them together.
1838 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1840 assert(Idx < Ops.size());
1841 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1842 // We found two constants, fold them together!
1843 ConstantInt *Fold = ConstantInt::get(
1844 APIntOps::umax(LHSC->getValue()->getValue(),
1845 RHSC->getValue()->getValue()));
1846 Ops[0] = getConstant(Fold);
1847 Ops.erase(Ops.begin()+1); // Erase the folded element
1848 if (Ops.size() == 1) return Ops[0];
1849 LHSC = cast<SCEVConstant>(Ops[0]);
1852 // If we are left with a constant zero, strip it off.
1853 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1854 Ops.erase(Ops.begin());
1859 if (Ops.size() == 1) return Ops[0];
1861 // Find the first UMax
1862 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1865 // Check to see if one of the operands is a UMax. If so, expand its operands
1866 // onto our operand list, and recurse to simplify.
1867 if (Idx < Ops.size()) {
1868 bool DeletedUMax = false;
1869 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1870 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1871 Ops.erase(Ops.begin()+Idx);
1876 return getUMaxExpr(Ops);
1879 // Okay, check to see if the same value occurs in the operand list twice. If
1880 // so, delete one. Since we sorted the list, these values are required to
1882 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1883 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1884 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1888 if (Ops.size() == 1) return Ops[0];
1890 assert(!Ops.empty() && "Reduced umax down to nothing!");
1892 // Okay, it looks like we really DO need a umax expr. Check to see if we
1893 // already have one, otherwise create a new one.
1894 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1895 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1897 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1901 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1902 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1903 return getConstant(CI);
1904 if (isa<ConstantPointerNull>(V))
1905 return getIntegerSCEV(0, V->getType());
1906 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1907 if (Result == 0) Result = new SCEVUnknown(V);
1911 //===----------------------------------------------------------------------===//
1912 // Basic SCEV Analysis and PHI Idiom Recognition Code
1915 /// isSCEVable - Test if values of the given type are analyzable within
1916 /// the SCEV framework. This primarily includes integer types, and it
1917 /// can optionally include pointer types if the ScalarEvolution class
1918 /// has access to target-specific information.
1919 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1920 // Integers are always SCEVable.
1921 if (Ty->isInteger())
1924 // Pointers are SCEVable if TargetData information is available
1925 // to provide pointer size information.
1926 if (isa<PointerType>(Ty))
1929 // Otherwise it's not SCEVable.
1933 /// getTypeSizeInBits - Return the size in bits of the specified type,
1934 /// for which isSCEVable must return true.
1935 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1936 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1938 // If we have a TargetData, use it!
1940 return TD->getTypeSizeInBits(Ty);
1942 // Otherwise, we support only integer types.
1943 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1944 return Ty->getPrimitiveSizeInBits();
1947 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1948 /// the given type and which represents how SCEV will treat the given
1949 /// type, for which isSCEVable must return true. For pointer types,
1950 /// this is the pointer-sized integer type.
1951 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1952 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1954 if (Ty->isInteger())
1957 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1958 return TD->getIntPtrType();
1961 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1962 return CouldNotCompute;
1965 /// hasSCEV - Return true if the SCEV for this value has already been
1967 bool ScalarEvolution::hasSCEV(Value *V) const {
1968 return Scalars.count(V);
1971 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1972 /// expression and create a new one.
1973 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1974 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1976 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1977 if (I != Scalars.end()) return I->second;
1978 SCEVHandle S = createSCEV(V);
1979 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1983 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1984 /// specified signed integer value and return a SCEV for the constant.
1985 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1986 Ty = getEffectiveSCEVType(Ty);
1989 C = Constant::getNullValue(Ty);
1990 else if (Ty->isFloatingPoint())
1991 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1992 APFloat::IEEEdouble, Val));
1994 C = ConstantInt::get(Ty, Val);
1995 return getUnknown(C);
1998 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2000 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
2001 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2002 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
2004 const Type *Ty = V->getType();
2005 Ty = getEffectiveSCEVType(Ty);
2006 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
2009 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2010 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
2011 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2012 return getUnknown(ConstantExpr::getNot(VC->getValue()));
2014 const Type *Ty = V->getType();
2015 Ty = getEffectiveSCEVType(Ty);
2016 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
2017 return getMinusSCEV(AllOnes, V);
2020 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2022 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
2023 const SCEVHandle &RHS) {
2025 return getAddExpr(LHS, getNegativeSCEV(RHS));
2028 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2029 /// input value to the specified type. If the type must be extended, it is zero
2032 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
2034 const Type *SrcTy = V->getType();
2035 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2036 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2037 "Cannot truncate or zero extend with non-integer arguments!");
2038 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2039 return V; // No conversion
2040 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2041 return getTruncateExpr(V, Ty);
2042 return getZeroExtendExpr(V, Ty);
2045 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2046 /// input value to the specified type. If the type must be extended, it is sign
2049 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
2051 const Type *SrcTy = V->getType();
2052 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2053 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2054 "Cannot truncate or zero extend with non-integer arguments!");
2055 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2056 return V; // No conversion
2057 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2058 return getTruncateExpr(V, Ty);
2059 return getSignExtendExpr(V, Ty);
2062 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2063 /// input value to the specified type. If the type must be extended, it is zero
2064 /// extended. The conversion must not be narrowing.
2066 ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2067 const Type *SrcTy = V->getType();
2068 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2069 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2070 "Cannot noop or zero extend with non-integer arguments!");
2071 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2072 "getNoopOrZeroExtend cannot truncate!");
2073 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2074 return V; // No conversion
2075 return getZeroExtendExpr(V, Ty);
2078 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2079 /// input value to the specified type. If the type must be extended, it is sign
2080 /// extended. The conversion must not be narrowing.
2082 ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2083 const Type *SrcTy = V->getType();
2084 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2085 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2086 "Cannot noop or sign extend with non-integer arguments!");
2087 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2088 "getNoopOrSignExtend cannot truncate!");
2089 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2090 return V; // No conversion
2091 return getSignExtendExpr(V, Ty);
2094 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2095 /// the input value to the specified type. If the type must be extended,
2096 /// it is extended with unspecified bits. The conversion must not be
2099 ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2100 const Type *SrcTy = V->getType();
2101 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2102 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2103 "Cannot noop or any extend with non-integer arguments!");
2104 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2105 "getNoopOrAnyExtend cannot truncate!");
2106 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2107 return V; // No conversion
2108 return getAnyExtendExpr(V, Ty);
2111 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2112 /// input value to the specified type. The conversion must not be widening.
2114 ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2115 const Type *SrcTy = V->getType();
2116 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2117 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2118 "Cannot truncate or noop with non-integer arguments!");
2119 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2120 "getTruncateOrNoop cannot extend!");
2121 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2122 return V; // No conversion
2123 return getTruncateExpr(V, Ty);
2126 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2127 /// the specified instruction and replaces any references to the symbolic value
2128 /// SymName with the specified value. This is used during PHI resolution.
2129 void ScalarEvolution::
2130 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2131 const SCEVHandle &NewVal) {
2132 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2133 Scalars.find(SCEVCallbackVH(I, this));
2134 if (SI == Scalars.end()) return;
2137 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2138 if (NV == SI->second) return; // No change.
2140 SI->second = NV; // Update the scalars map!
2142 // Any instruction values that use this instruction might also need to be
2144 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2146 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2149 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2150 /// a loop header, making it a potential recurrence, or it doesn't.
2152 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
2153 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2154 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2155 if (L->getHeader() == PN->getParent()) {
2156 // If it lives in the loop header, it has two incoming values, one
2157 // from outside the loop, and one from inside.
2158 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2159 unsigned BackEdge = IncomingEdge^1;
2161 // While we are analyzing this PHI node, handle its value symbolically.
2162 SCEVHandle SymbolicName = getUnknown(PN);
2163 assert(Scalars.find(PN) == Scalars.end() &&
2164 "PHI node already processed?");
2165 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2167 // Using this symbolic name for the PHI, analyze the value coming around
2169 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2171 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2172 // has a special value for the first iteration of the loop.
2174 // If the value coming around the backedge is an add with the symbolic
2175 // value we just inserted, then we found a simple induction variable!
2176 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2177 // If there is a single occurrence of the symbolic value, replace it
2178 // with a recurrence.
2179 unsigned FoundIndex = Add->getNumOperands();
2180 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2181 if (Add->getOperand(i) == SymbolicName)
2182 if (FoundIndex == e) {
2187 if (FoundIndex != Add->getNumOperands()) {
2188 // Create an add with everything but the specified operand.
2189 SmallVector<SCEVHandle, 8> Ops;
2190 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2191 if (i != FoundIndex)
2192 Ops.push_back(Add->getOperand(i));
2193 SCEVHandle Accum = getAddExpr(Ops);
2195 // This is not a valid addrec if the step amount is varying each
2196 // loop iteration, but is not itself an addrec in this loop.
2197 if (Accum->isLoopInvariant(L) ||
2198 (isa<SCEVAddRecExpr>(Accum) &&
2199 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2200 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2201 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
2203 // Okay, for the entire analysis of this edge we assumed the PHI
2204 // to be symbolic. We now need to go back and update all of the
2205 // entries for the scalars that use the PHI (except for the PHI
2206 // itself) to use the new analyzed value instead of the "symbolic"
2208 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2212 } else if (const SCEVAddRecExpr *AddRec =
2213 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2214 // Otherwise, this could be a loop like this:
2215 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2216 // In this case, j = {1,+,1} and BEValue is j.
2217 // Because the other in-value of i (0) fits the evolution of BEValue
2218 // i really is an addrec evolution.
2219 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2220 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2222 // If StartVal = j.start - j.stride, we can use StartVal as the
2223 // initial step of the addrec evolution.
2224 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2225 AddRec->getOperand(1))) {
2226 SCEVHandle PHISCEV =
2227 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2229 // Okay, for the entire analysis of this edge we assumed the PHI
2230 // to be symbolic. We now need to go back and update all of the
2231 // entries for the scalars that use the PHI (except for the PHI
2232 // itself) to use the new analyzed value instead of the "symbolic"
2234 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2240 return SymbolicName;
2243 // If it's not a loop phi, we can't handle it yet.
2244 return getUnknown(PN);
2247 /// createNodeForGEP - Expand GEP instructions into add and multiply
2248 /// operations. This allows them to be analyzed by regular SCEV code.
2250 SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
2252 const Type *IntPtrTy = TD->getIntPtrType();
2253 Value *Base = GEP->getOperand(0);
2254 // Don't attempt to analyze GEPs over unsized objects.
2255 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2256 return getUnknown(GEP);
2257 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
2258 gep_type_iterator GTI = gep_type_begin(GEP);
2259 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2263 // Compute the (potentially symbolic) offset in bytes for this index.
2264 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2265 // For a struct, add the member offset.
2266 const StructLayout &SL = *TD->getStructLayout(STy);
2267 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2268 uint64_t Offset = SL.getElementOffset(FieldNo);
2269 TotalOffset = getAddExpr(TotalOffset,
2270 getIntegerSCEV(Offset, IntPtrTy));
2272 // For an array, add the element offset, explicitly scaled.
2273 SCEVHandle LocalOffset = getSCEV(Index);
2274 if (!isa<PointerType>(LocalOffset->getType()))
2275 // Getelementptr indicies are signed.
2276 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2279 getMulExpr(LocalOffset,
2280 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2282 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2285 return getAddExpr(getSCEV(Base), TotalOffset);
2288 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2289 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2290 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2291 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2292 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
2293 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2294 return C->getValue()->getValue().countTrailingZeros();
2296 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2297 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2298 (uint32_t)SE.getTypeSizeInBits(T->getType()));
2300 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2301 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2302 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
2303 SE.getTypeSizeInBits(E->getType()) : OpRes;
2306 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2307 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2308 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
2309 SE.getTypeSizeInBits(E->getType()) : OpRes;
2312 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2313 // The result is the min of all operands results.
2314 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
2315 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2316 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2320 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2321 // The result is the sum of all operands results.
2322 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2323 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
2324 for (unsigned i = 1, e = M->getNumOperands();
2325 SumOpRes != BitWidth && i != e; ++i)
2326 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
2331 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2332 // The result is the min of all operands results.
2333 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
2334 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2335 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2339 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2340 // The result is the min of all operands results.
2341 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2342 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2343 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2347 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2348 // The result is the min of all operands results.
2349 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2350 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2351 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2355 // SCEVUDivExpr, SCEVUnknown
2359 /// createSCEV - We know that there is no SCEV for the specified value.
2360 /// Analyze the expression.
2362 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
2363 if (!isSCEVable(V->getType()))
2364 return getUnknown(V);
2366 unsigned Opcode = Instruction::UserOp1;
2367 if (Instruction *I = dyn_cast<Instruction>(V))
2368 Opcode = I->getOpcode();
2369 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2370 Opcode = CE->getOpcode();
2372 return getUnknown(V);
2374 User *U = cast<User>(V);
2376 case Instruction::Add:
2377 return getAddExpr(getSCEV(U->getOperand(0)),
2378 getSCEV(U->getOperand(1)));
2379 case Instruction::Mul:
2380 return getMulExpr(getSCEV(U->getOperand(0)),
2381 getSCEV(U->getOperand(1)));
2382 case Instruction::UDiv:
2383 return getUDivExpr(getSCEV(U->getOperand(0)),
2384 getSCEV(U->getOperand(1)));
2385 case Instruction::Sub:
2386 return getMinusSCEV(getSCEV(U->getOperand(0)),
2387 getSCEV(U->getOperand(1)));
2388 case Instruction::And:
2389 // For an expression like x&255 that merely masks off the high bits,
2390 // use zext(trunc(x)) as the SCEV expression.
2391 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2392 if (CI->isNullValue())
2393 return getSCEV(U->getOperand(1));
2394 if (CI->isAllOnesValue())
2395 return getSCEV(U->getOperand(0));
2396 const APInt &A = CI->getValue();
2397 unsigned Ones = A.countTrailingOnes();
2398 if (APIntOps::isMask(Ones, A))
2400 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2401 IntegerType::get(Ones)),
2405 case Instruction::Or:
2406 // If the RHS of the Or is a constant, we may have something like:
2407 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2408 // optimizations will transparently handle this case.
2410 // In order for this transformation to be safe, the LHS must be of the
2411 // form X*(2^n) and the Or constant must be less than 2^n.
2412 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2413 SCEVHandle LHS = getSCEV(U->getOperand(0));
2414 const APInt &CIVal = CI->getValue();
2415 if (GetMinTrailingZeros(LHS, *this) >=
2416 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2417 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2420 case Instruction::Xor:
2421 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2422 // If the RHS of the xor is a signbit, then this is just an add.
2423 // Instcombine turns add of signbit into xor as a strength reduction step.
2424 if (CI->getValue().isSignBit())
2425 return getAddExpr(getSCEV(U->getOperand(0)),
2426 getSCEV(U->getOperand(1)));
2428 // If the RHS of xor is -1, then this is a not operation.
2429 if (CI->isAllOnesValue())
2430 return getNotSCEV(getSCEV(U->getOperand(0)));
2432 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2433 // This is a variant of the check for xor with -1, and it handles
2434 // the case where instcombine has trimmed non-demanded bits out
2435 // of an xor with -1.
2436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2437 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2438 if (BO->getOpcode() == Instruction::And &&
2439 LCI->getValue() == CI->getValue())
2440 if (const SCEVZeroExtendExpr *Z =
2441 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2442 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2447 case Instruction::Shl:
2448 // Turn shift left of a constant amount into a multiply.
2449 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2450 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2451 Constant *X = ConstantInt::get(
2452 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2453 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2457 case Instruction::LShr:
2458 // Turn logical shift right of a constant into a unsigned divide.
2459 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2460 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2461 Constant *X = ConstantInt::get(
2462 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2463 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2467 case Instruction::AShr:
2468 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2469 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2470 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2471 if (L->getOpcode() == Instruction::Shl &&
2472 L->getOperand(1) == U->getOperand(1)) {
2473 unsigned BitWidth = getTypeSizeInBits(U->getType());
2474 uint64_t Amt = BitWidth - CI->getZExtValue();
2475 if (Amt == BitWidth)
2476 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2478 return getIntegerSCEV(0, U->getType()); // value is undefined
2480 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2481 IntegerType::get(Amt)),
2486 case Instruction::Trunc:
2487 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2489 case Instruction::ZExt:
2490 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2492 case Instruction::SExt:
2493 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2495 case Instruction::BitCast:
2496 // BitCasts are no-op casts so we just eliminate the cast.
2497 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2498 return getSCEV(U->getOperand(0));
2501 case Instruction::IntToPtr:
2502 if (!TD) break; // Without TD we can't analyze pointers.
2503 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2504 TD->getIntPtrType());
2506 case Instruction::PtrToInt:
2507 if (!TD) break; // Without TD we can't analyze pointers.
2508 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2511 case Instruction::GetElementPtr:
2512 if (!TD) break; // Without TD we can't analyze pointers.
2513 return createNodeForGEP(U);
2515 case Instruction::PHI:
2516 return createNodeForPHI(cast<PHINode>(U));
2518 case Instruction::Select:
2519 // This could be a smax or umax that was lowered earlier.
2520 // Try to recover it.
2521 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2522 Value *LHS = ICI->getOperand(0);
2523 Value *RHS = ICI->getOperand(1);
2524 switch (ICI->getPredicate()) {
2525 case ICmpInst::ICMP_SLT:
2526 case ICmpInst::ICMP_SLE:
2527 std::swap(LHS, RHS);
2529 case ICmpInst::ICMP_SGT:
2530 case ICmpInst::ICMP_SGE:
2531 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2532 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2533 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2534 // ~smax(~x, ~y) == smin(x, y).
2535 return getNotSCEV(getSMaxExpr(
2536 getNotSCEV(getSCEV(LHS)),
2537 getNotSCEV(getSCEV(RHS))));
2539 case ICmpInst::ICMP_ULT:
2540 case ICmpInst::ICMP_ULE:
2541 std::swap(LHS, RHS);
2543 case ICmpInst::ICMP_UGT:
2544 case ICmpInst::ICMP_UGE:
2545 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2546 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2547 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2548 // ~umax(~x, ~y) == umin(x, y)
2549 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2550 getNotSCEV(getSCEV(RHS))));
2557 default: // We cannot analyze this expression.
2561 return getUnknown(V);
2566 //===----------------------------------------------------------------------===//
2567 // Iteration Count Computation Code
2570 /// getBackedgeTakenCount - If the specified loop has a predictable
2571 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2572 /// object. The backedge-taken count is the number of times the loop header
2573 /// will be branched to from within the loop. This is one less than the
2574 /// trip count of the loop, since it doesn't count the first iteration,
2575 /// when the header is branched to from outside the loop.
2577 /// Note that it is not valid to call this method on a loop without a
2578 /// loop-invariant backedge-taken count (see
2579 /// hasLoopInvariantBackedgeTakenCount).
2581 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2582 return getBackedgeTakenInfo(L).Exact;
2585 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2586 /// return the least SCEV value that is known never to be less than the
2587 /// actual backedge taken count.
2588 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2589 return getBackedgeTakenInfo(L).Max;
2592 const ScalarEvolution::BackedgeTakenInfo &
2593 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2594 // Initially insert a CouldNotCompute for this loop. If the insertion
2595 // succeeds, procede to actually compute a backedge-taken count and
2596 // update the value. The temporary CouldNotCompute value tells SCEV
2597 // code elsewhere that it shouldn't attempt to request a new
2598 // backedge-taken count, which could result in infinite recursion.
2599 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2600 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2602 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2603 if (ItCount.Exact != CouldNotCompute) {
2604 assert(ItCount.Exact->isLoopInvariant(L) &&
2605 ItCount.Max->isLoopInvariant(L) &&
2606 "Computed trip count isn't loop invariant for loop!");
2607 ++NumTripCountsComputed;
2609 // Update the value in the map.
2610 Pair.first->second = ItCount;
2611 } else if (isa<PHINode>(L->getHeader()->begin())) {
2612 // Only count loops that have phi nodes as not being computable.
2613 ++NumTripCountsNotComputed;
2616 // Now that we know more about the trip count for this loop, forget any
2617 // existing SCEV values for PHI nodes in this loop since they are only
2618 // conservative estimates made without the benefit
2619 // of trip count information.
2620 if (ItCount.hasAnyInfo())
2623 return Pair.first->second;
2626 /// forgetLoopBackedgeTakenCount - This method should be called by the
2627 /// client when it has changed a loop in a way that may effect
2628 /// ScalarEvolution's ability to compute a trip count, or if the loop
2630 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2631 BackedgeTakenCounts.erase(L);
2635 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2636 /// PHI nodes in the given loop. This is used when the trip count of
2637 /// the loop may have changed.
2638 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2639 BasicBlock *Header = L->getHeader();
2641 // Push all Loop-header PHIs onto the Worklist stack, except those
2642 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2643 // a PHI either means that it has an unrecognized structure, or it's
2644 // a PHI that's in the progress of being computed by createNodeForPHI.
2645 // In the former case, additional loop trip count information isn't
2646 // going to change anything. In the later case, createNodeForPHI will
2647 // perform the necessary updates on its own when it gets to that point.
2648 SmallVector<Instruction *, 16> Worklist;
2649 for (BasicBlock::iterator I = Header->begin();
2650 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2651 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2652 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2653 Worklist.push_back(PN);
2656 while (!Worklist.empty()) {
2657 Instruction *I = Worklist.pop_back_val();
2658 if (Scalars.erase(I))
2659 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2661 Worklist.push_back(cast<Instruction>(UI));
2665 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2666 /// of the specified loop will execute.
2667 ScalarEvolution::BackedgeTakenInfo
2668 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2669 // If the loop has a non-one exit block count, we can't analyze it.
2670 BasicBlock *ExitBlock = L->getExitBlock();
2672 return CouldNotCompute;
2674 // Okay, there is one exit block. Try to find the condition that causes the
2675 // loop to be exited.
2676 BasicBlock *ExitingBlock = L->getExitingBlock();
2678 return CouldNotCompute; // More than one block exiting!
2680 // Okay, we've computed the exiting block. See what condition causes us to
2683 // FIXME: we should be able to handle switch instructions (with a single exit)
2684 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2685 if (ExitBr == 0) return CouldNotCompute;
2686 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2688 // At this point, we know we have a conditional branch that determines whether
2689 // the loop is exited. However, we don't know if the branch is executed each
2690 // time through the loop. If not, then the execution count of the branch will
2691 // not be equal to the trip count of the loop.
2693 // Currently we check for this by checking to see if the Exit branch goes to
2694 // the loop header. If so, we know it will always execute the same number of
2695 // times as the loop. We also handle the case where the exit block *is* the
2696 // loop header. This is common for un-rotated loops. More extensive analysis
2697 // could be done to handle more cases here.
2698 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2699 ExitBr->getSuccessor(1) != L->getHeader() &&
2700 ExitBr->getParent() != L->getHeader())
2701 return CouldNotCompute;
2703 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2705 // If it's not an integer or pointer comparison then compute it the hard way.
2707 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2708 ExitBr->getSuccessor(0) == ExitBlock);
2710 // If the condition was exit on true, convert the condition to exit on false
2711 ICmpInst::Predicate Cond;
2712 if (ExitBr->getSuccessor(1) == ExitBlock)
2713 Cond = ExitCond->getPredicate();
2715 Cond = ExitCond->getInversePredicate();
2717 // Handle common loops like: for (X = "string"; *X; ++X)
2718 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2719 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2721 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2722 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2725 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2726 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2728 // Try to evaluate any dependencies out of the loop.
2729 LHS = getSCEVAtScope(LHS, L);
2730 RHS = getSCEVAtScope(RHS, L);
2732 // At this point, we would like to compute how many iterations of the
2733 // loop the predicate will return true for these inputs.
2734 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2735 // If there is a loop-invariant, force it into the RHS.
2736 std::swap(LHS, RHS);
2737 Cond = ICmpInst::getSwappedPredicate(Cond);
2740 // If we have a comparison of a chrec against a constant, try to use value
2741 // ranges to answer this query.
2742 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2743 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2744 if (AddRec->getLoop() == L) {
2745 // Form the constant range.
2746 ConstantRange CompRange(
2747 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
2749 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2750 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2754 case ICmpInst::ICMP_NE: { // while (X != Y)
2755 // Convert to: while (X-Y != 0)
2756 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2757 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2760 case ICmpInst::ICMP_EQ: {
2761 // Convert to: while (X-Y == 0) // while (X == Y)
2762 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2763 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2766 case ICmpInst::ICMP_SLT: {
2767 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2768 if (BTI.hasAnyInfo()) return BTI;
2771 case ICmpInst::ICMP_SGT: {
2772 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2773 getNotSCEV(RHS), L, true);
2774 if (BTI.hasAnyInfo()) return BTI;
2777 case ICmpInst::ICMP_ULT: {
2778 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2779 if (BTI.hasAnyInfo()) return BTI;
2782 case ICmpInst::ICMP_UGT: {
2783 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2784 getNotSCEV(RHS), L, false);
2785 if (BTI.hasAnyInfo()) return BTI;
2790 errs() << "ComputeBackedgeTakenCount ";
2791 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2792 errs() << "[unsigned] ";
2793 errs() << *LHS << " "
2794 << Instruction::getOpcodeName(Instruction::ICmp)
2795 << " " << *RHS << "\n";
2800 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2801 ExitBr->getSuccessor(0) == ExitBlock);
2804 static ConstantInt *
2805 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2806 ScalarEvolution &SE) {
2807 SCEVHandle InVal = SE.getConstant(C);
2808 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2809 assert(isa<SCEVConstant>(Val) &&
2810 "Evaluation of SCEV at constant didn't fold correctly?");
2811 return cast<SCEVConstant>(Val)->getValue();
2814 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2815 /// and a GEP expression (missing the pointer index) indexing into it, return
2816 /// the addressed element of the initializer or null if the index expression is
2819 GetAddressedElementFromGlobal(GlobalVariable *GV,
2820 const std::vector<ConstantInt*> &Indices) {
2821 Constant *Init = GV->getInitializer();
2822 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2823 uint64_t Idx = Indices[i]->getZExtValue();
2824 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2825 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2826 Init = cast<Constant>(CS->getOperand(Idx));
2827 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2828 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2829 Init = cast<Constant>(CA->getOperand(Idx));
2830 } else if (isa<ConstantAggregateZero>(Init)) {
2831 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2832 assert(Idx < STy->getNumElements() && "Bad struct index!");
2833 Init = Constant::getNullValue(STy->getElementType(Idx));
2834 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2835 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2836 Init = Constant::getNullValue(ATy->getElementType());
2838 assert(0 && "Unknown constant aggregate type!");
2842 return 0; // Unknown initializer type
2848 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2849 /// 'icmp op load X, cst', try to see if we can compute the backedge
2850 /// execution count.
2851 SCEVHandle ScalarEvolution::
2852 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2854 ICmpInst::Predicate predicate) {
2855 if (LI->isVolatile()) return CouldNotCompute;
2857 // Check to see if the loaded pointer is a getelementptr of a global.
2858 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2859 if (!GEP) return CouldNotCompute;
2861 // Make sure that it is really a constant global we are gepping, with an
2862 // initializer, and make sure the first IDX is really 0.
2863 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2864 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2865 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2866 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2867 return CouldNotCompute;
2869 // Okay, we allow one non-constant index into the GEP instruction.
2871 std::vector<ConstantInt*> Indexes;
2872 unsigned VarIdxNum = 0;
2873 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2874 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2875 Indexes.push_back(CI);
2876 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2877 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
2878 VarIdx = GEP->getOperand(i);
2880 Indexes.push_back(0);
2883 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2884 // Check to see if X is a loop variant variable value now.
2885 SCEVHandle Idx = getSCEV(VarIdx);
2886 Idx = getSCEVAtScope(Idx, L);
2888 // We can only recognize very limited forms of loop index expressions, in
2889 // particular, only affine AddRec's like {C1,+,C2}.
2890 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2891 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2892 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2893 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2894 return CouldNotCompute;
2896 unsigned MaxSteps = MaxBruteForceIterations;
2897 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2898 ConstantInt *ItCst =
2899 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
2900 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2902 // Form the GEP offset.
2903 Indexes[VarIdxNum] = Val;
2905 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2906 if (Result == 0) break; // Cannot compute!
2908 // Evaluate the condition for this iteration.
2909 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2910 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2911 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2913 errs() << "\n***\n*** Computed loop count " << *ItCst
2914 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2917 ++NumArrayLenItCounts;
2918 return getConstant(ItCst); // Found terminating iteration!
2921 return CouldNotCompute;
2925 /// CanConstantFold - Return true if we can constant fold an instruction of the
2926 /// specified type, assuming that all operands were constants.
2927 static bool CanConstantFold(const Instruction *I) {
2928 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2929 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2932 if (const CallInst *CI = dyn_cast<CallInst>(I))
2933 if (const Function *F = CI->getCalledFunction())
2934 return canConstantFoldCallTo(F);
2938 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2939 /// in the loop that V is derived from. We allow arbitrary operations along the
2940 /// way, but the operands of an operation must either be constants or a value
2941 /// derived from a constant PHI. If this expression does not fit with these
2942 /// constraints, return null.
2943 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2944 // If this is not an instruction, or if this is an instruction outside of the
2945 // loop, it can't be derived from a loop PHI.
2946 Instruction *I = dyn_cast<Instruction>(V);
2947 if (I == 0 || !L->contains(I->getParent())) return 0;
2949 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2950 if (L->getHeader() == I->getParent())
2953 // We don't currently keep track of the control flow needed to evaluate
2954 // PHIs, so we cannot handle PHIs inside of loops.
2958 // If we won't be able to constant fold this expression even if the operands
2959 // are constants, return early.
2960 if (!CanConstantFold(I)) return 0;
2962 // Otherwise, we can evaluate this instruction if all of its operands are
2963 // constant or derived from a PHI node themselves.
2965 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2966 if (!(isa<Constant>(I->getOperand(Op)) ||
2967 isa<GlobalValue>(I->getOperand(Op)))) {
2968 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2969 if (P == 0) return 0; // Not evolving from PHI
2973 return 0; // Evolving from multiple different PHIs.
2976 // This is a expression evolving from a constant PHI!
2980 /// EvaluateExpression - Given an expression that passes the
2981 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2982 /// in the loop has the value PHIVal. If we can't fold this expression for some
2983 /// reason, return null.
2984 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2985 if (isa<PHINode>(V)) return PHIVal;
2986 if (Constant *C = dyn_cast<Constant>(V)) return C;
2987 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2988 Instruction *I = cast<Instruction>(V);
2990 std::vector<Constant*> Operands;
2991 Operands.resize(I->getNumOperands());
2993 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2994 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2995 if (Operands[i] == 0) return 0;
2998 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2999 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3000 &Operands[0], Operands.size());
3002 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3003 &Operands[0], Operands.size());
3006 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3007 /// in the header of its containing loop, we know the loop executes a
3008 /// constant number of times, and the PHI node is just a recurrence
3009 /// involving constants, fold it.
3010 Constant *ScalarEvolution::
3011 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
3012 std::map<PHINode*, Constant*>::iterator I =
3013 ConstantEvolutionLoopExitValue.find(PN);
3014 if (I != ConstantEvolutionLoopExitValue.end())
3017 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3018 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3020 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3022 // Since the loop is canonicalized, the PHI node must have two entries. One
3023 // entry must be a constant (coming in from outside of the loop), and the
3024 // second must be derived from the same PHI.
3025 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3026 Constant *StartCST =
3027 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3029 return RetVal = 0; // Must be a constant.
3031 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3032 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3034 return RetVal = 0; // Not derived from same PHI.
3036 // Execute the loop symbolically to determine the exit value.
3037 if (BEs.getActiveBits() >= 32)
3038 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3040 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3041 unsigned IterationNum = 0;
3042 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3043 if (IterationNum == NumIterations)
3044 return RetVal = PHIVal; // Got exit value!
3046 // Compute the value of the PHI node for the next iteration.
3047 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3048 if (NextPHI == PHIVal)
3049 return RetVal = NextPHI; // Stopped evolving!
3051 return 0; // Couldn't evaluate!
3056 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3057 /// constant number of times (the condition evolves only from constants),
3058 /// try to evaluate a few iterations of the loop until we get the exit
3059 /// condition gets a value of ExitWhen (true or false). If we cannot
3060 /// evaluate the trip count of the loop, return CouldNotCompute.
3061 SCEVHandle ScalarEvolution::
3062 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
3063 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3064 if (PN == 0) return CouldNotCompute;
3066 // Since the loop is canonicalized, the PHI node must have two entries. One
3067 // entry must be a constant (coming in from outside of the loop), and the
3068 // second must be derived from the same PHI.
3069 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3070 Constant *StartCST =
3071 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3072 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
3074 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3075 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3076 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
3078 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3079 // the loop symbolically to determine when the condition gets a value of
3081 unsigned IterationNum = 0;
3082 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3083 for (Constant *PHIVal = StartCST;
3084 IterationNum != MaxIterations; ++IterationNum) {
3085 ConstantInt *CondVal =
3086 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3088 // Couldn't symbolically evaluate.
3089 if (!CondVal) return CouldNotCompute;
3091 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3092 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3093 ++NumBruteForceTripCountsComputed;
3094 return getConstant(Type::Int32Ty, IterationNum);
3097 // Compute the value of the PHI node for the next iteration.
3098 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3099 if (NextPHI == 0 || NextPHI == PHIVal)
3100 return CouldNotCompute; // Couldn't evaluate or not making progress...
3104 // Too many iterations were needed to evaluate.
3105 return CouldNotCompute;
3108 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3109 /// at the specified scope in the program. The L value specifies a loop
3110 /// nest to evaluate the expression at, where null is the top-level or a
3111 /// specified loop is immediately inside of the loop.
3113 /// This method can be used to compute the exit value for a variable defined
3114 /// in a loop by querying what the value will hold in the parent loop.
3116 /// In the case that a relevant loop exit value cannot be computed, the
3117 /// original value V is returned.
3118 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3119 // FIXME: this should be turned into a virtual method on SCEV!
3121 if (isa<SCEVConstant>(V)) return V;
3123 // If this instruction is evolved from a constant-evolving PHI, compute the
3124 // exit value from the loop without using SCEVs.
3125 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3126 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3127 const Loop *LI = (*this->LI)[I->getParent()];
3128 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3129 if (PHINode *PN = dyn_cast<PHINode>(I))
3130 if (PN->getParent() == LI->getHeader()) {
3131 // Okay, there is no closed form solution for the PHI node. Check
3132 // to see if the loop that contains it has a known backedge-taken
3133 // count. If so, we may be able to force computation of the exit
3135 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
3136 if (const SCEVConstant *BTCC =
3137 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3138 // Okay, we know how many times the containing loop executes. If
3139 // this is a constant evolving PHI node, get the final value at
3140 // the specified iteration number.
3141 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3142 BTCC->getValue()->getValue(),
3144 if (RV) return getUnknown(RV);
3148 // Okay, this is an expression that we cannot symbolically evaluate
3149 // into a SCEV. Check to see if it's possible to symbolically evaluate
3150 // the arguments into constants, and if so, try to constant propagate the
3151 // result. This is particularly useful for computing loop exit values.
3152 if (CanConstantFold(I)) {
3153 // Check to see if we've folded this instruction at this loop before.
3154 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3155 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3156 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3158 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3160 std::vector<Constant*> Operands;
3161 Operands.reserve(I->getNumOperands());
3162 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3163 Value *Op = I->getOperand(i);
3164 if (Constant *C = dyn_cast<Constant>(Op)) {
3165 Operands.push_back(C);
3167 // If any of the operands is non-constant and if they are
3168 // non-integer and non-pointer, don't even try to analyze them
3169 // with scev techniques.
3170 if (!isSCEVable(Op->getType()))
3173 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
3174 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3175 Constant *C = SC->getValue();
3176 if (C->getType() != Op->getType())
3177 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3181 Operands.push_back(C);
3182 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3183 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3184 if (C->getType() != Op->getType())
3186 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3190 Operands.push_back(C);
3200 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3201 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3202 &Operands[0], Operands.size());
3204 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3205 &Operands[0], Operands.size());
3206 Pair.first->second = C;
3207 return getUnknown(C);
3211 // This is some other type of SCEVUnknown, just return it.
3215 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3216 // Avoid performing the look-up in the common case where the specified
3217 // expression has no loop-variant portions.
3218 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3219 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3220 if (OpAtScope != Comm->getOperand(i)) {
3221 // Okay, at least one of these operands is loop variant but might be
3222 // foldable. Build a new instance of the folded commutative expression.
3223 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
3224 NewOps.push_back(OpAtScope);
3226 for (++i; i != e; ++i) {
3227 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3228 NewOps.push_back(OpAtScope);
3230 if (isa<SCEVAddExpr>(Comm))
3231 return getAddExpr(NewOps);
3232 if (isa<SCEVMulExpr>(Comm))
3233 return getMulExpr(NewOps);
3234 if (isa<SCEVSMaxExpr>(Comm))
3235 return getSMaxExpr(NewOps);
3236 if (isa<SCEVUMaxExpr>(Comm))
3237 return getUMaxExpr(NewOps);
3238 assert(0 && "Unknown commutative SCEV type!");
3241 // If we got here, all operands are loop invariant.
3245 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3246 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
3247 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
3248 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3249 return Div; // must be loop invariant
3250 return getUDivExpr(LHS, RHS);
3253 // If this is a loop recurrence for a loop that does not contain L, then we
3254 // are dealing with the final value computed by the loop.
3255 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3256 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3257 // To evaluate this recurrence, we need to know how many times the AddRec
3258 // loop iterates. Compute this now.
3259 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3260 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
3262 // Then, evaluate the AddRec.
3263 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3268 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3269 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3270 if (Op == Cast->getOperand())
3271 return Cast; // must be loop invariant
3272 return getZeroExtendExpr(Op, Cast->getType());
3275 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3276 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3277 if (Op == Cast->getOperand())
3278 return Cast; // must be loop invariant
3279 return getSignExtendExpr(Op, Cast->getType());
3282 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3283 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3284 if (Op == Cast->getOperand())
3285 return Cast; // must be loop invariant
3286 return getTruncateExpr(Op, Cast->getType());
3289 assert(0 && "Unknown SCEV type!");
3293 /// getSCEVAtScope - This is a convenience function which does
3294 /// getSCEVAtScope(getSCEV(V), L).
3295 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3296 return getSCEVAtScope(getSCEV(V), L);
3299 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3300 /// following equation:
3302 /// A * X = B (mod N)
3304 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3305 /// A and B isn't important.
3307 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3308 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3309 ScalarEvolution &SE) {
3310 uint32_t BW = A.getBitWidth();
3311 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3312 assert(A != 0 && "A must be non-zero.");
3316 // The gcd of A and N may have only one prime factor: 2. The number of
3317 // trailing zeros in A is its multiplicity
3318 uint32_t Mult2 = A.countTrailingZeros();
3321 // 2. Check if B is divisible by D.
3323 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3324 // is not less than multiplicity of this prime factor for D.
3325 if (B.countTrailingZeros() < Mult2)
3326 return SE.getCouldNotCompute();
3328 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3331 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3332 // bit width during computations.
3333 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3334 APInt Mod(BW + 1, 0);
3335 Mod.set(BW - Mult2); // Mod = N / D
3336 APInt I = AD.multiplicativeInverse(Mod);
3338 // 4. Compute the minimum unsigned root of the equation:
3339 // I * (B / D) mod (N / D)
3340 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3342 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3344 return SE.getConstant(Result.trunc(BW));
3347 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3348 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3349 /// might be the same) or two SCEVCouldNotCompute objects.
3351 static std::pair<SCEVHandle,SCEVHandle>
3352 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3353 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3354 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3355 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3356 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3358 // We currently can only solve this if the coefficients are constants.
3359 if (!LC || !MC || !NC) {
3360 const SCEV *CNC = SE.getCouldNotCompute();
3361 return std::make_pair(CNC, CNC);
3364 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3365 const APInt &L = LC->getValue()->getValue();
3366 const APInt &M = MC->getValue()->getValue();
3367 const APInt &N = NC->getValue()->getValue();
3368 APInt Two(BitWidth, 2);
3369 APInt Four(BitWidth, 4);
3372 using namespace APIntOps;
3374 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3375 // The B coefficient is M-N/2
3379 // The A coefficient is N/2
3380 APInt A(N.sdiv(Two));
3382 // Compute the B^2-4ac term.
3385 SqrtTerm -= Four * (A * C);
3387 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3388 // integer value or else APInt::sqrt() will assert.
3389 APInt SqrtVal(SqrtTerm.sqrt());
3391 // Compute the two solutions for the quadratic formula.
3392 // The divisions must be performed as signed divisions.
3394 APInt TwoA( A << 1 );
3395 if (TwoA.isMinValue()) {
3396 const SCEV *CNC = SE.getCouldNotCompute();
3397 return std::make_pair(CNC, CNC);
3400 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3401 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3403 return std::make_pair(SE.getConstant(Solution1),
3404 SE.getConstant(Solution2));
3405 } // end APIntOps namespace
3408 /// HowFarToZero - Return the number of times a backedge comparing the specified
3409 /// value to zero will execute. If not computable, return CouldNotCompute.
3410 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3411 // If the value is a constant
3412 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3413 // If the value is already zero, the branch will execute zero times.
3414 if (C->getValue()->isZero()) return C;
3415 return CouldNotCompute; // Otherwise it will loop infinitely.
3418 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3419 if (!AddRec || AddRec->getLoop() != L)
3420 return CouldNotCompute;
3422 if (AddRec->isAffine()) {
3423 // If this is an affine expression, the execution count of this branch is
3424 // the minimum unsigned root of the following equation:
3426 // Start + Step*N = 0 (mod 2^BW)
3430 // Step*N = -Start (mod 2^BW)
3432 // where BW is the common bit width of Start and Step.
3434 // Get the initial value for the loop.
3435 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3436 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
3438 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3439 // For now we handle only constant steps.
3441 // First, handle unitary steps.
3442 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3443 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3444 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3445 return Start; // N = Start (as unsigned)
3447 // Then, try to solve the above equation provided that Start is constant.
3448 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3449 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3450 -StartC->getValue()->getValue(),
3453 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3454 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3455 // the quadratic equation to solve it.
3456 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3458 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3459 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3462 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3463 << " sol#2: " << *R2 << "\n";
3465 // Pick the smallest positive root value.
3466 if (ConstantInt *CB =
3467 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3468 R1->getValue(), R2->getValue()))) {
3469 if (CB->getZExtValue() == false)
3470 std::swap(R1, R2); // R1 is the minimum root now.
3472 // We can only use this value if the chrec ends up with an exact zero
3473 // value at this index. When solving for "X*X != 5", for example, we
3474 // should not accept a root of 2.
3475 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3477 return R1; // We found a quadratic root!
3482 return CouldNotCompute;
3485 /// HowFarToNonZero - Return the number of times a backedge checking the
3486 /// specified value for nonzero will execute. If not computable, return
3488 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3489 // Loops that look like: while (X == 0) are very strange indeed. We don't
3490 // handle them yet except for the trivial case. This could be expanded in the
3491 // future as needed.
3493 // If the value is a constant, check to see if it is known to be non-zero
3494 // already. If so, the backedge will execute zero times.
3495 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3496 if (!C->getValue()->isNullValue())
3497 return getIntegerSCEV(0, C->getType());
3498 return CouldNotCompute; // Otherwise it will loop infinitely.
3501 // We could implement others, but I really doubt anyone writes loops like
3502 // this, and if they did, they would already be constant folded.
3503 return CouldNotCompute;
3506 /// getLoopPredecessor - If the given loop's header has exactly one unique
3507 /// predecessor outside the loop, return it. Otherwise return null.
3509 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3510 BasicBlock *Header = L->getHeader();
3511 BasicBlock *Pred = 0;
3512 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3514 if (!L->contains(*PI)) {
3515 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3521 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3522 /// (which may not be an immediate predecessor) which has exactly one
3523 /// successor from which BB is reachable, or null if no such block is
3527 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3528 // If the block has a unique predecessor, then there is no path from the
3529 // predecessor to the block that does not go through the direct edge
3530 // from the predecessor to the block.
3531 if (BasicBlock *Pred = BB->getSinglePredecessor())
3534 // A loop's header is defined to be a block that dominates the loop.
3535 // If the header has a unique predecessor outside the loop, it must be
3536 // a block that has exactly one successor that can reach the loop.
3537 if (Loop *L = LI->getLoopFor(BB))
3538 return getLoopPredecessor(L);
3543 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3544 /// a conditional between LHS and RHS. This is used to help avoid max
3545 /// expressions in loop trip counts.
3546 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3547 ICmpInst::Predicate Pred,
3548 const SCEV *LHS, const SCEV *RHS) {
3549 // Interpret a null as meaning no loop, where there is obviously no guard
3550 // (interprocedural conditions notwithstanding).
3551 if (!L) return false;
3553 BasicBlock *Predecessor = getLoopPredecessor(L);
3554 BasicBlock *PredecessorDest = L->getHeader();
3556 // Starting at the loop predecessor, climb up the predecessor chain, as long
3557 // as there are predecessors that can be found that have unique successors
3558 // leading to the original header.
3560 PredecessorDest = Predecessor,
3561 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
3563 BranchInst *LoopEntryPredicate =
3564 dyn_cast<BranchInst>(Predecessor->getTerminator());
3565 if (!LoopEntryPredicate ||
3566 LoopEntryPredicate->isUnconditional())
3569 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3572 // Now that we found a conditional branch that dominates the loop, check to
3573 // see if it is the comparison we are looking for.
3574 Value *PreCondLHS = ICI->getOperand(0);
3575 Value *PreCondRHS = ICI->getOperand(1);
3576 ICmpInst::Predicate Cond;
3577 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
3578 Cond = ICI->getPredicate();
3580 Cond = ICI->getInversePredicate();
3583 ; // An exact match.
3584 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3585 ; // The actual condition is beyond sufficient.
3587 // Check a few special cases.
3589 case ICmpInst::ICMP_UGT:
3590 if (Pred == ICmpInst::ICMP_ULT) {
3591 std::swap(PreCondLHS, PreCondRHS);
3592 Cond = ICmpInst::ICMP_ULT;
3596 case ICmpInst::ICMP_SGT:
3597 if (Pred == ICmpInst::ICMP_SLT) {
3598 std::swap(PreCondLHS, PreCondRHS);
3599 Cond = ICmpInst::ICMP_SLT;
3603 case ICmpInst::ICMP_NE:
3604 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3605 // so check for this case by checking if the NE is comparing against
3606 // a minimum or maximum constant.
3607 if (!ICmpInst::isTrueWhenEqual(Pred))
3608 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3609 const APInt &A = CI->getValue();
3611 case ICmpInst::ICMP_SLT:
3612 if (A.isMaxSignedValue()) break;
3614 case ICmpInst::ICMP_SGT:
3615 if (A.isMinSignedValue()) break;
3617 case ICmpInst::ICMP_ULT:
3618 if (A.isMaxValue()) break;
3620 case ICmpInst::ICMP_UGT:
3621 if (A.isMinValue()) break;
3626 Cond = ICmpInst::ICMP_NE;
3627 // NE is symmetric but the original comparison may not be. Swap
3628 // the operands if necessary so that they match below.
3629 if (isa<SCEVConstant>(LHS))
3630 std::swap(PreCondLHS, PreCondRHS);
3635 // We weren't able to reconcile the condition.
3639 if (!PreCondLHS->getType()->isInteger()) continue;
3641 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3642 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3643 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3644 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3645 RHS == getNotSCEV(PreCondLHSSCEV)))
3652 /// HowManyLessThans - Return the number of times a backedge containing the
3653 /// specified less-than comparison will execute. If not computable, return
3654 /// CouldNotCompute.
3655 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
3656 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3657 const Loop *L, bool isSigned) {
3658 // Only handle: "ADDREC < LoopInvariant".
3659 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
3661 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3662 if (!AddRec || AddRec->getLoop() != L)
3663 return CouldNotCompute;
3665 if (AddRec->isAffine()) {
3666 // FORNOW: We only support unit strides.
3667 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3668 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3669 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3671 // TODO: handle non-constant strides.
3672 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3673 if (!CStep || CStep->isZero())
3674 return CouldNotCompute;
3675 if (CStep->isOne()) {
3676 // With unit stride, the iteration never steps past the limit value.
3677 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3678 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3679 // Test whether a positive iteration iteration can step past the limit
3680 // value and past the maximum value for its type in a single step.
3682 APInt Max = APInt::getSignedMaxValue(BitWidth);
3683 if ((Max - CStep->getValue()->getValue())
3684 .slt(CLimit->getValue()->getValue()))
3685 return CouldNotCompute;
3687 APInt Max = APInt::getMaxValue(BitWidth);
3688 if ((Max - CStep->getValue()->getValue())
3689 .ult(CLimit->getValue()->getValue()))
3690 return CouldNotCompute;
3693 // TODO: handle non-constant limit values below.
3694 return CouldNotCompute;
3696 // TODO: handle negative strides below.
3697 return CouldNotCompute;
3699 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3700 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3701 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
3702 // treat m-n as signed nor unsigned due to overflow possibility.
3704 // First, we get the value of the LHS in the first iteration: n
3705 SCEVHandle Start = AddRec->getOperand(0);
3707 // Determine the minimum constant start value.
3708 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3709 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3710 APInt::getMinValue(BitWidth));
3712 // If we know that the condition is true in order to enter the loop,
3713 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3714 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3715 // the division must round up.
3716 SCEVHandle End = RHS;
3717 if (!isLoopGuardedByCond(L,
3718 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3719 getMinusSCEV(Start, Step), RHS))
3720 End = isSigned ? getSMaxExpr(RHS, Start)
3721 : getUMaxExpr(RHS, Start);
3723 // Determine the maximum constant end value.
3724 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3725 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3726 APInt::getMaxValue(BitWidth));
3728 // Finally, we subtract these two values and divide, rounding up, to get
3729 // the number of times the backedge is executed.
3730 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3731 getAddExpr(Step, NegOne)),
3734 // The maximum backedge count is similar, except using the minimum start
3735 // value and the maximum end value.
3736 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3738 getAddExpr(Step, NegOne)),
3741 return BackedgeTakenInfo(BECount, MaxBECount);
3744 return CouldNotCompute;
3747 /// getNumIterationsInRange - Return the number of iterations of this loop that
3748 /// produce values in the specified constant range. Another way of looking at
3749 /// this is that it returns the first iteration number where the value is not in
3750 /// the condition, thus computing the exit count. If the iteration count can't
3751 /// be computed, an instance of SCEVCouldNotCompute is returned.
3752 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3753 ScalarEvolution &SE) const {
3754 if (Range.isFullSet()) // Infinite loop.
3755 return SE.getCouldNotCompute();
3757 // If the start is a non-zero constant, shift the range to simplify things.
3758 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3759 if (!SC->getValue()->isZero()) {
3760 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
3761 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3762 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3763 if (const SCEVAddRecExpr *ShiftedAddRec =
3764 dyn_cast<SCEVAddRecExpr>(Shifted))
3765 return ShiftedAddRec->getNumIterationsInRange(
3766 Range.subtract(SC->getValue()->getValue()), SE);
3767 // This is strange and shouldn't happen.
3768 return SE.getCouldNotCompute();
3771 // The only time we can solve this is when we have all constant indices.
3772 // Otherwise, we cannot determine the overflow conditions.
3773 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3774 if (!isa<SCEVConstant>(getOperand(i)))
3775 return SE.getCouldNotCompute();
3778 // Okay at this point we know that all elements of the chrec are constants and
3779 // that the start element is zero.
3781 // First check to see if the range contains zero. If not, the first
3783 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3784 if (!Range.contains(APInt(BitWidth, 0)))
3785 return SE.getIntegerSCEV(0, getType());
3788 // If this is an affine expression then we have this situation:
3789 // Solve {0,+,A} in Range === Ax in Range
3791 // We know that zero is in the range. If A is positive then we know that
3792 // the upper value of the range must be the first possible exit value.
3793 // If A is negative then the lower of the range is the last possible loop
3794 // value. Also note that we already checked for a full range.
3795 APInt One(BitWidth,1);
3796 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3797 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3799 // The exit value should be (End+A)/A.
3800 APInt ExitVal = (End + A).udiv(A);
3801 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3803 // Evaluate at the exit value. If we really did fall out of the valid
3804 // range, then we computed our trip count, otherwise wrap around or other
3805 // things must have happened.
3806 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3807 if (Range.contains(Val->getValue()))
3808 return SE.getCouldNotCompute(); // Something strange happened
3810 // Ensure that the previous value is in the range. This is a sanity check.
3811 assert(Range.contains(
3812 EvaluateConstantChrecAtConstant(this,
3813 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3814 "Linear scev computation is off in a bad way!");
3815 return SE.getConstant(ExitValue);
3816 } else if (isQuadratic()) {
3817 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3818 // quadratic equation to solve it. To do this, we must frame our problem in
3819 // terms of figuring out when zero is crossed, instead of when
3820 // Range.getUpper() is crossed.
3821 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
3822 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3823 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3825 // Next, solve the constructed addrec
3826 std::pair<SCEVHandle,SCEVHandle> Roots =
3827 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3828 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3829 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3831 // Pick the smallest positive root value.
3832 if (ConstantInt *CB =
3833 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3834 R1->getValue(), R2->getValue()))) {
3835 if (CB->getZExtValue() == false)
3836 std::swap(R1, R2); // R1 is the minimum root now.
3838 // Make sure the root is not off by one. The returned iteration should
3839 // not be in the range, but the previous one should be. When solving
3840 // for "X*X < 5", for example, we should not return a root of 2.
3841 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3844 if (Range.contains(R1Val->getValue())) {
3845 // The next iteration must be out of the range...
3846 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3848 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3849 if (!Range.contains(R1Val->getValue()))
3850 return SE.getConstant(NextVal);
3851 return SE.getCouldNotCompute(); // Something strange happened
3854 // If R1 was not in the range, then it is a good return value. Make
3855 // sure that R1-1 WAS in the range though, just in case.
3856 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3857 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3858 if (Range.contains(R1Val->getValue()))
3860 return SE.getCouldNotCompute(); // Something strange happened
3865 return SE.getCouldNotCompute();
3870 //===----------------------------------------------------------------------===//
3871 // SCEVCallbackVH Class Implementation
3872 //===----------------------------------------------------------------------===//
3874 void ScalarEvolution::SCEVCallbackVH::deleted() {
3875 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3876 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3877 SE->ConstantEvolutionLoopExitValue.erase(PN);
3878 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3879 SE->ValuesAtScopes.erase(I);
3880 SE->Scalars.erase(getValPtr());
3881 // this now dangles!
3884 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
3885 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3887 // Forget all the expressions associated with users of the old value,
3888 // so that future queries will recompute the expressions using the new
3890 SmallVector<User *, 16> Worklist;
3891 Value *Old = getValPtr();
3892 bool DeleteOld = false;
3893 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3895 Worklist.push_back(*UI);
3896 while (!Worklist.empty()) {
3897 User *U = Worklist.pop_back_val();
3898 // Deleting the Old value will cause this to dangle. Postpone
3899 // that until everything else is done.
3904 if (PHINode *PN = dyn_cast<PHINode>(U))
3905 SE->ConstantEvolutionLoopExitValue.erase(PN);
3906 if (Instruction *I = dyn_cast<Instruction>(U))
3907 SE->ValuesAtScopes.erase(I);
3908 if (SE->Scalars.erase(U))
3909 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3911 Worklist.push_back(*UI);
3914 if (PHINode *PN = dyn_cast<PHINode>(Old))
3915 SE->ConstantEvolutionLoopExitValue.erase(PN);
3916 if (Instruction *I = dyn_cast<Instruction>(Old))
3917 SE->ValuesAtScopes.erase(I);
3918 SE->Scalars.erase(Old);
3919 // this now dangles!
3924 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3925 : CallbackVH(V), SE(se) {}
3927 //===----------------------------------------------------------------------===//
3928 // ScalarEvolution Class Implementation
3929 //===----------------------------------------------------------------------===//
3931 ScalarEvolution::ScalarEvolution()
3932 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
3935 bool ScalarEvolution::runOnFunction(Function &F) {
3937 LI = &getAnalysis<LoopInfo>();
3938 TD = getAnalysisIfAvailable<TargetData>();
3942 void ScalarEvolution::releaseMemory() {
3944 BackedgeTakenCounts.clear();
3945 ConstantEvolutionLoopExitValue.clear();
3946 ValuesAtScopes.clear();
3949 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3950 AU.setPreservesAll();
3951 AU.addRequiredTransitive<LoopInfo>();
3954 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3955 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3958 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3960 // Print all inner loops first
3961 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3962 PrintLoopInfo(OS, SE, *I);
3964 OS << "Loop " << L->getHeader()->getName() << ": ";
3966 SmallVector<BasicBlock*, 8> ExitBlocks;
3967 L->getExitBlocks(ExitBlocks);
3968 if (ExitBlocks.size() != 1)
3969 OS << "<multiple exits> ";
3971 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3972 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3974 OS << "Unpredictable backedge-taken count. ";
3980 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3981 // ScalarEvolution's implementaiton of the print method is to print
3982 // out SCEV values of all instructions that are interesting. Doing
3983 // this potentially causes it to create new SCEV objects though,
3984 // which technically conflicts with the const qualifier. This isn't
3985 // observable from outside the class though (the hasSCEV function
3986 // notwithstanding), so casting away the const isn't dangerous.
3987 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3989 OS << "Classifying expressions for: " << F->getName() << "\n";
3990 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3991 if (isSCEVable(I->getType())) {
3994 SCEVHandle SV = SE.getSCEV(&*I);
3998 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
4000 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
4001 if (!ExitValue->isLoopInvariant(L)) {
4002 OS << "<<Unknown>>";
4011 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4012 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4013 PrintLoopInfo(OS, &SE, *I);
4016 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4017 raw_os_ostream OS(o);