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/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/Assembly/Writer.h"
75 #include "llvm/Target/TargetData.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/Compiler.h"
78 #include "llvm/Support/ConstantRange.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/GetElementPtrTypeIterator.h"
81 #include "llvm/Support/InstIterator.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/STLExtras.h"
86 #include "llvm/ADT/SmallPtrSet.h"
90 STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant "
106 static RegisterPass<ScalarEvolution>
107 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
120 void SCEV::dump() const {
125 bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
131 bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
137 bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
143 SCEVCouldNotCompute::SCEVCouldNotCompute() :
144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
146 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
151 const Type *SCEVCouldNotCompute::getType() const {
152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
156 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
161 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
166 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
167 OS << "***COULDNOTCOMPUTE***";
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
174 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
176 ID.AddInteger(scConstant);
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
181 new (S) SCEVConstant(ID, V);
182 UniqueSCEVs.InsertNode(S, IP);
186 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(getContext(), Val));
191 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
196 const Type *SCEVConstant::getType() const { return V->getType(); }
198 void SCEVConstant::print(raw_ostream &OS) const {
199 WriteAsOperand(OS, V, false);
202 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
206 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
210 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
211 const SCEV *op, const Type *ty)
212 : SCEVCastExpr(ID, scTruncate, op, ty) {
213 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
214 (Ty->isInteger() || isa<PointerType>(Ty)) &&
215 "Cannot truncate non-integer value!");
218 void SCEVTruncateExpr::print(raw_ostream &OS) const {
219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
222 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
223 const SCEV *op, const Type *ty)
224 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
225 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
226 (Ty->isInteger() || isa<PointerType>(Ty)) &&
227 "Cannot zero extend non-integer value!");
230 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
231 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
234 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
235 const SCEV *op, const Type *ty)
236 : SCEVCastExpr(ID, scSignExtend, op, ty) {
237 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
238 (Ty->isInteger() || isa<PointerType>(Ty)) &&
239 "Cannot sign extend non-integer value!");
242 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
243 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
246 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
247 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
248 const char *OpStr = getOperationStr();
249 OS << "(" << *Operands[0];
250 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
251 OS << OpStr << *Operands[i];
255 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
256 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
257 if (!getOperand(i)->dominates(BB, DT))
263 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
264 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
267 void SCEVUDivExpr::print(raw_ostream &OS) const {
268 OS << "(" << *LHS << " /u " << *RHS << ")";
271 const Type *SCEVUDivExpr::getType() const {
272 // In most cases the types of LHS and RHS will be the same, but in some
273 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
274 // depend on the type for correctness, but handling types carefully can
275 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
276 // a pointer type than the RHS, so use the RHS' type here.
277 return RHS->getType();
280 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
281 // Add recurrences are never invariant in the function-body (null loop).
285 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
286 if (QueryLoop->contains(L->getHeader()))
289 // This recurrence is variant w.r.t. QueryLoop if any of its operands
291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
292 if (!getOperand(i)->isLoopInvariant(QueryLoop))
295 // Otherwise it's loop-invariant.
299 void SCEVAddRecExpr::print(raw_ostream &OS) const {
300 OS << "{" << *Operands[0];
301 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
302 OS << ",+," << *Operands[i];
303 OS << "}<" << L->getHeader()->getName() + ">";
306 void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
307 // LLVM struct fields don't have names, so just print the field number.
308 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
311 void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
312 OS << "sizeof(" << *AllocTy << ")";
315 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
316 // All non-instruction values are loop invariant. All instructions are loop
317 // invariant if they are not contained in the specified loop.
318 // Instructions are never considered invariant in the function body
319 // (null loop) because they are defined within the "loop".
320 if (Instruction *I = dyn_cast<Instruction>(V))
321 return L && !L->contains(I->getParent());
325 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 if (Instruction *I = dyn_cast<Instruction>(getValue()))
327 return DT->dominates(I->getParent(), BB);
331 const Type *SCEVUnknown::getType() const {
335 void SCEVUnknown::print(raw_ostream &OS) const {
336 WriteAsOperand(OS, V, false);
339 //===----------------------------------------------------------------------===//
341 //===----------------------------------------------------------------------===//
343 static bool CompareTypes(const Type *A, const Type *B) {
344 if (A->getTypeID() != B->getTypeID())
345 return A->getTypeID() < B->getTypeID();
346 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
347 const IntegerType *BI = cast<IntegerType>(B);
348 return AI->getBitWidth() < BI->getBitWidth();
350 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
351 const PointerType *BI = cast<PointerType>(B);
352 return CompareTypes(AI->getElementType(), BI->getElementType());
354 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
355 const ArrayType *BI = cast<ArrayType>(B);
356 if (AI->getNumElements() != BI->getNumElements())
357 return AI->getNumElements() < BI->getNumElements();
358 return CompareTypes(AI->getElementType(), BI->getElementType());
360 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
361 const VectorType *BI = cast<VectorType>(B);
362 if (AI->getNumElements() != BI->getNumElements())
363 return AI->getNumElements() < BI->getNumElements();
364 return CompareTypes(AI->getElementType(), BI->getElementType());
366 if (const StructType *AI = dyn_cast<StructType>(A)) {
367 const StructType *BI = cast<StructType>(B);
368 if (AI->getNumElements() != BI->getNumElements())
369 return AI->getNumElements() < BI->getNumElements();
370 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
371 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
372 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
373 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
379 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
380 /// than the complexity of the RHS. This comparator is used to canonicalize
382 class VISIBILITY_HIDDEN SCEVComplexityCompare {
385 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
387 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
388 // Primarily, sort the SCEVs by their getSCEVType().
389 if (LHS->getSCEVType() != RHS->getSCEVType())
390 return LHS->getSCEVType() < RHS->getSCEVType();
392 // Aside from the getSCEVType() ordering, the particular ordering
393 // isn't very important except that it's beneficial to be consistent,
394 // so that (a + b) and (b + a) don't end up as different expressions.
396 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
397 // not as complete as it could be.
398 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
399 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
401 // Order pointer values after integer values. This helps SCEVExpander
403 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
405 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
408 // Compare getValueID values.
409 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
410 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
412 // Sort arguments by their position.
413 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
414 const Argument *RA = cast<Argument>(RU->getValue());
415 return LA->getArgNo() < RA->getArgNo();
418 // For instructions, compare their loop depth, and their opcode.
419 // This is pretty loose.
420 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
421 Instruction *RV = cast<Instruction>(RU->getValue());
423 // Compare loop depths.
424 if (LI->getLoopDepth(LV->getParent()) !=
425 LI->getLoopDepth(RV->getParent()))
426 return LI->getLoopDepth(LV->getParent()) <
427 LI->getLoopDepth(RV->getParent());
430 if (LV->getOpcode() != RV->getOpcode())
431 return LV->getOpcode() < RV->getOpcode();
433 // Compare the number of operands.
434 if (LV->getNumOperands() != RV->getNumOperands())
435 return LV->getNumOperands() < RV->getNumOperands();
441 // Compare constant values.
442 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
443 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
444 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
445 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
446 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
449 // Compare addrec loop depths.
450 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
451 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
452 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
453 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
456 // Lexicographically compare n-ary expressions.
457 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
458 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
459 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
460 if (i >= RC->getNumOperands())
462 if (operator()(LC->getOperand(i), RC->getOperand(i)))
464 if (operator()(RC->getOperand(i), LC->getOperand(i)))
467 return LC->getNumOperands() < RC->getNumOperands();
470 // Lexicographically compare udiv expressions.
471 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
472 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
473 if (operator()(LC->getLHS(), RC->getLHS()))
475 if (operator()(RC->getLHS(), LC->getLHS()))
477 if (operator()(LC->getRHS(), RC->getRHS()))
479 if (operator()(RC->getRHS(), LC->getRHS()))
484 // Compare cast expressions by operand.
485 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
486 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
487 return operator()(LC->getOperand(), RC->getOperand());
490 // Compare offsetof expressions.
491 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
492 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
493 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
494 CompareTypes(RA->getStructType(), LA->getStructType()))
495 return CompareTypes(LA->getStructType(), RA->getStructType());
496 return LA->getFieldNo() < RA->getFieldNo();
499 // Compare sizeof expressions by the allocation type.
500 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
501 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
502 return CompareTypes(LA->getAllocType(), RA->getAllocType());
505 llvm_unreachable("Unknown SCEV kind!");
511 /// GroupByComplexity - Given a list of SCEV objects, order them by their
512 /// complexity, and group objects of the same complexity together by value.
513 /// When this routine is finished, we know that any duplicates in the vector are
514 /// consecutive and that complexity is monotonically increasing.
516 /// Note that we go take special precautions to ensure that we get determinstic
517 /// results from this routine. In other words, we don't want the results of
518 /// this to depend on where the addresses of various SCEV objects happened to
521 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
523 if (Ops.size() < 2) return; // Noop
524 if (Ops.size() == 2) {
525 // This is the common case, which also happens to be trivially simple.
527 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
528 std::swap(Ops[0], Ops[1]);
532 // Do the rough sort by complexity.
533 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
535 // Now that we are sorted by complexity, group elements of the same
536 // complexity. Note that this is, at worst, N^2, but the vector is likely to
537 // be extremely short in practice. Note that we take this approach because we
538 // do not want to depend on the addresses of the objects we are grouping.
539 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
540 const SCEV *S = Ops[i];
541 unsigned Complexity = S->getSCEVType();
543 // If there are any objects of the same complexity and same value as this
545 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
546 if (Ops[j] == S) { // Found a duplicate.
547 // Move it to immediately after i'th element.
548 std::swap(Ops[i+1], Ops[j]);
549 ++i; // no need to rescan it.
550 if (i == e-2) return; // Done!
558 //===----------------------------------------------------------------------===//
559 // Simple SCEV method implementations
560 //===----------------------------------------------------------------------===//
562 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
564 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
566 const Type* ResultTy) {
567 // Handle the simplest case efficiently.
569 return SE.getTruncateOrZeroExtend(It, ResultTy);
571 // We are using the following formula for BC(It, K):
573 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
575 // Suppose, W is the bitwidth of the return value. We must be prepared for
576 // overflow. Hence, we must assure that the result of our computation is
577 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
578 // safe in modular arithmetic.
580 // However, this code doesn't use exactly that formula; the formula it uses
581 // is something like the following, where T is the number of factors of 2 in
582 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
585 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
587 // This formula is trivially equivalent to the previous formula. However,
588 // this formula can be implemented much more efficiently. The trick is that
589 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
590 // arithmetic. To do exact division in modular arithmetic, all we have
591 // to do is multiply by the inverse. Therefore, this step can be done at
594 // The next issue is how to safely do the division by 2^T. The way this
595 // is done is by doing the multiplication step at a width of at least W + T
596 // bits. This way, the bottom W+T bits of the product are accurate. Then,
597 // when we perform the division by 2^T (which is equivalent to a right shift
598 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
599 // truncated out after the division by 2^T.
601 // In comparison to just directly using the first formula, this technique
602 // is much more efficient; using the first formula requires W * K bits,
603 // but this formula less than W + K bits. Also, the first formula requires
604 // a division step, whereas this formula only requires multiplies and shifts.
606 // It doesn't matter whether the subtraction step is done in the calculation
607 // width or the input iteration count's width; if the subtraction overflows,
608 // the result must be zero anyway. We prefer here to do it in the width of
609 // the induction variable because it helps a lot for certain cases; CodeGen
610 // isn't smart enough to ignore the overflow, which leads to much less
611 // efficient code if the width of the subtraction is wider than the native
614 // (It's possible to not widen at all by pulling out factors of 2 before
615 // the multiplication; for example, K=2 can be calculated as
616 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
617 // extra arithmetic, so it's not an obvious win, and it gets
618 // much more complicated for K > 3.)
620 // Protection from insane SCEVs; this bound is conservative,
621 // but it probably doesn't matter.
623 return SE.getCouldNotCompute();
625 unsigned W = SE.getTypeSizeInBits(ResultTy);
627 // Calculate K! / 2^T and T; we divide out the factors of two before
628 // multiplying for calculating K! / 2^T to avoid overflow.
629 // Other overflow doesn't matter because we only care about the bottom
630 // W bits of the result.
631 APInt OddFactorial(W, 1);
633 for (unsigned i = 3; i <= K; ++i) {
635 unsigned TwoFactors = Mult.countTrailingZeros();
637 Mult = Mult.lshr(TwoFactors);
638 OddFactorial *= Mult;
641 // We need at least W + T bits for the multiplication step
642 unsigned CalculationBits = W + T;
644 // Calcuate 2^T, at width T+W.
645 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
647 // Calculate the multiplicative inverse of K! / 2^T;
648 // this multiplication factor will perform the exact division by
650 APInt Mod = APInt::getSignedMinValue(W+1);
651 APInt MultiplyFactor = OddFactorial.zext(W+1);
652 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
653 MultiplyFactor = MultiplyFactor.trunc(W);
655 // Calculate the product, at width T+W
656 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
658 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
659 for (unsigned i = 1; i != K; ++i) {
660 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
661 Dividend = SE.getMulExpr(Dividend,
662 SE.getTruncateOrZeroExtend(S, CalculationTy));
666 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
668 // Truncate the result, and divide by K! / 2^T.
670 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
671 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
674 /// evaluateAtIteration - Return the value of this chain of recurrences at
675 /// the specified iteration number. We can evaluate this recurrence by
676 /// multiplying each element in the chain by the binomial coefficient
677 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
679 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
681 /// where BC(It, k) stands for binomial coefficient.
683 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
684 ScalarEvolution &SE) const {
685 const SCEV *Result = getStart();
686 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
687 // The computation is correct in the face of overflow provided that the
688 // multiplication is performed _after_ the evaluation of the binomial
690 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
691 if (isa<SCEVCouldNotCompute>(Coeff))
694 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
699 //===----------------------------------------------------------------------===//
700 // SCEV Expression folder implementations
701 //===----------------------------------------------------------------------===//
703 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
705 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
706 "This is not a truncating conversion!");
707 assert(isSCEVable(Ty) &&
708 "This is not a conversion to a SCEVable type!");
709 Ty = getEffectiveSCEVType(Ty);
712 ID.AddInteger(scTruncate);
716 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
718 // Fold if the operand is constant.
719 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
721 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
723 // trunc(trunc(x)) --> trunc(x)
724 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
725 return getTruncateExpr(ST->getOperand(), Ty);
727 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
728 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
729 return getTruncateOrSignExtend(SS->getOperand(), Ty);
731 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
732 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
733 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
735 // If the input value is a chrec scev, truncate the chrec's operands.
736 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
737 SmallVector<const SCEV *, 4> Operands;
738 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
739 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
740 return getAddRecExpr(Operands, AddRec->getLoop());
743 // The cast wasn't folded; create an explicit cast node.
744 // Recompute the insert position, as it may have been invalidated.
745 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
746 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
747 new (S) SCEVTruncateExpr(ID, Op, Ty);
748 UniqueSCEVs.InsertNode(S, IP);
752 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
754 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
755 "This is not an extending conversion!");
756 assert(isSCEVable(Ty) &&
757 "This is not a conversion to a SCEVable type!");
758 Ty = getEffectiveSCEVType(Ty);
760 // Fold if the operand is constant.
761 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
762 const Type *IntTy = getEffectiveSCEVType(Ty);
763 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
764 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
765 return getConstant(cast<ConstantInt>(C));
768 // zext(zext(x)) --> zext(x)
769 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
770 return getZeroExtendExpr(SZ->getOperand(), Ty);
772 // Before doing any expensive analysis, check to see if we've already
773 // computed a SCEV for this Op and Ty.
775 ID.AddInteger(scZeroExtend);
779 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
781 // If the input value is a chrec scev, and we can prove that the value
782 // did not overflow the old, smaller, value, we can zero extend all of the
783 // operands (often constants). This allows analysis of something like
784 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
785 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
786 if (AR->isAffine()) {
787 const SCEV *Start = AR->getStart();
788 const SCEV *Step = AR->getStepRecurrence(*this);
789 unsigned BitWidth = getTypeSizeInBits(AR->getType());
790 const Loop *L = AR->getLoop();
792 // If we have special knowledge that this addrec won't overflow,
793 // we don't need to do any further analysis.
794 if (AR->hasNoUnsignedWrap())
795 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
796 getZeroExtendExpr(Step, Ty),
799 // Check whether the backedge-taken count is SCEVCouldNotCompute.
800 // Note that this serves two purposes: It filters out loops that are
801 // simply not analyzable, and it covers the case where this code is
802 // being called from within backedge-taken count analysis, such that
803 // attempting to ask for the backedge-taken count would likely result
804 // in infinite recursion. In the later case, the analysis code will
805 // cope with a conservative value, and it will take care to purge
806 // that value once it has finished.
807 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
808 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
809 // Manually compute the final value for AR, checking for
812 // Check whether the backedge-taken count can be losslessly casted to
813 // the addrec's type. The count is always unsigned.
814 const SCEV *CastedMaxBECount =
815 getTruncateOrZeroExtend(MaxBECount, Start->getType());
816 const SCEV *RecastedMaxBECount =
817 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
818 if (MaxBECount == RecastedMaxBECount) {
819 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
820 // Check whether Start+Step*MaxBECount has no unsigned overflow.
822 getMulExpr(CastedMaxBECount,
823 getTruncateOrZeroExtend(Step, Start->getType()));
824 const SCEV *Add = getAddExpr(Start, ZMul);
825 const SCEV *OperandExtendedAdd =
826 getAddExpr(getZeroExtendExpr(Start, WideTy),
827 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
828 getZeroExtendExpr(Step, WideTy)));
829 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
830 // Return the expression with the addrec on the outside.
831 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
832 getZeroExtendExpr(Step, Ty),
835 // Similar to above, only this time treat the step value as signed.
836 // This covers loops that count down.
838 getMulExpr(CastedMaxBECount,
839 getTruncateOrSignExtend(Step, Start->getType()));
840 Add = getAddExpr(Start, SMul);
842 getAddExpr(getZeroExtendExpr(Start, WideTy),
843 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
844 getSignExtendExpr(Step, WideTy)));
845 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
846 // Return the expression with the addrec on the outside.
847 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
848 getSignExtendExpr(Step, Ty),
852 // If the backedge is guarded by a comparison with the pre-inc value
853 // the addrec is safe. Also, if the entry is guarded by a comparison
854 // with the start value and the backedge is guarded by a comparison
855 // with the post-inc value, the addrec is safe.
856 if (isKnownPositive(Step)) {
857 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
858 getUnsignedRange(Step).getUnsignedMax());
859 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
860 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
861 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
862 AR->getPostIncExpr(*this), N)))
863 // Return the expression with the addrec on the outside.
864 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
865 getZeroExtendExpr(Step, Ty),
867 } else if (isKnownNegative(Step)) {
868 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
869 getSignedRange(Step).getSignedMin());
870 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
871 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
872 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
873 AR->getPostIncExpr(*this), N)))
874 // Return the expression with the addrec on the outside.
875 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
876 getSignExtendExpr(Step, Ty),
882 // The cast wasn't folded; create an explicit cast node.
883 // Recompute the insert position, as it may have been invalidated.
884 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
885 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
886 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
887 UniqueSCEVs.InsertNode(S, IP);
891 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
893 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
894 "This is not an extending conversion!");
895 assert(isSCEVable(Ty) &&
896 "This is not a conversion to a SCEVable type!");
897 Ty = getEffectiveSCEVType(Ty);
899 // Fold if the operand is constant.
900 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
901 const Type *IntTy = getEffectiveSCEVType(Ty);
902 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
903 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
904 return getConstant(cast<ConstantInt>(C));
907 // sext(sext(x)) --> sext(x)
908 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
909 return getSignExtendExpr(SS->getOperand(), Ty);
911 // Before doing any expensive analysis, check to see if we've already
912 // computed a SCEV for this Op and Ty.
914 ID.AddInteger(scSignExtend);
918 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
920 // If the input value is a chrec scev, and we can prove that the value
921 // did not overflow the old, smaller, value, we can sign extend all of the
922 // operands (often constants). This allows analysis of something like
923 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
924 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
925 if (AR->isAffine()) {
926 const SCEV *Start = AR->getStart();
927 const SCEV *Step = AR->getStepRecurrence(*this);
928 unsigned BitWidth = getTypeSizeInBits(AR->getType());
929 const Loop *L = AR->getLoop();
931 // If we have special knowledge that this addrec won't overflow,
932 // we don't need to do any further analysis.
933 if (AR->hasNoSignedWrap())
934 return getAddRecExpr(getSignExtendExpr(Start, Ty),
935 getSignExtendExpr(Step, Ty),
938 // Check whether the backedge-taken count is SCEVCouldNotCompute.
939 // Note that this serves two purposes: It filters out loops that are
940 // simply not analyzable, and it covers the case where this code is
941 // being called from within backedge-taken count analysis, such that
942 // attempting to ask for the backedge-taken count would likely result
943 // in infinite recursion. In the later case, the analysis code will
944 // cope with a conservative value, and it will take care to purge
945 // that value once it has finished.
946 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
947 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
948 // Manually compute the final value for AR, checking for
951 // Check whether the backedge-taken count can be losslessly casted to
952 // the addrec's type. The count is always unsigned.
953 const SCEV *CastedMaxBECount =
954 getTruncateOrZeroExtend(MaxBECount, Start->getType());
955 const SCEV *RecastedMaxBECount =
956 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
957 if (MaxBECount == RecastedMaxBECount) {
958 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
959 // Check whether Start+Step*MaxBECount has no signed overflow.
961 getMulExpr(CastedMaxBECount,
962 getTruncateOrSignExtend(Step, Start->getType()));
963 const SCEV *Add = getAddExpr(Start, SMul);
964 const SCEV *OperandExtendedAdd =
965 getAddExpr(getSignExtendExpr(Start, WideTy),
966 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
967 getSignExtendExpr(Step, WideTy)));
968 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
969 // Return the expression with the addrec on the outside.
970 return getAddRecExpr(getSignExtendExpr(Start, Ty),
971 getSignExtendExpr(Step, Ty),
974 // Similar to above, only this time treat the step value as unsigned.
975 // This covers loops that count up with an unsigned step.
977 getMulExpr(CastedMaxBECount,
978 getTruncateOrZeroExtend(Step, Start->getType()));
979 Add = getAddExpr(Start, UMul);
981 getAddExpr(getSignExtendExpr(Start, WideTy),
982 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
983 getZeroExtendExpr(Step, WideTy)));
984 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
985 // Return the expression with the addrec on the outside.
986 return getAddRecExpr(getSignExtendExpr(Start, Ty),
987 getZeroExtendExpr(Step, Ty),
991 // If the backedge is guarded by a comparison with the pre-inc value
992 // the addrec is safe. Also, if the entry is guarded by a comparison
993 // with the start value and the backedge is guarded by a comparison
994 // with the post-inc value, the addrec is safe.
995 if (isKnownPositive(Step)) {
996 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
997 getSignedRange(Step).getSignedMax());
998 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
999 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1000 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1001 AR->getPostIncExpr(*this), N)))
1002 // Return the expression with the addrec on the outside.
1003 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1004 getSignExtendExpr(Step, Ty),
1006 } else if (isKnownNegative(Step)) {
1007 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1008 getSignedRange(Step).getSignedMin());
1009 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1010 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1011 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1012 AR->getPostIncExpr(*this), N)))
1013 // Return the expression with the addrec on the outside.
1014 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1015 getSignExtendExpr(Step, Ty),
1021 // The cast wasn't folded; create an explicit cast node.
1022 // Recompute the insert position, as it may have been invalidated.
1023 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1024 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1025 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1026 UniqueSCEVs.InsertNode(S, IP);
1030 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1031 /// unspecified bits out to the given type.
1033 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1035 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1036 "This is not an extending conversion!");
1037 assert(isSCEVable(Ty) &&
1038 "This is not a conversion to a SCEVable type!");
1039 Ty = getEffectiveSCEVType(Ty);
1041 // Sign-extend negative constants.
1042 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1043 if (SC->getValue()->getValue().isNegative())
1044 return getSignExtendExpr(Op, Ty);
1046 // Peel off a truncate cast.
1047 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1048 const SCEV *NewOp = T->getOperand();
1049 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1050 return getAnyExtendExpr(NewOp, Ty);
1051 return getTruncateOrNoop(NewOp, Ty);
1054 // Next try a zext cast. If the cast is folded, use it.
1055 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1056 if (!isa<SCEVZeroExtendExpr>(ZExt))
1059 // Next try a sext cast. If the cast is folded, use it.
1060 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1061 if (!isa<SCEVSignExtendExpr>(SExt))
1064 // If the expression is obviously signed, use the sext cast value.
1065 if (isa<SCEVSMaxExpr>(Op))
1068 // Absent any other information, use the zext cast value.
1072 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1073 /// a list of operands to be added under the given scale, update the given
1074 /// map. This is a helper function for getAddRecExpr. As an example of
1075 /// what it does, given a sequence of operands that would form an add
1076 /// expression like this:
1078 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1080 /// where A and B are constants, update the map with these values:
1082 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1084 /// and add 13 + A*B*29 to AccumulatedConstant.
1085 /// This will allow getAddRecExpr to produce this:
1087 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1089 /// This form often exposes folding opportunities that are hidden in
1090 /// the original operand list.
1092 /// Return true iff it appears that any interesting folding opportunities
1093 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1094 /// the common case where no interesting opportunities are present, and
1095 /// is also used as a check to avoid infinite recursion.
1098 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1099 SmallVector<const SCEV *, 8> &NewOps,
1100 APInt &AccumulatedConstant,
1101 const SmallVectorImpl<const SCEV *> &Ops,
1103 ScalarEvolution &SE) {
1104 bool Interesting = false;
1106 // Iterate over the add operands.
1107 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1108 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1109 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1111 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1112 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1113 // A multiplication of a constant with another add; recurse.
1115 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1116 cast<SCEVAddExpr>(Mul->getOperand(1))
1120 // A multiplication of a constant with some other value. Update
1122 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1123 const SCEV *Key = SE.getMulExpr(MulOps);
1124 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1125 M.insert(std::make_pair(Key, NewScale));
1127 NewOps.push_back(Pair.first->first);
1129 Pair.first->second += NewScale;
1130 // The map already had an entry for this value, which may indicate
1131 // a folding opportunity.
1135 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1136 // Pull a buried constant out to the outside.
1137 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1139 AccumulatedConstant += Scale * C->getValue()->getValue();
1141 // An ordinary operand. Update the map.
1142 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1143 M.insert(std::make_pair(Ops[i], Scale));
1145 NewOps.push_back(Pair.first->first);
1147 Pair.first->second += Scale;
1148 // The map already had an entry for this value, which may indicate
1149 // a folding opportunity.
1159 struct APIntCompare {
1160 bool operator()(const APInt &LHS, const APInt &RHS) const {
1161 return LHS.ult(RHS);
1166 /// getAddExpr - Get a canonical add expression, or something simpler if
1168 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1169 assert(!Ops.empty() && "Cannot get empty add!");
1170 if (Ops.size() == 1) return Ops[0];
1172 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1173 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1174 getEffectiveSCEVType(Ops[0]->getType()) &&
1175 "SCEVAddExpr operand types don't match!");
1178 // Sort by complexity, this groups all similar expression types together.
1179 GroupByComplexity(Ops, LI);
1181 // If there are any constants, fold them together.
1183 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1185 assert(Idx < Ops.size());
1186 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1187 // We found two constants, fold them together!
1188 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1189 RHSC->getValue()->getValue());
1190 if (Ops.size() == 2) return Ops[0];
1191 Ops.erase(Ops.begin()+1); // Erase the folded element
1192 LHSC = cast<SCEVConstant>(Ops[0]);
1195 // If we are left with a constant zero being added, strip it off.
1196 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1197 Ops.erase(Ops.begin());
1202 if (Ops.size() == 1) return Ops[0];
1204 // Okay, check to see if the same value occurs in the operand list twice. If
1205 // so, merge them together into an multiply expression. Since we sorted the
1206 // list, these values are required to be adjacent.
1207 const Type *Ty = Ops[0]->getType();
1208 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1209 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1210 // Found a match, merge the two values into a multiply, and add any
1211 // remaining values to the result.
1212 const SCEV *Two = getIntegerSCEV(2, Ty);
1213 const SCEV *Mul = getMulExpr(Ops[i], Two);
1214 if (Ops.size() == 2)
1216 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1218 return getAddExpr(Ops);
1221 // Check for truncates. If all the operands are truncated from the same
1222 // type, see if factoring out the truncate would permit the result to be
1223 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1224 // if the contents of the resulting outer trunc fold to something simple.
1225 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1226 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1227 const Type *DstType = Trunc->getType();
1228 const Type *SrcType = Trunc->getOperand()->getType();
1229 SmallVector<const SCEV *, 8> LargeOps;
1231 // Check all the operands to see if they can be represented in the
1232 // source type of the truncate.
1233 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1234 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1235 if (T->getOperand()->getType() != SrcType) {
1239 LargeOps.push_back(T->getOperand());
1240 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1241 // This could be either sign or zero extension, but sign extension
1242 // is much more likely to be foldable here.
1243 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1244 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1245 SmallVector<const SCEV *, 8> LargeMulOps;
1246 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1247 if (const SCEVTruncateExpr *T =
1248 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1249 if (T->getOperand()->getType() != SrcType) {
1253 LargeMulOps.push_back(T->getOperand());
1254 } else if (const SCEVConstant *C =
1255 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1256 // This could be either sign or zero extension, but sign extension
1257 // is much more likely to be foldable here.
1258 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1265 LargeOps.push_back(getMulExpr(LargeMulOps));
1272 // Evaluate the expression in the larger type.
1273 const SCEV *Fold = getAddExpr(LargeOps);
1274 // If it folds to something simple, use it. Otherwise, don't.
1275 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1276 return getTruncateExpr(Fold, DstType);
1280 // Skip past any other cast SCEVs.
1281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1284 // If there are add operands they would be next.
1285 if (Idx < Ops.size()) {
1286 bool DeletedAdd = false;
1287 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1288 // If we have an add, expand the add operands onto the end of the operands
1290 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1291 Ops.erase(Ops.begin()+Idx);
1295 // If we deleted at least one add, we added operands to the end of the list,
1296 // and they are not necessarily sorted. Recurse to resort and resimplify
1297 // any operands we just aquired.
1299 return getAddExpr(Ops);
1302 // Skip over the add expression until we get to a multiply.
1303 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1306 // Check to see if there are any folding opportunities present with
1307 // operands multiplied by constant values.
1308 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1309 uint64_t BitWidth = getTypeSizeInBits(Ty);
1310 DenseMap<const SCEV *, APInt> M;
1311 SmallVector<const SCEV *, 8> NewOps;
1312 APInt AccumulatedConstant(BitWidth, 0);
1313 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1314 Ops, APInt(BitWidth, 1), *this)) {
1315 // Some interesting folding opportunity is present, so its worthwhile to
1316 // re-generate the operands list. Group the operands by constant scale,
1317 // to avoid multiplying by the same constant scale multiple times.
1318 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1319 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1320 E = NewOps.end(); I != E; ++I)
1321 MulOpLists[M.find(*I)->second].push_back(*I);
1322 // Re-generate the operands list.
1324 if (AccumulatedConstant != 0)
1325 Ops.push_back(getConstant(AccumulatedConstant));
1326 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1327 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1329 Ops.push_back(getMulExpr(getConstant(I->first),
1330 getAddExpr(I->second)));
1332 return getIntegerSCEV(0, Ty);
1333 if (Ops.size() == 1)
1335 return getAddExpr(Ops);
1339 // If we are adding something to a multiply expression, make sure the
1340 // something is not already an operand of the multiply. If so, merge it into
1342 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1343 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1344 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1345 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1346 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1347 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1348 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1349 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1350 if (Mul->getNumOperands() != 2) {
1351 // If the multiply has more than two operands, we must get the
1353 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1354 MulOps.erase(MulOps.begin()+MulOp);
1355 InnerMul = getMulExpr(MulOps);
1357 const SCEV *One = getIntegerSCEV(1, Ty);
1358 const SCEV *AddOne = getAddExpr(InnerMul, One);
1359 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1360 if (Ops.size() == 2) return OuterMul;
1362 Ops.erase(Ops.begin()+AddOp);
1363 Ops.erase(Ops.begin()+Idx-1);
1365 Ops.erase(Ops.begin()+Idx);
1366 Ops.erase(Ops.begin()+AddOp-1);
1368 Ops.push_back(OuterMul);
1369 return getAddExpr(Ops);
1372 // Check this multiply against other multiplies being added together.
1373 for (unsigned OtherMulIdx = Idx+1;
1374 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1376 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1377 // If MulOp occurs in OtherMul, we can fold the two multiplies
1379 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1380 OMulOp != e; ++OMulOp)
1381 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1382 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1383 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1384 if (Mul->getNumOperands() != 2) {
1385 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1387 MulOps.erase(MulOps.begin()+MulOp);
1388 InnerMul1 = getMulExpr(MulOps);
1390 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1391 if (OtherMul->getNumOperands() != 2) {
1392 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1393 OtherMul->op_end());
1394 MulOps.erase(MulOps.begin()+OMulOp);
1395 InnerMul2 = getMulExpr(MulOps);
1397 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1398 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1399 if (Ops.size() == 2) return OuterMul;
1400 Ops.erase(Ops.begin()+Idx);
1401 Ops.erase(Ops.begin()+OtherMulIdx-1);
1402 Ops.push_back(OuterMul);
1403 return getAddExpr(Ops);
1409 // If there are any add recurrences in the operands list, see if any other
1410 // added values are loop invariant. If so, we can fold them into the
1412 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1415 // Scan over all recurrences, trying to fold loop invariants into them.
1416 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1417 // Scan all of the other operands to this add and add them to the vector if
1418 // they are loop invariant w.r.t. the recurrence.
1419 SmallVector<const SCEV *, 8> LIOps;
1420 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1421 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1422 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1423 LIOps.push_back(Ops[i]);
1424 Ops.erase(Ops.begin()+i);
1428 // If we found some loop invariants, fold them into the recurrence.
1429 if (!LIOps.empty()) {
1430 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1431 LIOps.push_back(AddRec->getStart());
1433 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1435 AddRecOps[0] = getAddExpr(LIOps);
1437 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1438 // If all of the other operands were loop invariant, we are done.
1439 if (Ops.size() == 1) return NewRec;
1441 // Otherwise, add the folded AddRec by the non-liv parts.
1442 for (unsigned i = 0;; ++i)
1443 if (Ops[i] == AddRec) {
1447 return getAddExpr(Ops);
1450 // Okay, if there weren't any loop invariants to be folded, check to see if
1451 // there are multiple AddRec's with the same loop induction variable being
1452 // added together. If so, we can fold them.
1453 for (unsigned OtherIdx = Idx+1;
1454 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1455 if (OtherIdx != Idx) {
1456 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1457 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1458 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1459 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1461 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1462 if (i >= NewOps.size()) {
1463 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1464 OtherAddRec->op_end());
1467 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1469 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1471 if (Ops.size() == 2) return NewAddRec;
1473 Ops.erase(Ops.begin()+Idx);
1474 Ops.erase(Ops.begin()+OtherIdx-1);
1475 Ops.push_back(NewAddRec);
1476 return getAddExpr(Ops);
1480 // Otherwise couldn't fold anything into this recurrence. Move onto the
1484 // Okay, it looks like we really DO need an add expr. Check to see if we
1485 // already have one, otherwise create a new one.
1486 FoldingSetNodeID ID;
1487 ID.AddInteger(scAddExpr);
1488 ID.AddInteger(Ops.size());
1489 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1490 ID.AddPointer(Ops[i]);
1492 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1493 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1494 new (S) SCEVAddExpr(ID, Ops);
1495 UniqueSCEVs.InsertNode(S, IP);
1500 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1502 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1503 assert(!Ops.empty() && "Cannot get empty mul!");
1505 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1506 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1507 getEffectiveSCEVType(Ops[0]->getType()) &&
1508 "SCEVMulExpr operand types don't match!");
1511 // Sort by complexity, this groups all similar expression types together.
1512 GroupByComplexity(Ops, LI);
1514 // If there are any constants, fold them together.
1516 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1518 // C1*(C2+V) -> C1*C2 + C1*V
1519 if (Ops.size() == 2)
1520 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1521 if (Add->getNumOperands() == 2 &&
1522 isa<SCEVConstant>(Add->getOperand(0)))
1523 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1524 getMulExpr(LHSC, Add->getOperand(1)));
1528 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1529 // We found two constants, fold them together!
1530 ConstantInt *Fold = ConstantInt::get(getContext(),
1531 LHSC->getValue()->getValue() *
1532 RHSC->getValue()->getValue());
1533 Ops[0] = getConstant(Fold);
1534 Ops.erase(Ops.begin()+1); // Erase the folded element
1535 if (Ops.size() == 1) return Ops[0];
1536 LHSC = cast<SCEVConstant>(Ops[0]);
1539 // If we are left with a constant one being multiplied, strip it off.
1540 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1541 Ops.erase(Ops.begin());
1543 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1544 // If we have a multiply of zero, it will always be zero.
1549 // Skip over the add expression until we get to a multiply.
1550 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1553 if (Ops.size() == 1)
1556 // If there are mul operands inline them all into this expression.
1557 if (Idx < Ops.size()) {
1558 bool DeletedMul = false;
1559 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1560 // If we have an mul, expand the mul operands onto the end of the operands
1562 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1563 Ops.erase(Ops.begin()+Idx);
1567 // If we deleted at least one mul, we added operands to the end of the list,
1568 // and they are not necessarily sorted. Recurse to resort and resimplify
1569 // any operands we just aquired.
1571 return getMulExpr(Ops);
1574 // If there are any add recurrences in the operands list, see if any other
1575 // added values are loop invariant. If so, we can fold them into the
1577 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1580 // Scan over all recurrences, trying to fold loop invariants into them.
1581 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1582 // Scan all of the other operands to this mul and add them to the vector if
1583 // they are loop invariant w.r.t. the recurrence.
1584 SmallVector<const SCEV *, 8> LIOps;
1585 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1586 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1587 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1588 LIOps.push_back(Ops[i]);
1589 Ops.erase(Ops.begin()+i);
1593 // If we found some loop invariants, fold them into the recurrence.
1594 if (!LIOps.empty()) {
1595 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1596 SmallVector<const SCEV *, 4> NewOps;
1597 NewOps.reserve(AddRec->getNumOperands());
1598 if (LIOps.size() == 1) {
1599 const SCEV *Scale = LIOps[0];
1600 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1601 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1603 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1604 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1605 MulOps.push_back(AddRec->getOperand(i));
1606 NewOps.push_back(getMulExpr(MulOps));
1610 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1612 // If all of the other operands were loop invariant, we are done.
1613 if (Ops.size() == 1) return NewRec;
1615 // Otherwise, multiply the folded AddRec by the non-liv parts.
1616 for (unsigned i = 0;; ++i)
1617 if (Ops[i] == AddRec) {
1621 return getMulExpr(Ops);
1624 // Okay, if there weren't any loop invariants to be folded, check to see if
1625 // there are multiple AddRec's with the same loop induction variable being
1626 // multiplied together. If so, we can fold them.
1627 for (unsigned OtherIdx = Idx+1;
1628 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1629 if (OtherIdx != Idx) {
1630 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1631 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1632 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1633 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1634 const SCEV *NewStart = getMulExpr(F->getStart(),
1636 const SCEV *B = F->getStepRecurrence(*this);
1637 const SCEV *D = G->getStepRecurrence(*this);
1638 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1641 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1643 if (Ops.size() == 2) return NewAddRec;
1645 Ops.erase(Ops.begin()+Idx);
1646 Ops.erase(Ops.begin()+OtherIdx-1);
1647 Ops.push_back(NewAddRec);
1648 return getMulExpr(Ops);
1652 // Otherwise couldn't fold anything into this recurrence. Move onto the
1656 // Okay, it looks like we really DO need an mul expr. Check to see if we
1657 // already have one, otherwise create a new one.
1658 FoldingSetNodeID ID;
1659 ID.AddInteger(scMulExpr);
1660 ID.AddInteger(Ops.size());
1661 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1662 ID.AddPointer(Ops[i]);
1664 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1665 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1666 new (S) SCEVMulExpr(ID, Ops);
1667 UniqueSCEVs.InsertNode(S, IP);
1671 /// getUDivExpr - Get a canonical unsigned division expression, or something
1672 /// simpler if possible.
1673 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1675 assert(getEffectiveSCEVType(LHS->getType()) ==
1676 getEffectiveSCEVType(RHS->getType()) &&
1677 "SCEVUDivExpr operand types don't match!");
1679 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1680 if (RHSC->getValue()->equalsInt(1))
1681 return LHS; // X udiv 1 --> x
1683 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1685 // Determine if the division can be folded into the operands of
1687 // TODO: Generalize this to non-constants by using known-bits information.
1688 const Type *Ty = LHS->getType();
1689 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1690 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1691 // For non-power-of-two values, effectively round the value up to the
1692 // nearest power of two.
1693 if (!RHSC->getValue()->getValue().isPowerOf2())
1695 const IntegerType *ExtTy =
1696 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1697 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1698 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1699 if (const SCEVConstant *Step =
1700 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1701 if (!Step->getValue()->getValue()
1702 .urem(RHSC->getValue()->getValue()) &&
1703 getZeroExtendExpr(AR, ExtTy) ==
1704 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1705 getZeroExtendExpr(Step, ExtTy),
1707 SmallVector<const SCEV *, 4> Operands;
1708 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1709 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1710 return getAddRecExpr(Operands, AR->getLoop());
1712 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1713 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1714 SmallVector<const SCEV *, 4> Operands;
1715 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1716 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1717 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1718 // Find an operand that's safely divisible.
1719 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1720 const SCEV *Op = M->getOperand(i);
1721 const SCEV *Div = getUDivExpr(Op, RHSC);
1722 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1723 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1724 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1727 return getMulExpr(Operands);
1731 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1732 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1733 SmallVector<const SCEV *, 4> Operands;
1734 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1735 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1736 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1738 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1739 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1740 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1742 Operands.push_back(Op);
1744 if (Operands.size() == A->getNumOperands())
1745 return getAddExpr(Operands);
1749 // Fold if both operands are constant.
1750 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1751 Constant *LHSCV = LHSC->getValue();
1752 Constant *RHSCV = RHSC->getValue();
1753 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1758 FoldingSetNodeID ID;
1759 ID.AddInteger(scUDivExpr);
1763 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1764 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1765 new (S) SCEVUDivExpr(ID, LHS, RHS);
1766 UniqueSCEVs.InsertNode(S, IP);
1771 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1772 /// Simplify the expression as much as possible.
1773 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1774 const SCEV *Step, const Loop *L) {
1775 SmallVector<const SCEV *, 4> Operands;
1776 Operands.push_back(Start);
1777 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1778 if (StepChrec->getLoop() == L) {
1779 Operands.insert(Operands.end(), StepChrec->op_begin(),
1780 StepChrec->op_end());
1781 return getAddRecExpr(Operands, L);
1784 Operands.push_back(Step);
1785 return getAddRecExpr(Operands, L);
1788 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1789 /// Simplify the expression as much as possible.
1791 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1793 if (Operands.size() == 1) return Operands[0];
1795 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1796 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1797 getEffectiveSCEVType(Operands[0]->getType()) &&
1798 "SCEVAddRecExpr operand types don't match!");
1801 if (Operands.back()->isZero()) {
1802 Operands.pop_back();
1803 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1806 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1807 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1808 const Loop* NestedLoop = NestedAR->getLoop();
1809 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1810 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1811 NestedAR->op_end());
1812 Operands[0] = NestedAR->getStart();
1813 // AddRecs require their operands be loop-invariant with respect to their
1814 // loops. Don't perform this transformation if it would break this
1816 bool AllInvariant = true;
1817 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1818 if (!Operands[i]->isLoopInvariant(L)) {
1819 AllInvariant = false;
1823 NestedOperands[0] = getAddRecExpr(Operands, L);
1824 AllInvariant = true;
1825 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1826 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1827 AllInvariant = false;
1831 // Ok, both add recurrences are valid after the transformation.
1832 return getAddRecExpr(NestedOperands, NestedLoop);
1834 // Reset Operands to its original state.
1835 Operands[0] = NestedAR;
1839 FoldingSetNodeID ID;
1840 ID.AddInteger(scAddRecExpr);
1841 ID.AddInteger(Operands.size());
1842 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1843 ID.AddPointer(Operands[i]);
1846 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1847 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1848 new (S) SCEVAddRecExpr(ID, Operands, L);
1849 UniqueSCEVs.InsertNode(S, IP);
1853 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1855 SmallVector<const SCEV *, 2> Ops;
1858 return getSMaxExpr(Ops);
1862 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1863 assert(!Ops.empty() && "Cannot get empty smax!");
1864 if (Ops.size() == 1) return Ops[0];
1866 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1867 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1868 getEffectiveSCEVType(Ops[0]->getType()) &&
1869 "SCEVSMaxExpr operand types don't match!");
1872 // Sort by complexity, this groups all similar expression types together.
1873 GroupByComplexity(Ops, LI);
1875 // If there are any constants, fold them together.
1877 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1879 assert(Idx < Ops.size());
1880 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1881 // We found two constants, fold them together!
1882 ConstantInt *Fold = ConstantInt::get(getContext(),
1883 APIntOps::smax(LHSC->getValue()->getValue(),
1884 RHSC->getValue()->getValue()));
1885 Ops[0] = getConstant(Fold);
1886 Ops.erase(Ops.begin()+1); // Erase the folded element
1887 if (Ops.size() == 1) return Ops[0];
1888 LHSC = cast<SCEVConstant>(Ops[0]);
1891 // If we are left with a constant minimum-int, strip it off.
1892 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1893 Ops.erase(Ops.begin());
1895 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1896 // If we have an smax with a constant maximum-int, it will always be
1902 if (Ops.size() == 1) return Ops[0];
1904 // Find the first SMax
1905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1908 // Check to see if one of the operands is an SMax. If so, expand its operands
1909 // onto our operand list, and recurse to simplify.
1910 if (Idx < Ops.size()) {
1911 bool DeletedSMax = false;
1912 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1913 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1914 Ops.erase(Ops.begin()+Idx);
1919 return getSMaxExpr(Ops);
1922 // Okay, check to see if the same value occurs in the operand list twice. If
1923 // so, delete one. Since we sorted the list, these values are required to
1925 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1926 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1927 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1931 if (Ops.size() == 1) return Ops[0];
1933 assert(!Ops.empty() && "Reduced smax down to nothing!");
1935 // Okay, it looks like we really DO need an smax expr. Check to see if we
1936 // already have one, otherwise create a new one.
1937 FoldingSetNodeID ID;
1938 ID.AddInteger(scSMaxExpr);
1939 ID.AddInteger(Ops.size());
1940 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1941 ID.AddPointer(Ops[i]);
1943 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1944 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1945 new (S) SCEVSMaxExpr(ID, Ops);
1946 UniqueSCEVs.InsertNode(S, IP);
1950 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1952 SmallVector<const SCEV *, 2> Ops;
1955 return getUMaxExpr(Ops);
1959 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1960 assert(!Ops.empty() && "Cannot get empty umax!");
1961 if (Ops.size() == 1) return Ops[0];
1963 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1964 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1965 getEffectiveSCEVType(Ops[0]->getType()) &&
1966 "SCEVUMaxExpr operand types don't match!");
1969 // Sort by complexity, this groups all similar expression types together.
1970 GroupByComplexity(Ops, LI);
1972 // If there are any constants, fold them together.
1974 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1976 assert(Idx < Ops.size());
1977 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1978 // We found two constants, fold them together!
1979 ConstantInt *Fold = ConstantInt::get(getContext(),
1980 APIntOps::umax(LHSC->getValue()->getValue(),
1981 RHSC->getValue()->getValue()));
1982 Ops[0] = getConstant(Fold);
1983 Ops.erase(Ops.begin()+1); // Erase the folded element
1984 if (Ops.size() == 1) return Ops[0];
1985 LHSC = cast<SCEVConstant>(Ops[0]);
1988 // If we are left with a constant minimum-int, strip it off.
1989 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1990 Ops.erase(Ops.begin());
1992 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1993 // If we have an umax with a constant maximum-int, it will always be
1999 if (Ops.size() == 1) return Ops[0];
2001 // Find the first UMax
2002 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2005 // Check to see if one of the operands is a UMax. If so, expand its operands
2006 // onto our operand list, and recurse to simplify.
2007 if (Idx < Ops.size()) {
2008 bool DeletedUMax = false;
2009 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2010 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2011 Ops.erase(Ops.begin()+Idx);
2016 return getUMaxExpr(Ops);
2019 // Okay, check to see if the same value occurs in the operand list twice. If
2020 // so, delete one. Since we sorted the list, these values are required to
2022 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2023 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2024 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2028 if (Ops.size() == 1) return Ops[0];
2030 assert(!Ops.empty() && "Reduced umax down to nothing!");
2032 // Okay, it looks like we really DO need a umax expr. Check to see if we
2033 // already have one, otherwise create a new one.
2034 FoldingSetNodeID ID;
2035 ID.AddInteger(scUMaxExpr);
2036 ID.AddInteger(Ops.size());
2037 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2038 ID.AddPointer(Ops[i]);
2040 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2041 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2042 new (S) SCEVUMaxExpr(ID, Ops);
2043 UniqueSCEVs.InsertNode(S, IP);
2047 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2049 // ~smax(~x, ~y) == smin(x, y).
2050 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2053 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2055 // ~umax(~x, ~y) == umin(x, y)
2056 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2059 const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2061 // If we have TargetData we can determine the constant offset.
2063 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2064 const StructLayout &SL = *TD->getStructLayout(STy);
2065 uint64_t Offset = SL.getElementOffset(FieldNo);
2066 return getIntegerSCEV(Offset, IntPtrTy);
2069 // Field 0 is always at offset 0.
2071 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2072 return getIntegerSCEV(0, Ty);
2075 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2076 // already have one, otherwise create a new one.
2077 FoldingSetNodeID ID;
2078 ID.AddInteger(scFieldOffset);
2080 ID.AddInteger(FieldNo);
2082 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2083 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2084 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2085 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2086 UniqueSCEVs.InsertNode(S, IP);
2090 const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2091 // If we have TargetData we can determine the constant size.
2092 if (TD && AllocTy->isSized()) {
2093 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2094 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2097 // Expand an array size into the element size times the number
2099 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2100 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2102 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2103 ATy->getNumElements())));
2106 // Expand a vector size into the element size times the number
2108 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2109 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2111 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2112 VTy->getNumElements())));
2115 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2116 // already have one, otherwise create a new one.
2117 FoldingSetNodeID ID;
2118 ID.AddInteger(scAllocSize);
2119 ID.AddPointer(AllocTy);
2121 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2122 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2123 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2124 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2125 UniqueSCEVs.InsertNode(S, IP);
2129 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2130 // Don't attempt to do anything other than create a SCEVUnknown object
2131 // here. createSCEV only calls getUnknown after checking for all other
2132 // interesting possibilities, and any other code that calls getUnknown
2133 // is doing so in order to hide a value from SCEV canonicalization.
2135 FoldingSetNodeID ID;
2136 ID.AddInteger(scUnknown);
2139 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2140 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2141 new (S) SCEVUnknown(ID, V);
2142 UniqueSCEVs.InsertNode(S, IP);
2146 //===----------------------------------------------------------------------===//
2147 // Basic SCEV Analysis and PHI Idiom Recognition Code
2150 /// isSCEVable - Test if values of the given type are analyzable within
2151 /// the SCEV framework. This primarily includes integer types, and it
2152 /// can optionally include pointer types if the ScalarEvolution class
2153 /// has access to target-specific information.
2154 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2155 // Integers and pointers are always SCEVable.
2156 return Ty->isInteger() || isa<PointerType>(Ty);
2159 /// getTypeSizeInBits - Return the size in bits of the specified type,
2160 /// for which isSCEVable must return true.
2161 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2162 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2164 // If we have a TargetData, use it!
2166 return TD->getTypeSizeInBits(Ty);
2168 // Integer types have fixed sizes.
2169 if (Ty->isInteger())
2170 return Ty->getPrimitiveSizeInBits();
2172 // The only other support type is pointer. Without TargetData, conservatively
2173 // assume pointers are 64-bit.
2174 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2178 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2179 /// the given type and which represents how SCEV will treat the given
2180 /// type, for which isSCEVable must return true. For pointer types,
2181 /// this is the pointer-sized integer type.
2182 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2183 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2185 if (Ty->isInteger())
2188 // The only other support type is pointer.
2189 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2190 if (TD) return TD->getIntPtrType(getContext());
2192 // Without TargetData, conservatively assume pointers are 64-bit.
2193 return Type::getInt64Ty(getContext());
2196 const SCEV *ScalarEvolution::getCouldNotCompute() {
2197 return &CouldNotCompute;
2200 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2201 /// expression and create a new one.
2202 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2203 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2205 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2206 if (I != Scalars.end()) return I->second;
2207 const SCEV *S = createSCEV(V);
2208 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2212 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2213 /// specified signed integer value and return a SCEV for the constant.
2214 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2215 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2216 return getConstant(ConstantInt::get(ITy, Val));
2219 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2221 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2222 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2224 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2226 const Type *Ty = V->getType();
2227 Ty = getEffectiveSCEVType(Ty);
2228 return getMulExpr(V,
2229 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2232 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2233 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2234 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2236 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2238 const Type *Ty = V->getType();
2239 Ty = getEffectiveSCEVType(Ty);
2240 const SCEV *AllOnes =
2241 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2242 return getMinusSCEV(AllOnes, V);
2245 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2247 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2250 return getAddExpr(LHS, getNegativeSCEV(RHS));
2253 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2254 /// input value to the specified type. If the type must be extended, it is zero
2257 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2259 const Type *SrcTy = V->getType();
2260 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2261 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2262 "Cannot truncate or zero extend with non-integer arguments!");
2263 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2264 return V; // No conversion
2265 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2266 return getTruncateExpr(V, Ty);
2267 return getZeroExtendExpr(V, Ty);
2270 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2271 /// input value to the specified type. If the type must be extended, it is sign
2274 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2276 const Type *SrcTy = V->getType();
2277 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2278 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2279 "Cannot truncate or zero extend with non-integer arguments!");
2280 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2281 return V; // No conversion
2282 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2283 return getTruncateExpr(V, Ty);
2284 return getSignExtendExpr(V, Ty);
2287 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2288 /// input value to the specified type. If the type must be extended, it is zero
2289 /// extended. The conversion must not be narrowing.
2291 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2292 const Type *SrcTy = V->getType();
2293 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2294 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2295 "Cannot noop or zero extend with non-integer arguments!");
2296 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2297 "getNoopOrZeroExtend cannot truncate!");
2298 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2299 return V; // No conversion
2300 return getZeroExtendExpr(V, Ty);
2303 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2304 /// input value to the specified type. If the type must be extended, it is sign
2305 /// extended. The conversion must not be narrowing.
2307 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2308 const Type *SrcTy = V->getType();
2309 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2310 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2311 "Cannot noop or sign extend with non-integer arguments!");
2312 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2313 "getNoopOrSignExtend cannot truncate!");
2314 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2315 return V; // No conversion
2316 return getSignExtendExpr(V, Ty);
2319 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2320 /// the input value to the specified type. If the type must be extended,
2321 /// it is extended with unspecified bits. The conversion must not be
2324 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2325 const Type *SrcTy = V->getType();
2326 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2327 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2328 "Cannot noop or any extend with non-integer arguments!");
2329 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2330 "getNoopOrAnyExtend cannot truncate!");
2331 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2332 return V; // No conversion
2333 return getAnyExtendExpr(V, Ty);
2336 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2337 /// input value to the specified type. The conversion must not be widening.
2339 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2340 const Type *SrcTy = V->getType();
2341 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2342 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2343 "Cannot truncate or noop with non-integer arguments!");
2344 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2345 "getTruncateOrNoop cannot extend!");
2346 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2347 return V; // No conversion
2348 return getTruncateExpr(V, Ty);
2351 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2352 /// the types using zero-extension, and then perform a umax operation
2354 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2356 const SCEV *PromotedLHS = LHS;
2357 const SCEV *PromotedRHS = RHS;
2359 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2360 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2362 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2364 return getUMaxExpr(PromotedLHS, PromotedRHS);
2367 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2368 /// the types using zero-extension, and then perform a umin operation
2370 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2372 const SCEV *PromotedLHS = LHS;
2373 const SCEV *PromotedRHS = RHS;
2375 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2376 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2378 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2380 return getUMinExpr(PromotedLHS, PromotedRHS);
2383 /// PushDefUseChildren - Push users of the given Instruction
2384 /// onto the given Worklist.
2386 PushDefUseChildren(Instruction *I,
2387 SmallVectorImpl<Instruction *> &Worklist) {
2388 // Push the def-use children onto the Worklist stack.
2389 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2391 Worklist.push_back(cast<Instruction>(UI));
2394 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2395 /// instructions that depend on the given instruction and removes them from
2396 /// the Scalars map if they reference SymName. This is used during PHI
2399 ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2400 SmallVector<Instruction *, 16> Worklist;
2401 PushDefUseChildren(I, Worklist);
2403 SmallPtrSet<Instruction *, 8> Visited;
2405 while (!Worklist.empty()) {
2406 Instruction *I = Worklist.pop_back_val();
2407 if (!Visited.insert(I)) continue;
2409 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2410 Scalars.find(static_cast<Value *>(I));
2411 if (It != Scalars.end()) {
2412 // Short-circuit the def-use traversal if the symbolic name
2413 // ceases to appear in expressions.
2414 if (!It->second->hasOperand(SymName))
2417 // SCEVUnknown for a PHI either means that it has an unrecognized
2418 // structure, or it's a PHI that's in the progress of being computed
2419 // by createNodeForPHI. In the former case, additional loop trip
2420 // count information isn't going to change anything. In the later
2421 // case, createNodeForPHI will perform the necessary updates on its
2422 // own when it gets to that point.
2423 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2425 ValuesAtScopes.erase(I);
2428 PushDefUseChildren(I, Worklist);
2432 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2433 /// a loop header, making it a potential recurrence, or it doesn't.
2435 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2436 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2437 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2438 if (L->getHeader() == PN->getParent()) {
2439 // If it lives in the loop header, it has two incoming values, one
2440 // from outside the loop, and one from inside.
2441 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2442 unsigned BackEdge = IncomingEdge^1;
2444 // While we are analyzing this PHI node, handle its value symbolically.
2445 const SCEV *SymbolicName = getUnknown(PN);
2446 assert(Scalars.find(PN) == Scalars.end() &&
2447 "PHI node already processed?");
2448 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2450 // Using this symbolic name for the PHI, analyze the value coming around
2452 Value *BEValueV = PN->getIncomingValue(BackEdge);
2453 const SCEV *BEValue = getSCEV(BEValueV);
2455 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2456 // has a special value for the first iteration of the loop.
2458 // If the value coming around the backedge is an add with the symbolic
2459 // value we just inserted, then we found a simple induction variable!
2460 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2461 // If there is a single occurrence of the symbolic value, replace it
2462 // with a recurrence.
2463 unsigned FoundIndex = Add->getNumOperands();
2464 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2465 if (Add->getOperand(i) == SymbolicName)
2466 if (FoundIndex == e) {
2471 if (FoundIndex != Add->getNumOperands()) {
2472 // Create an add with everything but the specified operand.
2473 SmallVector<const SCEV *, 8> Ops;
2474 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2475 if (i != FoundIndex)
2476 Ops.push_back(Add->getOperand(i));
2477 const SCEV *Accum = getAddExpr(Ops);
2479 // This is not a valid addrec if the step amount is varying each
2480 // loop iteration, but is not itself an addrec in this loop.
2481 if (Accum->isLoopInvariant(L) ||
2482 (isa<SCEVAddRecExpr>(Accum) &&
2483 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2484 const SCEV *StartVal =
2485 getSCEV(PN->getIncomingValue(IncomingEdge));
2486 const SCEVAddRecExpr *PHISCEV =
2487 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2489 // If the increment doesn't overflow, then neither the addrec nor the
2490 // post-increment will overflow.
2491 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2492 if (OBO->getOperand(0) == PN &&
2493 getSCEV(OBO->getOperand(1)) ==
2494 PHISCEV->getStepRecurrence(*this)) {
2495 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
2496 if (OBO->hasNoUnsignedWrap()) {
2497 const_cast<SCEVAddRecExpr *>(PHISCEV)
2498 ->setHasNoUnsignedWrap(true);
2499 const_cast<SCEVAddRecExpr *>(PostInc)
2500 ->setHasNoUnsignedWrap(true);
2502 if (OBO->hasNoSignedWrap()) {
2503 const_cast<SCEVAddRecExpr *>(PHISCEV)
2504 ->setHasNoSignedWrap(true);
2505 const_cast<SCEVAddRecExpr *>(PostInc)
2506 ->setHasNoSignedWrap(true);
2510 // Okay, for the entire analysis of this edge we assumed the PHI
2511 // to be symbolic. We now need to go back and purge all of the
2512 // entries for the scalars that use the symbolic expression.
2513 ForgetSymbolicName(PN, SymbolicName);
2514 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2518 } else if (const SCEVAddRecExpr *AddRec =
2519 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2520 // Otherwise, this could be a loop like this:
2521 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2522 // In this case, j = {1,+,1} and BEValue is j.
2523 // Because the other in-value of i (0) fits the evolution of BEValue
2524 // i really is an addrec evolution.
2525 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2526 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2528 // If StartVal = j.start - j.stride, we can use StartVal as the
2529 // initial step of the addrec evolution.
2530 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2531 AddRec->getOperand(1))) {
2532 const SCEV *PHISCEV =
2533 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2535 // Okay, for the entire analysis of this edge we assumed the PHI
2536 // to be symbolic. We now need to go back and purge all of the
2537 // entries for the scalars that use the symbolic expression.
2538 ForgetSymbolicName(PN, SymbolicName);
2539 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2545 return SymbolicName;
2548 // It's tempting to recognize PHIs with a unique incoming value, however
2549 // this leads passes like indvars to break LCSSA form. Fortunately, such
2550 // PHIs are rare, as instcombine zaps them.
2552 // If it's not a loop phi, we can't handle it yet.
2553 return getUnknown(PN);
2556 /// createNodeForGEP - Expand GEP instructions into add and multiply
2557 /// operations. This allows them to be analyzed by regular SCEV code.
2559 const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
2561 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2562 Value *Base = GEP->getOperand(0);
2563 // Don't attempt to analyze GEPs over unsized objects.
2564 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2565 return getUnknown(GEP);
2566 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2567 gep_type_iterator GTI = gep_type_begin(GEP);
2568 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2572 // Compute the (potentially symbolic) offset in bytes for this index.
2573 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2574 // For a struct, add the member offset.
2575 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2576 TotalOffset = getAddExpr(TotalOffset,
2577 getFieldOffsetExpr(STy, FieldNo));
2579 // For an array, add the element offset, explicitly scaled.
2580 const SCEV *LocalOffset = getSCEV(Index);
2581 if (!isa<PointerType>(LocalOffset->getType()))
2582 // Getelementptr indicies are signed.
2583 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2584 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
2585 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2588 return getAddExpr(getSCEV(Base), TotalOffset);
2591 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2592 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2593 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2594 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2596 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2597 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2598 return C->getValue()->getValue().countTrailingZeros();
2600 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2601 return std::min(GetMinTrailingZeros(T->getOperand()),
2602 (uint32_t)getTypeSizeInBits(T->getType()));
2604 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2605 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2606 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2607 getTypeSizeInBits(E->getType()) : OpRes;
2610 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2611 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2612 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2613 getTypeSizeInBits(E->getType()) : OpRes;
2616 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2617 // The result is the min of all operands results.
2618 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2619 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2620 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2624 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2625 // The result is the sum of all operands results.
2626 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2627 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2628 for (unsigned i = 1, e = M->getNumOperands();
2629 SumOpRes != BitWidth && i != e; ++i)
2630 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2635 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2636 // The result is the min of all operands results.
2637 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2638 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2639 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2643 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2644 // The result is the min of all operands results.
2645 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2646 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2647 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2651 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2652 // The result is the min of all operands results.
2653 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2654 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2655 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2659 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2660 // For a SCEVUnknown, ask ValueTracking.
2661 unsigned BitWidth = getTypeSizeInBits(U->getType());
2662 APInt Mask = APInt::getAllOnesValue(BitWidth);
2663 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2664 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2665 return Zeros.countTrailingOnes();
2672 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2675 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2677 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2678 return ConstantRange(C->getValue()->getValue());
2680 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2681 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2682 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2683 X = X.add(getUnsignedRange(Add->getOperand(i)));
2687 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2688 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2689 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2690 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2694 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2695 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2696 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2697 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2701 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2702 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2703 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2704 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2708 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2709 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2710 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2714 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2715 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2716 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2719 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2720 ConstantRange X = getUnsignedRange(SExt->getOperand());
2721 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2724 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2725 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2726 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2729 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2731 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2732 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2733 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2734 if (!Trip) return FullSet;
2736 // TODO: non-affine addrec
2737 if (AddRec->isAffine()) {
2738 const Type *Ty = AddRec->getType();
2739 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2740 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2741 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2743 const SCEV *Start = AddRec->getStart();
2744 const SCEV *Step = AddRec->getStepRecurrence(*this);
2745 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2747 // Check for overflow.
2748 // TODO: This is very conservative.
2749 if (!(Step->isOne() &&
2750 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2751 !(Step->isAllOnesValue() &&
2752 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
2755 ConstantRange StartRange = getUnsignedRange(Start);
2756 ConstantRange EndRange = getUnsignedRange(End);
2757 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2758 EndRange.getUnsignedMin());
2759 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2760 EndRange.getUnsignedMax());
2761 if (Min.isMinValue() && Max.isMaxValue())
2763 return ConstantRange(Min, Max+1);
2768 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2769 // For a SCEVUnknown, ask ValueTracking.
2770 unsigned BitWidth = getTypeSizeInBits(U->getType());
2771 APInt Mask = APInt::getAllOnesValue(BitWidth);
2772 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2773 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2774 if (Ones == ~Zeros + 1)
2776 return ConstantRange(Ones, ~Zeros + 1);
2782 /// getSignedRange - Determine the signed range for a particular SCEV.
2785 ScalarEvolution::getSignedRange(const SCEV *S) {
2787 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2788 return ConstantRange(C->getValue()->getValue());
2790 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2791 ConstantRange X = getSignedRange(Add->getOperand(0));
2792 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2793 X = X.add(getSignedRange(Add->getOperand(i)));
2797 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2798 ConstantRange X = getSignedRange(Mul->getOperand(0));
2799 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2800 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2804 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2805 ConstantRange X = getSignedRange(SMax->getOperand(0));
2806 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2807 X = X.smax(getSignedRange(SMax->getOperand(i)));
2811 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2812 ConstantRange X = getSignedRange(UMax->getOperand(0));
2813 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2814 X = X.umax(getSignedRange(UMax->getOperand(i)));
2818 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2819 ConstantRange X = getSignedRange(UDiv->getLHS());
2820 ConstantRange Y = getSignedRange(UDiv->getRHS());
2824 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2825 ConstantRange X = getSignedRange(ZExt->getOperand());
2826 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2829 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2830 ConstantRange X = getSignedRange(SExt->getOperand());
2831 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2834 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2835 ConstantRange X = getSignedRange(Trunc->getOperand());
2836 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2839 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2841 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2842 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2843 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2844 if (!Trip) return FullSet;
2846 // TODO: non-affine addrec
2847 if (AddRec->isAffine()) {
2848 const Type *Ty = AddRec->getType();
2849 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2850 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2851 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2853 const SCEV *Start = AddRec->getStart();
2854 const SCEV *Step = AddRec->getStepRecurrence(*this);
2855 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2857 // Check for overflow.
2858 // TODO: This is very conservative.
2859 if (!(Step->isOne() &&
2860 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2861 !(Step->isAllOnesValue() &&
2862 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2865 ConstantRange StartRange = getSignedRange(Start);
2866 ConstantRange EndRange = getSignedRange(End);
2867 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2868 EndRange.getSignedMin());
2869 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2870 EndRange.getSignedMax());
2871 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2873 return ConstantRange(Min, Max+1);
2878 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2879 // For a SCEVUnknown, ask ValueTracking.
2880 unsigned BitWidth = getTypeSizeInBits(U->getType());
2881 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2885 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2886 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
2892 /// createSCEV - We know that there is no SCEV for the specified value.
2893 /// Analyze the expression.
2895 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2896 if (!isSCEVable(V->getType()))
2897 return getUnknown(V);
2899 unsigned Opcode = Instruction::UserOp1;
2900 if (Instruction *I = dyn_cast<Instruction>(V))
2901 Opcode = I->getOpcode();
2902 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2903 Opcode = CE->getOpcode();
2904 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2905 return getConstant(CI);
2906 else if (isa<ConstantPointerNull>(V))
2907 return getIntegerSCEV(0, V->getType());
2908 else if (isa<UndefValue>(V))
2909 return getIntegerSCEV(0, V->getType());
2910 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
2911 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
2913 return getUnknown(V);
2915 Operator *U = cast<Operator>(V);
2917 case Instruction::Add:
2918 return getAddExpr(getSCEV(U->getOperand(0)),
2919 getSCEV(U->getOperand(1)));
2920 case Instruction::Mul:
2921 return getMulExpr(getSCEV(U->getOperand(0)),
2922 getSCEV(U->getOperand(1)));
2923 case Instruction::UDiv:
2924 return getUDivExpr(getSCEV(U->getOperand(0)),
2925 getSCEV(U->getOperand(1)));
2926 case Instruction::Sub:
2927 return getMinusSCEV(getSCEV(U->getOperand(0)),
2928 getSCEV(U->getOperand(1)));
2929 case Instruction::And:
2930 // For an expression like x&255 that merely masks off the high bits,
2931 // use zext(trunc(x)) as the SCEV expression.
2932 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2933 if (CI->isNullValue())
2934 return getSCEV(U->getOperand(1));
2935 if (CI->isAllOnesValue())
2936 return getSCEV(U->getOperand(0));
2937 const APInt &A = CI->getValue();
2939 // Instcombine's ShrinkDemandedConstant may strip bits out of
2940 // constants, obscuring what would otherwise be a low-bits mask.
2941 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2942 // knew about to reconstruct a low-bits mask value.
2943 unsigned LZ = A.countLeadingZeros();
2944 unsigned BitWidth = A.getBitWidth();
2945 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2946 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2947 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2949 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2951 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2953 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2954 IntegerType::get(getContext(), BitWidth - LZ)),
2959 case Instruction::Or:
2960 // If the RHS of the Or is a constant, we may have something like:
2961 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2962 // optimizations will transparently handle this case.
2964 // In order for this transformation to be safe, the LHS must be of the
2965 // form X*(2^n) and the Or constant must be less than 2^n.
2966 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2967 const SCEV *LHS = getSCEV(U->getOperand(0));
2968 const APInt &CIVal = CI->getValue();
2969 if (GetMinTrailingZeros(LHS) >=
2970 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2971 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2974 case Instruction::Xor:
2975 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2976 // If the RHS of the xor is a signbit, then this is just an add.
2977 // Instcombine turns add of signbit into xor as a strength reduction step.
2978 if (CI->getValue().isSignBit())
2979 return getAddExpr(getSCEV(U->getOperand(0)),
2980 getSCEV(U->getOperand(1)));
2982 // If the RHS of xor is -1, then this is a not operation.
2983 if (CI->isAllOnesValue())
2984 return getNotSCEV(getSCEV(U->getOperand(0)));
2986 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2987 // This is a variant of the check for xor with -1, and it handles
2988 // the case where instcombine has trimmed non-demanded bits out
2989 // of an xor with -1.
2990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2991 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2992 if (BO->getOpcode() == Instruction::And &&
2993 LCI->getValue() == CI->getValue())
2994 if (const SCEVZeroExtendExpr *Z =
2995 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2996 const Type *UTy = U->getType();
2997 const SCEV *Z0 = Z->getOperand();
2998 const Type *Z0Ty = Z0->getType();
2999 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3001 // If C is a low-bits mask, the zero extend is zerving to
3002 // mask off the high bits. Complement the operand and
3003 // re-apply the zext.
3004 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3005 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3007 // If C is a single bit, it may be in the sign-bit position
3008 // before the zero-extend. In this case, represent the xor
3009 // using an add, which is equivalent, and re-apply the zext.
3010 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3011 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3013 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3019 case Instruction::Shl:
3020 // Turn shift left of a constant amount into a multiply.
3021 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3022 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3023 Constant *X = ConstantInt::get(getContext(),
3024 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3025 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3029 case Instruction::LShr:
3030 // Turn logical shift right of a constant into a unsigned divide.
3031 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3032 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3033 Constant *X = ConstantInt::get(getContext(),
3034 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3035 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3039 case Instruction::AShr:
3040 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3041 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3042 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3043 if (L->getOpcode() == Instruction::Shl &&
3044 L->getOperand(1) == U->getOperand(1)) {
3045 unsigned BitWidth = getTypeSizeInBits(U->getType());
3046 uint64_t Amt = BitWidth - CI->getZExtValue();
3047 if (Amt == BitWidth)
3048 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3050 return getIntegerSCEV(0, U->getType()); // value is undefined
3052 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3053 IntegerType::get(getContext(), Amt)),
3058 case Instruction::Trunc:
3059 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3061 case Instruction::ZExt:
3062 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3064 case Instruction::SExt:
3065 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3067 case Instruction::BitCast:
3068 // BitCasts are no-op casts so we just eliminate the cast.
3069 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3070 return getSCEV(U->getOperand(0));
3073 // It's tempting to handle inttoptr and ptrtoint, however this can
3074 // lead to pointer expressions which cannot be expanded to GEPs
3075 // (because they may overflow). For now, the only pointer-typed
3076 // expressions we handle are GEPs and address literals.
3078 case Instruction::GetElementPtr:
3079 return createNodeForGEP(U);
3081 case Instruction::PHI:
3082 return createNodeForPHI(cast<PHINode>(U));
3084 case Instruction::Select:
3085 // This could be a smax or umax that was lowered earlier.
3086 // Try to recover it.
3087 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3088 Value *LHS = ICI->getOperand(0);
3089 Value *RHS = ICI->getOperand(1);
3090 switch (ICI->getPredicate()) {
3091 case ICmpInst::ICMP_SLT:
3092 case ICmpInst::ICMP_SLE:
3093 std::swap(LHS, RHS);
3095 case ICmpInst::ICMP_SGT:
3096 case ICmpInst::ICMP_SGE:
3097 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3098 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
3099 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3100 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
3102 case ICmpInst::ICMP_ULT:
3103 case ICmpInst::ICMP_ULE:
3104 std::swap(LHS, RHS);
3106 case ICmpInst::ICMP_UGT:
3107 case ICmpInst::ICMP_UGE:
3108 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3109 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
3110 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3111 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
3113 case ICmpInst::ICMP_NE:
3114 // n != 0 ? n : 1 -> umax(n, 1)
3115 if (LHS == U->getOperand(1) &&
3116 isa<ConstantInt>(U->getOperand(2)) &&
3117 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3118 isa<ConstantInt>(RHS) &&
3119 cast<ConstantInt>(RHS)->isZero())
3120 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3122 case ICmpInst::ICMP_EQ:
3123 // n == 0 ? 1 : n -> umax(n, 1)
3124 if (LHS == U->getOperand(2) &&
3125 isa<ConstantInt>(U->getOperand(1)) &&
3126 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3127 isa<ConstantInt>(RHS) &&
3128 cast<ConstantInt>(RHS)->isZero())
3129 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3136 default: // We cannot analyze this expression.
3140 return getUnknown(V);
3145 //===----------------------------------------------------------------------===//
3146 // Iteration Count Computation Code
3149 /// getBackedgeTakenCount - If the specified loop has a predictable
3150 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3151 /// object. The backedge-taken count is the number of times the loop header
3152 /// will be branched to from within the loop. This is one less than the
3153 /// trip count of the loop, since it doesn't count the first iteration,
3154 /// when the header is branched to from outside the loop.
3156 /// Note that it is not valid to call this method on a loop without a
3157 /// loop-invariant backedge-taken count (see
3158 /// hasLoopInvariantBackedgeTakenCount).
3160 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3161 return getBackedgeTakenInfo(L).Exact;
3164 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3165 /// return the least SCEV value that is known never to be less than the
3166 /// actual backedge taken count.
3167 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3168 return getBackedgeTakenInfo(L).Max;
3171 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3172 /// onto the given Worklist.
3174 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3175 BasicBlock *Header = L->getHeader();
3177 // Push all Loop-header PHIs onto the Worklist stack.
3178 for (BasicBlock::iterator I = Header->begin();
3179 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3180 Worklist.push_back(PN);
3183 const ScalarEvolution::BackedgeTakenInfo &
3184 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3185 // Initially insert a CouldNotCompute for this loop. If the insertion
3186 // succeeds, procede to actually compute a backedge-taken count and
3187 // update the value. The temporary CouldNotCompute value tells SCEV
3188 // code elsewhere that it shouldn't attempt to request a new
3189 // backedge-taken count, which could result in infinite recursion.
3190 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
3191 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3193 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
3194 if (ItCount.Exact != getCouldNotCompute()) {
3195 assert(ItCount.Exact->isLoopInvariant(L) &&
3196 ItCount.Max->isLoopInvariant(L) &&
3197 "Computed trip count isn't loop invariant for loop!");
3198 ++NumTripCountsComputed;
3200 // Update the value in the map.
3201 Pair.first->second = ItCount;
3203 if (ItCount.Max != getCouldNotCompute())
3204 // Update the value in the map.
3205 Pair.first->second = ItCount;
3206 if (isa<PHINode>(L->getHeader()->begin()))
3207 // Only count loops that have phi nodes as not being computable.
3208 ++NumTripCountsNotComputed;
3211 // Now that we know more about the trip count for this loop, forget any
3212 // existing SCEV values for PHI nodes in this loop since they are only
3213 // conservative estimates made without the benefit of trip count
3214 // information. This is similar to the code in
3215 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3217 if (ItCount.hasAnyInfo()) {
3218 SmallVector<Instruction *, 16> Worklist;
3219 PushLoopPHIs(L, Worklist);
3221 SmallPtrSet<Instruction *, 8> Visited;
3222 while (!Worklist.empty()) {
3223 Instruction *I = Worklist.pop_back_val();
3224 if (!Visited.insert(I)) continue;
3226 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3227 Scalars.find(static_cast<Value *>(I));
3228 if (It != Scalars.end()) {
3229 // SCEVUnknown for a PHI either means that it has an unrecognized
3230 // structure, or it's a PHI that's in the progress of being computed
3231 // by createNodeForPHI. In the former case, additional loop trip
3232 // count information isn't going to change anything. In the later
3233 // case, createNodeForPHI will perform the necessary updates on its
3234 // own when it gets to that point.
3235 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3237 ValuesAtScopes.erase(I);
3238 if (PHINode *PN = dyn_cast<PHINode>(I))
3239 ConstantEvolutionLoopExitValue.erase(PN);
3242 PushDefUseChildren(I, Worklist);
3246 return Pair.first->second;
3249 /// forgetLoopBackedgeTakenCount - This method should be called by the
3250 /// client when it has changed a loop in a way that may effect
3251 /// ScalarEvolution's ability to compute a trip count, or if the loop
3253 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3254 BackedgeTakenCounts.erase(L);
3256 SmallVector<Instruction *, 16> Worklist;
3257 PushLoopPHIs(L, Worklist);
3259 SmallPtrSet<Instruction *, 8> Visited;
3260 while (!Worklist.empty()) {
3261 Instruction *I = Worklist.pop_back_val();
3262 if (!Visited.insert(I)) continue;
3264 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3265 Scalars.find(static_cast<Value *>(I));
3266 if (It != Scalars.end()) {
3268 ValuesAtScopes.erase(I);
3269 if (PHINode *PN = dyn_cast<PHINode>(I))
3270 ConstantEvolutionLoopExitValue.erase(PN);
3273 PushDefUseChildren(I, Worklist);
3277 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3278 /// of the specified loop will execute.
3279 ScalarEvolution::BackedgeTakenInfo
3280 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3281 SmallVector<BasicBlock*, 8> ExitingBlocks;
3282 L->getExitingBlocks(ExitingBlocks);
3284 // Examine all exits and pick the most conservative values.
3285 const SCEV *BECount = getCouldNotCompute();
3286 const SCEV *MaxBECount = getCouldNotCompute();
3287 bool CouldNotComputeBECount = false;
3288 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3289 BackedgeTakenInfo NewBTI =
3290 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3292 if (NewBTI.Exact == getCouldNotCompute()) {
3293 // We couldn't compute an exact value for this exit, so
3294 // we won't be able to compute an exact value for the loop.
3295 CouldNotComputeBECount = true;
3296 BECount = getCouldNotCompute();
3297 } else if (!CouldNotComputeBECount) {
3298 if (BECount == getCouldNotCompute())
3299 BECount = NewBTI.Exact;
3301 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3303 if (MaxBECount == getCouldNotCompute())
3304 MaxBECount = NewBTI.Max;
3305 else if (NewBTI.Max != getCouldNotCompute())
3306 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3309 return BackedgeTakenInfo(BECount, MaxBECount);
3312 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3313 /// of the specified loop will execute if it exits via the specified block.
3314 ScalarEvolution::BackedgeTakenInfo
3315 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3316 BasicBlock *ExitingBlock) {
3318 // Okay, we've chosen an exiting block. See what condition causes us to
3319 // exit at this block.
3321 // FIXME: we should be able to handle switch instructions (with a single exit)
3322 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3323 if (ExitBr == 0) return getCouldNotCompute();
3324 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3326 // At this point, we know we have a conditional branch that determines whether
3327 // the loop is exited. However, we don't know if the branch is executed each
3328 // time through the loop. If not, then the execution count of the branch will
3329 // not be equal to the trip count of the loop.
3331 // Currently we check for this by checking to see if the Exit branch goes to
3332 // the loop header. If so, we know it will always execute the same number of
3333 // times as the loop. We also handle the case where the exit block *is* the
3334 // loop header. This is common for un-rotated loops.
3336 // If both of those tests fail, walk up the unique predecessor chain to the
3337 // header, stopping if there is an edge that doesn't exit the loop. If the
3338 // header is reached, the execution count of the branch will be equal to the
3339 // trip count of the loop.
3341 // More extensive analysis could be done to handle more cases here.
3343 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3344 ExitBr->getSuccessor(1) != L->getHeader() &&
3345 ExitBr->getParent() != L->getHeader()) {
3346 // The simple checks failed, try climbing the unique predecessor chain
3347 // up to the header.
3349 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3350 BasicBlock *Pred = BB->getUniquePredecessor();
3352 return getCouldNotCompute();
3353 TerminatorInst *PredTerm = Pred->getTerminator();
3354 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3355 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3358 // If the predecessor has a successor that isn't BB and isn't
3359 // outside the loop, assume the worst.
3360 if (L->contains(PredSucc))
3361 return getCouldNotCompute();
3363 if (Pred == L->getHeader()) {
3370 return getCouldNotCompute();
3373 // Procede to the next level to examine the exit condition expression.
3374 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3375 ExitBr->getSuccessor(0),
3376 ExitBr->getSuccessor(1));
3379 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3380 /// backedge of the specified loop will execute if its exit condition
3381 /// were a conditional branch of ExitCond, TBB, and FBB.
3382 ScalarEvolution::BackedgeTakenInfo
3383 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3387 // Check if the controlling expression for this loop is an And or Or.
3388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3389 if (BO->getOpcode() == Instruction::And) {
3390 // Recurse on the operands of the and.
3391 BackedgeTakenInfo BTI0 =
3392 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3393 BackedgeTakenInfo BTI1 =
3394 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3395 const SCEV *BECount = getCouldNotCompute();
3396 const SCEV *MaxBECount = getCouldNotCompute();
3397 if (L->contains(TBB)) {
3398 // Both conditions must be true for the loop to continue executing.
3399 // Choose the less conservative count.
3400 if (BTI0.Exact == getCouldNotCompute() ||
3401 BTI1.Exact == getCouldNotCompute())
3402 BECount = getCouldNotCompute();
3404 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3405 if (BTI0.Max == getCouldNotCompute())
3406 MaxBECount = BTI1.Max;
3407 else if (BTI1.Max == getCouldNotCompute())
3408 MaxBECount = BTI0.Max;
3410 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3412 // Both conditions must be true for the loop to exit.
3413 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3414 if (BTI0.Exact != getCouldNotCompute() &&
3415 BTI1.Exact != getCouldNotCompute())
3416 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3417 if (BTI0.Max != getCouldNotCompute() &&
3418 BTI1.Max != getCouldNotCompute())
3419 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3422 return BackedgeTakenInfo(BECount, MaxBECount);
3424 if (BO->getOpcode() == Instruction::Or) {
3425 // Recurse on the operands of the or.
3426 BackedgeTakenInfo BTI0 =
3427 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3428 BackedgeTakenInfo BTI1 =
3429 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3430 const SCEV *BECount = getCouldNotCompute();
3431 const SCEV *MaxBECount = getCouldNotCompute();
3432 if (L->contains(FBB)) {
3433 // Both conditions must be false for the loop to continue executing.
3434 // Choose the less conservative count.
3435 if (BTI0.Exact == getCouldNotCompute() ||
3436 BTI1.Exact == getCouldNotCompute())
3437 BECount = getCouldNotCompute();
3439 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3440 if (BTI0.Max == getCouldNotCompute())
3441 MaxBECount = BTI1.Max;
3442 else if (BTI1.Max == getCouldNotCompute())
3443 MaxBECount = BTI0.Max;
3445 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3447 // Both conditions must be false for the loop to exit.
3448 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3449 if (BTI0.Exact != getCouldNotCompute() &&
3450 BTI1.Exact != getCouldNotCompute())
3451 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3452 if (BTI0.Max != getCouldNotCompute() &&
3453 BTI1.Max != getCouldNotCompute())
3454 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3457 return BackedgeTakenInfo(BECount, MaxBECount);
3461 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3462 // Procede to the next level to examine the icmp.
3463 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3464 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3466 // If it's not an integer or pointer comparison then compute it the hard way.
3467 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3470 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3471 /// backedge of the specified loop will execute if its exit condition
3472 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3473 ScalarEvolution::BackedgeTakenInfo
3474 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3479 // If the condition was exit on true, convert the condition to exit on false
3480 ICmpInst::Predicate Cond;
3481 if (!L->contains(FBB))
3482 Cond = ExitCond->getPredicate();
3484 Cond = ExitCond->getInversePredicate();
3486 // Handle common loops like: for (X = "string"; *X; ++X)
3487 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3488 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3490 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3491 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3492 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3493 return BackedgeTakenInfo(ItCnt,
3494 isa<SCEVConstant>(ItCnt) ? ItCnt :
3495 getConstant(APInt::getMaxValue(BitWidth)-1));
3499 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3500 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3502 // Try to evaluate any dependencies out of the loop.
3503 LHS = getSCEVAtScope(LHS, L);
3504 RHS = getSCEVAtScope(RHS, L);
3506 // At this point, we would like to compute how many iterations of the
3507 // loop the predicate will return true for these inputs.
3508 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3509 // If there is a loop-invariant, force it into the RHS.
3510 std::swap(LHS, RHS);
3511 Cond = ICmpInst::getSwappedPredicate(Cond);
3514 // If we have a comparison of a chrec against a constant, try to use value
3515 // ranges to answer this query.
3516 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3517 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3518 if (AddRec->getLoop() == L) {
3519 // Form the constant range.
3520 ConstantRange CompRange(
3521 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3523 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3524 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3528 case ICmpInst::ICMP_NE: { // while (X != Y)
3529 // Convert to: while (X-Y != 0)
3530 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3531 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3534 case ICmpInst::ICMP_EQ: { // while (X == Y)
3535 // Convert to: while (X-Y == 0)
3536 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3537 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3540 case ICmpInst::ICMP_SLT: {
3541 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3542 if (BTI.hasAnyInfo()) return BTI;
3545 case ICmpInst::ICMP_SGT: {
3546 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3547 getNotSCEV(RHS), L, true);
3548 if (BTI.hasAnyInfo()) return BTI;
3551 case ICmpInst::ICMP_ULT: {
3552 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3553 if (BTI.hasAnyInfo()) return BTI;
3556 case ICmpInst::ICMP_UGT: {
3557 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3558 getNotSCEV(RHS), L, false);
3559 if (BTI.hasAnyInfo()) return BTI;
3564 errs() << "ComputeBackedgeTakenCount ";
3565 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3566 errs() << "[unsigned] ";
3567 errs() << *LHS << " "
3568 << Instruction::getOpcodeName(Instruction::ICmp)
3569 << " " << *RHS << "\n";
3574 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3577 static ConstantInt *
3578 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3579 ScalarEvolution &SE) {
3580 const SCEV *InVal = SE.getConstant(C);
3581 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3582 assert(isa<SCEVConstant>(Val) &&
3583 "Evaluation of SCEV at constant didn't fold correctly?");
3584 return cast<SCEVConstant>(Val)->getValue();
3587 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3588 /// and a GEP expression (missing the pointer index) indexing into it, return
3589 /// the addressed element of the initializer or null if the index expression is
3592 GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
3593 const std::vector<ConstantInt*> &Indices) {
3594 Constant *Init = GV->getInitializer();
3595 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3596 uint64_t Idx = Indices[i]->getZExtValue();
3597 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3598 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3599 Init = cast<Constant>(CS->getOperand(Idx));
3600 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3601 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3602 Init = cast<Constant>(CA->getOperand(Idx));
3603 } else if (isa<ConstantAggregateZero>(Init)) {
3604 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3605 assert(Idx < STy->getNumElements() && "Bad struct index!");
3606 Init = Constant::getNullValue(STy->getElementType(Idx));
3607 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3608 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3609 Init = Constant::getNullValue(ATy->getElementType());
3611 llvm_unreachable("Unknown constant aggregate type!");
3615 return 0; // Unknown initializer type
3621 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3622 /// 'icmp op load X, cst', try to see if we can compute the backedge
3623 /// execution count.
3625 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3629 ICmpInst::Predicate predicate) {
3630 if (LI->isVolatile()) return getCouldNotCompute();
3632 // Check to see if the loaded pointer is a getelementptr of a global.
3633 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3634 if (!GEP) return getCouldNotCompute();
3636 // Make sure that it is really a constant global we are gepping, with an
3637 // initializer, and make sure the first IDX is really 0.
3638 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3639 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3640 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3641 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3642 return getCouldNotCompute();
3644 // Okay, we allow one non-constant index into the GEP instruction.
3646 std::vector<ConstantInt*> Indexes;
3647 unsigned VarIdxNum = 0;
3648 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3649 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3650 Indexes.push_back(CI);
3651 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3652 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3653 VarIdx = GEP->getOperand(i);
3655 Indexes.push_back(0);
3658 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3659 // Check to see if X is a loop variant variable value now.
3660 const SCEV *Idx = getSCEV(VarIdx);
3661 Idx = getSCEVAtScope(Idx, L);
3663 // We can only recognize very limited forms of loop index expressions, in
3664 // particular, only affine AddRec's like {C1,+,C2}.
3665 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3666 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3667 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3668 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3669 return getCouldNotCompute();
3671 unsigned MaxSteps = MaxBruteForceIterations;
3672 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3673 ConstantInt *ItCst = ConstantInt::get(
3674 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3675 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3677 // Form the GEP offset.
3678 Indexes[VarIdxNum] = Val;
3680 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
3681 if (Result == 0) break; // Cannot compute!
3683 // Evaluate the condition for this iteration.
3684 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3685 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3686 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3688 errs() << "\n***\n*** Computed loop count " << *ItCst
3689 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3692 ++NumArrayLenItCounts;
3693 return getConstant(ItCst); // Found terminating iteration!
3696 return getCouldNotCompute();
3700 /// CanConstantFold - Return true if we can constant fold an instruction of the
3701 /// specified type, assuming that all operands were constants.
3702 static bool CanConstantFold(const Instruction *I) {
3703 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3704 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3707 if (const CallInst *CI = dyn_cast<CallInst>(I))
3708 if (const Function *F = CI->getCalledFunction())
3709 return canConstantFoldCallTo(F);
3713 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3714 /// in the loop that V is derived from. We allow arbitrary operations along the
3715 /// way, but the operands of an operation must either be constants or a value
3716 /// derived from a constant PHI. If this expression does not fit with these
3717 /// constraints, return null.
3718 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3719 // If this is not an instruction, or if this is an instruction outside of the
3720 // loop, it can't be derived from a loop PHI.
3721 Instruction *I = dyn_cast<Instruction>(V);
3722 if (I == 0 || !L->contains(I->getParent())) return 0;
3724 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3725 if (L->getHeader() == I->getParent())
3728 // We don't currently keep track of the control flow needed to evaluate
3729 // PHIs, so we cannot handle PHIs inside of loops.
3733 // If we won't be able to constant fold this expression even if the operands
3734 // are constants, return early.
3735 if (!CanConstantFold(I)) return 0;
3737 // Otherwise, we can evaluate this instruction if all of its operands are
3738 // constant or derived from a PHI node themselves.
3740 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3741 if (!(isa<Constant>(I->getOperand(Op)) ||
3742 isa<GlobalValue>(I->getOperand(Op)))) {
3743 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3744 if (P == 0) return 0; // Not evolving from PHI
3748 return 0; // Evolving from multiple different PHIs.
3751 // This is a expression evolving from a constant PHI!
3755 /// EvaluateExpression - Given an expression that passes the
3756 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3757 /// in the loop has the value PHIVal. If we can't fold this expression for some
3758 /// reason, return null.
3759 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3760 if (isa<PHINode>(V)) return PHIVal;
3761 if (Constant *C = dyn_cast<Constant>(V)) return C;
3762 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3763 Instruction *I = cast<Instruction>(V);
3764 LLVMContext &Context = I->getParent()->getContext();
3766 std::vector<Constant*> Operands;
3767 Operands.resize(I->getNumOperands());
3769 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3770 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3771 if (Operands[i] == 0) return 0;
3774 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3775 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3776 &Operands[0], Operands.size(),
3779 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3780 &Operands[0], Operands.size(),
3784 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3785 /// in the header of its containing loop, we know the loop executes a
3786 /// constant number of times, and the PHI node is just a recurrence
3787 /// involving constants, fold it.
3789 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3792 std::map<PHINode*, Constant*>::iterator I =
3793 ConstantEvolutionLoopExitValue.find(PN);
3794 if (I != ConstantEvolutionLoopExitValue.end())
3797 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3798 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3800 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3802 // Since the loop is canonicalized, the PHI node must have two entries. One
3803 // entry must be a constant (coming in from outside of the loop), and the
3804 // second must be derived from the same PHI.
3805 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3806 Constant *StartCST =
3807 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3809 return RetVal = 0; // Must be a constant.
3811 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3812 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3814 return RetVal = 0; // Not derived from same PHI.
3816 // Execute the loop symbolically to determine the exit value.
3817 if (BEs.getActiveBits() >= 32)
3818 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3820 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3821 unsigned IterationNum = 0;
3822 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3823 if (IterationNum == NumIterations)
3824 return RetVal = PHIVal; // Got exit value!
3826 // Compute the value of the PHI node for the next iteration.
3827 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3828 if (NextPHI == PHIVal)
3829 return RetVal = NextPHI; // Stopped evolving!
3831 return 0; // Couldn't evaluate!
3836 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
3837 /// constant number of times (the condition evolves only from constants),
3838 /// try to evaluate a few iterations of the loop until we get the exit
3839 /// condition gets a value of ExitWhen (true or false). If we cannot
3840 /// evaluate the trip count of the loop, return getCouldNotCompute().
3842 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3845 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3846 if (PN == 0) return getCouldNotCompute();
3848 // Since the loop is canonicalized, the PHI node must have two entries. One
3849 // entry must be a constant (coming in from outside of the loop), and the
3850 // second must be derived from the same PHI.
3851 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3852 Constant *StartCST =
3853 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3854 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3856 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3857 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3858 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3860 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3861 // the loop symbolically to determine when the condition gets a value of
3863 unsigned IterationNum = 0;
3864 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3865 for (Constant *PHIVal = StartCST;
3866 IterationNum != MaxIterations; ++IterationNum) {
3867 ConstantInt *CondVal =
3868 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3870 // Couldn't symbolically evaluate.
3871 if (!CondVal) return getCouldNotCompute();
3873 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3874 ++NumBruteForceTripCountsComputed;
3875 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
3878 // Compute the value of the PHI node for the next iteration.
3879 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3880 if (NextPHI == 0 || NextPHI == PHIVal)
3881 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3885 // Too many iterations were needed to evaluate.
3886 return getCouldNotCompute();
3889 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3890 /// at the specified scope in the program. The L value specifies a loop
3891 /// nest to evaluate the expression at, where null is the top-level or a
3892 /// specified loop is immediately inside of the loop.
3894 /// This method can be used to compute the exit value for a variable defined
3895 /// in a loop by querying what the value will hold in the parent loop.
3897 /// In the case that a relevant loop exit value cannot be computed, the
3898 /// original value V is returned.
3899 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3900 // FIXME: this should be turned into a virtual method on SCEV!
3902 if (isa<SCEVConstant>(V)) return V;
3904 // If this instruction is evolved from a constant-evolving PHI, compute the
3905 // exit value from the loop without using SCEVs.
3906 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3907 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3908 const Loop *LI = (*this->LI)[I->getParent()];
3909 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3910 if (PHINode *PN = dyn_cast<PHINode>(I))
3911 if (PN->getParent() == LI->getHeader()) {
3912 // Okay, there is no closed form solution for the PHI node. Check
3913 // to see if the loop that contains it has a known backedge-taken
3914 // count. If so, we may be able to force computation of the exit
3916 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3917 if (const SCEVConstant *BTCC =
3918 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3919 // Okay, we know how many times the containing loop executes. If
3920 // this is a constant evolving PHI node, get the final value at
3921 // the specified iteration number.
3922 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3923 BTCC->getValue()->getValue(),
3925 if (RV) return getSCEV(RV);
3929 // Okay, this is an expression that we cannot symbolically evaluate
3930 // into a SCEV. Check to see if it's possible to symbolically evaluate
3931 // the arguments into constants, and if so, try to constant propagate the
3932 // result. This is particularly useful for computing loop exit values.
3933 if (CanConstantFold(I)) {
3934 // Check to see if we've folded this instruction at this loop before.
3935 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3936 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3937 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3939 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3941 std::vector<Constant*> Operands;
3942 Operands.reserve(I->getNumOperands());
3943 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3944 Value *Op = I->getOperand(i);
3945 if (Constant *C = dyn_cast<Constant>(Op)) {
3946 Operands.push_back(C);
3948 // If any of the operands is non-constant and if they are
3949 // non-integer and non-pointer, don't even try to analyze them
3950 // with scev techniques.
3951 if (!isSCEVable(Op->getType()))
3954 const SCEV* OpV = getSCEVAtScope(Op, L);
3955 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3956 Constant *C = SC->getValue();
3957 if (C->getType() != Op->getType())
3958 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3962 Operands.push_back(C);
3963 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3964 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3965 if (C->getType() != Op->getType())
3967 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3971 Operands.push_back(C);
3981 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3982 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3983 &Operands[0], Operands.size(),
3986 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3987 &Operands[0], Operands.size(),
3989 Pair.first->second = C;
3994 // This is some other type of SCEVUnknown, just return it.
3998 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3999 // Avoid performing the look-up in the common case where the specified
4000 // expression has no loop-variant portions.
4001 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4002 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4003 if (OpAtScope != Comm->getOperand(i)) {
4004 // Okay, at least one of these operands is loop variant but might be
4005 // foldable. Build a new instance of the folded commutative expression.
4006 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4007 Comm->op_begin()+i);
4008 NewOps.push_back(OpAtScope);
4010 for (++i; i != e; ++i) {
4011 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4012 NewOps.push_back(OpAtScope);
4014 if (isa<SCEVAddExpr>(Comm))
4015 return getAddExpr(NewOps);
4016 if (isa<SCEVMulExpr>(Comm))
4017 return getMulExpr(NewOps);
4018 if (isa<SCEVSMaxExpr>(Comm))
4019 return getSMaxExpr(NewOps);
4020 if (isa<SCEVUMaxExpr>(Comm))
4021 return getUMaxExpr(NewOps);
4022 llvm_unreachable("Unknown commutative SCEV type!");
4025 // If we got here, all operands are loop invariant.
4029 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4030 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4031 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4032 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4033 return Div; // must be loop invariant
4034 return getUDivExpr(LHS, RHS);
4037 // If this is a loop recurrence for a loop that does not contain L, then we
4038 // are dealing with the final value computed by the loop.
4039 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4040 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4041 // To evaluate this recurrence, we need to know how many times the AddRec
4042 // loop iterates. Compute this now.
4043 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4044 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4046 // Then, evaluate the AddRec.
4047 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4052 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4053 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4054 if (Op == Cast->getOperand())
4055 return Cast; // must be loop invariant
4056 return getZeroExtendExpr(Op, Cast->getType());
4059 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4060 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4061 if (Op == Cast->getOperand())
4062 return Cast; // must be loop invariant
4063 return getSignExtendExpr(Op, Cast->getType());
4066 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4067 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4068 if (Op == Cast->getOperand())
4069 return Cast; // must be loop invariant
4070 return getTruncateExpr(Op, Cast->getType());
4073 if (isa<SCEVTargetDataConstant>(V))
4076 llvm_unreachable("Unknown SCEV type!");
4080 /// getSCEVAtScope - This is a convenience function which does
4081 /// getSCEVAtScope(getSCEV(V), L).
4082 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4083 return getSCEVAtScope(getSCEV(V), L);
4086 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4087 /// following equation:
4089 /// A * X = B (mod N)
4091 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4092 /// A and B isn't important.
4094 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4095 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4096 ScalarEvolution &SE) {
4097 uint32_t BW = A.getBitWidth();
4098 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4099 assert(A != 0 && "A must be non-zero.");
4103 // The gcd of A and N may have only one prime factor: 2. The number of
4104 // trailing zeros in A is its multiplicity
4105 uint32_t Mult2 = A.countTrailingZeros();
4108 // 2. Check if B is divisible by D.
4110 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4111 // is not less than multiplicity of this prime factor for D.
4112 if (B.countTrailingZeros() < Mult2)
4113 return SE.getCouldNotCompute();
4115 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4118 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4119 // bit width during computations.
4120 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4121 APInt Mod(BW + 1, 0);
4122 Mod.set(BW - Mult2); // Mod = N / D
4123 APInt I = AD.multiplicativeInverse(Mod);
4125 // 4. Compute the minimum unsigned root of the equation:
4126 // I * (B / D) mod (N / D)
4127 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4129 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4131 return SE.getConstant(Result.trunc(BW));
4134 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4135 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4136 /// might be the same) or two SCEVCouldNotCompute objects.
4138 static std::pair<const SCEV *,const SCEV *>
4139 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4140 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4141 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4142 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4143 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4145 // We currently can only solve this if the coefficients are constants.
4146 if (!LC || !MC || !NC) {
4147 const SCEV *CNC = SE.getCouldNotCompute();
4148 return std::make_pair(CNC, CNC);
4151 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4152 const APInt &L = LC->getValue()->getValue();
4153 const APInt &M = MC->getValue()->getValue();
4154 const APInt &N = NC->getValue()->getValue();
4155 APInt Two(BitWidth, 2);
4156 APInt Four(BitWidth, 4);
4159 using namespace APIntOps;
4161 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4162 // The B coefficient is M-N/2
4166 // The A coefficient is N/2
4167 APInt A(N.sdiv(Two));
4169 // Compute the B^2-4ac term.
4172 SqrtTerm -= Four * (A * C);
4174 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4175 // integer value or else APInt::sqrt() will assert.
4176 APInt SqrtVal(SqrtTerm.sqrt());
4178 // Compute the two solutions for the quadratic formula.
4179 // The divisions must be performed as signed divisions.
4181 APInt TwoA( A << 1 );
4182 if (TwoA.isMinValue()) {
4183 const SCEV *CNC = SE.getCouldNotCompute();
4184 return std::make_pair(CNC, CNC);
4187 LLVMContext &Context = SE.getContext();
4189 ConstantInt *Solution1 =
4190 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4191 ConstantInt *Solution2 =
4192 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4194 return std::make_pair(SE.getConstant(Solution1),
4195 SE.getConstant(Solution2));
4196 } // end APIntOps namespace
4199 /// HowFarToZero - Return the number of times a backedge comparing the specified
4200 /// value to zero will execute. If not computable, return CouldNotCompute.
4201 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4202 // If the value is a constant
4203 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4204 // If the value is already zero, the branch will execute zero times.
4205 if (C->getValue()->isZero()) return C;
4206 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4209 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4210 if (!AddRec || AddRec->getLoop() != L)
4211 return getCouldNotCompute();
4213 if (AddRec->isAffine()) {
4214 // If this is an affine expression, the execution count of this branch is
4215 // the minimum unsigned root of the following equation:
4217 // Start + Step*N = 0 (mod 2^BW)
4221 // Step*N = -Start (mod 2^BW)
4223 // where BW is the common bit width of Start and Step.
4225 // Get the initial value for the loop.
4226 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4227 L->getParentLoop());
4228 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4229 L->getParentLoop());
4231 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4232 // For now we handle only constant steps.
4234 // First, handle unitary steps.
4235 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4236 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4237 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4238 return Start; // N = Start (as unsigned)
4240 // Then, try to solve the above equation provided that Start is constant.
4241 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4242 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4243 -StartC->getValue()->getValue(),
4246 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4247 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4248 // the quadratic equation to solve it.
4249 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4251 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4252 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4255 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4256 << " sol#2: " << *R2 << "\n";
4258 // Pick the smallest positive root value.
4259 if (ConstantInt *CB =
4260 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4261 R1->getValue(), R2->getValue()))) {
4262 if (CB->getZExtValue() == false)
4263 std::swap(R1, R2); // R1 is the minimum root now.
4265 // We can only use this value if the chrec ends up with an exact zero
4266 // value at this index. When solving for "X*X != 5", for example, we
4267 // should not accept a root of 2.
4268 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4270 return R1; // We found a quadratic root!
4275 return getCouldNotCompute();
4278 /// HowFarToNonZero - Return the number of times a backedge checking the
4279 /// specified value for nonzero will execute. If not computable, return
4281 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4282 // Loops that look like: while (X == 0) are very strange indeed. We don't
4283 // handle them yet except for the trivial case. This could be expanded in the
4284 // future as needed.
4286 // If the value is a constant, check to see if it is known to be non-zero
4287 // already. If so, the backedge will execute zero times.
4288 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4289 if (!C->getValue()->isNullValue())
4290 return getIntegerSCEV(0, C->getType());
4291 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4294 // We could implement others, but I really doubt anyone writes loops like
4295 // this, and if they did, they would already be constant folded.
4296 return getCouldNotCompute();
4299 /// getLoopPredecessor - If the given loop's header has exactly one unique
4300 /// predecessor outside the loop, return it. Otherwise return null.
4302 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4303 BasicBlock *Header = L->getHeader();
4304 BasicBlock *Pred = 0;
4305 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4307 if (!L->contains(*PI)) {
4308 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4314 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4315 /// (which may not be an immediate predecessor) which has exactly one
4316 /// successor from which BB is reachable, or null if no such block is
4320 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4321 // If the block has a unique predecessor, then there is no path from the
4322 // predecessor to the block that does not go through the direct edge
4323 // from the predecessor to the block.
4324 if (BasicBlock *Pred = BB->getSinglePredecessor())
4327 // A loop's header is defined to be a block that dominates the loop.
4328 // If the header has a unique predecessor outside the loop, it must be
4329 // a block that has exactly one successor that can reach the loop.
4330 if (Loop *L = LI->getLoopFor(BB))
4331 return getLoopPredecessor(L);
4336 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4337 /// testing whether two expressions are equal, however for the purposes of
4338 /// looking for a condition guarding a loop, it can be useful to be a little
4339 /// more general, since a front-end may have replicated the controlling
4342 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4343 // Quick check to see if they are the same SCEV.
4344 if (A == B) return true;
4346 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4347 // two different instructions with the same value. Check for this case.
4348 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4349 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4350 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4351 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4352 if (AI->isIdenticalTo(BI))
4355 // Otherwise assume they may have a different value.
4359 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4360 return getSignedRange(S).getSignedMax().isNegative();
4363 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4364 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4367 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4368 return !getSignedRange(S).getSignedMin().isNegative();
4371 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4372 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4375 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4376 return isKnownNegative(S) || isKnownPositive(S);
4379 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4380 const SCEV *LHS, const SCEV *RHS) {
4382 if (HasSameValue(LHS, RHS))
4383 return ICmpInst::isTrueWhenEqual(Pred);
4387 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4389 case ICmpInst::ICMP_SGT:
4390 Pred = ICmpInst::ICMP_SLT;
4391 std::swap(LHS, RHS);
4392 case ICmpInst::ICMP_SLT: {
4393 ConstantRange LHSRange = getSignedRange(LHS);
4394 ConstantRange RHSRange = getSignedRange(RHS);
4395 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4397 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4401 case ICmpInst::ICMP_SGE:
4402 Pred = ICmpInst::ICMP_SLE;
4403 std::swap(LHS, RHS);
4404 case ICmpInst::ICMP_SLE: {
4405 ConstantRange LHSRange = getSignedRange(LHS);
4406 ConstantRange RHSRange = getSignedRange(RHS);
4407 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4409 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4413 case ICmpInst::ICMP_UGT:
4414 Pred = ICmpInst::ICMP_ULT;
4415 std::swap(LHS, RHS);
4416 case ICmpInst::ICMP_ULT: {
4417 ConstantRange LHSRange = getUnsignedRange(LHS);
4418 ConstantRange RHSRange = getUnsignedRange(RHS);
4419 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4421 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4425 case ICmpInst::ICMP_UGE:
4426 Pred = ICmpInst::ICMP_ULE;
4427 std::swap(LHS, RHS);
4428 case ICmpInst::ICMP_ULE: {
4429 ConstantRange LHSRange = getUnsignedRange(LHS);
4430 ConstantRange RHSRange = getUnsignedRange(RHS);
4431 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4433 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4437 case ICmpInst::ICMP_NE: {
4438 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4440 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4443 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4444 if (isKnownNonZero(Diff))
4448 case ICmpInst::ICMP_EQ:
4449 // The check at the top of the function catches the case where
4450 // the values are known to be equal.
4456 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4457 /// protected by a conditional between LHS and RHS. This is used to
4458 /// to eliminate casts.
4460 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4461 ICmpInst::Predicate Pred,
4462 const SCEV *LHS, const SCEV *RHS) {
4463 // Interpret a null as meaning no loop, where there is obviously no guard
4464 // (interprocedural conditions notwithstanding).
4465 if (!L) return true;
4467 BasicBlock *Latch = L->getLoopLatch();
4471 BranchInst *LoopContinuePredicate =
4472 dyn_cast<BranchInst>(Latch->getTerminator());
4473 if (!LoopContinuePredicate ||
4474 LoopContinuePredicate->isUnconditional())
4477 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4478 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4481 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4482 /// by a conditional between LHS and RHS. This is used to help avoid max
4483 /// expressions in loop trip counts, and to eliminate casts.
4485 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4486 ICmpInst::Predicate Pred,
4487 const SCEV *LHS, const SCEV *RHS) {
4488 // Interpret a null as meaning no loop, where there is obviously no guard
4489 // (interprocedural conditions notwithstanding).
4490 if (!L) return false;
4492 BasicBlock *Predecessor = getLoopPredecessor(L);
4493 BasicBlock *PredecessorDest = L->getHeader();
4495 // Starting at the loop predecessor, climb up the predecessor chain, as long
4496 // as there are predecessors that can be found that have unique successors
4497 // leading to the original header.
4499 PredecessorDest = Predecessor,
4500 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4502 BranchInst *LoopEntryPredicate =
4503 dyn_cast<BranchInst>(Predecessor->getTerminator());
4504 if (!LoopEntryPredicate ||
4505 LoopEntryPredicate->isUnconditional())
4508 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4509 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4516 /// isImpliedCond - Test whether the condition described by Pred, LHS,
4517 /// and RHS is true whenever the given Cond value evaluates to true.
4518 bool ScalarEvolution::isImpliedCond(Value *CondValue,
4519 ICmpInst::Predicate Pred,
4520 const SCEV *LHS, const SCEV *RHS,
4522 // Recursivly handle And and Or conditions.
4523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4524 if (BO->getOpcode() == Instruction::And) {
4526 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4527 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4528 } else if (BO->getOpcode() == Instruction::Or) {
4530 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4531 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4535 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4536 if (!ICI) return false;
4538 // Bail if the ICmp's operands' types are wider than the needed type
4539 // before attempting to call getSCEV on them. This avoids infinite
4540 // recursion, since the analysis of widening casts can require loop
4541 // exit condition information for overflow checking, which would
4543 if (getTypeSizeInBits(LHS->getType()) <
4544 getTypeSizeInBits(ICI->getOperand(0)->getType()))
4547 // Now that we found a conditional branch that dominates the loop, check to
4548 // see if it is the comparison we are looking for.
4549 ICmpInst::Predicate FoundPred;
4551 FoundPred = ICI->getInversePredicate();
4553 FoundPred = ICI->getPredicate();
4555 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4556 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
4558 // Balance the types. The case where FoundLHS' type is wider than
4559 // LHS' type is checked for above.
4560 if (getTypeSizeInBits(LHS->getType()) >
4561 getTypeSizeInBits(FoundLHS->getType())) {
4562 if (CmpInst::isSigned(Pred)) {
4563 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4564 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4566 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4567 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4571 // Canonicalize the query to match the way instcombine will have
4572 // canonicalized the comparison.
4573 // First, put a constant operand on the right.
4574 if (isa<SCEVConstant>(LHS)) {
4575 std::swap(LHS, RHS);
4576 Pred = ICmpInst::getSwappedPredicate(Pred);
4578 // Then, canonicalize comparisons with boundary cases.
4579 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4580 const APInt &RA = RC->getValue()->getValue();
4582 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4583 case ICmpInst::ICMP_EQ:
4584 case ICmpInst::ICMP_NE:
4586 case ICmpInst::ICMP_UGE:
4587 if ((RA - 1).isMinValue()) {
4588 Pred = ICmpInst::ICMP_NE;
4589 RHS = getConstant(RA - 1);
4592 if (RA.isMaxValue()) {
4593 Pred = ICmpInst::ICMP_EQ;
4596 if (RA.isMinValue()) return true;
4598 case ICmpInst::ICMP_ULE:
4599 if ((RA + 1).isMaxValue()) {
4600 Pred = ICmpInst::ICMP_NE;
4601 RHS = getConstant(RA + 1);
4604 if (RA.isMinValue()) {
4605 Pred = ICmpInst::ICMP_EQ;
4608 if (RA.isMaxValue()) return true;
4610 case ICmpInst::ICMP_SGE:
4611 if ((RA - 1).isMinSignedValue()) {
4612 Pred = ICmpInst::ICMP_NE;
4613 RHS = getConstant(RA - 1);
4616 if (RA.isMaxSignedValue()) {
4617 Pred = ICmpInst::ICMP_EQ;
4620 if (RA.isMinSignedValue()) return true;
4622 case ICmpInst::ICMP_SLE:
4623 if ((RA + 1).isMaxSignedValue()) {
4624 Pred = ICmpInst::ICMP_NE;
4625 RHS = getConstant(RA + 1);
4628 if (RA.isMinSignedValue()) {
4629 Pred = ICmpInst::ICMP_EQ;
4632 if (RA.isMaxSignedValue()) return true;
4634 case ICmpInst::ICMP_UGT:
4635 if (RA.isMinValue()) {
4636 Pred = ICmpInst::ICMP_NE;
4639 if ((RA + 1).isMaxValue()) {
4640 Pred = ICmpInst::ICMP_EQ;
4641 RHS = getConstant(RA + 1);
4644 if (RA.isMaxValue()) return false;
4646 case ICmpInst::ICMP_ULT:
4647 if (RA.isMaxValue()) {
4648 Pred = ICmpInst::ICMP_NE;
4651 if ((RA - 1).isMinValue()) {
4652 Pred = ICmpInst::ICMP_EQ;
4653 RHS = getConstant(RA - 1);
4656 if (RA.isMinValue()) return false;
4658 case ICmpInst::ICMP_SGT:
4659 if (RA.isMinSignedValue()) {
4660 Pred = ICmpInst::ICMP_NE;
4663 if ((RA + 1).isMaxSignedValue()) {
4664 Pred = ICmpInst::ICMP_EQ;
4665 RHS = getConstant(RA + 1);
4668 if (RA.isMaxSignedValue()) return false;
4670 case ICmpInst::ICMP_SLT:
4671 if (RA.isMaxSignedValue()) {
4672 Pred = ICmpInst::ICMP_NE;
4675 if ((RA - 1).isMinSignedValue()) {
4676 Pred = ICmpInst::ICMP_EQ;
4677 RHS = getConstant(RA - 1);
4680 if (RA.isMinSignedValue()) return false;
4685 // Check to see if we can make the LHS or RHS match.
4686 if (LHS == FoundRHS || RHS == FoundLHS) {
4687 if (isa<SCEVConstant>(RHS)) {
4688 std::swap(FoundLHS, FoundRHS);
4689 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4691 std::swap(LHS, RHS);
4692 Pred = ICmpInst::getSwappedPredicate(Pred);
4696 // Check whether the found predicate is the same as the desired predicate.
4697 if (FoundPred == Pred)
4698 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4700 // Check whether swapping the found predicate makes it the same as the
4701 // desired predicate.
4702 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4703 if (isa<SCEVConstant>(RHS))
4704 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4706 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4707 RHS, LHS, FoundLHS, FoundRHS);
4710 // Check whether the actual condition is beyond sufficient.
4711 if (FoundPred == ICmpInst::ICMP_EQ)
4712 if (ICmpInst::isTrueWhenEqual(Pred))
4713 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4715 if (Pred == ICmpInst::ICMP_NE)
4716 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4717 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4720 // Otherwise assume the worst.
4724 /// isImpliedCondOperands - Test whether the condition described by Pred,
4725 /// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4726 /// and FoundRHS is true.
4727 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4728 const SCEV *LHS, const SCEV *RHS,
4729 const SCEV *FoundLHS,
4730 const SCEV *FoundRHS) {
4731 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4732 FoundLHS, FoundRHS) ||
4733 // ~x < ~y --> x > y
4734 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4735 getNotSCEV(FoundRHS),
4736 getNotSCEV(FoundLHS));
4739 /// isImpliedCondOperandsHelper - Test whether the condition described by
4740 /// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4741 /// FoundLHS, and FoundRHS is true.
4743 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4744 const SCEV *LHS, const SCEV *RHS,
4745 const SCEV *FoundLHS,
4746 const SCEV *FoundRHS) {
4748 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4749 case ICmpInst::ICMP_EQ:
4750 case ICmpInst::ICMP_NE:
4751 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4754 case ICmpInst::ICMP_SLT:
4755 case ICmpInst::ICMP_SLE:
4756 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4757 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4760 case ICmpInst::ICMP_SGT:
4761 case ICmpInst::ICMP_SGE:
4762 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4763 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4766 case ICmpInst::ICMP_ULT:
4767 case ICmpInst::ICMP_ULE:
4768 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4769 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4772 case ICmpInst::ICMP_UGT:
4773 case ICmpInst::ICMP_UGE:
4774 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4775 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4783 /// getBECount - Subtract the end and start values and divide by the step,
4784 /// rounding up, to get the number of times the backedge is executed. Return
4785 /// CouldNotCompute if an intermediate computation overflows.
4786 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4789 const Type *Ty = Start->getType();
4790 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4791 const SCEV *Diff = getMinusSCEV(End, Start);
4792 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4794 // Add an adjustment to the difference between End and Start so that
4795 // the division will effectively round up.
4796 const SCEV *Add = getAddExpr(Diff, RoundUp);
4798 // Check Add for unsigned overflow.
4799 // TODO: More sophisticated things could be done here.
4800 const Type *WideTy = IntegerType::get(getContext(),
4801 getTypeSizeInBits(Ty) + 1);
4802 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4803 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4804 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4805 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4806 return getCouldNotCompute();
4808 return getUDivExpr(Add, Step);
4811 /// HowManyLessThans - Return the number of times a backedge containing the
4812 /// specified less-than comparison will execute. If not computable, return
4813 /// CouldNotCompute.
4814 ScalarEvolution::BackedgeTakenInfo
4815 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4816 const Loop *L, bool isSigned) {
4817 // Only handle: "ADDREC < LoopInvariant".
4818 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4820 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4821 if (!AddRec || AddRec->getLoop() != L)
4822 return getCouldNotCompute();
4824 if (AddRec->isAffine()) {
4825 // FORNOW: We only support unit strides.
4826 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4827 const SCEV *Step = AddRec->getStepRecurrence(*this);
4829 // TODO: handle non-constant strides.
4830 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4831 if (!CStep || CStep->isZero())
4832 return getCouldNotCompute();
4833 if (CStep->isOne()) {
4834 // With unit stride, the iteration never steps past the limit value.
4835 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4836 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4837 // Test whether a positive iteration iteration can step past the limit
4838 // value and past the maximum value for its type in a single step.
4840 APInt Max = APInt::getSignedMaxValue(BitWidth);
4841 if ((Max - CStep->getValue()->getValue())
4842 .slt(CLimit->getValue()->getValue()))
4843 return getCouldNotCompute();
4845 APInt Max = APInt::getMaxValue(BitWidth);
4846 if ((Max - CStep->getValue()->getValue())
4847 .ult(CLimit->getValue()->getValue()))
4848 return getCouldNotCompute();
4851 // TODO: handle non-constant limit values below.
4852 return getCouldNotCompute();
4854 // TODO: handle negative strides below.
4855 return getCouldNotCompute();
4857 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4858 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4859 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4860 // treat m-n as signed nor unsigned due to overflow possibility.
4862 // First, we get the value of the LHS in the first iteration: n
4863 const SCEV *Start = AddRec->getOperand(0);
4865 // Determine the minimum constant start value.
4866 const SCEV *MinStart = getConstant(isSigned ?
4867 getSignedRange(Start).getSignedMin() :
4868 getUnsignedRange(Start).getUnsignedMin());
4870 // If we know that the condition is true in order to enter the loop,
4871 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4872 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4873 // the division must round up.
4874 const SCEV *End = RHS;
4875 if (!isLoopGuardedByCond(L,
4876 isSigned ? ICmpInst::ICMP_SLT :
4878 getMinusSCEV(Start, Step), RHS))
4879 End = isSigned ? getSMaxExpr(RHS, Start)
4880 : getUMaxExpr(RHS, Start);
4882 // Determine the maximum constant end value.
4883 const SCEV *MaxEnd = getConstant(isSigned ?
4884 getSignedRange(End).getSignedMax() :
4885 getUnsignedRange(End).getUnsignedMax());
4887 // Finally, we subtract these two values and divide, rounding up, to get
4888 // the number of times the backedge is executed.
4889 const SCEV *BECount = getBECount(Start, End, Step);
4891 // The maximum backedge count is similar, except using the minimum start
4892 // value and the maximum end value.
4893 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
4895 return BackedgeTakenInfo(BECount, MaxBECount);
4898 return getCouldNotCompute();
4901 /// getNumIterationsInRange - Return the number of iterations of this loop that
4902 /// produce values in the specified constant range. Another way of looking at
4903 /// this is that it returns the first iteration number where the value is not in
4904 /// the condition, thus computing the exit count. If the iteration count can't
4905 /// be computed, an instance of SCEVCouldNotCompute is returned.
4906 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4907 ScalarEvolution &SE) const {
4908 if (Range.isFullSet()) // Infinite loop.
4909 return SE.getCouldNotCompute();
4911 // If the start is a non-zero constant, shift the range to simplify things.
4912 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4913 if (!SC->getValue()->isZero()) {
4914 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4915 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4916 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4917 if (const SCEVAddRecExpr *ShiftedAddRec =
4918 dyn_cast<SCEVAddRecExpr>(Shifted))
4919 return ShiftedAddRec->getNumIterationsInRange(
4920 Range.subtract(SC->getValue()->getValue()), SE);
4921 // This is strange and shouldn't happen.
4922 return SE.getCouldNotCompute();
4925 // The only time we can solve this is when we have all constant indices.
4926 // Otherwise, we cannot determine the overflow conditions.
4927 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4928 if (!isa<SCEVConstant>(getOperand(i)))
4929 return SE.getCouldNotCompute();
4932 // Okay at this point we know that all elements of the chrec are constants and
4933 // that the start element is zero.
4935 // First check to see if the range contains zero. If not, the first
4937 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4938 if (!Range.contains(APInt(BitWidth, 0)))
4939 return SE.getIntegerSCEV(0, getType());
4942 // If this is an affine expression then we have this situation:
4943 // Solve {0,+,A} in Range === Ax in Range
4945 // We know that zero is in the range. If A is positive then we know that
4946 // the upper value of the range must be the first possible exit value.
4947 // If A is negative then the lower of the range is the last possible loop
4948 // value. Also note that we already checked for a full range.
4949 APInt One(BitWidth,1);
4950 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4951 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4953 // The exit value should be (End+A)/A.
4954 APInt ExitVal = (End + A).udiv(A);
4955 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
4957 // Evaluate at the exit value. If we really did fall out of the valid
4958 // range, then we computed our trip count, otherwise wrap around or other
4959 // things must have happened.
4960 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4961 if (Range.contains(Val->getValue()))
4962 return SE.getCouldNotCompute(); // Something strange happened
4964 // Ensure that the previous value is in the range. This is a sanity check.
4965 assert(Range.contains(
4966 EvaluateConstantChrecAtConstant(this,
4967 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
4968 "Linear scev computation is off in a bad way!");
4969 return SE.getConstant(ExitValue);
4970 } else if (isQuadratic()) {
4971 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4972 // quadratic equation to solve it. To do this, we must frame our problem in
4973 // terms of figuring out when zero is crossed, instead of when
4974 // Range.getUpper() is crossed.
4975 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
4976 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4977 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4979 // Next, solve the constructed addrec
4980 std::pair<const SCEV *,const SCEV *> Roots =
4981 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4982 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4983 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4985 // Pick the smallest positive root value.
4986 if (ConstantInt *CB =
4987 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4988 R1->getValue(), R2->getValue()))) {
4989 if (CB->getZExtValue() == false)
4990 std::swap(R1, R2); // R1 is the minimum root now.
4992 // Make sure the root is not off by one. The returned iteration should
4993 // not be in the range, but the previous one should be. When solving
4994 // for "X*X < 5", for example, we should not return a root of 2.
4995 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4998 if (Range.contains(R1Val->getValue())) {
4999 // The next iteration must be out of the range...
5000 ConstantInt *NextVal =
5001 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5003 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5004 if (!Range.contains(R1Val->getValue()))
5005 return SE.getConstant(NextVal);
5006 return SE.getCouldNotCompute(); // Something strange happened
5009 // If R1 was not in the range, then it is a good return value. Make
5010 // sure that R1-1 WAS in the range though, just in case.
5011 ConstantInt *NextVal =
5012 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5013 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5014 if (Range.contains(R1Val->getValue()))
5016 return SE.getCouldNotCompute(); // Something strange happened
5021 return SE.getCouldNotCompute();
5026 //===----------------------------------------------------------------------===//
5027 // SCEVCallbackVH Class Implementation
5028 //===----------------------------------------------------------------------===//
5030 void ScalarEvolution::SCEVCallbackVH::deleted() {
5031 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5032 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5033 SE->ConstantEvolutionLoopExitValue.erase(PN);
5034 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
5035 SE->ValuesAtScopes.erase(I);
5036 SE->Scalars.erase(getValPtr());
5037 // this now dangles!
5040 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5041 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5043 // Forget all the expressions associated with users of the old value,
5044 // so that future queries will recompute the expressions using the new
5046 SmallVector<User *, 16> Worklist;
5047 SmallPtrSet<User *, 8> Visited;
5048 Value *Old = getValPtr();
5049 bool DeleteOld = false;
5050 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5052 Worklist.push_back(*UI);
5053 while (!Worklist.empty()) {
5054 User *U = Worklist.pop_back_val();
5055 // Deleting the Old value will cause this to dangle. Postpone
5056 // that until everything else is done.
5061 if (!Visited.insert(U))
5063 if (PHINode *PN = dyn_cast<PHINode>(U))
5064 SE->ConstantEvolutionLoopExitValue.erase(PN);
5065 if (Instruction *I = dyn_cast<Instruction>(U))
5066 SE->ValuesAtScopes.erase(I);
5067 SE->Scalars.erase(U);
5068 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5070 Worklist.push_back(*UI);
5072 // Delete the Old value if it (indirectly) references itself.
5074 if (PHINode *PN = dyn_cast<PHINode>(Old))
5075 SE->ConstantEvolutionLoopExitValue.erase(PN);
5076 if (Instruction *I = dyn_cast<Instruction>(Old))
5077 SE->ValuesAtScopes.erase(I);
5078 SE->Scalars.erase(Old);
5079 // this now dangles!
5084 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5085 : CallbackVH(V), SE(se) {}
5087 //===----------------------------------------------------------------------===//
5088 // ScalarEvolution Class Implementation
5089 //===----------------------------------------------------------------------===//
5091 ScalarEvolution::ScalarEvolution()
5092 : FunctionPass(&ID) {
5095 bool ScalarEvolution::runOnFunction(Function &F) {
5097 LI = &getAnalysis<LoopInfo>();
5098 TD = getAnalysisIfAvailable<TargetData>();
5102 void ScalarEvolution::releaseMemory() {
5104 BackedgeTakenCounts.clear();
5105 ConstantEvolutionLoopExitValue.clear();
5106 ValuesAtScopes.clear();
5107 UniqueSCEVs.clear();
5108 SCEVAllocator.Reset();
5111 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5112 AU.setPreservesAll();
5113 AU.addRequiredTransitive<LoopInfo>();
5116 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5117 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5120 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5122 // Print all inner loops first
5123 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5124 PrintLoopInfo(OS, SE, *I);
5126 OS << "Loop " << L->getHeader()->getName() << ": ";
5128 SmallVector<BasicBlock*, 8> ExitBlocks;
5129 L->getExitBlocks(ExitBlocks);
5130 if (ExitBlocks.size() != 1)
5131 OS << "<multiple exits> ";
5133 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5134 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5136 OS << "Unpredictable backedge-taken count. ";
5140 OS << "Loop " << L->getHeader()->getName() << ": ";
5142 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5143 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5145 OS << "Unpredictable max backedge-taken count. ";
5151 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
5152 // ScalarEvolution's implementaiton of the print method is to print
5153 // out SCEV values of all instructions that are interesting. Doing
5154 // this potentially causes it to create new SCEV objects though,
5155 // which technically conflicts with the const qualifier. This isn't
5156 // observable from outside the class though, so casting away the
5157 // const isn't dangerous.
5158 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
5160 OS << "Classifying expressions for: " << F->getName() << "\n";
5161 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5162 if (isSCEVable(I->getType())) {
5165 const SCEV *SV = SE.getSCEV(&*I);
5168 const Loop *L = LI->getLoopFor((*I).getParent());
5170 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5177 OS << "\t\t" "Exits: ";
5178 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5179 if (!ExitValue->isLoopInvariant(L)) {
5180 OS << "<<Unknown>>";
5189 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5190 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5191 PrintLoopInfo(OS, &SE, *I);