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. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression. These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
38 //===----------------------------------------------------------------------===//
40 // There are several good references for the techniques used in this analysis.
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 // On computational properties of chains of recurrences
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
59 //===----------------------------------------------------------------------===//
61 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/Instructions.h"
67 #include "llvm/LLVMContext.h"
68 #include "llvm/Operator.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/Dominators.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ValueTracking.h"
73 #include "llvm/Assembly/Writer.h"
74 #include "llvm/Target/TargetData.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/GetElementPtrTypeIterator.h"
80 #include "llvm/Support/InstIterator.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/ADT/Statistic.h"
84 #include "llvm/ADT/STLExtras.h"
85 #include "llvm/ADT/SmallPtrSet.h"
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
98 static cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant "
105 static RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
107 char ScalarEvolution::ID = 0;
109 //===----------------------------------------------------------------------===//
110 // SCEV class definitions
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
114 // Implementation of the SCEV class.
119 void SCEV::dump() const {
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 bool SCEV::isAllOnesValue() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isAllOnesValue();
142 SCEVCouldNotCompute::SCEVCouldNotCompute() :
143 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
145 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
146 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
150 const Type *SCEVCouldNotCompute::getType() const {
151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
155 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
160 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
165 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
166 OS << "***COULDNOTCOMPUTE***";
169 bool SCEVCouldNotCompute::classof(const SCEV *S) {
170 return S->getSCEVType() == scCouldNotCompute;
173 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
175 ID.AddInteger(scConstant);
178 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
179 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
180 new (S) SCEVConstant(ID, V);
181 UniqueSCEVs.InsertNode(S, IP);
185 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(getContext(), Val));
190 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
192 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(const FoldingSetNodeID &ID,
202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
205 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
209 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
210 const SCEV *op, const Type *ty)
211 : SCEVCastExpr(ID, scTruncate, op, ty) {
212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
214 "Cannot truncate non-integer value!");
217 void SCEVTruncateExpr::print(raw_ostream &OS) const {
218 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
221 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
222 const SCEV *op, const Type *ty)
223 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
224 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
225 (Ty->isInteger() || isa<PointerType>(Ty)) &&
226 "Cannot zero extend non-integer value!");
229 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
230 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
233 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
234 const SCEV *op, const Type *ty)
235 : SCEVCastExpr(ID, scSignExtend, op, ty) {
236 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
237 (Ty->isInteger() || isa<PointerType>(Ty)) &&
238 "Cannot sign extend non-integer value!");
241 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
242 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
245 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
246 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
247 const char *OpStr = getOperationStr();
248 OS << "(" << *Operands[0];
249 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
250 OS << OpStr << *Operands[i];
254 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
255 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
256 if (!getOperand(i)->dominates(BB, DT))
262 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
263 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
266 void SCEVUDivExpr::print(raw_ostream &OS) const {
267 OS << "(" << *LHS << " /u " << *RHS << ")";
270 const Type *SCEVUDivExpr::getType() const {
271 // In most cases the types of LHS and RHS will be the same, but in some
272 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
273 // depend on the type for correctness, but handling types carefully can
274 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
275 // a pointer type than the RHS, so use the RHS' type here.
276 return RHS->getType();
279 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
280 // Add recurrences are never invariant in the function-body (null loop).
284 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
285 if (QueryLoop->contains(L->getHeader()))
288 // This recurrence is variant w.r.t. QueryLoop if any of its operands
290 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
291 if (!getOperand(i)->isLoopInvariant(QueryLoop))
294 // Otherwise it's loop-invariant.
298 void SCEVAddRecExpr::print(raw_ostream &OS) const {
299 OS << "{" << *Operands[0];
300 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
301 OS << ",+," << *Operands[i];
302 OS << "}<" << L->getHeader()->getName() + ">";
305 void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
306 // LLVM struct fields don't have names, so just print the field number.
307 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
310 void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
311 OS << "sizeof(" << *AllocTy << ")";
314 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
315 // All non-instruction values are loop invariant. All instructions are loop
316 // invariant if they are not contained in the specified loop.
317 // Instructions are never considered invariant in the function body
318 // (null loop) because they are defined within the "loop".
319 if (Instruction *I = dyn_cast<Instruction>(V))
320 return L && !L->contains(I->getParent());
324 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
325 if (Instruction *I = dyn_cast<Instruction>(getValue()))
326 return DT->dominates(I->getParent(), BB);
330 const Type *SCEVUnknown::getType() const {
334 void SCEVUnknown::print(raw_ostream &OS) const {
335 WriteAsOperand(OS, V, false);
338 //===----------------------------------------------------------------------===//
340 //===----------------------------------------------------------------------===//
342 static bool CompareTypes(const Type *A, const Type *B) {
343 if (A->getTypeID() != B->getTypeID())
344 return A->getTypeID() < B->getTypeID();
345 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
346 const IntegerType *BI = cast<IntegerType>(B);
347 return AI->getBitWidth() < BI->getBitWidth();
349 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
350 const PointerType *BI = cast<PointerType>(B);
351 return CompareTypes(AI->getElementType(), BI->getElementType());
353 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
354 const ArrayType *BI = cast<ArrayType>(B);
355 if (AI->getNumElements() != BI->getNumElements())
356 return AI->getNumElements() < BI->getNumElements();
357 return CompareTypes(AI->getElementType(), BI->getElementType());
359 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
360 const VectorType *BI = cast<VectorType>(B);
361 if (AI->getNumElements() != BI->getNumElements())
362 return AI->getNumElements() < BI->getNumElements();
363 return CompareTypes(AI->getElementType(), BI->getElementType());
365 if (const StructType *AI = dyn_cast<StructType>(A)) {
366 const StructType *BI = cast<StructType>(B);
367 if (AI->getNumElements() != BI->getNumElements())
368 return AI->getNumElements() < BI->getNumElements();
369 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
370 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
371 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
372 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
378 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
379 /// than the complexity of the RHS. This comparator is used to canonicalize
381 class VISIBILITY_HIDDEN SCEVComplexityCompare {
384 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
386 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
387 // Primarily, sort the SCEVs by their getSCEVType().
388 if (LHS->getSCEVType() != RHS->getSCEVType())
389 return LHS->getSCEVType() < RHS->getSCEVType();
391 // Aside from the getSCEVType() ordering, the particular ordering
392 // isn't very important except that it's beneficial to be consistent,
393 // so that (a + b) and (b + a) don't end up as different expressions.
395 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
396 // not as complete as it could be.
397 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
398 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
400 // Order pointer values after integer values. This helps SCEVExpander
402 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
404 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
407 // Compare getValueID values.
408 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
409 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
411 // Sort arguments by their position.
412 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
413 const Argument *RA = cast<Argument>(RU->getValue());
414 return LA->getArgNo() < RA->getArgNo();
417 // For instructions, compare their loop depth, and their opcode.
418 // This is pretty loose.
419 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
420 Instruction *RV = cast<Instruction>(RU->getValue());
422 // Compare loop depths.
423 if (LI->getLoopDepth(LV->getParent()) !=
424 LI->getLoopDepth(RV->getParent()))
425 return LI->getLoopDepth(LV->getParent()) <
426 LI->getLoopDepth(RV->getParent());
429 if (LV->getOpcode() != RV->getOpcode())
430 return LV->getOpcode() < RV->getOpcode();
432 // Compare the number of operands.
433 if (LV->getNumOperands() != RV->getNumOperands())
434 return LV->getNumOperands() < RV->getNumOperands();
440 // Compare constant values.
441 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
442 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
443 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
444 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
445 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
448 // Compare addrec loop depths.
449 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
450 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
451 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
452 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
455 // Lexicographically compare n-ary expressions.
456 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
457 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
458 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
459 if (i >= RC->getNumOperands())
461 if (operator()(LC->getOperand(i), RC->getOperand(i)))
463 if (operator()(RC->getOperand(i), LC->getOperand(i)))
466 return LC->getNumOperands() < RC->getNumOperands();
469 // Lexicographically compare udiv expressions.
470 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
471 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
472 if (operator()(LC->getLHS(), RC->getLHS()))
474 if (operator()(RC->getLHS(), LC->getLHS()))
476 if (operator()(LC->getRHS(), RC->getRHS()))
478 if (operator()(RC->getRHS(), LC->getRHS()))
483 // Compare cast expressions by operand.
484 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
485 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
486 return operator()(LC->getOperand(), RC->getOperand());
489 // Compare offsetof expressions.
490 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
491 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
492 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
493 CompareTypes(RA->getStructType(), LA->getStructType()))
494 return CompareTypes(LA->getStructType(), RA->getStructType());
495 return LA->getFieldNo() < RA->getFieldNo();
498 // Compare sizeof expressions by the allocation type.
499 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
500 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
501 return CompareTypes(LA->getAllocType(), RA->getAllocType());
504 llvm_unreachable("Unknown SCEV kind!");
510 /// GroupByComplexity - Given a list of SCEV objects, order them by their
511 /// complexity, and group objects of the same complexity together by value.
512 /// When this routine is finished, we know that any duplicates in the vector are
513 /// consecutive and that complexity is monotonically increasing.
515 /// Note that we go take special precautions to ensure that we get determinstic
516 /// results from this routine. In other words, we don't want the results of
517 /// this to depend on where the addresses of various SCEV objects happened to
520 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
522 if (Ops.size() < 2) return; // Noop
523 if (Ops.size() == 2) {
524 // This is the common case, which also happens to be trivially simple.
526 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
527 std::swap(Ops[0], Ops[1]);
531 // Do the rough sort by complexity.
532 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
534 // Now that we are sorted by complexity, group elements of the same
535 // complexity. Note that this is, at worst, N^2, but the vector is likely to
536 // be extremely short in practice. Note that we take this approach because we
537 // do not want to depend on the addresses of the objects we are grouping.
538 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
539 const SCEV *S = Ops[i];
540 unsigned Complexity = S->getSCEVType();
542 // If there are any objects of the same complexity and same value as this
544 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
545 if (Ops[j] == S) { // Found a duplicate.
546 // Move it to immediately after i'th element.
547 std::swap(Ops[i+1], Ops[j]);
548 ++i; // no need to rescan it.
549 if (i == e-2) return; // Done!
557 //===----------------------------------------------------------------------===//
558 // Simple SCEV method implementations
559 //===----------------------------------------------------------------------===//
561 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
563 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
565 const Type* ResultTy) {
566 // Handle the simplest case efficiently.
568 return SE.getTruncateOrZeroExtend(It, ResultTy);
570 // We are using the following formula for BC(It, K):
572 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
574 // Suppose, W is the bitwidth of the return value. We must be prepared for
575 // overflow. Hence, we must assure that the result of our computation is
576 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
577 // safe in modular arithmetic.
579 // However, this code doesn't use exactly that formula; the formula it uses
580 // is something like the following, where T is the number of factors of 2 in
581 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
584 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
586 // This formula is trivially equivalent to the previous formula. However,
587 // this formula can be implemented much more efficiently. The trick is that
588 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
589 // arithmetic. To do exact division in modular arithmetic, all we have
590 // to do is multiply by the inverse. Therefore, this step can be done at
593 // The next issue is how to safely do the division by 2^T. The way this
594 // is done is by doing the multiplication step at a width of at least W + T
595 // bits. This way, the bottom W+T bits of the product are accurate. Then,
596 // when we perform the division by 2^T (which is equivalent to a right shift
597 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
598 // truncated out after the division by 2^T.
600 // In comparison to just directly using the first formula, this technique
601 // is much more efficient; using the first formula requires W * K bits,
602 // but this formula less than W + K bits. Also, the first formula requires
603 // a division step, whereas this formula only requires multiplies and shifts.
605 // It doesn't matter whether the subtraction step is done in the calculation
606 // width or the input iteration count's width; if the subtraction overflows,
607 // the result must be zero anyway. We prefer here to do it in the width of
608 // the induction variable because it helps a lot for certain cases; CodeGen
609 // isn't smart enough to ignore the overflow, which leads to much less
610 // efficient code if the width of the subtraction is wider than the native
613 // (It's possible to not widen at all by pulling out factors of 2 before
614 // the multiplication; for example, K=2 can be calculated as
615 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
616 // extra arithmetic, so it's not an obvious win, and it gets
617 // much more complicated for K > 3.)
619 // Protection from insane SCEVs; this bound is conservative,
620 // but it probably doesn't matter.
622 return SE.getCouldNotCompute();
624 unsigned W = SE.getTypeSizeInBits(ResultTy);
626 // Calculate K! / 2^T and T; we divide out the factors of two before
627 // multiplying for calculating K! / 2^T to avoid overflow.
628 // Other overflow doesn't matter because we only care about the bottom
629 // W bits of the result.
630 APInt OddFactorial(W, 1);
632 for (unsigned i = 3; i <= K; ++i) {
634 unsigned TwoFactors = Mult.countTrailingZeros();
636 Mult = Mult.lshr(TwoFactors);
637 OddFactorial *= Mult;
640 // We need at least W + T bits for the multiplication step
641 unsigned CalculationBits = W + T;
643 // Calcuate 2^T, at width T+W.
644 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
646 // Calculate the multiplicative inverse of K! / 2^T;
647 // this multiplication factor will perform the exact division by
649 APInt Mod = APInt::getSignedMinValue(W+1);
650 APInt MultiplyFactor = OddFactorial.zext(W+1);
651 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
652 MultiplyFactor = MultiplyFactor.trunc(W);
654 // Calculate the product, at width T+W
655 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
657 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
658 for (unsigned i = 1; i != K; ++i) {
659 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
660 Dividend = SE.getMulExpr(Dividend,
661 SE.getTruncateOrZeroExtend(S, CalculationTy));
665 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
667 // Truncate the result, and divide by K! / 2^T.
669 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
670 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
673 /// evaluateAtIteration - Return the value of this chain of recurrences at
674 /// the specified iteration number. We can evaluate this recurrence by
675 /// multiplying each element in the chain by the binomial coefficient
676 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
678 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
680 /// where BC(It, k) stands for binomial coefficient.
682 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
683 ScalarEvolution &SE) const {
684 const SCEV *Result = getStart();
685 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
686 // The computation is correct in the face of overflow provided that the
687 // multiplication is performed _after_ the evaluation of the binomial
689 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
690 if (isa<SCEVCouldNotCompute>(Coeff))
693 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
698 //===----------------------------------------------------------------------===//
699 // SCEV Expression folder implementations
700 //===----------------------------------------------------------------------===//
702 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
704 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
705 "This is not a truncating conversion!");
706 assert(isSCEVable(Ty) &&
707 "This is not a conversion to a SCEVable type!");
708 Ty = getEffectiveSCEVType(Ty);
711 ID.AddInteger(scTruncate);
715 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
717 // Fold if the operand is constant.
718 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
720 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
722 // trunc(trunc(x)) --> trunc(x)
723 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
724 return getTruncateExpr(ST->getOperand(), Ty);
726 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
727 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
728 return getTruncateOrSignExtend(SS->getOperand(), Ty);
730 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
731 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
732 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
734 // If the input value is a chrec scev, truncate the chrec's operands.
735 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
736 SmallVector<const SCEV *, 4> Operands;
737 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
738 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
739 return getAddRecExpr(Operands, AddRec->getLoop());
742 // The cast wasn't folded; create an explicit cast node.
743 // Recompute the insert position, as it may have been invalidated.
744 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
745 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
746 new (S) SCEVTruncateExpr(ID, Op, Ty);
747 UniqueSCEVs.InsertNode(S, IP);
751 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
753 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
754 "This is not an extending conversion!");
755 assert(isSCEVable(Ty) &&
756 "This is not a conversion to a SCEVable type!");
757 Ty = getEffectiveSCEVType(Ty);
759 // Fold if the operand is constant.
760 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
761 const Type *IntTy = getEffectiveSCEVType(Ty);
762 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
763 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
764 return getConstant(cast<ConstantInt>(C));
767 // zext(zext(x)) --> zext(x)
768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
769 return getZeroExtendExpr(SZ->getOperand(), Ty);
771 // Before doing any expensive analysis, check to see if we've already
772 // computed a SCEV for this Op and Ty.
774 ID.AddInteger(scZeroExtend);
778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
780 // If the input value is a chrec scev, and we can prove that the value
781 // did not overflow the old, smaller, value, we can zero extend all of the
782 // operands (often constants). This allows analysis of something like
783 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
784 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
785 if (AR->isAffine()) {
786 const SCEV *Start = AR->getStart();
787 const SCEV *Step = AR->getStepRecurrence(*this);
788 unsigned BitWidth = getTypeSizeInBits(AR->getType());
789 const Loop *L = AR->getLoop();
791 // If we have special knowledge that this addrec won't overflow,
792 // we don't need to do any further analysis.
793 if (AR->hasNoUnsignedWrap())
794 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
795 getZeroExtendExpr(Step, Ty),
798 // Check whether the backedge-taken count is SCEVCouldNotCompute.
799 // Note that this serves two purposes: It filters out loops that are
800 // simply not analyzable, and it covers the case where this code is
801 // being called from within backedge-taken count analysis, such that
802 // attempting to ask for the backedge-taken count would likely result
803 // in infinite recursion. In the later case, the analysis code will
804 // cope with a conservative value, and it will take care to purge
805 // that value once it has finished.
806 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
807 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
808 // Manually compute the final value for AR, checking for
811 // Check whether the backedge-taken count can be losslessly casted to
812 // the addrec's type. The count is always unsigned.
813 const SCEV *CastedMaxBECount =
814 getTruncateOrZeroExtend(MaxBECount, Start->getType());
815 const SCEV *RecastedMaxBECount =
816 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
817 if (MaxBECount == RecastedMaxBECount) {
818 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
819 // Check whether Start+Step*MaxBECount has no unsigned overflow.
821 getMulExpr(CastedMaxBECount,
822 getTruncateOrZeroExtend(Step, Start->getType()));
823 const SCEV *Add = getAddExpr(Start, ZMul);
824 const SCEV *OperandExtendedAdd =
825 getAddExpr(getZeroExtendExpr(Start, WideTy),
826 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
827 getZeroExtendExpr(Step, WideTy)));
828 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
829 // Return the expression with the addrec on the outside.
830 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
831 getZeroExtendExpr(Step, Ty),
834 // Similar to above, only this time treat the step value as signed.
835 // This covers loops that count down.
837 getMulExpr(CastedMaxBECount,
838 getTruncateOrSignExtend(Step, Start->getType()));
839 Add = getAddExpr(Start, SMul);
841 getAddExpr(getZeroExtendExpr(Start, WideTy),
842 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
843 getSignExtendExpr(Step, WideTy)));
844 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
845 // Return the expression with the addrec on the outside.
846 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
847 getSignExtendExpr(Step, Ty),
851 // If the backedge is guarded by a comparison with the pre-inc value
852 // the addrec is safe. Also, if the entry is guarded by a comparison
853 // with the start value and the backedge is guarded by a comparison
854 // with the post-inc value, the addrec is safe.
855 if (isKnownPositive(Step)) {
856 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
857 getUnsignedRange(Step).getUnsignedMax());
858 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
859 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
860 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
861 AR->getPostIncExpr(*this), N)))
862 // Return the expression with the addrec on the outside.
863 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
864 getZeroExtendExpr(Step, Ty),
866 } else if (isKnownNegative(Step)) {
867 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
868 getSignedRange(Step).getSignedMin());
869 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
870 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
871 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
872 AR->getPostIncExpr(*this), N)))
873 // Return the expression with the addrec on the outside.
874 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
875 getSignExtendExpr(Step, Ty),
881 // The cast wasn't folded; create an explicit cast node.
882 // Recompute the insert position, as it may have been invalidated.
883 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
884 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
885 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
886 UniqueSCEVs.InsertNode(S, IP);
890 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
892 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
893 "This is not an extending conversion!");
894 assert(isSCEVable(Ty) &&
895 "This is not a conversion to a SCEVable type!");
896 Ty = getEffectiveSCEVType(Ty);
898 // Fold if the operand is constant.
899 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
900 const Type *IntTy = getEffectiveSCEVType(Ty);
901 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
902 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
903 return getConstant(cast<ConstantInt>(C));
906 // sext(sext(x)) --> sext(x)
907 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
908 return getSignExtendExpr(SS->getOperand(), Ty);
910 // Before doing any expensive analysis, check to see if we've already
911 // computed a SCEV for this Op and Ty.
913 ID.AddInteger(scSignExtend);
917 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
919 // If the input value is a chrec scev, and we can prove that the value
920 // did not overflow the old, smaller, value, we can sign extend all of the
921 // operands (often constants). This allows analysis of something like
922 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
924 if (AR->isAffine()) {
925 const SCEV *Start = AR->getStart();
926 const SCEV *Step = AR->getStepRecurrence(*this);
927 unsigned BitWidth = getTypeSizeInBits(AR->getType());
928 const Loop *L = AR->getLoop();
930 // If we have special knowledge that this addrec won't overflow,
931 // we don't need to do any further analysis.
932 if (AR->hasNoSignedWrap())
933 return getAddRecExpr(getSignExtendExpr(Start, Ty),
934 getSignExtendExpr(Step, Ty),
937 // Check whether the backedge-taken count is SCEVCouldNotCompute.
938 // Note that this serves two purposes: It filters out loops that are
939 // simply not analyzable, and it covers the case where this code is
940 // being called from within backedge-taken count analysis, such that
941 // attempting to ask for the backedge-taken count would likely result
942 // in infinite recursion. In the later case, the analysis code will
943 // cope with a conservative value, and it will take care to purge
944 // that value once it has finished.
945 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
946 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
947 // Manually compute the final value for AR, checking for
950 // Check whether the backedge-taken count can be losslessly casted to
951 // the addrec's type. The count is always unsigned.
952 const SCEV *CastedMaxBECount =
953 getTruncateOrZeroExtend(MaxBECount, Start->getType());
954 const SCEV *RecastedMaxBECount =
955 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956 if (MaxBECount == RecastedMaxBECount) {
957 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
958 // Check whether Start+Step*MaxBECount has no signed overflow.
960 getMulExpr(CastedMaxBECount,
961 getTruncateOrSignExtend(Step, Start->getType()));
962 const SCEV *Add = getAddExpr(Start, SMul);
963 const SCEV *OperandExtendedAdd =
964 getAddExpr(getSignExtendExpr(Start, WideTy),
965 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
966 getSignExtendExpr(Step, WideTy)));
967 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
968 // Return the expression with the addrec on the outside.
969 return getAddRecExpr(getSignExtendExpr(Start, Ty),
970 getSignExtendExpr(Step, Ty),
973 // Similar to above, only this time treat the step value as unsigned.
974 // This covers loops that count up with an unsigned step.
976 getMulExpr(CastedMaxBECount,
977 getTruncateOrZeroExtend(Step, Start->getType()));
978 Add = getAddExpr(Start, UMul);
980 getAddExpr(getSignExtendExpr(Start, WideTy),
981 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
982 getZeroExtendExpr(Step, WideTy)));
983 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
984 // Return the expression with the addrec on the outside.
985 return getAddRecExpr(getSignExtendExpr(Start, Ty),
986 getZeroExtendExpr(Step, Ty),
990 // If the backedge is guarded by a comparison with the pre-inc value
991 // the addrec is safe. Also, if the entry is guarded by a comparison
992 // with the start value and the backedge is guarded by a comparison
993 // with the post-inc value, the addrec is safe.
994 if (isKnownPositive(Step)) {
995 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
996 getSignedRange(Step).getSignedMax());
997 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
998 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
999 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1000 AR->getPostIncExpr(*this), N)))
1001 // Return the expression with the addrec on the outside.
1002 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1003 getSignExtendExpr(Step, Ty),
1005 } else if (isKnownNegative(Step)) {
1006 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1007 getSignedRange(Step).getSignedMin());
1008 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1009 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1010 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1011 AR->getPostIncExpr(*this), N)))
1012 // Return the expression with the addrec on the outside.
1013 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1014 getSignExtendExpr(Step, Ty),
1020 // The cast wasn't folded; create an explicit cast node.
1021 // Recompute the insert position, as it may have been invalidated.
1022 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1023 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1024 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1025 UniqueSCEVs.InsertNode(S, IP);
1029 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1030 /// unspecified bits out to the given type.
1032 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1034 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1035 "This is not an extending conversion!");
1036 assert(isSCEVable(Ty) &&
1037 "This is not a conversion to a SCEVable type!");
1038 Ty = getEffectiveSCEVType(Ty);
1040 // Sign-extend negative constants.
1041 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1042 if (SC->getValue()->getValue().isNegative())
1043 return getSignExtendExpr(Op, Ty);
1045 // Peel off a truncate cast.
1046 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1047 const SCEV *NewOp = T->getOperand();
1048 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1049 return getAnyExtendExpr(NewOp, Ty);
1050 return getTruncateOrNoop(NewOp, Ty);
1053 // Next try a zext cast. If the cast is folded, use it.
1054 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1055 if (!isa<SCEVZeroExtendExpr>(ZExt))
1058 // Next try a sext cast. If the cast is folded, use it.
1059 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1060 if (!isa<SCEVSignExtendExpr>(SExt))
1063 // If the expression is obviously signed, use the sext cast value.
1064 if (isa<SCEVSMaxExpr>(Op))
1067 // Absent any other information, use the zext cast value.
1071 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1072 /// a list of operands to be added under the given scale, update the given
1073 /// map. This is a helper function for getAddRecExpr. As an example of
1074 /// what it does, given a sequence of operands that would form an add
1075 /// expression like this:
1077 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1079 /// where A and B are constants, update the map with these values:
1081 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1083 /// and add 13 + A*B*29 to AccumulatedConstant.
1084 /// This will allow getAddRecExpr to produce this:
1086 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1088 /// This form often exposes folding opportunities that are hidden in
1089 /// the original operand list.
1091 /// Return true iff it appears that any interesting folding opportunities
1092 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1093 /// the common case where no interesting opportunities are present, and
1094 /// is also used as a check to avoid infinite recursion.
1097 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1098 SmallVector<const SCEV *, 8> &NewOps,
1099 APInt &AccumulatedConstant,
1100 const SmallVectorImpl<const SCEV *> &Ops,
1102 ScalarEvolution &SE) {
1103 bool Interesting = false;
1105 // Iterate over the add operands.
1106 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1107 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1108 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1110 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1111 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1112 // A multiplication of a constant with another add; recurse.
1114 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1115 cast<SCEVAddExpr>(Mul->getOperand(1))
1119 // A multiplication of a constant with some other value. Update
1121 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1122 const SCEV *Key = SE.getMulExpr(MulOps);
1123 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1124 M.insert(std::make_pair(Key, NewScale));
1126 NewOps.push_back(Pair.first->first);
1128 Pair.first->second += NewScale;
1129 // The map already had an entry for this value, which may indicate
1130 // a folding opportunity.
1134 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1135 // Pull a buried constant out to the outside.
1136 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1138 AccumulatedConstant += Scale * C->getValue()->getValue();
1140 // An ordinary operand. Update the map.
1141 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1142 M.insert(std::make_pair(Ops[i], Scale));
1144 NewOps.push_back(Pair.first->first);
1146 Pair.first->second += Scale;
1147 // The map already had an entry for this value, which may indicate
1148 // a folding opportunity.
1158 struct APIntCompare {
1159 bool operator()(const APInt &LHS, const APInt &RHS) const {
1160 return LHS.ult(RHS);
1165 /// getAddExpr - Get a canonical add expression, or something simpler if
1167 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1168 assert(!Ops.empty() && "Cannot get empty add!");
1169 if (Ops.size() == 1) return Ops[0];
1171 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1172 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1173 getEffectiveSCEVType(Ops[0]->getType()) &&
1174 "SCEVAddExpr operand types don't match!");
1177 // Sort by complexity, this groups all similar expression types together.
1178 GroupByComplexity(Ops, LI);
1180 // If there are any constants, fold them together.
1182 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1184 assert(Idx < Ops.size());
1185 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1186 // We found two constants, fold them together!
1187 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1188 RHSC->getValue()->getValue());
1189 if (Ops.size() == 2) return Ops[0];
1190 Ops.erase(Ops.begin()+1); // Erase the folded element
1191 LHSC = cast<SCEVConstant>(Ops[0]);
1194 // If we are left with a constant zero being added, strip it off.
1195 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1196 Ops.erase(Ops.begin());
1201 if (Ops.size() == 1) return Ops[0];
1203 // Okay, check to see if the same value occurs in the operand list twice. If
1204 // so, merge them together into an multiply expression. Since we sorted the
1205 // list, these values are required to be adjacent.
1206 const Type *Ty = Ops[0]->getType();
1207 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1208 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1209 // Found a match, merge the two values into a multiply, and add any
1210 // remaining values to the result.
1211 const SCEV *Two = getIntegerSCEV(2, Ty);
1212 const SCEV *Mul = getMulExpr(Ops[i], Two);
1213 if (Ops.size() == 2)
1215 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1217 return getAddExpr(Ops);
1220 // Check for truncates. If all the operands are truncated from the same
1221 // type, see if factoring out the truncate would permit the result to be
1222 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1223 // if the contents of the resulting outer trunc fold to something simple.
1224 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1225 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1226 const Type *DstType = Trunc->getType();
1227 const Type *SrcType = Trunc->getOperand()->getType();
1228 SmallVector<const SCEV *, 8> LargeOps;
1230 // Check all the operands to see if they can be represented in the
1231 // source type of the truncate.
1232 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1233 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1234 if (T->getOperand()->getType() != SrcType) {
1238 LargeOps.push_back(T->getOperand());
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // This could be either sign or zero extension, but sign extension
1241 // is much more likely to be foldable here.
1242 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1243 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1244 SmallVector<const SCEV *, 8> LargeMulOps;
1245 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1246 if (const SCEVTruncateExpr *T =
1247 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1248 if (T->getOperand()->getType() != SrcType) {
1252 LargeMulOps.push_back(T->getOperand());
1253 } else if (const SCEVConstant *C =
1254 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1255 // This could be either sign or zero extension, but sign extension
1256 // is much more likely to be foldable here.
1257 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1264 LargeOps.push_back(getMulExpr(LargeMulOps));
1271 // Evaluate the expression in the larger type.
1272 const SCEV *Fold = getAddExpr(LargeOps);
1273 // If it folds to something simple, use it. Otherwise, don't.
1274 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1275 return getTruncateExpr(Fold, DstType);
1279 // Skip past any other cast SCEVs.
1280 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1283 // If there are add operands they would be next.
1284 if (Idx < Ops.size()) {
1285 bool DeletedAdd = false;
1286 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1287 // If we have an add, expand the add operands onto the end of the operands
1289 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1290 Ops.erase(Ops.begin()+Idx);
1294 // If we deleted at least one add, we added operands to the end of the list,
1295 // and they are not necessarily sorted. Recurse to resort and resimplify
1296 // any operands we just aquired.
1298 return getAddExpr(Ops);
1301 // Skip over the add expression until we get to a multiply.
1302 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1305 // Check to see if there are any folding opportunities present with
1306 // operands multiplied by constant values.
1307 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1308 uint64_t BitWidth = getTypeSizeInBits(Ty);
1309 DenseMap<const SCEV *, APInt> M;
1310 SmallVector<const SCEV *, 8> NewOps;
1311 APInt AccumulatedConstant(BitWidth, 0);
1312 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1313 Ops, APInt(BitWidth, 1), *this)) {
1314 // Some interesting folding opportunity is present, so its worthwhile to
1315 // re-generate the operands list. Group the operands by constant scale,
1316 // to avoid multiplying by the same constant scale multiple times.
1317 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1318 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1319 E = NewOps.end(); I != E; ++I)
1320 MulOpLists[M.find(*I)->second].push_back(*I);
1321 // Re-generate the operands list.
1323 if (AccumulatedConstant != 0)
1324 Ops.push_back(getConstant(AccumulatedConstant));
1325 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1326 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1328 Ops.push_back(getMulExpr(getConstant(I->first),
1329 getAddExpr(I->second)));
1331 return getIntegerSCEV(0, Ty);
1332 if (Ops.size() == 1)
1334 return getAddExpr(Ops);
1338 // If we are adding something to a multiply expression, make sure the
1339 // something is not already an operand of the multiply. If so, merge it into
1341 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1343 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1344 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1345 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1346 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1347 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1348 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1349 if (Mul->getNumOperands() != 2) {
1350 // If the multiply has more than two operands, we must get the
1352 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1353 MulOps.erase(MulOps.begin()+MulOp);
1354 InnerMul = getMulExpr(MulOps);
1356 const SCEV *One = getIntegerSCEV(1, Ty);
1357 const SCEV *AddOne = getAddExpr(InnerMul, One);
1358 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1359 if (Ops.size() == 2) return OuterMul;
1361 Ops.erase(Ops.begin()+AddOp);
1362 Ops.erase(Ops.begin()+Idx-1);
1364 Ops.erase(Ops.begin()+Idx);
1365 Ops.erase(Ops.begin()+AddOp-1);
1367 Ops.push_back(OuterMul);
1368 return getAddExpr(Ops);
1371 // Check this multiply against other multiplies being added together.
1372 for (unsigned OtherMulIdx = Idx+1;
1373 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1375 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1376 // If MulOp occurs in OtherMul, we can fold the two multiplies
1378 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1379 OMulOp != e; ++OMulOp)
1380 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1381 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1382 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1383 if (Mul->getNumOperands() != 2) {
1384 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1386 MulOps.erase(MulOps.begin()+MulOp);
1387 InnerMul1 = getMulExpr(MulOps);
1389 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1390 if (OtherMul->getNumOperands() != 2) {
1391 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1392 OtherMul->op_end());
1393 MulOps.erase(MulOps.begin()+OMulOp);
1394 InnerMul2 = getMulExpr(MulOps);
1396 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1397 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1398 if (Ops.size() == 2) return OuterMul;
1399 Ops.erase(Ops.begin()+Idx);
1400 Ops.erase(Ops.begin()+OtherMulIdx-1);
1401 Ops.push_back(OuterMul);
1402 return getAddExpr(Ops);
1408 // If there are any add recurrences in the operands list, see if any other
1409 // added values are loop invariant. If so, we can fold them into the
1411 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1414 // Scan over all recurrences, trying to fold loop invariants into them.
1415 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1416 // Scan all of the other operands to this add and add them to the vector if
1417 // they are loop invariant w.r.t. the recurrence.
1418 SmallVector<const SCEV *, 8> LIOps;
1419 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1420 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1421 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1422 LIOps.push_back(Ops[i]);
1423 Ops.erase(Ops.begin()+i);
1427 // If we found some loop invariants, fold them into the recurrence.
1428 if (!LIOps.empty()) {
1429 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1430 LIOps.push_back(AddRec->getStart());
1432 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1434 AddRecOps[0] = getAddExpr(LIOps);
1436 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1437 // If all of the other operands were loop invariant, we are done.
1438 if (Ops.size() == 1) return NewRec;
1440 // Otherwise, add the folded AddRec by the non-liv parts.
1441 for (unsigned i = 0;; ++i)
1442 if (Ops[i] == AddRec) {
1446 return getAddExpr(Ops);
1449 // Okay, if there weren't any loop invariants to be folded, check to see if
1450 // there are multiple AddRec's with the same loop induction variable being
1451 // added together. If so, we can fold them.
1452 for (unsigned OtherIdx = Idx+1;
1453 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1454 if (OtherIdx != Idx) {
1455 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1456 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1457 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1458 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1460 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1461 if (i >= NewOps.size()) {
1462 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1463 OtherAddRec->op_end());
1466 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1468 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1470 if (Ops.size() == 2) return NewAddRec;
1472 Ops.erase(Ops.begin()+Idx);
1473 Ops.erase(Ops.begin()+OtherIdx-1);
1474 Ops.push_back(NewAddRec);
1475 return getAddExpr(Ops);
1479 // Otherwise couldn't fold anything into this recurrence. Move onto the
1483 // Okay, it looks like we really DO need an add expr. Check to see if we
1484 // already have one, otherwise create a new one.
1485 FoldingSetNodeID ID;
1486 ID.AddInteger(scAddExpr);
1487 ID.AddInteger(Ops.size());
1488 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1489 ID.AddPointer(Ops[i]);
1491 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1492 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1493 new (S) SCEVAddExpr(ID, Ops);
1494 UniqueSCEVs.InsertNode(S, IP);
1499 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1501 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1502 assert(!Ops.empty() && "Cannot get empty mul!");
1504 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1505 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1506 getEffectiveSCEVType(Ops[0]->getType()) &&
1507 "SCEVMulExpr operand types don't match!");
1510 // Sort by complexity, this groups all similar expression types together.
1511 GroupByComplexity(Ops, LI);
1513 // If there are any constants, fold them together.
1515 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1517 // C1*(C2+V) -> C1*C2 + C1*V
1518 if (Ops.size() == 2)
1519 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1520 if (Add->getNumOperands() == 2 &&
1521 isa<SCEVConstant>(Add->getOperand(0)))
1522 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1523 getMulExpr(LHSC, Add->getOperand(1)));
1527 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1528 // We found two constants, fold them together!
1529 ConstantInt *Fold = ConstantInt::get(getContext(),
1530 LHSC->getValue()->getValue() *
1531 RHSC->getValue()->getValue());
1532 Ops[0] = getConstant(Fold);
1533 Ops.erase(Ops.begin()+1); // Erase the folded element
1534 if (Ops.size() == 1) return Ops[0];
1535 LHSC = cast<SCEVConstant>(Ops[0]);
1538 // If we are left with a constant one being multiplied, strip it off.
1539 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1540 Ops.erase(Ops.begin());
1542 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1543 // If we have a multiply of zero, it will always be zero.
1548 // Skip over the add expression until we get to a multiply.
1549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1552 if (Ops.size() == 1)
1555 // If there are mul operands inline them all into this expression.
1556 if (Idx < Ops.size()) {
1557 bool DeletedMul = false;
1558 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1559 // If we have an mul, expand the mul operands onto the end of the operands
1561 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1562 Ops.erase(Ops.begin()+Idx);
1566 // If we deleted at least one mul, we added operands to the end of the list,
1567 // and they are not necessarily sorted. Recurse to resort and resimplify
1568 // any operands we just aquired.
1570 return getMulExpr(Ops);
1573 // If there are any add recurrences in the operands list, see if any other
1574 // added values are loop invariant. If so, we can fold them into the
1576 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1579 // Scan over all recurrences, trying to fold loop invariants into them.
1580 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1581 // Scan all of the other operands to this mul and add them to the vector if
1582 // they are loop invariant w.r.t. the recurrence.
1583 SmallVector<const SCEV *, 8> LIOps;
1584 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1585 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1586 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1587 LIOps.push_back(Ops[i]);
1588 Ops.erase(Ops.begin()+i);
1592 // If we found some loop invariants, fold them into the recurrence.
1593 if (!LIOps.empty()) {
1594 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1595 SmallVector<const SCEV *, 4> NewOps;
1596 NewOps.reserve(AddRec->getNumOperands());
1597 if (LIOps.size() == 1) {
1598 const SCEV *Scale = LIOps[0];
1599 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1600 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1602 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1603 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1604 MulOps.push_back(AddRec->getOperand(i));
1605 NewOps.push_back(getMulExpr(MulOps));
1609 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1611 // If all of the other operands were loop invariant, we are done.
1612 if (Ops.size() == 1) return NewRec;
1614 // Otherwise, multiply the folded AddRec by the non-liv parts.
1615 for (unsigned i = 0;; ++i)
1616 if (Ops[i] == AddRec) {
1620 return getMulExpr(Ops);
1623 // Okay, if there weren't any loop invariants to be folded, check to see if
1624 // there are multiple AddRec's with the same loop induction variable being
1625 // multiplied together. If so, we can fold them.
1626 for (unsigned OtherIdx = Idx+1;
1627 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1628 if (OtherIdx != Idx) {
1629 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1630 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1631 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1632 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1633 const SCEV *NewStart = getMulExpr(F->getStart(),
1635 const SCEV *B = F->getStepRecurrence(*this);
1636 const SCEV *D = G->getStepRecurrence(*this);
1637 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1640 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1642 if (Ops.size() == 2) return NewAddRec;
1644 Ops.erase(Ops.begin()+Idx);
1645 Ops.erase(Ops.begin()+OtherIdx-1);
1646 Ops.push_back(NewAddRec);
1647 return getMulExpr(Ops);
1651 // Otherwise couldn't fold anything into this recurrence. Move onto the
1655 // Okay, it looks like we really DO need an mul expr. Check to see if we
1656 // already have one, otherwise create a new one.
1657 FoldingSetNodeID ID;
1658 ID.AddInteger(scMulExpr);
1659 ID.AddInteger(Ops.size());
1660 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1661 ID.AddPointer(Ops[i]);
1663 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1664 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1665 new (S) SCEVMulExpr(ID, Ops);
1666 UniqueSCEVs.InsertNode(S, IP);
1670 /// getUDivExpr - Get a canonical unsigned division expression, or something
1671 /// simpler if possible.
1672 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1674 assert(getEffectiveSCEVType(LHS->getType()) ==
1675 getEffectiveSCEVType(RHS->getType()) &&
1676 "SCEVUDivExpr operand types don't match!");
1678 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1679 if (RHSC->getValue()->equalsInt(1))
1680 return LHS; // X udiv 1 --> x
1682 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1684 // Determine if the division can be folded into the operands of
1686 // TODO: Generalize this to non-constants by using known-bits information.
1687 const Type *Ty = LHS->getType();
1688 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1689 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1690 // For non-power-of-two values, effectively round the value up to the
1691 // nearest power of two.
1692 if (!RHSC->getValue()->getValue().isPowerOf2())
1694 const IntegerType *ExtTy =
1695 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1696 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1697 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1698 if (const SCEVConstant *Step =
1699 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1700 if (!Step->getValue()->getValue()
1701 .urem(RHSC->getValue()->getValue()) &&
1702 getZeroExtendExpr(AR, ExtTy) ==
1703 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1704 getZeroExtendExpr(Step, ExtTy),
1706 SmallVector<const SCEV *, 4> Operands;
1707 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1708 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1709 return getAddRecExpr(Operands, AR->getLoop());
1711 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1712 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1713 SmallVector<const SCEV *, 4> Operands;
1714 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1715 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1716 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1717 // Find an operand that's safely divisible.
1718 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1719 const SCEV *Op = M->getOperand(i);
1720 const SCEV *Div = getUDivExpr(Op, RHSC);
1721 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1722 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1723 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1726 return getMulExpr(Operands);
1730 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1731 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1732 SmallVector<const SCEV *, 4> Operands;
1733 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1734 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1735 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1737 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1738 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1739 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1741 Operands.push_back(Op);
1743 if (Operands.size() == A->getNumOperands())
1744 return getAddExpr(Operands);
1748 // Fold if both operands are constant.
1749 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1750 Constant *LHSCV = LHSC->getValue();
1751 Constant *RHSCV = RHSC->getValue();
1752 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1757 FoldingSetNodeID ID;
1758 ID.AddInteger(scUDivExpr);
1762 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1763 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1764 new (S) SCEVUDivExpr(ID, LHS, RHS);
1765 UniqueSCEVs.InsertNode(S, IP);
1770 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1771 /// Simplify the expression as much as possible.
1772 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1773 const SCEV *Step, const Loop *L) {
1774 SmallVector<const SCEV *, 4> Operands;
1775 Operands.push_back(Start);
1776 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1777 if (StepChrec->getLoop() == L) {
1778 Operands.insert(Operands.end(), StepChrec->op_begin(),
1779 StepChrec->op_end());
1780 return getAddRecExpr(Operands, L);
1783 Operands.push_back(Step);
1784 return getAddRecExpr(Operands, L);
1787 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1788 /// Simplify the expression as much as possible.
1790 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1792 if (Operands.size() == 1) return Operands[0];
1794 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1795 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1796 getEffectiveSCEVType(Operands[0]->getType()) &&
1797 "SCEVAddRecExpr operand types don't match!");
1800 if (Operands.back()->isZero()) {
1801 Operands.pop_back();
1802 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1805 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1806 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1807 const Loop* NestedLoop = NestedAR->getLoop();
1808 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1809 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1810 NestedAR->op_end());
1811 Operands[0] = NestedAR->getStart();
1812 // AddRecs require their operands be loop-invariant with respect to their
1813 // loops. Don't perform this transformation if it would break this
1815 bool AllInvariant = true;
1816 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1817 if (!Operands[i]->isLoopInvariant(L)) {
1818 AllInvariant = false;
1822 NestedOperands[0] = getAddRecExpr(Operands, L);
1823 AllInvariant = true;
1824 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1825 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1826 AllInvariant = false;
1830 // Ok, both add recurrences are valid after the transformation.
1831 return getAddRecExpr(NestedOperands, NestedLoop);
1833 // Reset Operands to its original state.
1834 Operands[0] = NestedAR;
1838 FoldingSetNodeID ID;
1839 ID.AddInteger(scAddRecExpr);
1840 ID.AddInteger(Operands.size());
1841 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1842 ID.AddPointer(Operands[i]);
1845 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1846 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1847 new (S) SCEVAddRecExpr(ID, Operands, L);
1848 UniqueSCEVs.InsertNode(S, IP);
1852 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1854 SmallVector<const SCEV *, 2> Ops;
1857 return getSMaxExpr(Ops);
1861 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1862 assert(!Ops.empty() && "Cannot get empty smax!");
1863 if (Ops.size() == 1) return Ops[0];
1865 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1866 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1867 getEffectiveSCEVType(Ops[0]->getType()) &&
1868 "SCEVSMaxExpr operand types don't match!");
1871 // Sort by complexity, this groups all similar expression types together.
1872 GroupByComplexity(Ops, LI);
1874 // If there are any constants, fold them together.
1876 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1878 assert(Idx < Ops.size());
1879 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1880 // We found two constants, fold them together!
1881 ConstantInt *Fold = ConstantInt::get(getContext(),
1882 APIntOps::smax(LHSC->getValue()->getValue(),
1883 RHSC->getValue()->getValue()));
1884 Ops[0] = getConstant(Fold);
1885 Ops.erase(Ops.begin()+1); // Erase the folded element
1886 if (Ops.size() == 1) return Ops[0];
1887 LHSC = cast<SCEVConstant>(Ops[0]);
1890 // If we are left with a constant minimum-int, strip it off.
1891 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1892 Ops.erase(Ops.begin());
1894 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1895 // If we have an smax with a constant maximum-int, it will always be
1901 if (Ops.size() == 1) return Ops[0];
1903 // Find the first SMax
1904 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1907 // Check to see if one of the operands is an SMax. If so, expand its operands
1908 // onto our operand list, and recurse to simplify.
1909 if (Idx < Ops.size()) {
1910 bool DeletedSMax = false;
1911 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1912 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1913 Ops.erase(Ops.begin()+Idx);
1918 return getSMaxExpr(Ops);
1921 // Okay, check to see if the same value occurs in the operand list twice. If
1922 // so, delete one. Since we sorted the list, these values are required to
1924 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1925 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1926 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1930 if (Ops.size() == 1) return Ops[0];
1932 assert(!Ops.empty() && "Reduced smax down to nothing!");
1934 // Okay, it looks like we really DO need an smax expr. Check to see if we
1935 // already have one, otherwise create a new one.
1936 FoldingSetNodeID ID;
1937 ID.AddInteger(scSMaxExpr);
1938 ID.AddInteger(Ops.size());
1939 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1940 ID.AddPointer(Ops[i]);
1942 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1943 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1944 new (S) SCEVSMaxExpr(ID, Ops);
1945 UniqueSCEVs.InsertNode(S, IP);
1949 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1951 SmallVector<const SCEV *, 2> Ops;
1954 return getUMaxExpr(Ops);
1958 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1959 assert(!Ops.empty() && "Cannot get empty umax!");
1960 if (Ops.size() == 1) return Ops[0];
1962 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1963 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1964 getEffectiveSCEVType(Ops[0]->getType()) &&
1965 "SCEVUMaxExpr operand types don't match!");
1968 // Sort by complexity, this groups all similar expression types together.
1969 GroupByComplexity(Ops, LI);
1971 // If there are any constants, fold them together.
1973 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1975 assert(Idx < Ops.size());
1976 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1977 // We found two constants, fold them together!
1978 ConstantInt *Fold = ConstantInt::get(getContext(),
1979 APIntOps::umax(LHSC->getValue()->getValue(),
1980 RHSC->getValue()->getValue()));
1981 Ops[0] = getConstant(Fold);
1982 Ops.erase(Ops.begin()+1); // Erase the folded element
1983 if (Ops.size() == 1) return Ops[0];
1984 LHSC = cast<SCEVConstant>(Ops[0]);
1987 // If we are left with a constant minimum-int, strip it off.
1988 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1989 Ops.erase(Ops.begin());
1991 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1992 // If we have an umax with a constant maximum-int, it will always be
1998 if (Ops.size() == 1) return Ops[0];
2000 // Find the first UMax
2001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2004 // Check to see if one of the operands is a UMax. If so, expand its operands
2005 // onto our operand list, and recurse to simplify.
2006 if (Idx < Ops.size()) {
2007 bool DeletedUMax = false;
2008 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2009 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2010 Ops.erase(Ops.begin()+Idx);
2015 return getUMaxExpr(Ops);
2018 // Okay, check to see if the same value occurs in the operand list twice. If
2019 // so, delete one. Since we sorted the list, these values are required to
2021 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2022 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2023 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2027 if (Ops.size() == 1) return Ops[0];
2029 assert(!Ops.empty() && "Reduced umax down to nothing!");
2031 // Okay, it looks like we really DO need a umax expr. Check to see if we
2032 // already have one, otherwise create a new one.
2033 FoldingSetNodeID ID;
2034 ID.AddInteger(scUMaxExpr);
2035 ID.AddInteger(Ops.size());
2036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2037 ID.AddPointer(Ops[i]);
2039 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2040 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2041 new (S) SCEVUMaxExpr(ID, Ops);
2042 UniqueSCEVs.InsertNode(S, IP);
2046 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2048 // ~smax(~x, ~y) == smin(x, y).
2049 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2052 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2054 // ~umax(~x, ~y) == umin(x, y)
2055 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2058 const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2060 // If we have TargetData we can determine the constant offset.
2062 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2063 const StructLayout &SL = *TD->getStructLayout(STy);
2064 uint64_t Offset = SL.getElementOffset(FieldNo);
2065 return getIntegerSCEV(Offset, IntPtrTy);
2068 // Field 0 is always at offset 0.
2070 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2071 return getIntegerSCEV(0, Ty);
2074 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2075 // already have one, otherwise create a new one.
2076 FoldingSetNodeID ID;
2077 ID.AddInteger(scFieldOffset);
2079 ID.AddInteger(FieldNo);
2081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2082 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2083 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2084 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2085 UniqueSCEVs.InsertNode(S, IP);
2089 const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2090 // If we have TargetData we can determine the constant size.
2091 if (TD && AllocTy->isSized()) {
2092 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2093 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2096 // Expand an array size into the element size times the number
2098 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2099 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2101 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2102 ATy->getNumElements())));
2105 // Expand a vector size into the element size times the number
2107 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2108 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2110 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2111 VTy->getNumElements())));
2114 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2115 // already have one, otherwise create a new one.
2116 FoldingSetNodeID ID;
2117 ID.AddInteger(scAllocSize);
2118 ID.AddPointer(AllocTy);
2120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2121 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2122 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2123 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2124 UniqueSCEVs.InsertNode(S, IP);
2128 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2129 // Don't attempt to do anything other than create a SCEVUnknown object
2130 // here. createSCEV only calls getUnknown after checking for all other
2131 // interesting possibilities, and any other code that calls getUnknown
2132 // is doing so in order to hide a value from SCEV canonicalization.
2134 FoldingSetNodeID ID;
2135 ID.AddInteger(scUnknown);
2138 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2139 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2140 new (S) SCEVUnknown(ID, V);
2141 UniqueSCEVs.InsertNode(S, IP);
2145 //===----------------------------------------------------------------------===//
2146 // Basic SCEV Analysis and PHI Idiom Recognition Code
2149 /// isSCEVable - Test if values of the given type are analyzable within
2150 /// the SCEV framework. This primarily includes integer types, and it
2151 /// can optionally include pointer types if the ScalarEvolution class
2152 /// has access to target-specific information.
2153 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2154 // Integers and pointers are always SCEVable.
2155 return Ty->isInteger() || isa<PointerType>(Ty);
2158 /// getTypeSizeInBits - Return the size in bits of the specified type,
2159 /// for which isSCEVable must return true.
2160 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2161 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2163 // If we have a TargetData, use it!
2165 return TD->getTypeSizeInBits(Ty);
2167 // Integer types have fixed sizes.
2168 if (Ty->isInteger())
2169 return Ty->getPrimitiveSizeInBits();
2171 // The only other support type is pointer. Without TargetData, conservatively
2172 // assume pointers are 64-bit.
2173 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2177 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2178 /// the given type and which represents how SCEV will treat the given
2179 /// type, for which isSCEVable must return true. For pointer types,
2180 /// this is the pointer-sized integer type.
2181 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2182 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2184 if (Ty->isInteger())
2187 // The only other support type is pointer.
2188 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2189 if (TD) return TD->getIntPtrType(getContext());
2191 // Without TargetData, conservatively assume pointers are 64-bit.
2192 return Type::getInt64Ty(getContext());
2195 const SCEV *ScalarEvolution::getCouldNotCompute() {
2196 return &CouldNotCompute;
2199 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2200 /// expression and create a new one.
2201 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2202 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2204 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2205 if (I != Scalars.end()) return I->second;
2206 const SCEV *S = createSCEV(V);
2207 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2211 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2212 /// specified signed integer value and return a SCEV for the constant.
2213 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2214 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2215 return getConstant(ConstantInt::get(ITy, Val));
2218 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2220 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2221 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2223 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2225 const Type *Ty = V->getType();
2226 Ty = getEffectiveSCEVType(Ty);
2227 return getMulExpr(V,
2228 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2231 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2232 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2233 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2235 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2237 const Type *Ty = V->getType();
2238 Ty = getEffectiveSCEVType(Ty);
2239 const SCEV *AllOnes =
2240 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2241 return getMinusSCEV(AllOnes, V);
2244 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2246 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2249 return getAddExpr(LHS, getNegativeSCEV(RHS));
2252 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2253 /// input value to the specified type. If the type must be extended, it is zero
2256 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2258 const Type *SrcTy = V->getType();
2259 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2260 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2261 "Cannot truncate or zero extend with non-integer arguments!");
2262 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2263 return V; // No conversion
2264 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2265 return getTruncateExpr(V, Ty);
2266 return getZeroExtendExpr(V, Ty);
2269 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2270 /// input value to the specified type. If the type must be extended, it is sign
2273 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2275 const Type *SrcTy = V->getType();
2276 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2277 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2278 "Cannot truncate or zero extend with non-integer arguments!");
2279 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2280 return V; // No conversion
2281 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2282 return getTruncateExpr(V, Ty);
2283 return getSignExtendExpr(V, Ty);
2286 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2287 /// input value to the specified type. If the type must be extended, it is zero
2288 /// extended. The conversion must not be narrowing.
2290 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2291 const Type *SrcTy = V->getType();
2292 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2293 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2294 "Cannot noop or zero extend with non-integer arguments!");
2295 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2296 "getNoopOrZeroExtend cannot truncate!");
2297 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2298 return V; // No conversion
2299 return getZeroExtendExpr(V, Ty);
2302 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2303 /// input value to the specified type. If the type must be extended, it is sign
2304 /// extended. The conversion must not be narrowing.
2306 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2307 const Type *SrcTy = V->getType();
2308 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2309 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2310 "Cannot noop or sign extend with non-integer arguments!");
2311 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2312 "getNoopOrSignExtend cannot truncate!");
2313 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2314 return V; // No conversion
2315 return getSignExtendExpr(V, Ty);
2318 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2319 /// the input value to the specified type. If the type must be extended,
2320 /// it is extended with unspecified bits. The conversion must not be
2323 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2324 const Type *SrcTy = V->getType();
2325 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2326 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2327 "Cannot noop or any extend with non-integer arguments!");
2328 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2329 "getNoopOrAnyExtend cannot truncate!");
2330 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2331 return V; // No conversion
2332 return getAnyExtendExpr(V, Ty);
2335 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2336 /// input value to the specified type. The conversion must not be widening.
2338 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2339 const Type *SrcTy = V->getType();
2340 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2341 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2342 "Cannot truncate or noop with non-integer arguments!");
2343 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2344 "getTruncateOrNoop cannot extend!");
2345 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2346 return V; // No conversion
2347 return getTruncateExpr(V, Ty);
2350 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2351 /// the types using zero-extension, and then perform a umax operation
2353 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2355 const SCEV *PromotedLHS = LHS;
2356 const SCEV *PromotedRHS = RHS;
2358 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2359 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2361 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2363 return getUMaxExpr(PromotedLHS, PromotedRHS);
2366 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2367 /// the types using zero-extension, and then perform a umin operation
2369 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2371 const SCEV *PromotedLHS = LHS;
2372 const SCEV *PromotedRHS = RHS;
2374 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2375 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2377 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2379 return getUMinExpr(PromotedLHS, PromotedRHS);
2382 /// PushDefUseChildren - Push users of the given Instruction
2383 /// onto the given Worklist.
2385 PushDefUseChildren(Instruction *I,
2386 SmallVectorImpl<Instruction *> &Worklist) {
2387 // Push the def-use children onto the Worklist stack.
2388 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2390 Worklist.push_back(cast<Instruction>(UI));
2393 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2394 /// instructions that depend on the given instruction and removes them from
2395 /// the Scalars map if they reference SymName. This is used during PHI
2398 ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2399 SmallVector<Instruction *, 16> Worklist;
2400 PushDefUseChildren(I, Worklist);
2402 SmallPtrSet<Instruction *, 8> Visited;
2404 while (!Worklist.empty()) {
2405 Instruction *I = Worklist.pop_back_val();
2406 if (!Visited.insert(I)) continue;
2408 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2409 Scalars.find(static_cast<Value *>(I));
2410 if (It != Scalars.end()) {
2411 // Short-circuit the def-use traversal if the symbolic name
2412 // ceases to appear in expressions.
2413 if (!It->second->hasOperand(SymName))
2416 // SCEVUnknown for a PHI either means that it has an unrecognized
2417 // structure, or it's a PHI that's in the progress of being computed
2418 // by createNodeForPHI. In the former case, additional loop trip
2419 // count information isn't going to change anything. In the later
2420 // case, createNodeForPHI will perform the necessary updates on its
2421 // own when it gets to that point.
2422 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2424 ValuesAtScopes.erase(I);
2427 PushDefUseChildren(I, Worklist);
2431 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2432 /// a loop header, making it a potential recurrence, or it doesn't.
2434 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2435 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2436 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2437 if (L->getHeader() == PN->getParent()) {
2438 // If it lives in the loop header, it has two incoming values, one
2439 // from outside the loop, and one from inside.
2440 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2441 unsigned BackEdge = IncomingEdge^1;
2443 // While we are analyzing this PHI node, handle its value symbolically.
2444 const SCEV *SymbolicName = getUnknown(PN);
2445 assert(Scalars.find(PN) == Scalars.end() &&
2446 "PHI node already processed?");
2447 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2449 // Using this symbolic name for the PHI, analyze the value coming around
2451 Value *BEValueV = PN->getIncomingValue(BackEdge);
2452 const SCEV *BEValue = getSCEV(BEValueV);
2454 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2455 // has a special value for the first iteration of the loop.
2457 // If the value coming around the backedge is an add with the symbolic
2458 // value we just inserted, then we found a simple induction variable!
2459 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2460 // If there is a single occurrence of the symbolic value, replace it
2461 // with a recurrence.
2462 unsigned FoundIndex = Add->getNumOperands();
2463 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2464 if (Add->getOperand(i) == SymbolicName)
2465 if (FoundIndex == e) {
2470 if (FoundIndex != Add->getNumOperands()) {
2471 // Create an add with everything but the specified operand.
2472 SmallVector<const SCEV *, 8> Ops;
2473 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2474 if (i != FoundIndex)
2475 Ops.push_back(Add->getOperand(i));
2476 const SCEV *Accum = getAddExpr(Ops);
2478 // This is not a valid addrec if the step amount is varying each
2479 // loop iteration, but is not itself an addrec in this loop.
2480 if (Accum->isLoopInvariant(L) ||
2481 (isa<SCEVAddRecExpr>(Accum) &&
2482 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2483 const SCEV *StartVal =
2484 getSCEV(PN->getIncomingValue(IncomingEdge));
2485 const SCEVAddRecExpr *PHISCEV =
2486 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2488 // If the increment doesn't overflow, then neither the addrec nor the
2489 // post-increment will overflow.
2490 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2491 if (OBO->getOperand(0) == PN &&
2492 getSCEV(OBO->getOperand(1)) ==
2493 PHISCEV->getStepRecurrence(*this)) {
2494 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
2495 if (OBO->hasNoUnsignedWrap()) {
2496 const_cast<SCEVAddRecExpr *>(PHISCEV)
2497 ->setHasNoUnsignedWrap(true);
2498 const_cast<SCEVAddRecExpr *>(PostInc)
2499 ->setHasNoUnsignedWrap(true);
2501 if (OBO->hasNoSignedWrap()) {
2502 const_cast<SCEVAddRecExpr *>(PHISCEV)
2503 ->setHasNoSignedWrap(true);
2504 const_cast<SCEVAddRecExpr *>(PostInc)
2505 ->setHasNoSignedWrap(true);
2509 // Okay, for the entire analysis of this edge we assumed the PHI
2510 // to be symbolic. We now need to go back and purge all of the
2511 // entries for the scalars that use the symbolic expression.
2512 ForgetSymbolicName(PN, SymbolicName);
2513 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2517 } else if (const SCEVAddRecExpr *AddRec =
2518 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2519 // Otherwise, this could be a loop like this:
2520 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2521 // In this case, j = {1,+,1} and BEValue is j.
2522 // Because the other in-value of i (0) fits the evolution of BEValue
2523 // i really is an addrec evolution.
2524 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2525 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2527 // If StartVal = j.start - j.stride, we can use StartVal as the
2528 // initial step of the addrec evolution.
2529 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2530 AddRec->getOperand(1))) {
2531 const SCEV *PHISCEV =
2532 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2534 // Okay, for the entire analysis of this edge we assumed the PHI
2535 // to be symbolic. We now need to go back and purge all of the
2536 // entries for the scalars that use the symbolic expression.
2537 ForgetSymbolicName(PN, SymbolicName);
2538 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2544 return SymbolicName;
2547 // It's tempting to recognize PHIs with a unique incoming value, however
2548 // this leads passes like indvars to break LCSSA form. Fortunately, such
2549 // PHIs are rare, as instcombine zaps them.
2551 // If it's not a loop phi, we can't handle it yet.
2552 return getUnknown(PN);
2555 /// createNodeForGEP - Expand GEP instructions into add and multiply
2556 /// operations. This allows them to be analyzed by regular SCEV code.
2558 const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
2560 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2561 Value *Base = GEP->getOperand(0);
2562 // Don't attempt to analyze GEPs over unsized objects.
2563 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2564 return getUnknown(GEP);
2565 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2566 gep_type_iterator GTI = gep_type_begin(GEP);
2567 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2571 // Compute the (potentially symbolic) offset in bytes for this index.
2572 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2573 // For a struct, add the member offset.
2574 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2575 TotalOffset = getAddExpr(TotalOffset,
2576 getFieldOffsetExpr(STy, FieldNo));
2578 // For an array, add the element offset, explicitly scaled.
2579 const SCEV *LocalOffset = getSCEV(Index);
2580 if (!isa<PointerType>(LocalOffset->getType()))
2581 // Getelementptr indicies are signed.
2582 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2583 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
2584 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2587 return getAddExpr(getSCEV(Base), TotalOffset);
2590 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2591 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2592 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2593 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2595 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2596 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2597 return C->getValue()->getValue().countTrailingZeros();
2599 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2600 return std::min(GetMinTrailingZeros(T->getOperand()),
2601 (uint32_t)getTypeSizeInBits(T->getType()));
2603 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2604 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2605 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2606 getTypeSizeInBits(E->getType()) : OpRes;
2609 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2610 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2611 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2612 getTypeSizeInBits(E->getType()) : OpRes;
2615 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2616 // The result is the min of all operands results.
2617 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2618 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2619 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2623 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2624 // The result is the sum of all operands results.
2625 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2626 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2627 for (unsigned i = 1, e = M->getNumOperands();
2628 SumOpRes != BitWidth && i != e; ++i)
2629 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2634 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2635 // The result is the min of all operands results.
2636 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2637 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2638 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2642 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2643 // The result is the min of all operands results.
2644 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2645 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2646 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2650 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2651 // The result is the min of all operands results.
2652 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2653 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2654 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2658 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2659 // For a SCEVUnknown, ask ValueTracking.
2660 unsigned BitWidth = getTypeSizeInBits(U->getType());
2661 APInt Mask = APInt::getAllOnesValue(BitWidth);
2662 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2663 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2664 return Zeros.countTrailingOnes();
2671 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2674 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2676 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2677 return ConstantRange(C->getValue()->getValue());
2679 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2680 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2681 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2682 X = X.add(getUnsignedRange(Add->getOperand(i)));
2686 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2687 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2688 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2689 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2693 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2694 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2695 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2696 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2700 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2701 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2702 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2703 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2707 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2708 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2709 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2713 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2714 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2715 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2718 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2719 ConstantRange X = getUnsignedRange(SExt->getOperand());
2720 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2723 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2724 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2725 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2728 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2730 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2731 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2732 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2733 if (!Trip) return FullSet;
2735 // TODO: non-affine addrec
2736 if (AddRec->isAffine()) {
2737 const Type *Ty = AddRec->getType();
2738 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2739 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2740 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2742 const SCEV *Start = AddRec->getStart();
2743 const SCEV *Step = AddRec->getStepRecurrence(*this);
2744 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2746 // Check for overflow.
2747 // TODO: This is very conservative.
2748 if (!(Step->isOne() &&
2749 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2750 !(Step->isAllOnesValue() &&
2751 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
2754 ConstantRange StartRange = getUnsignedRange(Start);
2755 ConstantRange EndRange = getUnsignedRange(End);
2756 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2757 EndRange.getUnsignedMin());
2758 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2759 EndRange.getUnsignedMax());
2760 if (Min.isMinValue() && Max.isMaxValue())
2762 return ConstantRange(Min, Max+1);
2767 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2768 // For a SCEVUnknown, ask ValueTracking.
2769 unsigned BitWidth = getTypeSizeInBits(U->getType());
2770 APInt Mask = APInt::getAllOnesValue(BitWidth);
2771 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2772 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2773 if (Ones == ~Zeros + 1)
2775 return ConstantRange(Ones, ~Zeros + 1);
2781 /// getSignedRange - Determine the signed range for a particular SCEV.
2784 ScalarEvolution::getSignedRange(const SCEV *S) {
2786 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2787 return ConstantRange(C->getValue()->getValue());
2789 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2790 ConstantRange X = getSignedRange(Add->getOperand(0));
2791 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2792 X = X.add(getSignedRange(Add->getOperand(i)));
2796 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2797 ConstantRange X = getSignedRange(Mul->getOperand(0));
2798 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2799 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2803 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2804 ConstantRange X = getSignedRange(SMax->getOperand(0));
2805 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2806 X = X.smax(getSignedRange(SMax->getOperand(i)));
2810 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2811 ConstantRange X = getSignedRange(UMax->getOperand(0));
2812 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2813 X = X.umax(getSignedRange(UMax->getOperand(i)));
2817 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2818 ConstantRange X = getSignedRange(UDiv->getLHS());
2819 ConstantRange Y = getSignedRange(UDiv->getRHS());
2823 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2824 ConstantRange X = getSignedRange(ZExt->getOperand());
2825 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2828 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2829 ConstantRange X = getSignedRange(SExt->getOperand());
2830 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2833 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2834 ConstantRange X = getSignedRange(Trunc->getOperand());
2835 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2838 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2840 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2841 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2842 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2843 if (!Trip) return FullSet;
2845 // TODO: non-affine addrec
2846 if (AddRec->isAffine()) {
2847 const Type *Ty = AddRec->getType();
2848 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2849 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2850 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2852 const SCEV *Start = AddRec->getStart();
2853 const SCEV *Step = AddRec->getStepRecurrence(*this);
2854 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2856 // Check for overflow.
2857 // TODO: This is very conservative.
2858 if (!(Step->isOne() &&
2859 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2860 !(Step->isAllOnesValue() &&
2861 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2864 ConstantRange StartRange = getSignedRange(Start);
2865 ConstantRange EndRange = getSignedRange(End);
2866 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2867 EndRange.getSignedMin());
2868 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2869 EndRange.getSignedMax());
2870 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2872 return ConstantRange(Min, Max+1);
2877 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2878 // For a SCEVUnknown, ask ValueTracking.
2879 unsigned BitWidth = getTypeSizeInBits(U->getType());
2880 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2884 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2885 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
2891 /// createSCEV - We know that there is no SCEV for the specified value.
2892 /// Analyze the expression.
2894 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2895 if (!isSCEVable(V->getType()))
2896 return getUnknown(V);
2898 unsigned Opcode = Instruction::UserOp1;
2899 if (Instruction *I = dyn_cast<Instruction>(V))
2900 Opcode = I->getOpcode();
2901 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2902 Opcode = CE->getOpcode();
2903 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2904 return getConstant(CI);
2905 else if (isa<ConstantPointerNull>(V))
2906 return getIntegerSCEV(0, V->getType());
2907 else if (isa<UndefValue>(V))
2908 return getIntegerSCEV(0, V->getType());
2910 return getUnknown(V);
2912 Operator *U = cast<Operator>(V);
2914 case Instruction::Add:
2915 return getAddExpr(getSCEV(U->getOperand(0)),
2916 getSCEV(U->getOperand(1)));
2917 case Instruction::Mul:
2918 return getMulExpr(getSCEV(U->getOperand(0)),
2919 getSCEV(U->getOperand(1)));
2920 case Instruction::UDiv:
2921 return getUDivExpr(getSCEV(U->getOperand(0)),
2922 getSCEV(U->getOperand(1)));
2923 case Instruction::Sub:
2924 return getMinusSCEV(getSCEV(U->getOperand(0)),
2925 getSCEV(U->getOperand(1)));
2926 case Instruction::And:
2927 // For an expression like x&255 that merely masks off the high bits,
2928 // use zext(trunc(x)) as the SCEV expression.
2929 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2930 if (CI->isNullValue())
2931 return getSCEV(U->getOperand(1));
2932 if (CI->isAllOnesValue())
2933 return getSCEV(U->getOperand(0));
2934 const APInt &A = CI->getValue();
2936 // Instcombine's ShrinkDemandedConstant may strip bits out of
2937 // constants, obscuring what would otherwise be a low-bits mask.
2938 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2939 // knew about to reconstruct a low-bits mask value.
2940 unsigned LZ = A.countLeadingZeros();
2941 unsigned BitWidth = A.getBitWidth();
2942 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2943 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2944 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2946 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2948 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2950 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2951 IntegerType::get(getContext(), BitWidth - LZ)),
2956 case Instruction::Or:
2957 // If the RHS of the Or is a constant, we may have something like:
2958 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2959 // optimizations will transparently handle this case.
2961 // In order for this transformation to be safe, the LHS must be of the
2962 // form X*(2^n) and the Or constant must be less than 2^n.
2963 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2964 const SCEV *LHS = getSCEV(U->getOperand(0));
2965 const APInt &CIVal = CI->getValue();
2966 if (GetMinTrailingZeros(LHS) >=
2967 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2968 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2971 case Instruction::Xor:
2972 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2973 // If the RHS of the xor is a signbit, then this is just an add.
2974 // Instcombine turns add of signbit into xor as a strength reduction step.
2975 if (CI->getValue().isSignBit())
2976 return getAddExpr(getSCEV(U->getOperand(0)),
2977 getSCEV(U->getOperand(1)));
2979 // If the RHS of xor is -1, then this is a not operation.
2980 if (CI->isAllOnesValue())
2981 return getNotSCEV(getSCEV(U->getOperand(0)));
2983 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2984 // This is a variant of the check for xor with -1, and it handles
2985 // the case where instcombine has trimmed non-demanded bits out
2986 // of an xor with -1.
2987 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2988 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2989 if (BO->getOpcode() == Instruction::And &&
2990 LCI->getValue() == CI->getValue())
2991 if (const SCEVZeroExtendExpr *Z =
2992 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2993 const Type *UTy = U->getType();
2994 const SCEV *Z0 = Z->getOperand();
2995 const Type *Z0Ty = Z0->getType();
2996 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2998 // If C is a low-bits mask, the zero extend is zerving to
2999 // mask off the high bits. Complement the operand and
3000 // re-apply the zext.
3001 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3002 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3004 // If C is a single bit, it may be in the sign-bit position
3005 // before the zero-extend. In this case, represent the xor
3006 // using an add, which is equivalent, and re-apply the zext.
3007 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3008 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3010 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3016 case Instruction::Shl:
3017 // Turn shift left of a constant amount into a multiply.
3018 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3019 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3020 Constant *X = ConstantInt::get(getContext(),
3021 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3022 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3026 case Instruction::LShr:
3027 // Turn logical shift right of a constant into a unsigned divide.
3028 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3029 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3030 Constant *X = ConstantInt::get(getContext(),
3031 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3032 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3036 case Instruction::AShr:
3037 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3038 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3039 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3040 if (L->getOpcode() == Instruction::Shl &&
3041 L->getOperand(1) == U->getOperand(1)) {
3042 unsigned BitWidth = getTypeSizeInBits(U->getType());
3043 uint64_t Amt = BitWidth - CI->getZExtValue();
3044 if (Amt == BitWidth)
3045 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3047 return getIntegerSCEV(0, U->getType()); // value is undefined
3049 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3050 IntegerType::get(getContext(), Amt)),
3055 case Instruction::Trunc:
3056 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3058 case Instruction::ZExt:
3059 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3061 case Instruction::SExt:
3062 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3064 case Instruction::BitCast:
3065 // BitCasts are no-op casts so we just eliminate the cast.
3066 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3067 return getSCEV(U->getOperand(0));
3070 // It's tempting to handle inttoptr and ptrtoint, however this can
3071 // lead to pointer expressions which cannot be expanded to GEPs
3072 // (because they may overflow). For now, the only pointer-typed
3073 // expressions we handle are GEPs and address literals.
3075 case Instruction::GetElementPtr:
3076 return createNodeForGEP(U);
3078 case Instruction::PHI:
3079 return createNodeForPHI(cast<PHINode>(U));
3081 case Instruction::Select:
3082 // This could be a smax or umax that was lowered earlier.
3083 // Try to recover it.
3084 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3085 Value *LHS = ICI->getOperand(0);
3086 Value *RHS = ICI->getOperand(1);
3087 switch (ICI->getPredicate()) {
3088 case ICmpInst::ICMP_SLT:
3089 case ICmpInst::ICMP_SLE:
3090 std::swap(LHS, RHS);
3092 case ICmpInst::ICMP_SGT:
3093 case ICmpInst::ICMP_SGE:
3094 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3095 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
3096 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3097 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
3099 case ICmpInst::ICMP_ULT:
3100 case ICmpInst::ICMP_ULE:
3101 std::swap(LHS, RHS);
3103 case ICmpInst::ICMP_UGT:
3104 case ICmpInst::ICMP_UGE:
3105 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3106 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
3107 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3108 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
3110 case ICmpInst::ICMP_NE:
3111 // n != 0 ? n : 1 -> umax(n, 1)
3112 if (LHS == U->getOperand(1) &&
3113 isa<ConstantInt>(U->getOperand(2)) &&
3114 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3115 isa<ConstantInt>(RHS) &&
3116 cast<ConstantInt>(RHS)->isZero())
3117 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3119 case ICmpInst::ICMP_EQ:
3120 // n == 0 ? 1 : n -> umax(n, 1)
3121 if (LHS == U->getOperand(2) &&
3122 isa<ConstantInt>(U->getOperand(1)) &&
3123 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3124 isa<ConstantInt>(RHS) &&
3125 cast<ConstantInt>(RHS)->isZero())
3126 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3133 default: // We cannot analyze this expression.
3137 return getUnknown(V);
3142 //===----------------------------------------------------------------------===//
3143 // Iteration Count Computation Code
3146 /// getBackedgeTakenCount - If the specified loop has a predictable
3147 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3148 /// object. The backedge-taken count is the number of times the loop header
3149 /// will be branched to from within the loop. This is one less than the
3150 /// trip count of the loop, since it doesn't count the first iteration,
3151 /// when the header is branched to from outside the loop.
3153 /// Note that it is not valid to call this method on a loop without a
3154 /// loop-invariant backedge-taken count (see
3155 /// hasLoopInvariantBackedgeTakenCount).
3157 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3158 return getBackedgeTakenInfo(L).Exact;
3161 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3162 /// return the least SCEV value that is known never to be less than the
3163 /// actual backedge taken count.
3164 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3165 return getBackedgeTakenInfo(L).Max;
3168 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3169 /// onto the given Worklist.
3171 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3172 BasicBlock *Header = L->getHeader();
3174 // Push all Loop-header PHIs onto the Worklist stack.
3175 for (BasicBlock::iterator I = Header->begin();
3176 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3177 Worklist.push_back(PN);
3180 const ScalarEvolution::BackedgeTakenInfo &
3181 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3182 // Initially insert a CouldNotCompute for this loop. If the insertion
3183 // succeeds, procede to actually compute a backedge-taken count and
3184 // update the value. The temporary CouldNotCompute value tells SCEV
3185 // code elsewhere that it shouldn't attempt to request a new
3186 // backedge-taken count, which could result in infinite recursion.
3187 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
3188 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3190 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
3191 if (ItCount.Exact != getCouldNotCompute()) {
3192 assert(ItCount.Exact->isLoopInvariant(L) &&
3193 ItCount.Max->isLoopInvariant(L) &&
3194 "Computed trip count isn't loop invariant for loop!");
3195 ++NumTripCountsComputed;
3197 // Update the value in the map.
3198 Pair.first->second = ItCount;
3200 if (ItCount.Max != getCouldNotCompute())
3201 // Update the value in the map.
3202 Pair.first->second = ItCount;
3203 if (isa<PHINode>(L->getHeader()->begin()))
3204 // Only count loops that have phi nodes as not being computable.
3205 ++NumTripCountsNotComputed;
3208 // Now that we know more about the trip count for this loop, forget any
3209 // existing SCEV values for PHI nodes in this loop since they are only
3210 // conservative estimates made without the benefit of trip count
3211 // information. This is similar to the code in
3212 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3214 if (ItCount.hasAnyInfo()) {
3215 SmallVector<Instruction *, 16> Worklist;
3216 PushLoopPHIs(L, Worklist);
3218 SmallPtrSet<Instruction *, 8> Visited;
3219 while (!Worklist.empty()) {
3220 Instruction *I = Worklist.pop_back_val();
3221 if (!Visited.insert(I)) continue;
3223 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3224 Scalars.find(static_cast<Value *>(I));
3225 if (It != Scalars.end()) {
3226 // SCEVUnknown for a PHI either means that it has an unrecognized
3227 // structure, or it's a PHI that's in the progress of being computed
3228 // by createNodeForPHI. In the former case, additional loop trip
3229 // count information isn't going to change anything. In the later
3230 // case, createNodeForPHI will perform the necessary updates on its
3231 // own when it gets to that point.
3232 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3234 ValuesAtScopes.erase(I);
3235 if (PHINode *PN = dyn_cast<PHINode>(I))
3236 ConstantEvolutionLoopExitValue.erase(PN);
3239 PushDefUseChildren(I, Worklist);
3243 return Pair.first->second;
3246 /// forgetLoopBackedgeTakenCount - This method should be called by the
3247 /// client when it has changed a loop in a way that may effect
3248 /// ScalarEvolution's ability to compute a trip count, or if the loop
3250 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3251 BackedgeTakenCounts.erase(L);
3253 SmallVector<Instruction *, 16> Worklist;
3254 PushLoopPHIs(L, Worklist);
3256 SmallPtrSet<Instruction *, 8> Visited;
3257 while (!Worklist.empty()) {
3258 Instruction *I = Worklist.pop_back_val();
3259 if (!Visited.insert(I)) continue;
3261 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3262 Scalars.find(static_cast<Value *>(I));
3263 if (It != Scalars.end()) {
3265 ValuesAtScopes.erase(I);
3266 if (PHINode *PN = dyn_cast<PHINode>(I))
3267 ConstantEvolutionLoopExitValue.erase(PN);
3270 PushDefUseChildren(I, Worklist);
3274 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3275 /// of the specified loop will execute.
3276 ScalarEvolution::BackedgeTakenInfo
3277 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3278 SmallVector<BasicBlock*, 8> ExitingBlocks;
3279 L->getExitingBlocks(ExitingBlocks);
3281 // Examine all exits and pick the most conservative values.
3282 const SCEV *BECount = getCouldNotCompute();
3283 const SCEV *MaxBECount = getCouldNotCompute();
3284 bool CouldNotComputeBECount = false;
3285 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3286 BackedgeTakenInfo NewBTI =
3287 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3289 if (NewBTI.Exact == getCouldNotCompute()) {
3290 // We couldn't compute an exact value for this exit, so
3291 // we won't be able to compute an exact value for the loop.
3292 CouldNotComputeBECount = true;
3293 BECount = getCouldNotCompute();
3294 } else if (!CouldNotComputeBECount) {
3295 if (BECount == getCouldNotCompute())
3296 BECount = NewBTI.Exact;
3298 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3300 if (MaxBECount == getCouldNotCompute())
3301 MaxBECount = NewBTI.Max;
3302 else if (NewBTI.Max != getCouldNotCompute())
3303 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3306 return BackedgeTakenInfo(BECount, MaxBECount);
3309 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3310 /// of the specified loop will execute if it exits via the specified block.
3311 ScalarEvolution::BackedgeTakenInfo
3312 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3313 BasicBlock *ExitingBlock) {
3315 // Okay, we've chosen an exiting block. See what condition causes us to
3316 // exit at this block.
3318 // FIXME: we should be able to handle switch instructions (with a single exit)
3319 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3320 if (ExitBr == 0) return getCouldNotCompute();
3321 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3323 // At this point, we know we have a conditional branch that determines whether
3324 // the loop is exited. However, we don't know if the branch is executed each
3325 // time through the loop. If not, then the execution count of the branch will
3326 // not be equal to the trip count of the loop.
3328 // Currently we check for this by checking to see if the Exit branch goes to
3329 // the loop header. If so, we know it will always execute the same number of
3330 // times as the loop. We also handle the case where the exit block *is* the
3331 // loop header. This is common for un-rotated loops.
3333 // If both of those tests fail, walk up the unique predecessor chain to the
3334 // header, stopping if there is an edge that doesn't exit the loop. If the
3335 // header is reached, the execution count of the branch will be equal to the
3336 // trip count of the loop.
3338 // More extensive analysis could be done to handle more cases here.
3340 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3341 ExitBr->getSuccessor(1) != L->getHeader() &&
3342 ExitBr->getParent() != L->getHeader()) {
3343 // The simple checks failed, try climbing the unique predecessor chain
3344 // up to the header.
3346 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3347 BasicBlock *Pred = BB->getUniquePredecessor();
3349 return getCouldNotCompute();
3350 TerminatorInst *PredTerm = Pred->getTerminator();
3351 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3352 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3355 // If the predecessor has a successor that isn't BB and isn't
3356 // outside the loop, assume the worst.
3357 if (L->contains(PredSucc))
3358 return getCouldNotCompute();
3360 if (Pred == L->getHeader()) {
3367 return getCouldNotCompute();
3370 // Procede to the next level to examine the exit condition expression.
3371 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3372 ExitBr->getSuccessor(0),
3373 ExitBr->getSuccessor(1));
3376 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3377 /// backedge of the specified loop will execute if its exit condition
3378 /// were a conditional branch of ExitCond, TBB, and FBB.
3379 ScalarEvolution::BackedgeTakenInfo
3380 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3384 // Check if the controlling expression for this loop is an And or Or.
3385 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3386 if (BO->getOpcode() == Instruction::And) {
3387 // Recurse on the operands of the and.
3388 BackedgeTakenInfo BTI0 =
3389 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3390 BackedgeTakenInfo BTI1 =
3391 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3392 const SCEV *BECount = getCouldNotCompute();
3393 const SCEV *MaxBECount = getCouldNotCompute();
3394 if (L->contains(TBB)) {
3395 // Both conditions must be true for the loop to continue executing.
3396 // Choose the less conservative count.
3397 if (BTI0.Exact == getCouldNotCompute() ||
3398 BTI1.Exact == getCouldNotCompute())
3399 BECount = getCouldNotCompute();
3401 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3402 if (BTI0.Max == getCouldNotCompute())
3403 MaxBECount = BTI1.Max;
3404 else if (BTI1.Max == getCouldNotCompute())
3405 MaxBECount = BTI0.Max;
3407 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3409 // Both conditions must be true for the loop to exit.
3410 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3411 if (BTI0.Exact != getCouldNotCompute() &&
3412 BTI1.Exact != getCouldNotCompute())
3413 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3414 if (BTI0.Max != getCouldNotCompute() &&
3415 BTI1.Max != getCouldNotCompute())
3416 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3419 return BackedgeTakenInfo(BECount, MaxBECount);
3421 if (BO->getOpcode() == Instruction::Or) {
3422 // Recurse on the operands of the or.
3423 BackedgeTakenInfo BTI0 =
3424 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3425 BackedgeTakenInfo BTI1 =
3426 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3427 const SCEV *BECount = getCouldNotCompute();
3428 const SCEV *MaxBECount = getCouldNotCompute();
3429 if (L->contains(FBB)) {
3430 // Both conditions must be false for the loop to continue executing.
3431 // Choose the less conservative count.
3432 if (BTI0.Exact == getCouldNotCompute() ||
3433 BTI1.Exact == getCouldNotCompute())
3434 BECount = getCouldNotCompute();
3436 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3437 if (BTI0.Max == getCouldNotCompute())
3438 MaxBECount = BTI1.Max;
3439 else if (BTI1.Max == getCouldNotCompute())
3440 MaxBECount = BTI0.Max;
3442 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3444 // Both conditions must be false for the loop to exit.
3445 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3446 if (BTI0.Exact != getCouldNotCompute() &&
3447 BTI1.Exact != getCouldNotCompute())
3448 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3449 if (BTI0.Max != getCouldNotCompute() &&
3450 BTI1.Max != getCouldNotCompute())
3451 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3454 return BackedgeTakenInfo(BECount, MaxBECount);
3458 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3459 // Procede to the next level to examine the icmp.
3460 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3461 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3463 // If it's not an integer or pointer comparison then compute it the hard way.
3464 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3467 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3468 /// backedge of the specified loop will execute if its exit condition
3469 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3470 ScalarEvolution::BackedgeTakenInfo
3471 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3476 // If the condition was exit on true, convert the condition to exit on false
3477 ICmpInst::Predicate Cond;
3478 if (!L->contains(FBB))
3479 Cond = ExitCond->getPredicate();
3481 Cond = ExitCond->getInversePredicate();
3483 // Handle common loops like: for (X = "string"; *X; ++X)
3484 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3485 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3487 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3488 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3489 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3490 return BackedgeTakenInfo(ItCnt,
3491 isa<SCEVConstant>(ItCnt) ? ItCnt :
3492 getConstant(APInt::getMaxValue(BitWidth)-1));
3496 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3497 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3499 // Try to evaluate any dependencies out of the loop.
3500 LHS = getSCEVAtScope(LHS, L);
3501 RHS = getSCEVAtScope(RHS, L);
3503 // At this point, we would like to compute how many iterations of the
3504 // loop the predicate will return true for these inputs.
3505 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3506 // If there is a loop-invariant, force it into the RHS.
3507 std::swap(LHS, RHS);
3508 Cond = ICmpInst::getSwappedPredicate(Cond);
3511 // If we have a comparison of a chrec against a constant, try to use value
3512 // ranges to answer this query.
3513 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3514 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3515 if (AddRec->getLoop() == L) {
3516 // Form the constant range.
3517 ConstantRange CompRange(
3518 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3520 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3521 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3525 case ICmpInst::ICMP_NE: { // while (X != Y)
3526 // Convert to: while (X-Y != 0)
3527 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3528 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3531 case ICmpInst::ICMP_EQ: { // while (X == Y)
3532 // Convert to: while (X-Y == 0)
3533 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3534 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3537 case ICmpInst::ICMP_SLT: {
3538 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3539 if (BTI.hasAnyInfo()) return BTI;
3542 case ICmpInst::ICMP_SGT: {
3543 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3544 getNotSCEV(RHS), L, true);
3545 if (BTI.hasAnyInfo()) return BTI;
3548 case ICmpInst::ICMP_ULT: {
3549 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3550 if (BTI.hasAnyInfo()) return BTI;
3553 case ICmpInst::ICMP_UGT: {
3554 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3555 getNotSCEV(RHS), L, false);
3556 if (BTI.hasAnyInfo()) return BTI;
3561 errs() << "ComputeBackedgeTakenCount ";
3562 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3563 errs() << "[unsigned] ";
3564 errs() << *LHS << " "
3565 << Instruction::getOpcodeName(Instruction::ICmp)
3566 << " " << *RHS << "\n";
3571 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3574 static ConstantInt *
3575 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3576 ScalarEvolution &SE) {
3577 const SCEV *InVal = SE.getConstant(C);
3578 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3579 assert(isa<SCEVConstant>(Val) &&
3580 "Evaluation of SCEV at constant didn't fold correctly?");
3581 return cast<SCEVConstant>(Val)->getValue();
3584 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3585 /// and a GEP expression (missing the pointer index) indexing into it, return
3586 /// the addressed element of the initializer or null if the index expression is
3589 GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
3590 const std::vector<ConstantInt*> &Indices) {
3591 Constant *Init = GV->getInitializer();
3592 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3593 uint64_t Idx = Indices[i]->getZExtValue();
3594 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3595 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3596 Init = cast<Constant>(CS->getOperand(Idx));
3597 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3598 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3599 Init = cast<Constant>(CA->getOperand(Idx));
3600 } else if (isa<ConstantAggregateZero>(Init)) {
3601 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3602 assert(Idx < STy->getNumElements() && "Bad struct index!");
3603 Init = Constant::getNullValue(STy->getElementType(Idx));
3604 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3605 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3606 Init = Constant::getNullValue(ATy->getElementType());
3608 llvm_unreachable("Unknown constant aggregate type!");
3612 return 0; // Unknown initializer type
3618 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3619 /// 'icmp op load X, cst', try to see if we can compute the backedge
3620 /// execution count.
3622 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3626 ICmpInst::Predicate predicate) {
3627 if (LI->isVolatile()) return getCouldNotCompute();
3629 // Check to see if the loaded pointer is a getelementptr of a global.
3630 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3631 if (!GEP) return getCouldNotCompute();
3633 // Make sure that it is really a constant global we are gepping, with an
3634 // initializer, and make sure the first IDX is really 0.
3635 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3636 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3637 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3638 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3639 return getCouldNotCompute();
3641 // Okay, we allow one non-constant index into the GEP instruction.
3643 std::vector<ConstantInt*> Indexes;
3644 unsigned VarIdxNum = 0;
3645 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3646 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3647 Indexes.push_back(CI);
3648 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3649 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3650 VarIdx = GEP->getOperand(i);
3652 Indexes.push_back(0);
3655 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3656 // Check to see if X is a loop variant variable value now.
3657 const SCEV *Idx = getSCEV(VarIdx);
3658 Idx = getSCEVAtScope(Idx, L);
3660 // We can only recognize very limited forms of loop index expressions, in
3661 // particular, only affine AddRec's like {C1,+,C2}.
3662 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3663 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3664 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3665 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3666 return getCouldNotCompute();
3668 unsigned MaxSteps = MaxBruteForceIterations;
3669 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3670 ConstantInt *ItCst = ConstantInt::get(
3671 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3672 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3674 // Form the GEP offset.
3675 Indexes[VarIdxNum] = Val;
3677 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
3678 if (Result == 0) break; // Cannot compute!
3680 // Evaluate the condition for this iteration.
3681 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3682 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3683 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3685 errs() << "\n***\n*** Computed loop count " << *ItCst
3686 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3689 ++NumArrayLenItCounts;
3690 return getConstant(ItCst); // Found terminating iteration!
3693 return getCouldNotCompute();
3697 /// CanConstantFold - Return true if we can constant fold an instruction of the
3698 /// specified type, assuming that all operands were constants.
3699 static bool CanConstantFold(const Instruction *I) {
3700 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3701 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3704 if (const CallInst *CI = dyn_cast<CallInst>(I))
3705 if (const Function *F = CI->getCalledFunction())
3706 return canConstantFoldCallTo(F);
3710 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3711 /// in the loop that V is derived from. We allow arbitrary operations along the
3712 /// way, but the operands of an operation must either be constants or a value
3713 /// derived from a constant PHI. If this expression does not fit with these
3714 /// constraints, return null.
3715 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3716 // If this is not an instruction, or if this is an instruction outside of the
3717 // loop, it can't be derived from a loop PHI.
3718 Instruction *I = dyn_cast<Instruction>(V);
3719 if (I == 0 || !L->contains(I->getParent())) return 0;
3721 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3722 if (L->getHeader() == I->getParent())
3725 // We don't currently keep track of the control flow needed to evaluate
3726 // PHIs, so we cannot handle PHIs inside of loops.
3730 // If we won't be able to constant fold this expression even if the operands
3731 // are constants, return early.
3732 if (!CanConstantFold(I)) return 0;
3734 // Otherwise, we can evaluate this instruction if all of its operands are
3735 // constant or derived from a PHI node themselves.
3737 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3738 if (!(isa<Constant>(I->getOperand(Op)) ||
3739 isa<GlobalValue>(I->getOperand(Op)))) {
3740 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3741 if (P == 0) return 0; // Not evolving from PHI
3745 return 0; // Evolving from multiple different PHIs.
3748 // This is a expression evolving from a constant PHI!
3752 /// EvaluateExpression - Given an expression that passes the
3753 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3754 /// in the loop has the value PHIVal. If we can't fold this expression for some
3755 /// reason, return null.
3756 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3757 if (isa<PHINode>(V)) return PHIVal;
3758 if (Constant *C = dyn_cast<Constant>(V)) return C;
3759 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3760 Instruction *I = cast<Instruction>(V);
3761 LLVMContext &Context = I->getParent()->getContext();
3763 std::vector<Constant*> Operands;
3764 Operands.resize(I->getNumOperands());
3766 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3767 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3768 if (Operands[i] == 0) return 0;
3771 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3772 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3773 &Operands[0], Operands.size(),
3776 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3777 &Operands[0], Operands.size(),
3781 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3782 /// in the header of its containing loop, we know the loop executes a
3783 /// constant number of times, and the PHI node is just a recurrence
3784 /// involving constants, fold it.
3786 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3789 std::map<PHINode*, Constant*>::iterator I =
3790 ConstantEvolutionLoopExitValue.find(PN);
3791 if (I != ConstantEvolutionLoopExitValue.end())
3794 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3795 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3797 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3799 // Since the loop is canonicalized, the PHI node must have two entries. One
3800 // entry must be a constant (coming in from outside of the loop), and the
3801 // second must be derived from the same PHI.
3802 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3803 Constant *StartCST =
3804 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3806 return RetVal = 0; // Must be a constant.
3808 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3809 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3811 return RetVal = 0; // Not derived from same PHI.
3813 // Execute the loop symbolically to determine the exit value.
3814 if (BEs.getActiveBits() >= 32)
3815 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3817 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3818 unsigned IterationNum = 0;
3819 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3820 if (IterationNum == NumIterations)
3821 return RetVal = PHIVal; // Got exit value!
3823 // Compute the value of the PHI node for the next iteration.
3824 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3825 if (NextPHI == PHIVal)
3826 return RetVal = NextPHI; // Stopped evolving!
3828 return 0; // Couldn't evaluate!
3833 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
3834 /// constant number of times (the condition evolves only from constants),
3835 /// try to evaluate a few iterations of the loop until we get the exit
3836 /// condition gets a value of ExitWhen (true or false). If we cannot
3837 /// evaluate the trip count of the loop, return getCouldNotCompute().
3839 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3842 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3843 if (PN == 0) return getCouldNotCompute();
3845 // Since the loop is canonicalized, the PHI node must have two entries. One
3846 // entry must be a constant (coming in from outside of the loop), and the
3847 // second must be derived from the same PHI.
3848 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3849 Constant *StartCST =
3850 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3851 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3853 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3854 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3855 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3857 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3858 // the loop symbolically to determine when the condition gets a value of
3860 unsigned IterationNum = 0;
3861 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3862 for (Constant *PHIVal = StartCST;
3863 IterationNum != MaxIterations; ++IterationNum) {
3864 ConstantInt *CondVal =
3865 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3867 // Couldn't symbolically evaluate.
3868 if (!CondVal) return getCouldNotCompute();
3870 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3871 ++NumBruteForceTripCountsComputed;
3872 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
3875 // Compute the value of the PHI node for the next iteration.
3876 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3877 if (NextPHI == 0 || NextPHI == PHIVal)
3878 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3882 // Too many iterations were needed to evaluate.
3883 return getCouldNotCompute();
3886 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3887 /// at the specified scope in the program. The L value specifies a loop
3888 /// nest to evaluate the expression at, where null is the top-level or a
3889 /// specified loop is immediately inside of the loop.
3891 /// This method can be used to compute the exit value for a variable defined
3892 /// in a loop by querying what the value will hold in the parent loop.
3894 /// In the case that a relevant loop exit value cannot be computed, the
3895 /// original value V is returned.
3896 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3897 // FIXME: this should be turned into a virtual method on SCEV!
3899 if (isa<SCEVConstant>(V)) return V;
3901 // If this instruction is evolved from a constant-evolving PHI, compute the
3902 // exit value from the loop without using SCEVs.
3903 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3904 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3905 const Loop *LI = (*this->LI)[I->getParent()];
3906 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3907 if (PHINode *PN = dyn_cast<PHINode>(I))
3908 if (PN->getParent() == LI->getHeader()) {
3909 // Okay, there is no closed form solution for the PHI node. Check
3910 // to see if the loop that contains it has a known backedge-taken
3911 // count. If so, we may be able to force computation of the exit
3913 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3914 if (const SCEVConstant *BTCC =
3915 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3916 // Okay, we know how many times the containing loop executes. If
3917 // this is a constant evolving PHI node, get the final value at
3918 // the specified iteration number.
3919 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3920 BTCC->getValue()->getValue(),
3922 if (RV) return getSCEV(RV);
3926 // Okay, this is an expression that we cannot symbolically evaluate
3927 // into a SCEV. Check to see if it's possible to symbolically evaluate
3928 // the arguments into constants, and if so, try to constant propagate the
3929 // result. This is particularly useful for computing loop exit values.
3930 if (CanConstantFold(I)) {
3931 // Check to see if we've folded this instruction at this loop before.
3932 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3933 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3934 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3936 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3938 std::vector<Constant*> Operands;
3939 Operands.reserve(I->getNumOperands());
3940 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3941 Value *Op = I->getOperand(i);
3942 if (Constant *C = dyn_cast<Constant>(Op)) {
3943 Operands.push_back(C);
3945 // If any of the operands is non-constant and if they are
3946 // non-integer and non-pointer, don't even try to analyze them
3947 // with scev techniques.
3948 if (!isSCEVable(Op->getType()))
3951 const SCEV* OpV = getSCEVAtScope(Op, L);
3952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3953 Constant *C = SC->getValue();
3954 if (C->getType() != Op->getType())
3955 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3959 Operands.push_back(C);
3960 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3961 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3962 if (C->getType() != Op->getType())
3964 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3968 Operands.push_back(C);
3978 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3979 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3980 &Operands[0], Operands.size(),
3983 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3984 &Operands[0], Operands.size(),
3986 Pair.first->second = C;
3991 // This is some other type of SCEVUnknown, just return it.
3995 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3996 // Avoid performing the look-up in the common case where the specified
3997 // expression has no loop-variant portions.
3998 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3999 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4000 if (OpAtScope != Comm->getOperand(i)) {
4001 // Okay, at least one of these operands is loop variant but might be
4002 // foldable. Build a new instance of the folded commutative expression.
4003 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4004 Comm->op_begin()+i);
4005 NewOps.push_back(OpAtScope);
4007 for (++i; i != e; ++i) {
4008 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4009 NewOps.push_back(OpAtScope);
4011 if (isa<SCEVAddExpr>(Comm))
4012 return getAddExpr(NewOps);
4013 if (isa<SCEVMulExpr>(Comm))
4014 return getMulExpr(NewOps);
4015 if (isa<SCEVSMaxExpr>(Comm))
4016 return getSMaxExpr(NewOps);
4017 if (isa<SCEVUMaxExpr>(Comm))
4018 return getUMaxExpr(NewOps);
4019 llvm_unreachable("Unknown commutative SCEV type!");
4022 // If we got here, all operands are loop invariant.
4026 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4027 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4028 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4029 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4030 return Div; // must be loop invariant
4031 return getUDivExpr(LHS, RHS);
4034 // If this is a loop recurrence for a loop that does not contain L, then we
4035 // are dealing with the final value computed by the loop.
4036 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4037 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4038 // To evaluate this recurrence, we need to know how many times the AddRec
4039 // loop iterates. Compute this now.
4040 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4041 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4043 // Then, evaluate the AddRec.
4044 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4049 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4050 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4051 if (Op == Cast->getOperand())
4052 return Cast; // must be loop invariant
4053 return getZeroExtendExpr(Op, Cast->getType());
4056 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4057 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4058 if (Op == Cast->getOperand())
4059 return Cast; // must be loop invariant
4060 return getSignExtendExpr(Op, Cast->getType());
4063 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4064 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4065 if (Op == Cast->getOperand())
4066 return Cast; // must be loop invariant
4067 return getTruncateExpr(Op, Cast->getType());
4070 if (isa<SCEVTargetDataConstant>(V))
4073 llvm_unreachable("Unknown SCEV type!");
4077 /// getSCEVAtScope - This is a convenience function which does
4078 /// getSCEVAtScope(getSCEV(V), L).
4079 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4080 return getSCEVAtScope(getSCEV(V), L);
4083 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4084 /// following equation:
4086 /// A * X = B (mod N)
4088 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4089 /// A and B isn't important.
4091 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4092 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4093 ScalarEvolution &SE) {
4094 uint32_t BW = A.getBitWidth();
4095 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4096 assert(A != 0 && "A must be non-zero.");
4100 // The gcd of A and N may have only one prime factor: 2. The number of
4101 // trailing zeros in A is its multiplicity
4102 uint32_t Mult2 = A.countTrailingZeros();
4105 // 2. Check if B is divisible by D.
4107 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4108 // is not less than multiplicity of this prime factor for D.
4109 if (B.countTrailingZeros() < Mult2)
4110 return SE.getCouldNotCompute();
4112 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4115 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4116 // bit width during computations.
4117 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4118 APInt Mod(BW + 1, 0);
4119 Mod.set(BW - Mult2); // Mod = N / D
4120 APInt I = AD.multiplicativeInverse(Mod);
4122 // 4. Compute the minimum unsigned root of the equation:
4123 // I * (B / D) mod (N / D)
4124 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4126 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4128 return SE.getConstant(Result.trunc(BW));
4131 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4132 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4133 /// might be the same) or two SCEVCouldNotCompute objects.
4135 static std::pair<const SCEV *,const SCEV *>
4136 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4137 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4138 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4139 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4140 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4142 // We currently can only solve this if the coefficients are constants.
4143 if (!LC || !MC || !NC) {
4144 const SCEV *CNC = SE.getCouldNotCompute();
4145 return std::make_pair(CNC, CNC);
4148 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4149 const APInt &L = LC->getValue()->getValue();
4150 const APInt &M = MC->getValue()->getValue();
4151 const APInt &N = NC->getValue()->getValue();
4152 APInt Two(BitWidth, 2);
4153 APInt Four(BitWidth, 4);
4156 using namespace APIntOps;
4158 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4159 // The B coefficient is M-N/2
4163 // The A coefficient is N/2
4164 APInt A(N.sdiv(Two));
4166 // Compute the B^2-4ac term.
4169 SqrtTerm -= Four * (A * C);
4171 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4172 // integer value or else APInt::sqrt() will assert.
4173 APInt SqrtVal(SqrtTerm.sqrt());
4175 // Compute the two solutions for the quadratic formula.
4176 // The divisions must be performed as signed divisions.
4178 APInt TwoA( A << 1 );
4179 if (TwoA.isMinValue()) {
4180 const SCEV *CNC = SE.getCouldNotCompute();
4181 return std::make_pair(CNC, CNC);
4184 LLVMContext &Context = SE.getContext();
4186 ConstantInt *Solution1 =
4187 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4188 ConstantInt *Solution2 =
4189 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4191 return std::make_pair(SE.getConstant(Solution1),
4192 SE.getConstant(Solution2));
4193 } // end APIntOps namespace
4196 /// HowFarToZero - Return the number of times a backedge comparing the specified
4197 /// value to zero will execute. If not computable, return CouldNotCompute.
4198 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4199 // If the value is a constant
4200 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4201 // If the value is already zero, the branch will execute zero times.
4202 if (C->getValue()->isZero()) return C;
4203 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4206 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4207 if (!AddRec || AddRec->getLoop() != L)
4208 return getCouldNotCompute();
4210 if (AddRec->isAffine()) {
4211 // If this is an affine expression, the execution count of this branch is
4212 // the minimum unsigned root of the following equation:
4214 // Start + Step*N = 0 (mod 2^BW)
4218 // Step*N = -Start (mod 2^BW)
4220 // where BW is the common bit width of Start and Step.
4222 // Get the initial value for the loop.
4223 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4224 L->getParentLoop());
4225 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4226 L->getParentLoop());
4228 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4229 // For now we handle only constant steps.
4231 // First, handle unitary steps.
4232 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4233 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4234 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4235 return Start; // N = Start (as unsigned)
4237 // Then, try to solve the above equation provided that Start is constant.
4238 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4239 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4240 -StartC->getValue()->getValue(),
4243 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4244 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4245 // the quadratic equation to solve it.
4246 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4248 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4249 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4252 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4253 << " sol#2: " << *R2 << "\n";
4255 // Pick the smallest positive root value.
4256 if (ConstantInt *CB =
4257 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4258 R1->getValue(), R2->getValue()))) {
4259 if (CB->getZExtValue() == false)
4260 std::swap(R1, R2); // R1 is the minimum root now.
4262 // We can only use this value if the chrec ends up with an exact zero
4263 // value at this index. When solving for "X*X != 5", for example, we
4264 // should not accept a root of 2.
4265 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4267 return R1; // We found a quadratic root!
4272 return getCouldNotCompute();
4275 /// HowFarToNonZero - Return the number of times a backedge checking the
4276 /// specified value for nonzero will execute. If not computable, return
4278 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4279 // Loops that look like: while (X == 0) are very strange indeed. We don't
4280 // handle them yet except for the trivial case. This could be expanded in the
4281 // future as needed.
4283 // If the value is a constant, check to see if it is known to be non-zero
4284 // already. If so, the backedge will execute zero times.
4285 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4286 if (!C->getValue()->isNullValue())
4287 return getIntegerSCEV(0, C->getType());
4288 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4291 // We could implement others, but I really doubt anyone writes loops like
4292 // this, and if they did, they would already be constant folded.
4293 return getCouldNotCompute();
4296 /// getLoopPredecessor - If the given loop's header has exactly one unique
4297 /// predecessor outside the loop, return it. Otherwise return null.
4299 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4300 BasicBlock *Header = L->getHeader();
4301 BasicBlock *Pred = 0;
4302 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4304 if (!L->contains(*PI)) {
4305 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4311 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4312 /// (which may not be an immediate predecessor) which has exactly one
4313 /// successor from which BB is reachable, or null if no such block is
4317 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4318 // If the block has a unique predecessor, then there is no path from the
4319 // predecessor to the block that does not go through the direct edge
4320 // from the predecessor to the block.
4321 if (BasicBlock *Pred = BB->getSinglePredecessor())
4324 // A loop's header is defined to be a block that dominates the loop.
4325 // If the header has a unique predecessor outside the loop, it must be
4326 // a block that has exactly one successor that can reach the loop.
4327 if (Loop *L = LI->getLoopFor(BB))
4328 return getLoopPredecessor(L);
4333 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4334 /// testing whether two expressions are equal, however for the purposes of
4335 /// looking for a condition guarding a loop, it can be useful to be a little
4336 /// more general, since a front-end may have replicated the controlling
4339 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4340 // Quick check to see if they are the same SCEV.
4341 if (A == B) return true;
4343 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4344 // two different instructions with the same value. Check for this case.
4345 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4346 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4347 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4348 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4349 if (AI->isIdenticalTo(BI))
4352 // Otherwise assume they may have a different value.
4356 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4357 return getSignedRange(S).getSignedMax().isNegative();
4360 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4361 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4364 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4365 return !getSignedRange(S).getSignedMin().isNegative();
4368 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4369 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4372 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4373 return isKnownNegative(S) || isKnownPositive(S);
4376 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4377 const SCEV *LHS, const SCEV *RHS) {
4379 if (HasSameValue(LHS, RHS))
4380 return ICmpInst::isTrueWhenEqual(Pred);
4384 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4386 case ICmpInst::ICMP_SGT:
4387 Pred = ICmpInst::ICMP_SLT;
4388 std::swap(LHS, RHS);
4389 case ICmpInst::ICMP_SLT: {
4390 ConstantRange LHSRange = getSignedRange(LHS);
4391 ConstantRange RHSRange = getSignedRange(RHS);
4392 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4394 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4398 case ICmpInst::ICMP_SGE:
4399 Pred = ICmpInst::ICMP_SLE;
4400 std::swap(LHS, RHS);
4401 case ICmpInst::ICMP_SLE: {
4402 ConstantRange LHSRange = getSignedRange(LHS);
4403 ConstantRange RHSRange = getSignedRange(RHS);
4404 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4406 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4410 case ICmpInst::ICMP_UGT:
4411 Pred = ICmpInst::ICMP_ULT;
4412 std::swap(LHS, RHS);
4413 case ICmpInst::ICMP_ULT: {
4414 ConstantRange LHSRange = getUnsignedRange(LHS);
4415 ConstantRange RHSRange = getUnsignedRange(RHS);
4416 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4418 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4422 case ICmpInst::ICMP_UGE:
4423 Pred = ICmpInst::ICMP_ULE;
4424 std::swap(LHS, RHS);
4425 case ICmpInst::ICMP_ULE: {
4426 ConstantRange LHSRange = getUnsignedRange(LHS);
4427 ConstantRange RHSRange = getUnsignedRange(RHS);
4428 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4430 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4434 case ICmpInst::ICMP_NE: {
4435 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4437 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4440 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4441 if (isKnownNonZero(Diff))
4445 case ICmpInst::ICMP_EQ:
4446 // The check at the top of the function catches the case where
4447 // the values are known to be equal.
4453 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4454 /// protected by a conditional between LHS and RHS. This is used to
4455 /// to eliminate casts.
4457 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4458 ICmpInst::Predicate Pred,
4459 const SCEV *LHS, const SCEV *RHS) {
4460 // Interpret a null as meaning no loop, where there is obviously no guard
4461 // (interprocedural conditions notwithstanding).
4462 if (!L) return true;
4464 BasicBlock *Latch = L->getLoopLatch();
4468 BranchInst *LoopContinuePredicate =
4469 dyn_cast<BranchInst>(Latch->getTerminator());
4470 if (!LoopContinuePredicate ||
4471 LoopContinuePredicate->isUnconditional())
4474 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4475 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4478 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4479 /// by a conditional between LHS and RHS. This is used to help avoid max
4480 /// expressions in loop trip counts, and to eliminate casts.
4482 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4483 ICmpInst::Predicate Pred,
4484 const SCEV *LHS, const SCEV *RHS) {
4485 // Interpret a null as meaning no loop, where there is obviously no guard
4486 // (interprocedural conditions notwithstanding).
4487 if (!L) return false;
4489 BasicBlock *Predecessor = getLoopPredecessor(L);
4490 BasicBlock *PredecessorDest = L->getHeader();
4492 // Starting at the loop predecessor, climb up the predecessor chain, as long
4493 // as there are predecessors that can be found that have unique successors
4494 // leading to the original header.
4496 PredecessorDest = Predecessor,
4497 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4499 BranchInst *LoopEntryPredicate =
4500 dyn_cast<BranchInst>(Predecessor->getTerminator());
4501 if (!LoopEntryPredicate ||
4502 LoopEntryPredicate->isUnconditional())
4505 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4506 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4513 /// isImpliedCond - Test whether the condition described by Pred, LHS,
4514 /// and RHS is true whenever the given Cond value evaluates to true.
4515 bool ScalarEvolution::isImpliedCond(Value *CondValue,
4516 ICmpInst::Predicate Pred,
4517 const SCEV *LHS, const SCEV *RHS,
4519 // Recursivly handle And and Or conditions.
4520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4521 if (BO->getOpcode() == Instruction::And) {
4523 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4524 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4525 } else if (BO->getOpcode() == Instruction::Or) {
4527 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4528 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4532 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4533 if (!ICI) return false;
4535 // Bail if the ICmp's operands' types are wider than the needed type
4536 // before attempting to call getSCEV on them. This avoids infinite
4537 // recursion, since the analysis of widening casts can require loop
4538 // exit condition information for overflow checking, which would
4540 if (getTypeSizeInBits(LHS->getType()) <
4541 getTypeSizeInBits(ICI->getOperand(0)->getType()))
4544 // Now that we found a conditional branch that dominates the loop, check to
4545 // see if it is the comparison we are looking for.
4546 ICmpInst::Predicate FoundPred;
4548 FoundPred = ICI->getInversePredicate();
4550 FoundPred = ICI->getPredicate();
4552 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4553 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
4555 // Balance the types. The case where FoundLHS' type is wider than
4556 // LHS' type is checked for above.
4557 if (getTypeSizeInBits(LHS->getType()) >
4558 getTypeSizeInBits(FoundLHS->getType())) {
4559 if (CmpInst::isSigned(Pred)) {
4560 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4561 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4563 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4564 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4568 // Canonicalize the query to match the way instcombine will have
4569 // canonicalized the comparison.
4570 // First, put a constant operand on the right.
4571 if (isa<SCEVConstant>(LHS)) {
4572 std::swap(LHS, RHS);
4573 Pred = ICmpInst::getSwappedPredicate(Pred);
4575 // Then, canonicalize comparisons with boundary cases.
4576 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4577 const APInt &RA = RC->getValue()->getValue();
4579 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4580 case ICmpInst::ICMP_EQ:
4581 case ICmpInst::ICMP_NE:
4583 case ICmpInst::ICMP_UGE:
4584 if ((RA - 1).isMinValue()) {
4585 Pred = ICmpInst::ICMP_NE;
4586 RHS = getConstant(RA - 1);
4589 if (RA.isMaxValue()) {
4590 Pred = ICmpInst::ICMP_EQ;
4593 if (RA.isMinValue()) return true;
4595 case ICmpInst::ICMP_ULE:
4596 if ((RA + 1).isMaxValue()) {
4597 Pred = ICmpInst::ICMP_NE;
4598 RHS = getConstant(RA + 1);
4601 if (RA.isMinValue()) {
4602 Pred = ICmpInst::ICMP_EQ;
4605 if (RA.isMaxValue()) return true;
4607 case ICmpInst::ICMP_SGE:
4608 if ((RA - 1).isMinSignedValue()) {
4609 Pred = ICmpInst::ICMP_NE;
4610 RHS = getConstant(RA - 1);
4613 if (RA.isMaxSignedValue()) {
4614 Pred = ICmpInst::ICMP_EQ;
4617 if (RA.isMinSignedValue()) return true;
4619 case ICmpInst::ICMP_SLE:
4620 if ((RA + 1).isMaxSignedValue()) {
4621 Pred = ICmpInst::ICMP_NE;
4622 RHS = getConstant(RA + 1);
4625 if (RA.isMinSignedValue()) {
4626 Pred = ICmpInst::ICMP_EQ;
4629 if (RA.isMaxSignedValue()) return true;
4631 case ICmpInst::ICMP_UGT:
4632 if (RA.isMinValue()) {
4633 Pred = ICmpInst::ICMP_NE;
4636 if ((RA + 1).isMaxValue()) {
4637 Pred = ICmpInst::ICMP_EQ;
4638 RHS = getConstant(RA + 1);
4641 if (RA.isMaxValue()) return false;
4643 case ICmpInst::ICMP_ULT:
4644 if (RA.isMaxValue()) {
4645 Pred = ICmpInst::ICMP_NE;
4648 if ((RA - 1).isMinValue()) {
4649 Pred = ICmpInst::ICMP_EQ;
4650 RHS = getConstant(RA - 1);
4653 if (RA.isMinValue()) return false;
4655 case ICmpInst::ICMP_SGT:
4656 if (RA.isMinSignedValue()) {
4657 Pred = ICmpInst::ICMP_NE;
4660 if ((RA + 1).isMaxSignedValue()) {
4661 Pred = ICmpInst::ICMP_EQ;
4662 RHS = getConstant(RA + 1);
4665 if (RA.isMaxSignedValue()) return false;
4667 case ICmpInst::ICMP_SLT:
4668 if (RA.isMaxSignedValue()) {
4669 Pred = ICmpInst::ICMP_NE;
4672 if ((RA - 1).isMinSignedValue()) {
4673 Pred = ICmpInst::ICMP_EQ;
4674 RHS = getConstant(RA - 1);
4677 if (RA.isMinSignedValue()) return false;
4682 // Check to see if we can make the LHS or RHS match.
4683 if (LHS == FoundRHS || RHS == FoundLHS) {
4684 if (isa<SCEVConstant>(RHS)) {
4685 std::swap(FoundLHS, FoundRHS);
4686 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4688 std::swap(LHS, RHS);
4689 Pred = ICmpInst::getSwappedPredicate(Pred);
4693 // Check whether the found predicate is the same as the desired predicate.
4694 if (FoundPred == Pred)
4695 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4697 // Check whether swapping the found predicate makes it the same as the
4698 // desired predicate.
4699 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4700 if (isa<SCEVConstant>(RHS))
4701 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4703 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4704 RHS, LHS, FoundLHS, FoundRHS);
4707 // Check whether the actual condition is beyond sufficient.
4708 if (FoundPred == ICmpInst::ICMP_EQ)
4709 if (ICmpInst::isTrueWhenEqual(Pred))
4710 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4712 if (Pred == ICmpInst::ICMP_NE)
4713 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4714 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4717 // Otherwise assume the worst.
4721 /// isImpliedCondOperands - Test whether the condition described by Pred,
4722 /// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4723 /// and FoundRHS is true.
4724 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4725 const SCEV *LHS, const SCEV *RHS,
4726 const SCEV *FoundLHS,
4727 const SCEV *FoundRHS) {
4728 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4729 FoundLHS, FoundRHS) ||
4730 // ~x < ~y --> x > y
4731 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4732 getNotSCEV(FoundRHS),
4733 getNotSCEV(FoundLHS));
4736 /// isImpliedCondOperandsHelper - Test whether the condition described by
4737 /// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4738 /// FoundLHS, and FoundRHS is true.
4740 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4741 const SCEV *LHS, const SCEV *RHS,
4742 const SCEV *FoundLHS,
4743 const SCEV *FoundRHS) {
4745 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4746 case ICmpInst::ICMP_EQ:
4747 case ICmpInst::ICMP_NE:
4748 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4751 case ICmpInst::ICMP_SLT:
4752 case ICmpInst::ICMP_SLE:
4753 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4754 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4757 case ICmpInst::ICMP_SGT:
4758 case ICmpInst::ICMP_SGE:
4759 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4760 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4763 case ICmpInst::ICMP_ULT:
4764 case ICmpInst::ICMP_ULE:
4765 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4766 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4769 case ICmpInst::ICMP_UGT:
4770 case ICmpInst::ICMP_UGE:
4771 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4772 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4780 /// getBECount - Subtract the end and start values and divide by the step,
4781 /// rounding up, to get the number of times the backedge is executed. Return
4782 /// CouldNotCompute if an intermediate computation overflows.
4783 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4786 const Type *Ty = Start->getType();
4787 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4788 const SCEV *Diff = getMinusSCEV(End, Start);
4789 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4791 // Add an adjustment to the difference between End and Start so that
4792 // the division will effectively round up.
4793 const SCEV *Add = getAddExpr(Diff, RoundUp);
4795 // Check Add for unsigned overflow.
4796 // TODO: More sophisticated things could be done here.
4797 const Type *WideTy = IntegerType::get(getContext(),
4798 getTypeSizeInBits(Ty) + 1);
4799 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4800 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4801 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4802 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4803 return getCouldNotCompute();
4805 return getUDivExpr(Add, Step);
4808 /// HowManyLessThans - Return the number of times a backedge containing the
4809 /// specified less-than comparison will execute. If not computable, return
4810 /// CouldNotCompute.
4811 ScalarEvolution::BackedgeTakenInfo
4812 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4813 const Loop *L, bool isSigned) {
4814 // Only handle: "ADDREC < LoopInvariant".
4815 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4817 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4818 if (!AddRec || AddRec->getLoop() != L)
4819 return getCouldNotCompute();
4821 if (AddRec->isAffine()) {
4822 // FORNOW: We only support unit strides.
4823 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4824 const SCEV *Step = AddRec->getStepRecurrence(*this);
4826 // TODO: handle non-constant strides.
4827 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4828 if (!CStep || CStep->isZero())
4829 return getCouldNotCompute();
4830 if (CStep->isOne()) {
4831 // With unit stride, the iteration never steps past the limit value.
4832 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4833 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4834 // Test whether a positive iteration iteration can step past the limit
4835 // value and past the maximum value for its type in a single step.
4837 APInt Max = APInt::getSignedMaxValue(BitWidth);
4838 if ((Max - CStep->getValue()->getValue())
4839 .slt(CLimit->getValue()->getValue()))
4840 return getCouldNotCompute();
4842 APInt Max = APInt::getMaxValue(BitWidth);
4843 if ((Max - CStep->getValue()->getValue())
4844 .ult(CLimit->getValue()->getValue()))
4845 return getCouldNotCompute();
4848 // TODO: handle non-constant limit values below.
4849 return getCouldNotCompute();
4851 // TODO: handle negative strides below.
4852 return getCouldNotCompute();
4854 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4855 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4856 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4857 // treat m-n as signed nor unsigned due to overflow possibility.
4859 // First, we get the value of the LHS in the first iteration: n
4860 const SCEV *Start = AddRec->getOperand(0);
4862 // Determine the minimum constant start value.
4863 const SCEV *MinStart = getConstant(isSigned ?
4864 getSignedRange(Start).getSignedMin() :
4865 getUnsignedRange(Start).getUnsignedMin());
4867 // If we know that the condition is true in order to enter the loop,
4868 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4869 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4870 // the division must round up.
4871 const SCEV *End = RHS;
4872 if (!isLoopGuardedByCond(L,
4873 isSigned ? ICmpInst::ICMP_SLT :
4875 getMinusSCEV(Start, Step), RHS))
4876 End = isSigned ? getSMaxExpr(RHS, Start)
4877 : getUMaxExpr(RHS, Start);
4879 // Determine the maximum constant end value.
4880 const SCEV *MaxEnd = getConstant(isSigned ?
4881 getSignedRange(End).getSignedMax() :
4882 getUnsignedRange(End).getUnsignedMax());
4884 // Finally, we subtract these two values and divide, rounding up, to get
4885 // the number of times the backedge is executed.
4886 const SCEV *BECount = getBECount(Start, End, Step);
4888 // The maximum backedge count is similar, except using the minimum start
4889 // value and the maximum end value.
4890 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
4892 return BackedgeTakenInfo(BECount, MaxBECount);
4895 return getCouldNotCompute();
4898 /// getNumIterationsInRange - Return the number of iterations of this loop that
4899 /// produce values in the specified constant range. Another way of looking at
4900 /// this is that it returns the first iteration number where the value is not in
4901 /// the condition, thus computing the exit count. If the iteration count can't
4902 /// be computed, an instance of SCEVCouldNotCompute is returned.
4903 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4904 ScalarEvolution &SE) const {
4905 if (Range.isFullSet()) // Infinite loop.
4906 return SE.getCouldNotCompute();
4908 // If the start is a non-zero constant, shift the range to simplify things.
4909 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4910 if (!SC->getValue()->isZero()) {
4911 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4912 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4913 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4914 if (const SCEVAddRecExpr *ShiftedAddRec =
4915 dyn_cast<SCEVAddRecExpr>(Shifted))
4916 return ShiftedAddRec->getNumIterationsInRange(
4917 Range.subtract(SC->getValue()->getValue()), SE);
4918 // This is strange and shouldn't happen.
4919 return SE.getCouldNotCompute();
4922 // The only time we can solve this is when we have all constant indices.
4923 // Otherwise, we cannot determine the overflow conditions.
4924 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4925 if (!isa<SCEVConstant>(getOperand(i)))
4926 return SE.getCouldNotCompute();
4929 // Okay at this point we know that all elements of the chrec are constants and
4930 // that the start element is zero.
4932 // First check to see if the range contains zero. If not, the first
4934 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4935 if (!Range.contains(APInt(BitWidth, 0)))
4936 return SE.getIntegerSCEV(0, getType());
4939 // If this is an affine expression then we have this situation:
4940 // Solve {0,+,A} in Range === Ax in Range
4942 // We know that zero is in the range. If A is positive then we know that
4943 // the upper value of the range must be the first possible exit value.
4944 // If A is negative then the lower of the range is the last possible loop
4945 // value. Also note that we already checked for a full range.
4946 APInt One(BitWidth,1);
4947 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4948 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4950 // The exit value should be (End+A)/A.
4951 APInt ExitVal = (End + A).udiv(A);
4952 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
4954 // Evaluate at the exit value. If we really did fall out of the valid
4955 // range, then we computed our trip count, otherwise wrap around or other
4956 // things must have happened.
4957 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4958 if (Range.contains(Val->getValue()))
4959 return SE.getCouldNotCompute(); // Something strange happened
4961 // Ensure that the previous value is in the range. This is a sanity check.
4962 assert(Range.contains(
4963 EvaluateConstantChrecAtConstant(this,
4964 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
4965 "Linear scev computation is off in a bad way!");
4966 return SE.getConstant(ExitValue);
4967 } else if (isQuadratic()) {
4968 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4969 // quadratic equation to solve it. To do this, we must frame our problem in
4970 // terms of figuring out when zero is crossed, instead of when
4971 // Range.getUpper() is crossed.
4972 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
4973 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4974 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4976 // Next, solve the constructed addrec
4977 std::pair<const SCEV *,const SCEV *> Roots =
4978 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4979 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4980 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4982 // Pick the smallest positive root value.
4983 if (ConstantInt *CB =
4984 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4985 R1->getValue(), R2->getValue()))) {
4986 if (CB->getZExtValue() == false)
4987 std::swap(R1, R2); // R1 is the minimum root now.
4989 // Make sure the root is not off by one. The returned iteration should
4990 // not be in the range, but the previous one should be. When solving
4991 // for "X*X < 5", for example, we should not return a root of 2.
4992 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4995 if (Range.contains(R1Val->getValue())) {
4996 // The next iteration must be out of the range...
4997 ConstantInt *NextVal =
4998 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5000 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5001 if (!Range.contains(R1Val->getValue()))
5002 return SE.getConstant(NextVal);
5003 return SE.getCouldNotCompute(); // Something strange happened
5006 // If R1 was not in the range, then it is a good return value. Make
5007 // sure that R1-1 WAS in the range though, just in case.
5008 ConstantInt *NextVal =
5009 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5010 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5011 if (Range.contains(R1Val->getValue()))
5013 return SE.getCouldNotCompute(); // Something strange happened
5018 return SE.getCouldNotCompute();
5023 //===----------------------------------------------------------------------===//
5024 // SCEVCallbackVH Class Implementation
5025 //===----------------------------------------------------------------------===//
5027 void ScalarEvolution::SCEVCallbackVH::deleted() {
5028 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5029 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5030 SE->ConstantEvolutionLoopExitValue.erase(PN);
5031 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
5032 SE->ValuesAtScopes.erase(I);
5033 SE->Scalars.erase(getValPtr());
5034 // this now dangles!
5037 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5038 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5040 // Forget all the expressions associated with users of the old value,
5041 // so that future queries will recompute the expressions using the new
5043 SmallVector<User *, 16> Worklist;
5044 SmallPtrSet<User *, 8> Visited;
5045 Value *Old = getValPtr();
5046 bool DeleteOld = false;
5047 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5049 Worklist.push_back(*UI);
5050 while (!Worklist.empty()) {
5051 User *U = Worklist.pop_back_val();
5052 // Deleting the Old value will cause this to dangle. Postpone
5053 // that until everything else is done.
5058 if (!Visited.insert(U))
5060 if (PHINode *PN = dyn_cast<PHINode>(U))
5061 SE->ConstantEvolutionLoopExitValue.erase(PN);
5062 if (Instruction *I = dyn_cast<Instruction>(U))
5063 SE->ValuesAtScopes.erase(I);
5064 SE->Scalars.erase(U);
5065 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5067 Worklist.push_back(*UI);
5069 // Delete the Old value if it (indirectly) references itself.
5071 if (PHINode *PN = dyn_cast<PHINode>(Old))
5072 SE->ConstantEvolutionLoopExitValue.erase(PN);
5073 if (Instruction *I = dyn_cast<Instruction>(Old))
5074 SE->ValuesAtScopes.erase(I);
5075 SE->Scalars.erase(Old);
5076 // this now dangles!
5081 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5082 : CallbackVH(V), SE(se) {}
5084 //===----------------------------------------------------------------------===//
5085 // ScalarEvolution Class Implementation
5086 //===----------------------------------------------------------------------===//
5088 ScalarEvolution::ScalarEvolution()
5089 : FunctionPass(&ID) {
5092 bool ScalarEvolution::runOnFunction(Function &F) {
5094 LI = &getAnalysis<LoopInfo>();
5095 TD = getAnalysisIfAvailable<TargetData>();
5099 void ScalarEvolution::releaseMemory() {
5101 BackedgeTakenCounts.clear();
5102 ConstantEvolutionLoopExitValue.clear();
5103 ValuesAtScopes.clear();
5104 UniqueSCEVs.clear();
5105 SCEVAllocator.Reset();
5108 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5109 AU.setPreservesAll();
5110 AU.addRequiredTransitive<LoopInfo>();
5113 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5114 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5117 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5119 // Print all inner loops first
5120 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5121 PrintLoopInfo(OS, SE, *I);
5123 OS << "Loop " << L->getHeader()->getName() << ": ";
5125 SmallVector<BasicBlock*, 8> ExitBlocks;
5126 L->getExitBlocks(ExitBlocks);
5127 if (ExitBlocks.size() != 1)
5128 OS << "<multiple exits> ";
5130 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5131 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5133 OS << "Unpredictable backedge-taken count. ";
5137 OS << "Loop " << L->getHeader()->getName() << ": ";
5139 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5140 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5142 OS << "Unpredictable max backedge-taken count. ";
5148 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
5149 // ScalarEvolution's implementaiton of the print method is to print
5150 // out SCEV values of all instructions that are interesting. Doing
5151 // this potentially causes it to create new SCEV objects though,
5152 // which technically conflicts with the const qualifier. This isn't
5153 // observable from outside the class though, so casting away the
5154 // const isn't dangerous.
5155 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
5157 OS << "Classifying expressions for: " << F->getName() << "\n";
5158 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5159 if (isSCEVable(I->getType())) {
5162 const SCEV *SV = SE.getSCEV(&*I);
5165 const Loop *L = LI->getLoopFor((*I).getParent());
5167 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5174 OS << "\t\t" "Exits: ";
5175 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5176 if (!ExitValue->isLoopInvariant(L)) {
5177 OS << "<<Unknown>>";
5186 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5187 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5188 PrintLoopInfo(OS, &SE, *I);