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/Analysis/ValueTracking.h"
72 #include "llvm/Assembly/Writer.h"
73 #include "llvm/Target/TargetData.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Compiler.h"
76 #include "llvm/Support/ConstantRange.h"
77 #include "llvm/Support/GetElementPtrTypeIterator.h"
78 #include "llvm/Support/InstIterator.h"
79 #include "llvm/Support/ManagedStatic.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/ADT/Statistic.h"
83 #include "llvm/ADT/STLExtras.h"
87 STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89 STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91 STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93 STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
96 static cl::opt<unsigned>
97 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
102 static RegisterPass<ScalarEvolution>
103 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
104 char ScalarEvolution::ID = 0;
106 //===----------------------------------------------------------------------===//
107 // SCEV class definitions
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
111 // Implementation of the SCEV class.
114 void SCEV::dump() const {
119 void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
124 bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
130 bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
136 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137 SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
139 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 const Type *SCEVCouldNotCompute::getType() const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
154 SCEVHandle SCEVCouldNotCompute::
155 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
156 const SCEVHandle &Conc,
157 ScalarEvolution &SE) const {
161 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
162 OS << "***COULDNOTCOMPUTE***";
165 bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
170 // SCEVConstants - Only allow the creation of one SCEVConstant for any
171 // particular value. Don't use a SCEVHandle here, or else the object will
173 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
176 SCEVConstant::~SCEVConstant() {
177 SCEVConstants->erase(V);
180 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
181 SCEVConstant *&R = (*SCEVConstants)[V];
182 if (R == 0) R = new SCEVConstant(V);
186 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(Val));
191 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
192 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
195 const Type *SCEVConstant::getType() const { return V->getType(); }
197 void SCEVConstant::print(raw_ostream &OS) const {
198 WriteAsOperand(OS, V, false);
201 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
202 const SCEVHandle &op, const Type *ty)
203 : SCEV(SCEVTy), Op(op), Ty(ty) {}
205 SCEVCastExpr::~SCEVCastExpr() {}
207 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
208 return Op->dominates(BB, DT);
211 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
212 // particular input. Don't use a SCEVHandle here, or else the object will
214 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
215 SCEVTruncateExpr*> > SCEVTruncates;
217 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
218 : SCEVCastExpr(scTruncate, op, ty) {
219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
221 "Cannot truncate non-integer value!");
224 SCEVTruncateExpr::~SCEVTruncateExpr() {
225 SCEVTruncates->erase(std::make_pair(Op, Ty));
228 void SCEVTruncateExpr::print(raw_ostream &OS) const {
229 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
232 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
233 // particular input. Don't use a SCEVHandle here, or else the object will never
235 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
236 SCEVZeroExtendExpr*> > SCEVZeroExtends;
238 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
239 : SCEVCastExpr(scZeroExtend, op, ty) {
240 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
241 (Ty->isInteger() || isa<PointerType>(Ty)) &&
242 "Cannot zero extend non-integer value!");
245 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
246 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
249 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
250 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
253 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254 // particular input. Don't use a SCEVHandle here, or else the object will never
256 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
259 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEVCastExpr(scSignExtend, op, ty) {
261 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
262 (Ty->isInteger() || isa<PointerType>(Ty)) &&
263 "Cannot sign extend non-integer value!");
266 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
267 SCEVSignExtends->erase(std::make_pair(Op, Ty));
270 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
271 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
274 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
275 // particular input. Don't use a SCEVHandle here, or else the object will never
277 static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
278 SCEVCommutativeExpr*> > SCEVCommExprs;
280 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
281 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
282 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
285 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
286 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
287 const char *OpStr = getOperationStr();
288 OS << "(" << *Operands[0];
289 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
290 OS << OpStr << *Operands[i];
294 SCEVHandle SCEVCommutativeExpr::
295 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
296 const SCEVHandle &Conc,
297 ScalarEvolution &SE) const {
298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
300 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
301 if (H != getOperand(i)) {
302 SmallVector<SCEVHandle, 8> NewOps;
303 NewOps.reserve(getNumOperands());
304 for (unsigned j = 0; j != i; ++j)
305 NewOps.push_back(getOperand(j));
307 for (++i; i != e; ++i)
308 NewOps.push_back(getOperand(i)->
309 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
311 if (isa<SCEVAddExpr>(this))
312 return SE.getAddExpr(NewOps);
313 else if (isa<SCEVMulExpr>(this))
314 return SE.getMulExpr(NewOps);
315 else if (isa<SCEVSMaxExpr>(this))
316 return SE.getSMaxExpr(NewOps);
317 else if (isa<SCEVUMaxExpr>(this))
318 return SE.getUMaxExpr(NewOps);
320 assert(0 && "Unknown commutative expr!");
326 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
327 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
328 if (!getOperand(i)->dominates(BB, DT))
335 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
336 // input. Don't use a SCEVHandle here, or else the object will never be
338 static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
339 SCEVUDivExpr*> > SCEVUDivs;
341 SCEVUDivExpr::~SCEVUDivExpr() {
342 SCEVUDivs->erase(std::make_pair(LHS, RHS));
345 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
346 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
349 void SCEVUDivExpr::print(raw_ostream &OS) const {
350 OS << "(" << *LHS << " /u " << *RHS << ")";
353 const Type *SCEVUDivExpr::getType() const {
354 // In most cases the types of LHS and RHS will be the same, but in some
355 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
356 // depend on the type for correctness, but handling types carefully can
357 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
358 // a pointer type than the RHS, so use the RHS' type here.
359 return RHS->getType();
362 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
363 // particular input. Don't use a SCEVHandle here, or else the object will never
365 static ManagedStatic<std::map<std::pair<const Loop *,
366 std::vector<const SCEV*> >,
367 SCEVAddRecExpr*> > SCEVAddRecExprs;
369 SCEVAddRecExpr::~SCEVAddRecExpr() {
370 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
371 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
374 SCEVHandle SCEVAddRecExpr::
375 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
376 const SCEVHandle &Conc,
377 ScalarEvolution &SE) const {
378 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
380 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
381 if (H != getOperand(i)) {
382 SmallVector<SCEVHandle, 8> NewOps;
383 NewOps.reserve(getNumOperands());
384 for (unsigned j = 0; j != i; ++j)
385 NewOps.push_back(getOperand(j));
387 for (++i; i != e; ++i)
388 NewOps.push_back(getOperand(i)->
389 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
391 return SE.getAddRecExpr(NewOps, L);
398 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
399 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
400 // contain L and if the start is invariant.
401 // Add recurrences are never invariant in the function-body (null loop).
403 !QueryLoop->contains(L->getHeader()) &&
404 getOperand(0)->isLoopInvariant(QueryLoop);
408 void SCEVAddRecExpr::print(raw_ostream &OS) const {
409 OS << "{" << *Operands[0];
410 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
411 OS << ",+," << *Operands[i];
412 OS << "}<" << L->getHeader()->getName() + ">";
415 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
416 // value. Don't use a SCEVHandle here, or else the object will never be
418 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
420 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
422 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
423 // All non-instruction values are loop invariant. All instructions are loop
424 // invariant if they are not contained in the specified loop.
425 // Instructions are never considered invariant in the function body
426 // (null loop) because they are defined within the "loop".
427 if (Instruction *I = dyn_cast<Instruction>(V))
428 return L && !L->contains(I->getParent());
432 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
433 if (Instruction *I = dyn_cast<Instruction>(getValue()))
434 return DT->dominates(I->getParent(), BB);
438 const Type *SCEVUnknown::getType() const {
442 void SCEVUnknown::print(raw_ostream &OS) const {
443 WriteAsOperand(OS, V, false);
446 //===----------------------------------------------------------------------===//
448 //===----------------------------------------------------------------------===//
451 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
452 /// than the complexity of the RHS. This comparator is used to canonicalize
454 class VISIBILITY_HIDDEN SCEVComplexityCompare {
457 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
459 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
460 // Primarily, sort the SCEVs by their getSCEVType().
461 if (LHS->getSCEVType() != RHS->getSCEVType())
462 return LHS->getSCEVType() < RHS->getSCEVType();
464 // Aside from the getSCEVType() ordering, the particular ordering
465 // isn't very important except that it's beneficial to be consistent,
466 // so that (a + b) and (b + a) don't end up as different expressions.
468 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
469 // not as complete as it could be.
470 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
471 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
473 // Order pointer values after integer values. This helps SCEVExpander
475 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
477 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
480 // Compare getValueID values.
481 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
482 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
484 // Sort arguments by their position.
485 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
486 const Argument *RA = cast<Argument>(RU->getValue());
487 return LA->getArgNo() < RA->getArgNo();
490 // For instructions, compare their loop depth, and their opcode.
491 // This is pretty loose.
492 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
493 Instruction *RV = cast<Instruction>(RU->getValue());
495 // Compare loop depths.
496 if (LI->getLoopDepth(LV->getParent()) !=
497 LI->getLoopDepth(RV->getParent()))
498 return LI->getLoopDepth(LV->getParent()) <
499 LI->getLoopDepth(RV->getParent());
502 if (LV->getOpcode() != RV->getOpcode())
503 return LV->getOpcode() < RV->getOpcode();
505 // Compare the number of operands.
506 if (LV->getNumOperands() != RV->getNumOperands())
507 return LV->getNumOperands() < RV->getNumOperands();
513 // Compare constant values.
514 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
515 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
516 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
519 // Compare addrec loop depths.
520 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
521 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
522 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
523 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
526 // Lexicographically compare n-ary expressions.
527 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
528 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
529 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
530 if (i >= RC->getNumOperands())
532 if (operator()(LC->getOperand(i), RC->getOperand(i)))
534 if (operator()(RC->getOperand(i), LC->getOperand(i)))
537 return LC->getNumOperands() < RC->getNumOperands();
540 // Lexicographically compare udiv expressions.
541 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
542 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
543 if (operator()(LC->getLHS(), RC->getLHS()))
545 if (operator()(RC->getLHS(), LC->getLHS()))
547 if (operator()(LC->getRHS(), RC->getRHS()))
549 if (operator()(RC->getRHS(), LC->getRHS()))
554 // Compare cast expressions by operand.
555 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
556 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
557 return operator()(LC->getOperand(), RC->getOperand());
560 assert(0 && "Unknown SCEV kind!");
566 /// GroupByComplexity - Given a list of SCEV objects, order them by their
567 /// complexity, and group objects of the same complexity together by value.
568 /// When this routine is finished, we know that any duplicates in the vector are
569 /// consecutive and that complexity is monotonically increasing.
571 /// Note that we go take special precautions to ensure that we get determinstic
572 /// results from this routine. In other words, we don't want the results of
573 /// this to depend on where the addresses of various SCEV objects happened to
576 static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
578 if (Ops.size() < 2) return; // Noop
579 if (Ops.size() == 2) {
580 // This is the common case, which also happens to be trivially simple.
582 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
583 std::swap(Ops[0], Ops[1]);
587 // Do the rough sort by complexity.
588 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
590 // Now that we are sorted by complexity, group elements of the same
591 // complexity. Note that this is, at worst, N^2, but the vector is likely to
592 // be extremely short in practice. Note that we take this approach because we
593 // do not want to depend on the addresses of the objects we are grouping.
594 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
595 const SCEV *S = Ops[i];
596 unsigned Complexity = S->getSCEVType();
598 // If there are any objects of the same complexity and same value as this
600 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
601 if (Ops[j] == S) { // Found a duplicate.
602 // Move it to immediately after i'th element.
603 std::swap(Ops[i+1], Ops[j]);
604 ++i; // no need to rescan it.
605 if (i == e-2) return; // Done!
613 //===----------------------------------------------------------------------===//
614 // Simple SCEV method implementations
615 //===----------------------------------------------------------------------===//
617 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
619 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
621 const Type* ResultTy) {
622 // Handle the simplest case efficiently.
624 return SE.getTruncateOrZeroExtend(It, ResultTy);
626 // We are using the following formula for BC(It, K):
628 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
630 // Suppose, W is the bitwidth of the return value. We must be prepared for
631 // overflow. Hence, we must assure that the result of our computation is
632 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
633 // safe in modular arithmetic.
635 // However, this code doesn't use exactly that formula; the formula it uses
636 // is something like the following, where T is the number of factors of 2 in
637 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
640 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
642 // This formula is trivially equivalent to the previous formula. However,
643 // this formula can be implemented much more efficiently. The trick is that
644 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
645 // arithmetic. To do exact division in modular arithmetic, all we have
646 // to do is multiply by the inverse. Therefore, this step can be done at
649 // The next issue is how to safely do the division by 2^T. The way this
650 // is done is by doing the multiplication step at a width of at least W + T
651 // bits. This way, the bottom W+T bits of the product are accurate. Then,
652 // when we perform the division by 2^T (which is equivalent to a right shift
653 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
654 // truncated out after the division by 2^T.
656 // In comparison to just directly using the first formula, this technique
657 // is much more efficient; using the first formula requires W * K bits,
658 // but this formula less than W + K bits. Also, the first formula requires
659 // a division step, whereas this formula only requires multiplies and shifts.
661 // It doesn't matter whether the subtraction step is done in the calculation
662 // width or the input iteration count's width; if the subtraction overflows,
663 // the result must be zero anyway. We prefer here to do it in the width of
664 // the induction variable because it helps a lot for certain cases; CodeGen
665 // isn't smart enough to ignore the overflow, which leads to much less
666 // efficient code if the width of the subtraction is wider than the native
669 // (It's possible to not widen at all by pulling out factors of 2 before
670 // the multiplication; for example, K=2 can be calculated as
671 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
672 // extra arithmetic, so it's not an obvious win, and it gets
673 // much more complicated for K > 3.)
675 // Protection from insane SCEVs; this bound is conservative,
676 // but it probably doesn't matter.
678 return SE.getCouldNotCompute();
680 unsigned W = SE.getTypeSizeInBits(ResultTy);
682 // Calculate K! / 2^T and T; we divide out the factors of two before
683 // multiplying for calculating K! / 2^T to avoid overflow.
684 // Other overflow doesn't matter because we only care about the bottom
685 // W bits of the result.
686 APInt OddFactorial(W, 1);
688 for (unsigned i = 3; i <= K; ++i) {
690 unsigned TwoFactors = Mult.countTrailingZeros();
692 Mult = Mult.lshr(TwoFactors);
693 OddFactorial *= Mult;
696 // We need at least W + T bits for the multiplication step
697 unsigned CalculationBits = W + T;
699 // Calcuate 2^T, at width T+W.
700 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
702 // Calculate the multiplicative inverse of K! / 2^T;
703 // this multiplication factor will perform the exact division by
705 APInt Mod = APInt::getSignedMinValue(W+1);
706 APInt MultiplyFactor = OddFactorial.zext(W+1);
707 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
708 MultiplyFactor = MultiplyFactor.trunc(W);
710 // Calculate the product, at width T+W
711 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
712 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
713 for (unsigned i = 1; i != K; ++i) {
714 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
715 Dividend = SE.getMulExpr(Dividend,
716 SE.getTruncateOrZeroExtend(S, CalculationTy));
720 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
722 // Truncate the result, and divide by K! / 2^T.
724 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
725 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
728 /// evaluateAtIteration - Return the value of this chain of recurrences at
729 /// the specified iteration number. We can evaluate this recurrence by
730 /// multiplying each element in the chain by the binomial coefficient
731 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
733 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
735 /// where BC(It, k) stands for binomial coefficient.
737 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
738 ScalarEvolution &SE) const {
739 SCEVHandle Result = getStart();
740 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
741 // The computation is correct in the face of overflow provided that the
742 // multiplication is performed _after_ the evaluation of the binomial
744 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
745 if (isa<SCEVCouldNotCompute>(Coeff))
748 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
753 //===----------------------------------------------------------------------===//
754 // SCEV Expression folder implementations
755 //===----------------------------------------------------------------------===//
757 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
759 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
760 "This is not a truncating conversion!");
761 assert(isSCEVable(Ty) &&
762 "This is not a conversion to a SCEVable type!");
763 Ty = getEffectiveSCEVType(Ty);
765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
767 ConstantExpr::getTrunc(SC->getValue(), Ty));
769 // trunc(trunc(x)) --> trunc(x)
770 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
771 return getTruncateExpr(ST->getOperand(), Ty);
773 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
774 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
775 return getTruncateOrSignExtend(SS->getOperand(), Ty);
777 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
778 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
779 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
781 // If the input value is a chrec scev made out of constants, truncate
782 // all of the constants.
783 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
784 SmallVector<SCEVHandle, 4> Operands;
785 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
786 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
787 return getAddRecExpr(Operands, AddRec->getLoop());
790 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
791 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
795 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
797 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
798 "This is not an extending conversion!");
799 assert(isSCEVable(Ty) &&
800 "This is not a conversion to a SCEVable type!");
801 Ty = getEffectiveSCEVType(Ty);
803 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
804 const Type *IntTy = getEffectiveSCEVType(Ty);
805 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
806 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
807 return getUnknown(C);
810 // zext(zext(x)) --> zext(x)
811 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
812 return getZeroExtendExpr(SZ->getOperand(), Ty);
814 // If the input value is a chrec scev, and we can prove that the value
815 // did not overflow the old, smaller, value, we can zero extend all of the
816 // operands (often constants). This allows analysis of something like
817 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
818 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
819 if (AR->isAffine()) {
820 // Check whether the backedge-taken count is SCEVCouldNotCompute.
821 // Note that this serves two purposes: It filters out loops that are
822 // simply not analyzable, and it covers the case where this code is
823 // being called from within backedge-taken count analysis, such that
824 // attempting to ask for the backedge-taken count would likely result
825 // in infinite recursion. In the later case, the analysis code will
826 // cope with a conservative value, and it will take care to purge
827 // that value once it has finished.
828 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
829 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
830 // Manually compute the final value for AR, checking for
832 SCEVHandle Start = AR->getStart();
833 SCEVHandle Step = AR->getStepRecurrence(*this);
835 // Check whether the backedge-taken count can be losslessly casted to
836 // the addrec's type. The count is always unsigned.
837 SCEVHandle CastedMaxBECount =
838 getTruncateOrZeroExtend(MaxBECount, Start->getType());
839 SCEVHandle RecastedMaxBECount =
840 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
841 if (MaxBECount == RecastedMaxBECount) {
843 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
844 // Check whether Start+Step*MaxBECount has no unsigned overflow.
846 getMulExpr(CastedMaxBECount,
847 getTruncateOrZeroExtend(Step, Start->getType()));
848 SCEVHandle Add = getAddExpr(Start, ZMul);
849 SCEVHandle OperandExtendedAdd =
850 getAddExpr(getZeroExtendExpr(Start, WideTy),
851 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
852 getZeroExtendExpr(Step, WideTy)));
853 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
854 // Return the expression with the addrec on the outside.
855 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
856 getZeroExtendExpr(Step, Ty),
859 // Similar to above, only this time treat the step value as signed.
860 // This covers loops that count down.
862 getMulExpr(CastedMaxBECount,
863 getTruncateOrSignExtend(Step, Start->getType()));
864 Add = getAddExpr(Start, SMul);
866 getAddExpr(getZeroExtendExpr(Start, WideTy),
867 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
868 getSignExtendExpr(Step, WideTy)));
869 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
870 // Return the expression with the addrec on the outside.
871 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
872 getSignExtendExpr(Step, Ty),
878 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
879 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
883 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
886 "This is not an extending conversion!");
887 assert(isSCEVable(Ty) &&
888 "This is not a conversion to a SCEVable type!");
889 Ty = getEffectiveSCEVType(Ty);
891 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
892 const Type *IntTy = getEffectiveSCEVType(Ty);
893 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
894 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
895 return getUnknown(C);
898 // sext(sext(x)) --> sext(x)
899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
900 return getSignExtendExpr(SS->getOperand(), Ty);
902 // If the input value is a chrec scev, and we can prove that the value
903 // did not overflow the old, smaller, value, we can sign extend all of the
904 // operands (often constants). This allows analysis of something like
905 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
906 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
907 if (AR->isAffine()) {
908 // Check whether the backedge-taken count is SCEVCouldNotCompute.
909 // Note that this serves two purposes: It filters out loops that are
910 // simply not analyzable, and it covers the case where this code is
911 // being called from within backedge-taken count analysis, such that
912 // attempting to ask for the backedge-taken count would likely result
913 // in infinite recursion. In the later case, the analysis code will
914 // cope with a conservative value, and it will take care to purge
915 // that value once it has finished.
916 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
917 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
918 // Manually compute the final value for AR, checking for
920 SCEVHandle Start = AR->getStart();
921 SCEVHandle Step = AR->getStepRecurrence(*this);
923 // Check whether the backedge-taken count can be losslessly casted to
924 // the addrec's type. The count is always unsigned.
925 SCEVHandle CastedMaxBECount =
926 getTruncateOrZeroExtend(MaxBECount, Start->getType());
927 SCEVHandle RecastedMaxBECount =
928 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
929 if (MaxBECount == RecastedMaxBECount) {
931 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
932 // Check whether Start+Step*MaxBECount has no signed overflow.
934 getMulExpr(CastedMaxBECount,
935 getTruncateOrSignExtend(Step, Start->getType()));
936 SCEVHandle Add = getAddExpr(Start, SMul);
937 SCEVHandle OperandExtendedAdd =
938 getAddExpr(getSignExtendExpr(Start, WideTy),
939 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
940 getSignExtendExpr(Step, WideTy)));
941 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
942 // Return the expression with the addrec on the outside.
943 return getAddRecExpr(getSignExtendExpr(Start, Ty),
944 getSignExtendExpr(Step, Ty),
950 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
951 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
955 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
956 /// unspecified bits out to the given type.
958 SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
960 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
961 "This is not an extending conversion!");
962 assert(isSCEVable(Ty) &&
963 "This is not a conversion to a SCEVable type!");
964 Ty = getEffectiveSCEVType(Ty);
966 // Sign-extend negative constants.
967 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
968 if (SC->getValue()->getValue().isNegative())
969 return getSignExtendExpr(Op, Ty);
971 // Peel off a truncate cast.
972 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
973 SCEVHandle NewOp = T->getOperand();
974 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
975 return getAnyExtendExpr(NewOp, Ty);
976 return getTruncateOrNoop(NewOp, Ty);
979 // Next try a zext cast. If the cast is folded, use it.
980 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
981 if (!isa<SCEVZeroExtendExpr>(ZExt))
984 // Next try a sext cast. If the cast is folded, use it.
985 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
986 if (!isa<SCEVSignExtendExpr>(SExt))
989 // If the expression is obviously signed, use the sext cast value.
990 if (isa<SCEVSMaxExpr>(Op))
993 // Absent any other information, use the zext cast value.
997 /// CollectAddOperandsWithScales - Process the given Ops list, which is
998 /// a list of operands to be added under the given scale, update the given
999 /// map. This is a helper function for getAddRecExpr. As an example of
1000 /// what it does, given a sequence of operands that would form an add
1001 /// expression like this:
1003 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1005 /// where A and B are constants, update the map with these values:
1007 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1009 /// and add 13 + A*B*29 to AccumulatedConstant.
1010 /// This will allow getAddRecExpr to produce this:
1012 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1014 /// This form often exposes folding opportunities that are hidden in
1015 /// the original operand list.
1017 /// Return true iff it appears that any interesting folding opportunities
1018 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1019 /// the common case where no interesting opportunities are present, and
1020 /// is also used as a check to avoid infinite recursion.
1023 CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1024 SmallVector<SCEVHandle, 8> &NewOps,
1025 APInt &AccumulatedConstant,
1026 const SmallVectorImpl<SCEVHandle> &Ops,
1028 ScalarEvolution &SE) {
1029 bool Interesting = false;
1031 // Iterate over the add operands.
1032 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1033 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1034 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1036 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1037 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1038 // A multiplication of a constant with another add; recurse.
1040 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1041 cast<SCEVAddExpr>(Mul->getOperand(1))
1045 // A multiplication of a constant with some other value. Update
1047 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1048 SCEVHandle Key = SE.getMulExpr(MulOps);
1049 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1050 M.insert(std::make_pair(Key, APInt()));
1052 Pair.first->second = NewScale;
1053 NewOps.push_back(Pair.first->first);
1055 Pair.first->second += NewScale;
1056 // The map already had an entry for this value, which may indicate
1057 // a folding opportunity.
1061 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1062 // Pull a buried constant out to the outside.
1063 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1065 AccumulatedConstant += Scale * C->getValue()->getValue();
1067 // An ordinary operand. Update the map.
1068 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1069 M.insert(std::make_pair(Ops[i], APInt()));
1071 Pair.first->second = Scale;
1072 NewOps.push_back(Pair.first->first);
1074 Pair.first->second += Scale;
1075 // The map already had an entry for this value, which may indicate
1076 // a folding opportunity.
1086 struct APIntCompare {
1087 bool operator()(const APInt &LHS, const APInt &RHS) const {
1088 return LHS.ult(RHS);
1093 /// getAddExpr - Get a canonical add expression, or something simpler if
1095 SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1096 assert(!Ops.empty() && "Cannot get empty add!");
1097 if (Ops.size() == 1) return Ops[0];
1099 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1100 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1101 getEffectiveSCEVType(Ops[0]->getType()) &&
1102 "SCEVAddExpr operand types don't match!");
1105 // Sort by complexity, this groups all similar expression types together.
1106 GroupByComplexity(Ops, LI);
1108 // If there are any constants, fold them together.
1110 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1112 assert(Idx < Ops.size());
1113 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1114 // We found two constants, fold them together!
1115 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1116 RHSC->getValue()->getValue());
1117 if (Ops.size() == 2) return Ops[0];
1118 Ops.erase(Ops.begin()+1); // Erase the folded element
1119 LHSC = cast<SCEVConstant>(Ops[0]);
1122 // If we are left with a constant zero being added, strip it off.
1123 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1124 Ops.erase(Ops.begin());
1129 if (Ops.size() == 1) return Ops[0];
1131 // Okay, check to see if the same value occurs in the operand list twice. If
1132 // so, merge them together into an multiply expression. Since we sorted the
1133 // list, these values are required to be adjacent.
1134 const Type *Ty = Ops[0]->getType();
1135 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1136 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1137 // Found a match, merge the two values into a multiply, and add any
1138 // remaining values to the result.
1139 SCEVHandle Two = getIntegerSCEV(2, Ty);
1140 SCEVHandle Mul = getMulExpr(Ops[i], Two);
1141 if (Ops.size() == 2)
1143 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1145 return getAddExpr(Ops);
1148 // Check for truncates. If all the operands are truncated from the same
1149 // type, see if factoring out the truncate would permit the result to be
1150 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1151 // if the contents of the resulting outer trunc fold to something simple.
1152 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1153 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1154 const Type *DstType = Trunc->getType();
1155 const Type *SrcType = Trunc->getOperand()->getType();
1156 SmallVector<SCEVHandle, 8> LargeOps;
1158 // Check all the operands to see if they can be represented in the
1159 // source type of the truncate.
1160 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1161 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1162 if (T->getOperand()->getType() != SrcType) {
1166 LargeOps.push_back(T->getOperand());
1167 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1168 // This could be either sign or zero extension, but sign extension
1169 // is much more likely to be foldable here.
1170 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1171 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1172 SmallVector<SCEVHandle, 8> LargeMulOps;
1173 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1174 if (const SCEVTruncateExpr *T =
1175 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1176 if (T->getOperand()->getType() != SrcType) {
1180 LargeMulOps.push_back(T->getOperand());
1181 } else if (const SCEVConstant *C =
1182 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1183 // This could be either sign or zero extension, but sign extension
1184 // is much more likely to be foldable here.
1185 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1192 LargeOps.push_back(getMulExpr(LargeMulOps));
1199 // Evaluate the expression in the larger type.
1200 SCEVHandle Fold = getAddExpr(LargeOps);
1201 // If it folds to something simple, use it. Otherwise, don't.
1202 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1203 return getTruncateExpr(Fold, DstType);
1207 // Skip past any other cast SCEVs.
1208 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1211 // If there are add operands they would be next.
1212 if (Idx < Ops.size()) {
1213 bool DeletedAdd = false;
1214 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1215 // If we have an add, expand the add operands onto the end of the operands
1217 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1218 Ops.erase(Ops.begin()+Idx);
1222 // If we deleted at least one add, we added operands to the end of the list,
1223 // and they are not necessarily sorted. Recurse to resort and resimplify
1224 // any operands we just aquired.
1226 return getAddExpr(Ops);
1229 // Skip over the add expression until we get to a multiply.
1230 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1233 // Check to see if there are any folding opportunities present with
1234 // operands multiplied by constant values.
1235 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1236 uint64_t BitWidth = getTypeSizeInBits(Ty);
1237 DenseMap<SCEVHandle, APInt> M;
1238 SmallVector<SCEVHandle, 8> NewOps;
1239 APInt AccumulatedConstant(BitWidth, 0);
1240 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1241 Ops, APInt(BitWidth, 1), *this)) {
1242 // Some interesting folding opportunity is present, so its worthwhile to
1243 // re-generate the operands list. Group the operands by constant scale,
1244 // to avoid multiplying by the same constant scale multiple times.
1245 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1246 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1247 E = NewOps.end(); I != E; ++I)
1248 MulOpLists[M.find(*I)->second].push_back(*I);
1249 // Re-generate the operands list.
1251 if (AccumulatedConstant != 0)
1252 Ops.push_back(getConstant(AccumulatedConstant));
1253 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1254 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1256 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1258 return getIntegerSCEV(0, Ty);
1259 if (Ops.size() == 1)
1261 return getAddExpr(Ops);
1265 // If we are adding something to a multiply expression, make sure the
1266 // something is not already an operand of the multiply. If so, merge it into
1268 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1269 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1270 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1271 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1272 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1273 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1274 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1275 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1276 if (Mul->getNumOperands() != 2) {
1277 // If the multiply has more than two operands, we must get the
1279 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1280 MulOps.erase(MulOps.begin()+MulOp);
1281 InnerMul = getMulExpr(MulOps);
1283 SCEVHandle One = getIntegerSCEV(1, Ty);
1284 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1285 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1286 if (Ops.size() == 2) return OuterMul;
1288 Ops.erase(Ops.begin()+AddOp);
1289 Ops.erase(Ops.begin()+Idx-1);
1291 Ops.erase(Ops.begin()+Idx);
1292 Ops.erase(Ops.begin()+AddOp-1);
1294 Ops.push_back(OuterMul);
1295 return getAddExpr(Ops);
1298 // Check this multiply against other multiplies being added together.
1299 for (unsigned OtherMulIdx = Idx+1;
1300 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1302 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1303 // If MulOp occurs in OtherMul, we can fold the two multiplies
1305 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1306 OMulOp != e; ++OMulOp)
1307 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1308 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1309 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1310 if (Mul->getNumOperands() != 2) {
1311 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1312 MulOps.erase(MulOps.begin()+MulOp);
1313 InnerMul1 = getMulExpr(MulOps);
1315 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1316 if (OtherMul->getNumOperands() != 2) {
1317 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
1318 OtherMul->op_end());
1319 MulOps.erase(MulOps.begin()+OMulOp);
1320 InnerMul2 = getMulExpr(MulOps);
1322 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1323 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1324 if (Ops.size() == 2) return OuterMul;
1325 Ops.erase(Ops.begin()+Idx);
1326 Ops.erase(Ops.begin()+OtherMulIdx-1);
1327 Ops.push_back(OuterMul);
1328 return getAddExpr(Ops);
1334 // If there are any add recurrences in the operands list, see if any other
1335 // added values are loop invariant. If so, we can fold them into the
1337 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1340 // Scan over all recurrences, trying to fold loop invariants into them.
1341 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1342 // Scan all of the other operands to this add and add them to the vector if
1343 // they are loop invariant w.r.t. the recurrence.
1344 SmallVector<SCEVHandle, 8> LIOps;
1345 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1346 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1347 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1348 LIOps.push_back(Ops[i]);
1349 Ops.erase(Ops.begin()+i);
1353 // If we found some loop invariants, fold them into the recurrence.
1354 if (!LIOps.empty()) {
1355 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1356 LIOps.push_back(AddRec->getStart());
1358 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1360 AddRecOps[0] = getAddExpr(LIOps);
1362 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1363 // If all of the other operands were loop invariant, we are done.
1364 if (Ops.size() == 1) return NewRec;
1366 // Otherwise, add the folded AddRec by the non-liv parts.
1367 for (unsigned i = 0;; ++i)
1368 if (Ops[i] == AddRec) {
1372 return getAddExpr(Ops);
1375 // Okay, if there weren't any loop invariants to be folded, check to see if
1376 // there are multiple AddRec's with the same loop induction variable being
1377 // added together. If so, we can fold them.
1378 for (unsigned OtherIdx = Idx+1;
1379 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1380 if (OtherIdx != Idx) {
1381 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1382 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1383 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1384 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
1385 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1386 if (i >= NewOps.size()) {
1387 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1388 OtherAddRec->op_end());
1391 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1393 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1395 if (Ops.size() == 2) return NewAddRec;
1397 Ops.erase(Ops.begin()+Idx);
1398 Ops.erase(Ops.begin()+OtherIdx-1);
1399 Ops.push_back(NewAddRec);
1400 return getAddExpr(Ops);
1404 // Otherwise couldn't fold anything into this recurrence. Move onto the
1408 // Okay, it looks like we really DO need an add expr. Check to see if we
1409 // already have one, otherwise create a new one.
1410 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1411 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1413 if (Result == 0) Result = new SCEVAddExpr(Ops);
1418 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1420 SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1421 assert(!Ops.empty() && "Cannot get empty mul!");
1423 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1424 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1425 getEffectiveSCEVType(Ops[0]->getType()) &&
1426 "SCEVMulExpr operand types don't match!");
1429 // Sort by complexity, this groups all similar expression types together.
1430 GroupByComplexity(Ops, LI);
1432 // If there are any constants, fold them together.
1434 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1436 // C1*(C2+V) -> C1*C2 + C1*V
1437 if (Ops.size() == 2)
1438 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1439 if (Add->getNumOperands() == 2 &&
1440 isa<SCEVConstant>(Add->getOperand(0)))
1441 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1442 getMulExpr(LHSC, Add->getOperand(1)));
1446 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1447 // We found two constants, fold them together!
1448 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1449 RHSC->getValue()->getValue());
1450 Ops[0] = getConstant(Fold);
1451 Ops.erase(Ops.begin()+1); // Erase the folded element
1452 if (Ops.size() == 1) return Ops[0];
1453 LHSC = cast<SCEVConstant>(Ops[0]);
1456 // If we are left with a constant one being multiplied, strip it off.
1457 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1458 Ops.erase(Ops.begin());
1460 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1461 // If we have a multiply of zero, it will always be zero.
1466 // Skip over the add expression until we get to a multiply.
1467 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1470 if (Ops.size() == 1)
1473 // If there are mul operands inline them all into this expression.
1474 if (Idx < Ops.size()) {
1475 bool DeletedMul = false;
1476 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1477 // If we have an mul, expand the mul operands onto the end of the operands
1479 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1480 Ops.erase(Ops.begin()+Idx);
1484 // If we deleted at least one mul, we added operands to the end of the list,
1485 // and they are not necessarily sorted. Recurse to resort and resimplify
1486 // any operands we just aquired.
1488 return getMulExpr(Ops);
1491 // If there are any add recurrences in the operands list, see if any other
1492 // added values are loop invariant. If so, we can fold them into the
1494 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1497 // Scan over all recurrences, trying to fold loop invariants into them.
1498 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1499 // Scan all of the other operands to this mul and add them to the vector if
1500 // they are loop invariant w.r.t. the recurrence.
1501 SmallVector<SCEVHandle, 8> LIOps;
1502 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1503 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1504 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1505 LIOps.push_back(Ops[i]);
1506 Ops.erase(Ops.begin()+i);
1510 // If we found some loop invariants, fold them into the recurrence.
1511 if (!LIOps.empty()) {
1512 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1513 SmallVector<SCEVHandle, 4> NewOps;
1514 NewOps.reserve(AddRec->getNumOperands());
1515 if (LIOps.size() == 1) {
1516 const SCEV *Scale = LIOps[0];
1517 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1518 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1520 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1521 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
1522 MulOps.push_back(AddRec->getOperand(i));
1523 NewOps.push_back(getMulExpr(MulOps));
1527 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1529 // If all of the other operands were loop invariant, we are done.
1530 if (Ops.size() == 1) return NewRec;
1532 // Otherwise, multiply the folded AddRec by the non-liv parts.
1533 for (unsigned i = 0;; ++i)
1534 if (Ops[i] == AddRec) {
1538 return getMulExpr(Ops);
1541 // Okay, if there weren't any loop invariants to be folded, check to see if
1542 // there are multiple AddRec's with the same loop induction variable being
1543 // multiplied together. If so, we can fold them.
1544 for (unsigned OtherIdx = Idx+1;
1545 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1546 if (OtherIdx != Idx) {
1547 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1548 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1549 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1550 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1551 SCEVHandle NewStart = getMulExpr(F->getStart(),
1553 SCEVHandle B = F->getStepRecurrence(*this);
1554 SCEVHandle D = G->getStepRecurrence(*this);
1555 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1558 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1560 if (Ops.size() == 2) return NewAddRec;
1562 Ops.erase(Ops.begin()+Idx);
1563 Ops.erase(Ops.begin()+OtherIdx-1);
1564 Ops.push_back(NewAddRec);
1565 return getMulExpr(Ops);
1569 // Otherwise couldn't fold anything into this recurrence. Move onto the
1573 // Okay, it looks like we really DO need an mul expr. Check to see if we
1574 // already have one, otherwise create a new one.
1575 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1576 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1579 Result = new SCEVMulExpr(Ops);
1583 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1585 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1586 const SCEVHandle &RHS) {
1587 assert(getEffectiveSCEVType(LHS->getType()) ==
1588 getEffectiveSCEVType(RHS->getType()) &&
1589 "SCEVUDivExpr operand types don't match!");
1591 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1592 if (RHSC->getValue()->equalsInt(1))
1593 return LHS; // X udiv 1 --> x
1595 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1597 // Determine if the division can be folded into the operands of
1599 // TODO: Generalize this to non-constants by using known-bits information.
1600 const Type *Ty = LHS->getType();
1601 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1602 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1603 // For non-power-of-two values, effectively round the value up to the
1604 // nearest power of two.
1605 if (!RHSC->getValue()->getValue().isPowerOf2())
1607 const IntegerType *ExtTy =
1608 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1609 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1610 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1611 if (const SCEVConstant *Step =
1612 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1613 if (!Step->getValue()->getValue()
1614 .urem(RHSC->getValue()->getValue()) &&
1615 getZeroExtendExpr(AR, ExtTy) ==
1616 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1617 getZeroExtendExpr(Step, ExtTy),
1619 SmallVector<SCEVHandle, 4> Operands;
1620 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1621 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1622 return getAddRecExpr(Operands, AR->getLoop());
1624 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1625 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1626 SmallVector<SCEVHandle, 4> Operands;
1627 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1628 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1629 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1630 // Find an operand that's safely divisible.
1631 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1632 SCEVHandle Op = M->getOperand(i);
1633 SCEVHandle Div = getUDivExpr(Op, RHSC);
1634 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1635 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1636 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1639 return getMulExpr(Operands);
1643 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1644 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1645 SmallVector<SCEVHandle, 4> Operands;
1646 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1647 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1648 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1650 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1651 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1652 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1654 Operands.push_back(Op);
1656 if (Operands.size() == A->getNumOperands())
1657 return getAddExpr(Operands);
1661 // Fold if both operands are constant.
1662 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1663 Constant *LHSCV = LHSC->getValue();
1664 Constant *RHSCV = RHSC->getValue();
1665 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1669 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1670 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1675 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1676 /// Simplify the expression as much as possible.
1677 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1678 const SCEVHandle &Step, const Loop *L) {
1679 SmallVector<SCEVHandle, 4> Operands;
1680 Operands.push_back(Start);
1681 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1682 if (StepChrec->getLoop() == L) {
1683 Operands.insert(Operands.end(), StepChrec->op_begin(),
1684 StepChrec->op_end());
1685 return getAddRecExpr(Operands, L);
1688 Operands.push_back(Step);
1689 return getAddRecExpr(Operands, L);
1692 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1693 /// Simplify the expression as much as possible.
1694 SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
1696 if (Operands.size() == 1) return Operands[0];
1698 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1699 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1700 getEffectiveSCEVType(Operands[0]->getType()) &&
1701 "SCEVAddRecExpr operand types don't match!");
1704 if (Operands.back()->isZero()) {
1705 Operands.pop_back();
1706 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1709 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1710 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1711 const Loop* NestedLoop = NestedAR->getLoop();
1712 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1713 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1714 NestedAR->op_end());
1715 SCEVHandle NestedARHandle(NestedAR);
1716 Operands[0] = NestedAR->getStart();
1717 NestedOperands[0] = getAddRecExpr(Operands, L);
1718 return getAddRecExpr(NestedOperands, NestedLoop);
1722 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1723 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1724 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1728 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1729 const SCEVHandle &RHS) {
1730 SmallVector<SCEVHandle, 2> Ops;
1733 return getSMaxExpr(Ops);
1737 ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1738 assert(!Ops.empty() && "Cannot get empty smax!");
1739 if (Ops.size() == 1) return Ops[0];
1741 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1742 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1743 getEffectiveSCEVType(Ops[0]->getType()) &&
1744 "SCEVSMaxExpr operand types don't match!");
1747 // Sort by complexity, this groups all similar expression types together.
1748 GroupByComplexity(Ops, LI);
1750 // If there are any constants, fold them together.
1752 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1754 assert(Idx < Ops.size());
1755 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1756 // We found two constants, fold them together!
1757 ConstantInt *Fold = ConstantInt::get(
1758 APIntOps::smax(LHSC->getValue()->getValue(),
1759 RHSC->getValue()->getValue()));
1760 Ops[0] = getConstant(Fold);
1761 Ops.erase(Ops.begin()+1); // Erase the folded element
1762 if (Ops.size() == 1) return Ops[0];
1763 LHSC = cast<SCEVConstant>(Ops[0]);
1766 // If we are left with a constant -inf, strip it off.
1767 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1768 Ops.erase(Ops.begin());
1773 if (Ops.size() == 1) return Ops[0];
1775 // Find the first SMax
1776 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1779 // Check to see if one of the operands is an SMax. If so, expand its operands
1780 // onto our operand list, and recurse to simplify.
1781 if (Idx < Ops.size()) {
1782 bool DeletedSMax = false;
1783 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1784 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1785 Ops.erase(Ops.begin()+Idx);
1790 return getSMaxExpr(Ops);
1793 // Okay, check to see if the same value occurs in the operand list twice. If
1794 // so, delete one. Since we sorted the list, these values are required to
1796 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1797 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1798 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1802 if (Ops.size() == 1) return Ops[0];
1804 assert(!Ops.empty() && "Reduced smax down to nothing!");
1806 // Okay, it looks like we really DO need an smax expr. Check to see if we
1807 // already have one, otherwise create a new one.
1808 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1809 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1811 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1815 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1816 const SCEVHandle &RHS) {
1817 SmallVector<SCEVHandle, 2> Ops;
1820 return getUMaxExpr(Ops);
1824 ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1825 assert(!Ops.empty() && "Cannot get empty umax!");
1826 if (Ops.size() == 1) return Ops[0];
1828 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1829 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1830 getEffectiveSCEVType(Ops[0]->getType()) &&
1831 "SCEVUMaxExpr operand types don't match!");
1834 // Sort by complexity, this groups all similar expression types together.
1835 GroupByComplexity(Ops, LI);
1837 // If there are any constants, fold them together.
1839 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1841 assert(Idx < Ops.size());
1842 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1843 // We found two constants, fold them together!
1844 ConstantInt *Fold = ConstantInt::get(
1845 APIntOps::umax(LHSC->getValue()->getValue(),
1846 RHSC->getValue()->getValue()));
1847 Ops[0] = getConstant(Fold);
1848 Ops.erase(Ops.begin()+1); // Erase the folded element
1849 if (Ops.size() == 1) return Ops[0];
1850 LHSC = cast<SCEVConstant>(Ops[0]);
1853 // If we are left with a constant zero, strip it off.
1854 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1855 Ops.erase(Ops.begin());
1860 if (Ops.size() == 1) return Ops[0];
1862 // Find the first UMax
1863 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1866 // Check to see if one of the operands is a UMax. If so, expand its operands
1867 // onto our operand list, and recurse to simplify.
1868 if (Idx < Ops.size()) {
1869 bool DeletedUMax = false;
1870 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1871 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1872 Ops.erase(Ops.begin()+Idx);
1877 return getUMaxExpr(Ops);
1880 // Okay, check to see if the same value occurs in the operand list twice. If
1881 // so, delete one. Since we sorted the list, these values are required to
1883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1884 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1885 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1889 if (Ops.size() == 1) return Ops[0];
1891 assert(!Ops.empty() && "Reduced umax down to nothing!");
1893 // Okay, it looks like we really DO need a umax expr. Check to see if we
1894 // already have one, otherwise create a new one.
1895 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1896 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1898 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1902 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1903 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1904 return getConstant(CI);
1905 if (isa<ConstantPointerNull>(V))
1906 return getIntegerSCEV(0, V->getType());
1907 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1908 if (Result == 0) Result = new SCEVUnknown(V);
1912 //===----------------------------------------------------------------------===//
1913 // Basic SCEV Analysis and PHI Idiom Recognition Code
1916 /// isSCEVable - Test if values of the given type are analyzable within
1917 /// the SCEV framework. This primarily includes integer types, and it
1918 /// can optionally include pointer types if the ScalarEvolution class
1919 /// has access to target-specific information.
1920 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1921 // Integers are always SCEVable.
1922 if (Ty->isInteger())
1925 // Pointers are SCEVable if TargetData information is available
1926 // to provide pointer size information.
1927 if (isa<PointerType>(Ty))
1930 // Otherwise it's not SCEVable.
1934 /// getTypeSizeInBits - Return the size in bits of the specified type,
1935 /// for which isSCEVable must return true.
1936 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1937 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1939 // If we have a TargetData, use it!
1941 return TD->getTypeSizeInBits(Ty);
1943 // Otherwise, we support only integer types.
1944 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1945 return Ty->getPrimitiveSizeInBits();
1948 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1949 /// the given type and which represents how SCEV will treat the given
1950 /// type, for which isSCEVable must return true. For pointer types,
1951 /// this is the pointer-sized integer type.
1952 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1953 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1955 if (Ty->isInteger())
1958 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1959 return TD->getIntPtrType();
1962 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1963 return CouldNotCompute;
1966 /// hasSCEV - Return true if the SCEV for this value has already been
1968 bool ScalarEvolution::hasSCEV(Value *V) const {
1969 return Scalars.count(V);
1972 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1973 /// expression and create a new one.
1974 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1975 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1977 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1978 if (I != Scalars.end()) return I->second;
1979 SCEVHandle S = createSCEV(V);
1980 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1984 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1985 /// specified signed integer value and return a SCEV for the constant.
1986 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1987 Ty = getEffectiveSCEVType(Ty);
1990 C = Constant::getNullValue(Ty);
1991 else if (Ty->isFloatingPoint())
1992 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1993 APFloat::IEEEdouble, Val));
1995 C = ConstantInt::get(Ty, Val);
1996 return getUnknown(C);
1999 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2001 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
2002 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2003 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
2005 const Type *Ty = V->getType();
2006 Ty = getEffectiveSCEVType(Ty);
2007 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
2010 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2011 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
2012 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2013 return getUnknown(ConstantExpr::getNot(VC->getValue()));
2015 const Type *Ty = V->getType();
2016 Ty = getEffectiveSCEVType(Ty);
2017 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
2018 return getMinusSCEV(AllOnes, V);
2021 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2023 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
2024 const SCEVHandle &RHS) {
2026 return getAddExpr(LHS, getNegativeSCEV(RHS));
2029 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2030 /// input value to the specified type. If the type must be extended, it is zero
2033 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
2035 const Type *SrcTy = V->getType();
2036 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2037 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2038 "Cannot truncate or zero extend with non-integer arguments!");
2039 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2040 return V; // No conversion
2041 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2042 return getTruncateExpr(V, Ty);
2043 return getZeroExtendExpr(V, Ty);
2046 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2047 /// input value to the specified type. If the type must be extended, it is sign
2050 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
2052 const Type *SrcTy = V->getType();
2053 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2054 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2055 "Cannot truncate or zero extend with non-integer arguments!");
2056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2057 return V; // No conversion
2058 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2059 return getTruncateExpr(V, Ty);
2060 return getSignExtendExpr(V, Ty);
2063 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2064 /// input value to the specified type. If the type must be extended, it is zero
2065 /// extended. The conversion must not be narrowing.
2067 ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2068 const Type *SrcTy = V->getType();
2069 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2070 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2071 "Cannot noop or zero extend with non-integer arguments!");
2072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2073 "getNoopOrZeroExtend cannot truncate!");
2074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2075 return V; // No conversion
2076 return getZeroExtendExpr(V, Ty);
2079 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2080 /// input value to the specified type. If the type must be extended, it is sign
2081 /// extended. The conversion must not be narrowing.
2083 ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2084 const Type *SrcTy = V->getType();
2085 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2086 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2087 "Cannot noop or sign extend with non-integer arguments!");
2088 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2089 "getNoopOrSignExtend cannot truncate!");
2090 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2091 return V; // No conversion
2092 return getSignExtendExpr(V, Ty);
2095 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2096 /// the input value to the specified type. If the type must be extended,
2097 /// it is extended with unspecified bits. The conversion must not be
2100 ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2101 const Type *SrcTy = V->getType();
2102 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2103 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2104 "Cannot noop or any extend with non-integer arguments!");
2105 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2106 "getNoopOrAnyExtend cannot truncate!");
2107 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2108 return V; // No conversion
2109 return getAnyExtendExpr(V, Ty);
2112 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2113 /// input value to the specified type. The conversion must not be widening.
2115 ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2116 const Type *SrcTy = V->getType();
2117 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2118 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2119 "Cannot truncate or noop with non-integer arguments!");
2120 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2121 "getTruncateOrNoop cannot extend!");
2122 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2123 return V; // No conversion
2124 return getTruncateExpr(V, Ty);
2127 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2128 /// the specified instruction and replaces any references to the symbolic value
2129 /// SymName with the specified value. This is used during PHI resolution.
2130 void ScalarEvolution::
2131 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2132 const SCEVHandle &NewVal) {
2133 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2134 Scalars.find(SCEVCallbackVH(I, this));
2135 if (SI == Scalars.end()) return;
2138 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2139 if (NV == SI->second) return; // No change.
2141 SI->second = NV; // Update the scalars map!
2143 // Any instruction values that use this instruction might also need to be
2145 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2147 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2150 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2151 /// a loop header, making it a potential recurrence, or it doesn't.
2153 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
2154 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2155 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2156 if (L->getHeader() == PN->getParent()) {
2157 // If it lives in the loop header, it has two incoming values, one
2158 // from outside the loop, and one from inside.
2159 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2160 unsigned BackEdge = IncomingEdge^1;
2162 // While we are analyzing this PHI node, handle its value symbolically.
2163 SCEVHandle SymbolicName = getUnknown(PN);
2164 assert(Scalars.find(PN) == Scalars.end() &&
2165 "PHI node already processed?");
2166 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2168 // Using this symbolic name for the PHI, analyze the value coming around
2170 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2172 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2173 // has a special value for the first iteration of the loop.
2175 // If the value coming around the backedge is an add with the symbolic
2176 // value we just inserted, then we found a simple induction variable!
2177 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2178 // If there is a single occurrence of the symbolic value, replace it
2179 // with a recurrence.
2180 unsigned FoundIndex = Add->getNumOperands();
2181 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2182 if (Add->getOperand(i) == SymbolicName)
2183 if (FoundIndex == e) {
2188 if (FoundIndex != Add->getNumOperands()) {
2189 // Create an add with everything but the specified operand.
2190 SmallVector<SCEVHandle, 8> Ops;
2191 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2192 if (i != FoundIndex)
2193 Ops.push_back(Add->getOperand(i));
2194 SCEVHandle Accum = getAddExpr(Ops);
2196 // This is not a valid addrec if the step amount is varying each
2197 // loop iteration, but is not itself an addrec in this loop.
2198 if (Accum->isLoopInvariant(L) ||
2199 (isa<SCEVAddRecExpr>(Accum) &&
2200 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2201 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2202 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
2204 // Okay, for the entire analysis of this edge we assumed the PHI
2205 // to be symbolic. We now need to go back and update all of the
2206 // entries for the scalars that use the PHI (except for the PHI
2207 // itself) to use the new analyzed value instead of the "symbolic"
2209 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2213 } else if (const SCEVAddRecExpr *AddRec =
2214 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2215 // Otherwise, this could be a loop like this:
2216 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2217 // In this case, j = {1,+,1} and BEValue is j.
2218 // Because the other in-value of i (0) fits the evolution of BEValue
2219 // i really is an addrec evolution.
2220 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2221 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2223 // If StartVal = j.start - j.stride, we can use StartVal as the
2224 // initial step of the addrec evolution.
2225 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2226 AddRec->getOperand(1))) {
2227 SCEVHandle PHISCEV =
2228 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2230 // Okay, for the entire analysis of this edge we assumed the PHI
2231 // to be symbolic. We now need to go back and update all of the
2232 // entries for the scalars that use the PHI (except for the PHI
2233 // itself) to use the new analyzed value instead of the "symbolic"
2235 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2241 return SymbolicName;
2244 // If it's not a loop phi, we can't handle it yet.
2245 return getUnknown(PN);
2248 /// createNodeForGEP - Expand GEP instructions into add and multiply
2249 /// operations. This allows them to be analyzed by regular SCEV code.
2251 SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
2253 const Type *IntPtrTy = TD->getIntPtrType();
2254 Value *Base = GEP->getOperand(0);
2255 // Don't attempt to analyze GEPs over unsized objects.
2256 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2257 return getUnknown(GEP);
2258 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
2259 gep_type_iterator GTI = gep_type_begin(GEP);
2260 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2264 // Compute the (potentially symbolic) offset in bytes for this index.
2265 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2266 // For a struct, add the member offset.
2267 const StructLayout &SL = *TD->getStructLayout(STy);
2268 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2269 uint64_t Offset = SL.getElementOffset(FieldNo);
2270 TotalOffset = getAddExpr(TotalOffset,
2271 getIntegerSCEV(Offset, IntPtrTy));
2273 // For an array, add the element offset, explicitly scaled.
2274 SCEVHandle LocalOffset = getSCEV(Index);
2275 if (!isa<PointerType>(LocalOffset->getType()))
2276 // Getelementptr indicies are signed.
2277 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2280 getMulExpr(LocalOffset,
2281 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2283 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2286 return getAddExpr(getSCEV(Base), TotalOffset);
2289 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2290 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2291 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2292 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2293 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
2294 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2295 return C->getValue()->getValue().countTrailingZeros();
2297 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2298 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2299 (uint32_t)SE.getTypeSizeInBits(T->getType()));
2301 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2302 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2303 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
2304 SE.getTypeSizeInBits(E->getType()) : OpRes;
2307 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2308 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2309 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
2310 SE.getTypeSizeInBits(E->getType()) : OpRes;
2313 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2314 // The result is the min of all operands results.
2315 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
2316 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2317 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2321 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2322 // The result is the sum of all operands results.
2323 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2324 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
2325 for (unsigned i = 1, e = M->getNumOperands();
2326 SumOpRes != BitWidth && i != e; ++i)
2327 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
2332 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2333 // The result is the min of all operands results.
2334 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
2335 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2336 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
2340 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2341 // The result is the min of all operands results.
2342 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2343 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2344 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2348 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2349 // The result is the min of all operands results.
2350 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2351 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2352 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
2356 // SCEVUDivExpr, SCEVUnknown
2360 /// createSCEV - We know that there is no SCEV for the specified value.
2361 /// Analyze the expression.
2363 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
2364 if (!isSCEVable(V->getType()))
2365 return getUnknown(V);
2367 unsigned Opcode = Instruction::UserOp1;
2368 if (Instruction *I = dyn_cast<Instruction>(V))
2369 Opcode = I->getOpcode();
2370 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2371 Opcode = CE->getOpcode();
2373 return getUnknown(V);
2375 User *U = cast<User>(V);
2377 case Instruction::Add:
2378 return getAddExpr(getSCEV(U->getOperand(0)),
2379 getSCEV(U->getOperand(1)));
2380 case Instruction::Mul:
2381 return getMulExpr(getSCEV(U->getOperand(0)),
2382 getSCEV(U->getOperand(1)));
2383 case Instruction::UDiv:
2384 return getUDivExpr(getSCEV(U->getOperand(0)),
2385 getSCEV(U->getOperand(1)));
2386 case Instruction::Sub:
2387 return getMinusSCEV(getSCEV(U->getOperand(0)),
2388 getSCEV(U->getOperand(1)));
2389 case Instruction::And:
2390 // For an expression like x&255 that merely masks off the high bits,
2391 // use zext(trunc(x)) as the SCEV expression.
2392 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2393 if (CI->isNullValue())
2394 return getSCEV(U->getOperand(1));
2395 if (CI->isAllOnesValue())
2396 return getSCEV(U->getOperand(0));
2397 const APInt &A = CI->getValue();
2399 // Instcombine's ShrinkDemandedConstant may strip bits out of
2400 // constants, obscuring what would otherwise be a low-bits mask.
2401 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2402 // knew about to reconstruct a low-bits mask value.
2403 unsigned LZ = A.countLeadingZeros();
2404 unsigned BitWidth = A.getBitWidth();
2405 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2406 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2407 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2409 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2411 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2413 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2414 IntegerType::get(BitWidth - LZ)),
2419 case Instruction::Or:
2420 // If the RHS of the Or is a constant, we may have something like:
2421 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2422 // optimizations will transparently handle this case.
2424 // In order for this transformation to be safe, the LHS must be of the
2425 // form X*(2^n) and the Or constant must be less than 2^n.
2426 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2427 SCEVHandle LHS = getSCEV(U->getOperand(0));
2428 const APInt &CIVal = CI->getValue();
2429 if (GetMinTrailingZeros(LHS, *this) >=
2430 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2431 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2434 case Instruction::Xor:
2435 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2436 // If the RHS of the xor is a signbit, then this is just an add.
2437 // Instcombine turns add of signbit into xor as a strength reduction step.
2438 if (CI->getValue().isSignBit())
2439 return getAddExpr(getSCEV(U->getOperand(0)),
2440 getSCEV(U->getOperand(1)));
2442 // If the RHS of xor is -1, then this is a not operation.
2443 if (CI->isAllOnesValue())
2444 return getNotSCEV(getSCEV(U->getOperand(0)));
2446 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2447 // This is a variant of the check for xor with -1, and it handles
2448 // the case where instcombine has trimmed non-demanded bits out
2449 // of an xor with -1.
2450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2451 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2452 if (BO->getOpcode() == Instruction::And &&
2453 LCI->getValue() == CI->getValue())
2454 if (const SCEVZeroExtendExpr *Z =
2455 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2456 const Type *UTy = U->getType();
2457 SCEVHandle Z0 = Z->getOperand();
2458 const Type *Z0Ty = Z0->getType();
2459 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2461 // If C is a low-bits mask, the zero extend is zerving to
2462 // mask off the high bits. Complement the operand and
2463 // re-apply the zext.
2464 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2465 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2467 // If C is a single bit, it may be in the sign-bit position
2468 // before the zero-extend. In this case, represent the xor
2469 // using an add, which is equivalent, and re-apply the zext.
2470 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2471 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2473 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2479 case Instruction::Shl:
2480 // Turn shift left of a constant amount into a multiply.
2481 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2482 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2483 Constant *X = ConstantInt::get(
2484 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2485 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2489 case Instruction::LShr:
2490 // Turn logical shift right of a constant into a unsigned divide.
2491 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2492 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2493 Constant *X = ConstantInt::get(
2494 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2495 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2499 case Instruction::AShr:
2500 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2501 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2502 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2503 if (L->getOpcode() == Instruction::Shl &&
2504 L->getOperand(1) == U->getOperand(1)) {
2505 unsigned BitWidth = getTypeSizeInBits(U->getType());
2506 uint64_t Amt = BitWidth - CI->getZExtValue();
2507 if (Amt == BitWidth)
2508 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2510 return getIntegerSCEV(0, U->getType()); // value is undefined
2512 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2513 IntegerType::get(Amt)),
2518 case Instruction::Trunc:
2519 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2521 case Instruction::ZExt:
2522 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2524 case Instruction::SExt:
2525 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2527 case Instruction::BitCast:
2528 // BitCasts are no-op casts so we just eliminate the cast.
2529 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2530 return getSCEV(U->getOperand(0));
2533 case Instruction::IntToPtr:
2534 if (!TD) break; // Without TD we can't analyze pointers.
2535 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2536 TD->getIntPtrType());
2538 case Instruction::PtrToInt:
2539 if (!TD) break; // Without TD we can't analyze pointers.
2540 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2543 case Instruction::GetElementPtr:
2544 if (!TD) break; // Without TD we can't analyze pointers.
2545 return createNodeForGEP(U);
2547 case Instruction::PHI:
2548 return createNodeForPHI(cast<PHINode>(U));
2550 case Instruction::Select:
2551 // This could be a smax or umax that was lowered earlier.
2552 // Try to recover it.
2553 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2554 Value *LHS = ICI->getOperand(0);
2555 Value *RHS = ICI->getOperand(1);
2556 switch (ICI->getPredicate()) {
2557 case ICmpInst::ICMP_SLT:
2558 case ICmpInst::ICMP_SLE:
2559 std::swap(LHS, RHS);
2561 case ICmpInst::ICMP_SGT:
2562 case ICmpInst::ICMP_SGE:
2563 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2564 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2565 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2566 // ~smax(~x, ~y) == smin(x, y).
2567 return getNotSCEV(getSMaxExpr(
2568 getNotSCEV(getSCEV(LHS)),
2569 getNotSCEV(getSCEV(RHS))));
2571 case ICmpInst::ICMP_ULT:
2572 case ICmpInst::ICMP_ULE:
2573 std::swap(LHS, RHS);
2575 case ICmpInst::ICMP_UGT:
2576 case ICmpInst::ICMP_UGE:
2577 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2578 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2579 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2580 // ~umax(~x, ~y) == umin(x, y)
2581 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2582 getNotSCEV(getSCEV(RHS))));
2589 default: // We cannot analyze this expression.
2593 return getUnknown(V);
2598 //===----------------------------------------------------------------------===//
2599 // Iteration Count Computation Code
2602 /// getBackedgeTakenCount - If the specified loop has a predictable
2603 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2604 /// object. The backedge-taken count is the number of times the loop header
2605 /// will be branched to from within the loop. This is one less than the
2606 /// trip count of the loop, since it doesn't count the first iteration,
2607 /// when the header is branched to from outside the loop.
2609 /// Note that it is not valid to call this method on a loop without a
2610 /// loop-invariant backedge-taken count (see
2611 /// hasLoopInvariantBackedgeTakenCount).
2613 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2614 return getBackedgeTakenInfo(L).Exact;
2617 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2618 /// return the least SCEV value that is known never to be less than the
2619 /// actual backedge taken count.
2620 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2621 return getBackedgeTakenInfo(L).Max;
2624 const ScalarEvolution::BackedgeTakenInfo &
2625 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2626 // Initially insert a CouldNotCompute for this loop. If the insertion
2627 // succeeds, procede to actually compute a backedge-taken count and
2628 // update the value. The temporary CouldNotCompute value tells SCEV
2629 // code elsewhere that it shouldn't attempt to request a new
2630 // backedge-taken count, which could result in infinite recursion.
2631 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2632 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2634 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2635 if (ItCount.Exact != CouldNotCompute) {
2636 assert(ItCount.Exact->isLoopInvariant(L) &&
2637 ItCount.Max->isLoopInvariant(L) &&
2638 "Computed trip count isn't loop invariant for loop!");
2639 ++NumTripCountsComputed;
2641 // Update the value in the map.
2642 Pair.first->second = ItCount;
2643 } else if (isa<PHINode>(L->getHeader()->begin())) {
2644 // Only count loops that have phi nodes as not being computable.
2645 ++NumTripCountsNotComputed;
2648 // Now that we know more about the trip count for this loop, forget any
2649 // existing SCEV values for PHI nodes in this loop since they are only
2650 // conservative estimates made without the benefit
2651 // of trip count information.
2652 if (ItCount.hasAnyInfo())
2655 return Pair.first->second;
2658 /// forgetLoopBackedgeTakenCount - This method should be called by the
2659 /// client when it has changed a loop in a way that may effect
2660 /// ScalarEvolution's ability to compute a trip count, or if the loop
2662 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2663 BackedgeTakenCounts.erase(L);
2667 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2668 /// PHI nodes in the given loop. This is used when the trip count of
2669 /// the loop may have changed.
2670 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2671 BasicBlock *Header = L->getHeader();
2673 // Push all Loop-header PHIs onto the Worklist stack, except those
2674 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2675 // a PHI either means that it has an unrecognized structure, or it's
2676 // a PHI that's in the progress of being computed by createNodeForPHI.
2677 // In the former case, additional loop trip count information isn't
2678 // going to change anything. In the later case, createNodeForPHI will
2679 // perform the necessary updates on its own when it gets to that point.
2680 SmallVector<Instruction *, 16> Worklist;
2681 for (BasicBlock::iterator I = Header->begin();
2682 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2683 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2684 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2685 Worklist.push_back(PN);
2688 while (!Worklist.empty()) {
2689 Instruction *I = Worklist.pop_back_val();
2690 if (Scalars.erase(I))
2691 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2693 Worklist.push_back(cast<Instruction>(UI));
2697 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2698 /// of the specified loop will execute.
2699 ScalarEvolution::BackedgeTakenInfo
2700 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2701 // If the loop has a non-one exit block count, we can't analyze it.
2702 BasicBlock *ExitBlock = L->getExitBlock();
2704 return CouldNotCompute;
2706 // Okay, there is one exit block. Try to find the condition that causes the
2707 // loop to be exited.
2708 BasicBlock *ExitingBlock = L->getExitingBlock();
2710 return CouldNotCompute; // More than one block exiting!
2712 // Okay, we've computed the exiting block. See what condition causes us to
2715 // FIXME: we should be able to handle switch instructions (with a single exit)
2716 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2717 if (ExitBr == 0) return CouldNotCompute;
2718 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2720 // At this point, we know we have a conditional branch that determines whether
2721 // the loop is exited. However, we don't know if the branch is executed each
2722 // time through the loop. If not, then the execution count of the branch will
2723 // not be equal to the trip count of the loop.
2725 // Currently we check for this by checking to see if the Exit branch goes to
2726 // the loop header. If so, we know it will always execute the same number of
2727 // times as the loop. We also handle the case where the exit block *is* the
2728 // loop header. This is common for un-rotated loops. More extensive analysis
2729 // could be done to handle more cases here.
2730 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2731 ExitBr->getSuccessor(1) != L->getHeader() &&
2732 ExitBr->getParent() != L->getHeader())
2733 return CouldNotCompute;
2735 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2737 // If it's not an integer or pointer comparison then compute it the hard way.
2739 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2740 ExitBr->getSuccessor(0) == ExitBlock);
2742 // If the condition was exit on true, convert the condition to exit on false
2743 ICmpInst::Predicate Cond;
2744 if (ExitBr->getSuccessor(1) == ExitBlock)
2745 Cond = ExitCond->getPredicate();
2747 Cond = ExitCond->getInversePredicate();
2749 // Handle common loops like: for (X = "string"; *X; ++X)
2750 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2751 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2753 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2754 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2757 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2758 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2760 // Try to evaluate any dependencies out of the loop.
2761 LHS = getSCEVAtScope(LHS, L);
2762 RHS = getSCEVAtScope(RHS, L);
2764 // At this point, we would like to compute how many iterations of the
2765 // loop the predicate will return true for these inputs.
2766 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2767 // If there is a loop-invariant, force it into the RHS.
2768 std::swap(LHS, RHS);
2769 Cond = ICmpInst::getSwappedPredicate(Cond);
2772 // If we have a comparison of a chrec against a constant, try to use value
2773 // ranges to answer this query.
2774 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2775 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2776 if (AddRec->getLoop() == L) {
2777 // Form the constant range.
2778 ConstantRange CompRange(
2779 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
2781 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2782 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2786 case ICmpInst::ICMP_NE: { // while (X != Y)
2787 // Convert to: while (X-Y != 0)
2788 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2789 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2792 case ICmpInst::ICMP_EQ: {
2793 // Convert to: while (X-Y == 0) // while (X == Y)
2794 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2795 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2798 case ICmpInst::ICMP_SLT: {
2799 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2800 if (BTI.hasAnyInfo()) return BTI;
2803 case ICmpInst::ICMP_SGT: {
2804 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2805 getNotSCEV(RHS), L, true);
2806 if (BTI.hasAnyInfo()) return BTI;
2809 case ICmpInst::ICMP_ULT: {
2810 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2811 if (BTI.hasAnyInfo()) return BTI;
2814 case ICmpInst::ICMP_UGT: {
2815 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2816 getNotSCEV(RHS), L, false);
2817 if (BTI.hasAnyInfo()) return BTI;
2822 errs() << "ComputeBackedgeTakenCount ";
2823 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2824 errs() << "[unsigned] ";
2825 errs() << *LHS << " "
2826 << Instruction::getOpcodeName(Instruction::ICmp)
2827 << " " << *RHS << "\n";
2832 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2833 ExitBr->getSuccessor(0) == ExitBlock);
2836 static ConstantInt *
2837 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2838 ScalarEvolution &SE) {
2839 SCEVHandle InVal = SE.getConstant(C);
2840 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2841 assert(isa<SCEVConstant>(Val) &&
2842 "Evaluation of SCEV at constant didn't fold correctly?");
2843 return cast<SCEVConstant>(Val)->getValue();
2846 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2847 /// and a GEP expression (missing the pointer index) indexing into it, return
2848 /// the addressed element of the initializer or null if the index expression is
2851 GetAddressedElementFromGlobal(GlobalVariable *GV,
2852 const std::vector<ConstantInt*> &Indices) {
2853 Constant *Init = GV->getInitializer();
2854 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2855 uint64_t Idx = Indices[i]->getZExtValue();
2856 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2857 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2858 Init = cast<Constant>(CS->getOperand(Idx));
2859 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2860 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2861 Init = cast<Constant>(CA->getOperand(Idx));
2862 } else if (isa<ConstantAggregateZero>(Init)) {
2863 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2864 assert(Idx < STy->getNumElements() && "Bad struct index!");
2865 Init = Constant::getNullValue(STy->getElementType(Idx));
2866 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2867 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2868 Init = Constant::getNullValue(ATy->getElementType());
2870 assert(0 && "Unknown constant aggregate type!");
2874 return 0; // Unknown initializer type
2880 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2881 /// 'icmp op load X, cst', try to see if we can compute the backedge
2882 /// execution count.
2883 SCEVHandle ScalarEvolution::
2884 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2886 ICmpInst::Predicate predicate) {
2887 if (LI->isVolatile()) return CouldNotCompute;
2889 // Check to see if the loaded pointer is a getelementptr of a global.
2890 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2891 if (!GEP) return CouldNotCompute;
2893 // Make sure that it is really a constant global we are gepping, with an
2894 // initializer, and make sure the first IDX is really 0.
2895 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2896 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2897 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2898 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2899 return CouldNotCompute;
2901 // Okay, we allow one non-constant index into the GEP instruction.
2903 std::vector<ConstantInt*> Indexes;
2904 unsigned VarIdxNum = 0;
2905 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2906 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2907 Indexes.push_back(CI);
2908 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2909 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
2910 VarIdx = GEP->getOperand(i);
2912 Indexes.push_back(0);
2915 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2916 // Check to see if X is a loop variant variable value now.
2917 SCEVHandle Idx = getSCEV(VarIdx);
2918 Idx = getSCEVAtScope(Idx, L);
2920 // We can only recognize very limited forms of loop index expressions, in
2921 // particular, only affine AddRec's like {C1,+,C2}.
2922 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2923 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2924 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2925 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2926 return CouldNotCompute;
2928 unsigned MaxSteps = MaxBruteForceIterations;
2929 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2930 ConstantInt *ItCst =
2931 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
2932 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2934 // Form the GEP offset.
2935 Indexes[VarIdxNum] = Val;
2937 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2938 if (Result == 0) break; // Cannot compute!
2940 // Evaluate the condition for this iteration.
2941 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2942 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2943 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2945 errs() << "\n***\n*** Computed loop count " << *ItCst
2946 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2949 ++NumArrayLenItCounts;
2950 return getConstant(ItCst); // Found terminating iteration!
2953 return CouldNotCompute;
2957 /// CanConstantFold - Return true if we can constant fold an instruction of the
2958 /// specified type, assuming that all operands were constants.
2959 static bool CanConstantFold(const Instruction *I) {
2960 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2961 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2964 if (const CallInst *CI = dyn_cast<CallInst>(I))
2965 if (const Function *F = CI->getCalledFunction())
2966 return canConstantFoldCallTo(F);
2970 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2971 /// in the loop that V is derived from. We allow arbitrary operations along the
2972 /// way, but the operands of an operation must either be constants or a value
2973 /// derived from a constant PHI. If this expression does not fit with these
2974 /// constraints, return null.
2975 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2976 // If this is not an instruction, or if this is an instruction outside of the
2977 // loop, it can't be derived from a loop PHI.
2978 Instruction *I = dyn_cast<Instruction>(V);
2979 if (I == 0 || !L->contains(I->getParent())) return 0;
2981 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2982 if (L->getHeader() == I->getParent())
2985 // We don't currently keep track of the control flow needed to evaluate
2986 // PHIs, so we cannot handle PHIs inside of loops.
2990 // If we won't be able to constant fold this expression even if the operands
2991 // are constants, return early.
2992 if (!CanConstantFold(I)) return 0;
2994 // Otherwise, we can evaluate this instruction if all of its operands are
2995 // constant or derived from a PHI node themselves.
2997 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2998 if (!(isa<Constant>(I->getOperand(Op)) ||
2999 isa<GlobalValue>(I->getOperand(Op)))) {
3000 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3001 if (P == 0) return 0; // Not evolving from PHI
3005 return 0; // Evolving from multiple different PHIs.
3008 // This is a expression evolving from a constant PHI!
3012 /// EvaluateExpression - Given an expression that passes the
3013 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3014 /// in the loop has the value PHIVal. If we can't fold this expression for some
3015 /// reason, return null.
3016 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3017 if (isa<PHINode>(V)) return PHIVal;
3018 if (Constant *C = dyn_cast<Constant>(V)) return C;
3019 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3020 Instruction *I = cast<Instruction>(V);
3022 std::vector<Constant*> Operands;
3023 Operands.resize(I->getNumOperands());
3025 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3026 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3027 if (Operands[i] == 0) return 0;
3030 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3031 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3032 &Operands[0], Operands.size());
3034 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3035 &Operands[0], Operands.size());
3038 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3039 /// in the header of its containing loop, we know the loop executes a
3040 /// constant number of times, and the PHI node is just a recurrence
3041 /// involving constants, fold it.
3042 Constant *ScalarEvolution::
3043 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
3044 std::map<PHINode*, Constant*>::iterator I =
3045 ConstantEvolutionLoopExitValue.find(PN);
3046 if (I != ConstantEvolutionLoopExitValue.end())
3049 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3050 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3052 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3054 // Since the loop is canonicalized, the PHI node must have two entries. One
3055 // entry must be a constant (coming in from outside of the loop), and the
3056 // second must be derived from the same PHI.
3057 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3058 Constant *StartCST =
3059 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3061 return RetVal = 0; // Must be a constant.
3063 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3064 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3066 return RetVal = 0; // Not derived from same PHI.
3068 // Execute the loop symbolically to determine the exit value.
3069 if (BEs.getActiveBits() >= 32)
3070 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3072 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3073 unsigned IterationNum = 0;
3074 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3075 if (IterationNum == NumIterations)
3076 return RetVal = PHIVal; // Got exit value!
3078 // Compute the value of the PHI node for the next iteration.
3079 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3080 if (NextPHI == PHIVal)
3081 return RetVal = NextPHI; // Stopped evolving!
3083 return 0; // Couldn't evaluate!
3088 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3089 /// constant number of times (the condition evolves only from constants),
3090 /// try to evaluate a few iterations of the loop until we get the exit
3091 /// condition gets a value of ExitWhen (true or false). If we cannot
3092 /// evaluate the trip count of the loop, return CouldNotCompute.
3093 SCEVHandle ScalarEvolution::
3094 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
3095 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3096 if (PN == 0) return CouldNotCompute;
3098 // Since the loop is canonicalized, the PHI node must have two entries. One
3099 // entry must be a constant (coming in from outside of the loop), and the
3100 // second must be derived from the same PHI.
3101 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3102 Constant *StartCST =
3103 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3104 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
3106 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3107 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3108 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
3110 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3111 // the loop symbolically to determine when the condition gets a value of
3113 unsigned IterationNum = 0;
3114 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3115 for (Constant *PHIVal = StartCST;
3116 IterationNum != MaxIterations; ++IterationNum) {
3117 ConstantInt *CondVal =
3118 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3120 // Couldn't symbolically evaluate.
3121 if (!CondVal) return CouldNotCompute;
3123 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3124 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3125 ++NumBruteForceTripCountsComputed;
3126 return getConstant(Type::Int32Ty, IterationNum);
3129 // Compute the value of the PHI node for the next iteration.
3130 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3131 if (NextPHI == 0 || NextPHI == PHIVal)
3132 return CouldNotCompute; // Couldn't evaluate or not making progress...
3136 // Too many iterations were needed to evaluate.
3137 return CouldNotCompute;
3140 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3141 /// at the specified scope in the program. The L value specifies a loop
3142 /// nest to evaluate the expression at, where null is the top-level or a
3143 /// specified loop is immediately inside of the loop.
3145 /// This method can be used to compute the exit value for a variable defined
3146 /// in a loop by querying what the value will hold in the parent loop.
3148 /// In the case that a relevant loop exit value cannot be computed, the
3149 /// original value V is returned.
3150 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3151 // FIXME: this should be turned into a virtual method on SCEV!
3153 if (isa<SCEVConstant>(V)) return V;
3155 // If this instruction is evolved from a constant-evolving PHI, compute the
3156 // exit value from the loop without using SCEVs.
3157 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3158 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3159 const Loop *LI = (*this->LI)[I->getParent()];
3160 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3161 if (PHINode *PN = dyn_cast<PHINode>(I))
3162 if (PN->getParent() == LI->getHeader()) {
3163 // Okay, there is no closed form solution for the PHI node. Check
3164 // to see if the loop that contains it has a known backedge-taken
3165 // count. If so, we may be able to force computation of the exit
3167 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
3168 if (const SCEVConstant *BTCC =
3169 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3170 // Okay, we know how many times the containing loop executes. If
3171 // this is a constant evolving PHI node, get the final value at
3172 // the specified iteration number.
3173 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3174 BTCC->getValue()->getValue(),
3176 if (RV) return getUnknown(RV);
3180 // Okay, this is an expression that we cannot symbolically evaluate
3181 // into a SCEV. Check to see if it's possible to symbolically evaluate
3182 // the arguments into constants, and if so, try to constant propagate the
3183 // result. This is particularly useful for computing loop exit values.
3184 if (CanConstantFold(I)) {
3185 // Check to see if we've folded this instruction at this loop before.
3186 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3187 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3188 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3190 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3192 std::vector<Constant*> Operands;
3193 Operands.reserve(I->getNumOperands());
3194 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3195 Value *Op = I->getOperand(i);
3196 if (Constant *C = dyn_cast<Constant>(Op)) {
3197 Operands.push_back(C);
3199 // If any of the operands is non-constant and if they are
3200 // non-integer and non-pointer, don't even try to analyze them
3201 // with scev techniques.
3202 if (!isSCEVable(Op->getType()))
3205 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
3206 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3207 Constant *C = SC->getValue();
3208 if (C->getType() != Op->getType())
3209 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3213 Operands.push_back(C);
3214 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3215 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3216 if (C->getType() != Op->getType())
3218 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3222 Operands.push_back(C);
3232 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3233 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3234 &Operands[0], Operands.size());
3236 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3237 &Operands[0], Operands.size());
3238 Pair.first->second = C;
3239 return getUnknown(C);
3243 // This is some other type of SCEVUnknown, just return it.
3247 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3248 // Avoid performing the look-up in the common case where the specified
3249 // expression has no loop-variant portions.
3250 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3251 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3252 if (OpAtScope != Comm->getOperand(i)) {
3253 // Okay, at least one of these operands is loop variant but might be
3254 // foldable. Build a new instance of the folded commutative expression.
3255 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
3256 NewOps.push_back(OpAtScope);
3258 for (++i; i != e; ++i) {
3259 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3260 NewOps.push_back(OpAtScope);
3262 if (isa<SCEVAddExpr>(Comm))
3263 return getAddExpr(NewOps);
3264 if (isa<SCEVMulExpr>(Comm))
3265 return getMulExpr(NewOps);
3266 if (isa<SCEVSMaxExpr>(Comm))
3267 return getSMaxExpr(NewOps);
3268 if (isa<SCEVUMaxExpr>(Comm))
3269 return getUMaxExpr(NewOps);
3270 assert(0 && "Unknown commutative SCEV type!");
3273 // If we got here, all operands are loop invariant.
3277 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3278 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
3279 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
3280 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3281 return Div; // must be loop invariant
3282 return getUDivExpr(LHS, RHS);
3285 // If this is a loop recurrence for a loop that does not contain L, then we
3286 // are dealing with the final value computed by the loop.
3287 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3288 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3289 // To evaluate this recurrence, we need to know how many times the AddRec
3290 // loop iterates. Compute this now.
3291 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3292 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
3294 // Then, evaluate the AddRec.
3295 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3300 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3301 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3302 if (Op == Cast->getOperand())
3303 return Cast; // must be loop invariant
3304 return getZeroExtendExpr(Op, Cast->getType());
3307 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3308 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3309 if (Op == Cast->getOperand())
3310 return Cast; // must be loop invariant
3311 return getSignExtendExpr(Op, Cast->getType());
3314 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3315 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3316 if (Op == Cast->getOperand())
3317 return Cast; // must be loop invariant
3318 return getTruncateExpr(Op, Cast->getType());
3321 assert(0 && "Unknown SCEV type!");
3325 /// getSCEVAtScope - This is a convenience function which does
3326 /// getSCEVAtScope(getSCEV(V), L).
3327 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3328 return getSCEVAtScope(getSCEV(V), L);
3331 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3332 /// following equation:
3334 /// A * X = B (mod N)
3336 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3337 /// A and B isn't important.
3339 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3340 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3341 ScalarEvolution &SE) {
3342 uint32_t BW = A.getBitWidth();
3343 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3344 assert(A != 0 && "A must be non-zero.");
3348 // The gcd of A and N may have only one prime factor: 2. The number of
3349 // trailing zeros in A is its multiplicity
3350 uint32_t Mult2 = A.countTrailingZeros();
3353 // 2. Check if B is divisible by D.
3355 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3356 // is not less than multiplicity of this prime factor for D.
3357 if (B.countTrailingZeros() < Mult2)
3358 return SE.getCouldNotCompute();
3360 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3363 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3364 // bit width during computations.
3365 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3366 APInt Mod(BW + 1, 0);
3367 Mod.set(BW - Mult2); // Mod = N / D
3368 APInt I = AD.multiplicativeInverse(Mod);
3370 // 4. Compute the minimum unsigned root of the equation:
3371 // I * (B / D) mod (N / D)
3372 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3374 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3376 return SE.getConstant(Result.trunc(BW));
3379 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3380 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3381 /// might be the same) or two SCEVCouldNotCompute objects.
3383 static std::pair<SCEVHandle,SCEVHandle>
3384 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3385 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3386 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3387 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3388 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3390 // We currently can only solve this if the coefficients are constants.
3391 if (!LC || !MC || !NC) {
3392 const SCEV *CNC = SE.getCouldNotCompute();
3393 return std::make_pair(CNC, CNC);
3396 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3397 const APInt &L = LC->getValue()->getValue();
3398 const APInt &M = MC->getValue()->getValue();
3399 const APInt &N = NC->getValue()->getValue();
3400 APInt Two(BitWidth, 2);
3401 APInt Four(BitWidth, 4);
3404 using namespace APIntOps;
3406 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3407 // The B coefficient is M-N/2
3411 // The A coefficient is N/2
3412 APInt A(N.sdiv(Two));
3414 // Compute the B^2-4ac term.
3417 SqrtTerm -= Four * (A * C);
3419 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3420 // integer value or else APInt::sqrt() will assert.
3421 APInt SqrtVal(SqrtTerm.sqrt());
3423 // Compute the two solutions for the quadratic formula.
3424 // The divisions must be performed as signed divisions.
3426 APInt TwoA( A << 1 );
3427 if (TwoA.isMinValue()) {
3428 const SCEV *CNC = SE.getCouldNotCompute();
3429 return std::make_pair(CNC, CNC);
3432 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3433 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3435 return std::make_pair(SE.getConstant(Solution1),
3436 SE.getConstant(Solution2));
3437 } // end APIntOps namespace
3440 /// HowFarToZero - Return the number of times a backedge comparing the specified
3441 /// value to zero will execute. If not computable, return CouldNotCompute.
3442 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3443 // If the value is a constant
3444 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3445 // If the value is already zero, the branch will execute zero times.
3446 if (C->getValue()->isZero()) return C;
3447 return CouldNotCompute; // Otherwise it will loop infinitely.
3450 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3451 if (!AddRec || AddRec->getLoop() != L)
3452 return CouldNotCompute;
3454 if (AddRec->isAffine()) {
3455 // If this is an affine expression, the execution count of this branch is
3456 // the minimum unsigned root of the following equation:
3458 // Start + Step*N = 0 (mod 2^BW)
3462 // Step*N = -Start (mod 2^BW)
3464 // where BW is the common bit width of Start and Step.
3466 // Get the initial value for the loop.
3467 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3468 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
3470 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3471 // For now we handle only constant steps.
3473 // First, handle unitary steps.
3474 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3475 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3476 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3477 return Start; // N = Start (as unsigned)
3479 // Then, try to solve the above equation provided that Start is constant.
3480 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3481 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3482 -StartC->getValue()->getValue(),
3485 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3486 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3487 // the quadratic equation to solve it.
3488 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3490 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3491 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3494 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3495 << " sol#2: " << *R2 << "\n";
3497 // Pick the smallest positive root value.
3498 if (ConstantInt *CB =
3499 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3500 R1->getValue(), R2->getValue()))) {
3501 if (CB->getZExtValue() == false)
3502 std::swap(R1, R2); // R1 is the minimum root now.
3504 // We can only use this value if the chrec ends up with an exact zero
3505 // value at this index. When solving for "X*X != 5", for example, we
3506 // should not accept a root of 2.
3507 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3509 return R1; // We found a quadratic root!
3514 return CouldNotCompute;
3517 /// HowFarToNonZero - Return the number of times a backedge checking the
3518 /// specified value for nonzero will execute. If not computable, return
3520 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3521 // Loops that look like: while (X == 0) are very strange indeed. We don't
3522 // handle them yet except for the trivial case. This could be expanded in the
3523 // future as needed.
3525 // If the value is a constant, check to see if it is known to be non-zero
3526 // already. If so, the backedge will execute zero times.
3527 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3528 if (!C->getValue()->isNullValue())
3529 return getIntegerSCEV(0, C->getType());
3530 return CouldNotCompute; // Otherwise it will loop infinitely.
3533 // We could implement others, but I really doubt anyone writes loops like
3534 // this, and if they did, they would already be constant folded.
3535 return CouldNotCompute;
3538 /// getLoopPredecessor - If the given loop's header has exactly one unique
3539 /// predecessor outside the loop, return it. Otherwise return null.
3541 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3542 BasicBlock *Header = L->getHeader();
3543 BasicBlock *Pred = 0;
3544 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3546 if (!L->contains(*PI)) {
3547 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3553 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3554 /// (which may not be an immediate predecessor) which has exactly one
3555 /// successor from which BB is reachable, or null if no such block is
3559 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3560 // If the block has a unique predecessor, then there is no path from the
3561 // predecessor to the block that does not go through the direct edge
3562 // from the predecessor to the block.
3563 if (BasicBlock *Pred = BB->getSinglePredecessor())
3566 // A loop's header is defined to be a block that dominates the loop.
3567 // If the header has a unique predecessor outside the loop, it must be
3568 // a block that has exactly one successor that can reach the loop.
3569 if (Loop *L = LI->getLoopFor(BB))
3570 return getLoopPredecessor(L);
3575 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3576 /// a conditional between LHS and RHS. This is used to help avoid max
3577 /// expressions in loop trip counts.
3578 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3579 ICmpInst::Predicate Pred,
3580 const SCEV *LHS, const SCEV *RHS) {
3581 // Interpret a null as meaning no loop, where there is obviously no guard
3582 // (interprocedural conditions notwithstanding).
3583 if (!L) return false;
3585 BasicBlock *Predecessor = getLoopPredecessor(L);
3586 BasicBlock *PredecessorDest = L->getHeader();
3588 // Starting at the loop predecessor, climb up the predecessor chain, as long
3589 // as there are predecessors that can be found that have unique successors
3590 // leading to the original header.
3592 PredecessorDest = Predecessor,
3593 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
3595 BranchInst *LoopEntryPredicate =
3596 dyn_cast<BranchInst>(Predecessor->getTerminator());
3597 if (!LoopEntryPredicate ||
3598 LoopEntryPredicate->isUnconditional())
3601 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3604 // Now that we found a conditional branch that dominates the loop, check to
3605 // see if it is the comparison we are looking for.
3606 Value *PreCondLHS = ICI->getOperand(0);
3607 Value *PreCondRHS = ICI->getOperand(1);
3608 ICmpInst::Predicate Cond;
3609 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
3610 Cond = ICI->getPredicate();
3612 Cond = ICI->getInversePredicate();
3615 ; // An exact match.
3616 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3617 ; // The actual condition is beyond sufficient.
3619 // Check a few special cases.
3621 case ICmpInst::ICMP_UGT:
3622 if (Pred == ICmpInst::ICMP_ULT) {
3623 std::swap(PreCondLHS, PreCondRHS);
3624 Cond = ICmpInst::ICMP_ULT;
3628 case ICmpInst::ICMP_SGT:
3629 if (Pred == ICmpInst::ICMP_SLT) {
3630 std::swap(PreCondLHS, PreCondRHS);
3631 Cond = ICmpInst::ICMP_SLT;
3635 case ICmpInst::ICMP_NE:
3636 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3637 // so check for this case by checking if the NE is comparing against
3638 // a minimum or maximum constant.
3639 if (!ICmpInst::isTrueWhenEqual(Pred))
3640 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3641 const APInt &A = CI->getValue();
3643 case ICmpInst::ICMP_SLT:
3644 if (A.isMaxSignedValue()) break;
3646 case ICmpInst::ICMP_SGT:
3647 if (A.isMinSignedValue()) break;
3649 case ICmpInst::ICMP_ULT:
3650 if (A.isMaxValue()) break;
3652 case ICmpInst::ICMP_UGT:
3653 if (A.isMinValue()) break;
3658 Cond = ICmpInst::ICMP_NE;
3659 // NE is symmetric but the original comparison may not be. Swap
3660 // the operands if necessary so that they match below.
3661 if (isa<SCEVConstant>(LHS))
3662 std::swap(PreCondLHS, PreCondRHS);
3667 // We weren't able to reconcile the condition.
3671 if (!PreCondLHS->getType()->isInteger()) continue;
3673 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3674 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3675 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3676 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3677 RHS == getNotSCEV(PreCondLHSSCEV)))
3684 /// HowManyLessThans - Return the number of times a backedge containing the
3685 /// specified less-than comparison will execute. If not computable, return
3686 /// CouldNotCompute.
3687 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
3688 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3689 const Loop *L, bool isSigned) {
3690 // Only handle: "ADDREC < LoopInvariant".
3691 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
3693 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3694 if (!AddRec || AddRec->getLoop() != L)
3695 return CouldNotCompute;
3697 if (AddRec->isAffine()) {
3698 // FORNOW: We only support unit strides.
3699 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3700 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3701 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3703 // TODO: handle non-constant strides.
3704 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3705 if (!CStep || CStep->isZero())
3706 return CouldNotCompute;
3707 if (CStep->isOne()) {
3708 // With unit stride, the iteration never steps past the limit value.
3709 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3710 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3711 // Test whether a positive iteration iteration can step past the limit
3712 // value and past the maximum value for its type in a single step.
3714 APInt Max = APInt::getSignedMaxValue(BitWidth);
3715 if ((Max - CStep->getValue()->getValue())
3716 .slt(CLimit->getValue()->getValue()))
3717 return CouldNotCompute;
3719 APInt Max = APInt::getMaxValue(BitWidth);
3720 if ((Max - CStep->getValue()->getValue())
3721 .ult(CLimit->getValue()->getValue()))
3722 return CouldNotCompute;
3725 // TODO: handle non-constant limit values below.
3726 return CouldNotCompute;
3728 // TODO: handle negative strides below.
3729 return CouldNotCompute;
3731 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3732 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3733 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
3734 // treat m-n as signed nor unsigned due to overflow possibility.
3736 // First, we get the value of the LHS in the first iteration: n
3737 SCEVHandle Start = AddRec->getOperand(0);
3739 // Determine the minimum constant start value.
3740 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3741 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3742 APInt::getMinValue(BitWidth));
3744 // If we know that the condition is true in order to enter the loop,
3745 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3746 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3747 // the division must round up.
3748 SCEVHandle End = RHS;
3749 if (!isLoopGuardedByCond(L,
3750 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3751 getMinusSCEV(Start, Step), RHS))
3752 End = isSigned ? getSMaxExpr(RHS, Start)
3753 : getUMaxExpr(RHS, Start);
3755 // Determine the maximum constant end value.
3756 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3757 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3758 APInt::getMaxValue(BitWidth));
3760 // Finally, we subtract these two values and divide, rounding up, to get
3761 // the number of times the backedge is executed.
3762 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3763 getAddExpr(Step, NegOne)),
3766 // The maximum backedge count is similar, except using the minimum start
3767 // value and the maximum end value.
3768 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3770 getAddExpr(Step, NegOne)),
3773 return BackedgeTakenInfo(BECount, MaxBECount);
3776 return CouldNotCompute;
3779 /// getNumIterationsInRange - Return the number of iterations of this loop that
3780 /// produce values in the specified constant range. Another way of looking at
3781 /// this is that it returns the first iteration number where the value is not in
3782 /// the condition, thus computing the exit count. If the iteration count can't
3783 /// be computed, an instance of SCEVCouldNotCompute is returned.
3784 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3785 ScalarEvolution &SE) const {
3786 if (Range.isFullSet()) // Infinite loop.
3787 return SE.getCouldNotCompute();
3789 // If the start is a non-zero constant, shift the range to simplify things.
3790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3791 if (!SC->getValue()->isZero()) {
3792 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
3793 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3794 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3795 if (const SCEVAddRecExpr *ShiftedAddRec =
3796 dyn_cast<SCEVAddRecExpr>(Shifted))
3797 return ShiftedAddRec->getNumIterationsInRange(
3798 Range.subtract(SC->getValue()->getValue()), SE);
3799 // This is strange and shouldn't happen.
3800 return SE.getCouldNotCompute();
3803 // The only time we can solve this is when we have all constant indices.
3804 // Otherwise, we cannot determine the overflow conditions.
3805 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3806 if (!isa<SCEVConstant>(getOperand(i)))
3807 return SE.getCouldNotCompute();
3810 // Okay at this point we know that all elements of the chrec are constants and
3811 // that the start element is zero.
3813 // First check to see if the range contains zero. If not, the first
3815 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3816 if (!Range.contains(APInt(BitWidth, 0)))
3817 return SE.getIntegerSCEV(0, getType());
3820 // If this is an affine expression then we have this situation:
3821 // Solve {0,+,A} in Range === Ax in Range
3823 // We know that zero is in the range. If A is positive then we know that
3824 // the upper value of the range must be the first possible exit value.
3825 // If A is negative then the lower of the range is the last possible loop
3826 // value. Also note that we already checked for a full range.
3827 APInt One(BitWidth,1);
3828 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3829 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3831 // The exit value should be (End+A)/A.
3832 APInt ExitVal = (End + A).udiv(A);
3833 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3835 // Evaluate at the exit value. If we really did fall out of the valid
3836 // range, then we computed our trip count, otherwise wrap around or other
3837 // things must have happened.
3838 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3839 if (Range.contains(Val->getValue()))
3840 return SE.getCouldNotCompute(); // Something strange happened
3842 // Ensure that the previous value is in the range. This is a sanity check.
3843 assert(Range.contains(
3844 EvaluateConstantChrecAtConstant(this,
3845 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3846 "Linear scev computation is off in a bad way!");
3847 return SE.getConstant(ExitValue);
3848 } else if (isQuadratic()) {
3849 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3850 // quadratic equation to solve it. To do this, we must frame our problem in
3851 // terms of figuring out when zero is crossed, instead of when
3852 // Range.getUpper() is crossed.
3853 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
3854 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3855 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3857 // Next, solve the constructed addrec
3858 std::pair<SCEVHandle,SCEVHandle> Roots =
3859 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3860 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3861 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3863 // Pick the smallest positive root value.
3864 if (ConstantInt *CB =
3865 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3866 R1->getValue(), R2->getValue()))) {
3867 if (CB->getZExtValue() == false)
3868 std::swap(R1, R2); // R1 is the minimum root now.
3870 // Make sure the root is not off by one. The returned iteration should
3871 // not be in the range, but the previous one should be. When solving
3872 // for "X*X < 5", for example, we should not return a root of 2.
3873 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3876 if (Range.contains(R1Val->getValue())) {
3877 // The next iteration must be out of the range...
3878 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3880 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3881 if (!Range.contains(R1Val->getValue()))
3882 return SE.getConstant(NextVal);
3883 return SE.getCouldNotCompute(); // Something strange happened
3886 // If R1 was not in the range, then it is a good return value. Make
3887 // sure that R1-1 WAS in the range though, just in case.
3888 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3889 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3890 if (Range.contains(R1Val->getValue()))
3892 return SE.getCouldNotCompute(); // Something strange happened
3897 return SE.getCouldNotCompute();
3902 //===----------------------------------------------------------------------===//
3903 // SCEVCallbackVH Class Implementation
3904 //===----------------------------------------------------------------------===//
3906 void ScalarEvolution::SCEVCallbackVH::deleted() {
3907 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3908 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3909 SE->ConstantEvolutionLoopExitValue.erase(PN);
3910 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3911 SE->ValuesAtScopes.erase(I);
3912 SE->Scalars.erase(getValPtr());
3913 // this now dangles!
3916 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
3917 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3919 // Forget all the expressions associated with users of the old value,
3920 // so that future queries will recompute the expressions using the new
3922 SmallVector<User *, 16> Worklist;
3923 Value *Old = getValPtr();
3924 bool DeleteOld = false;
3925 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3927 Worklist.push_back(*UI);
3928 while (!Worklist.empty()) {
3929 User *U = Worklist.pop_back_val();
3930 // Deleting the Old value will cause this to dangle. Postpone
3931 // that until everything else is done.
3936 if (PHINode *PN = dyn_cast<PHINode>(U))
3937 SE->ConstantEvolutionLoopExitValue.erase(PN);
3938 if (Instruction *I = dyn_cast<Instruction>(U))
3939 SE->ValuesAtScopes.erase(I);
3940 if (SE->Scalars.erase(U))
3941 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3943 Worklist.push_back(*UI);
3946 if (PHINode *PN = dyn_cast<PHINode>(Old))
3947 SE->ConstantEvolutionLoopExitValue.erase(PN);
3948 if (Instruction *I = dyn_cast<Instruction>(Old))
3949 SE->ValuesAtScopes.erase(I);
3950 SE->Scalars.erase(Old);
3951 // this now dangles!
3956 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3957 : CallbackVH(V), SE(se) {}
3959 //===----------------------------------------------------------------------===//
3960 // ScalarEvolution Class Implementation
3961 //===----------------------------------------------------------------------===//
3963 ScalarEvolution::ScalarEvolution()
3964 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
3967 bool ScalarEvolution::runOnFunction(Function &F) {
3969 LI = &getAnalysis<LoopInfo>();
3970 TD = getAnalysisIfAvailable<TargetData>();
3974 void ScalarEvolution::releaseMemory() {
3976 BackedgeTakenCounts.clear();
3977 ConstantEvolutionLoopExitValue.clear();
3978 ValuesAtScopes.clear();
3981 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3982 AU.setPreservesAll();
3983 AU.addRequiredTransitive<LoopInfo>();
3986 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3987 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3990 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3992 // Print all inner loops first
3993 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3994 PrintLoopInfo(OS, SE, *I);
3996 OS << "Loop " << L->getHeader()->getName() << ": ";
3998 SmallVector<BasicBlock*, 8> ExitBlocks;
3999 L->getExitBlocks(ExitBlocks);
4000 if (ExitBlocks.size() != 1)
4001 OS << "<multiple exits> ";
4003 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4004 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4006 OS << "Unpredictable backedge-taken count. ";
4012 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4013 // ScalarEvolution's implementaiton of the print method is to print
4014 // out SCEV values of all instructions that are interesting. Doing
4015 // this potentially causes it to create new SCEV objects though,
4016 // which technically conflicts with the const qualifier. This isn't
4017 // observable from outside the class though (the hasSCEV function
4018 // notwithstanding), so casting away the const isn't dangerous.
4019 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4021 OS << "Classifying expressions for: " << F->getName() << "\n";
4022 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4023 if (isSCEVable(I->getType())) {
4026 SCEVHandle SV = SE.getSCEV(&*I);
4029 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
4030 OS << "\t\t" "Exits: ";
4031 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
4032 if (!ExitValue->isLoopInvariant(L)) {
4033 OS << "<<Unknown>>";
4042 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4043 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4044 PrintLoopInfo(OS, &SE, *I);
4047 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4048 raw_os_ostream OS(o);