1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the const SCEV *
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/Dominators.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ValueTracking.h"
73 #include "llvm/Assembly/Writer.h"
74 #include "llvm/Target/TargetData.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/GetElementPtrTypeIterator.h"
80 #include "llvm/Support/InstIterator.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/ADT/Statistic.h"
84 #include "llvm/ADT/STLExtras.h"
85 #include "llvm/ADT/SmallPtrSet.h"
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
98 static cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant "
105 static RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
107 char ScalarEvolution::ID = 0;
109 //===----------------------------------------------------------------------===//
110 // SCEV class definitions
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
114 // Implementation of the SCEV class.
119 void SCEV::dump() const {
124 void SCEV::print(std::ostream &o) const {
125 raw_os_ostream OS(o);
129 bool SCEV::isZero() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isZero();
135 bool SCEV::isOne() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isOne();
141 bool SCEV::isAllOnesValue() const {
142 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
143 return SC->getValue()->isAllOnesValue();
147 SCEVCouldNotCompute::SCEVCouldNotCompute() :
148 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
150 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
155 const Type *SCEVCouldNotCompute::getType() const {
156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
160 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
166 SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
169 ScalarEvolution &SE) const {
173 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
174 OS << "***COULDNOTCOMPUTE***";
177 bool SCEVCouldNotCompute::classof(const SCEV *S) {
178 return S->getSCEVType() == scCouldNotCompute;
181 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
183 ID.AddInteger(scConstant);
186 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
187 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
188 new (S) SCEVConstant(ID, V);
189 UniqueSCEVs.InsertNode(S, IP);
193 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
194 return getConstant(ConstantInt::get(Val));
198 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
199 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
202 const Type *SCEVConstant::getType() const { return V->getType(); }
204 void SCEVConstant::print(raw_ostream &OS) const {
205 WriteAsOperand(OS, V, false);
208 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
209 unsigned SCEVTy, const SCEV *op, const Type *ty)
210 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
212 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
213 return Op->dominates(BB, DT);
216 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
217 const SCEV *op, const Type *ty)
218 : SCEVCastExpr(ID, scTruncate, op, ty) {
219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
221 "Cannot truncate non-integer value!");
224 void SCEVTruncateExpr::print(raw_ostream &OS) const {
225 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
229 const SCEV *op, const Type *ty)
230 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
233 "Cannot zero extend non-integer value!");
236 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
237 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
240 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
241 const SCEV *op, const Type *ty)
242 : SCEVCastExpr(ID, scSignExtend, op, ty) {
243 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
244 (Ty->isInteger() || isa<PointerType>(Ty)) &&
245 "Cannot sign extend non-integer value!");
248 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
249 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
252 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
253 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
254 const char *OpStr = getOperationStr();
255 OS << "(" << *Operands[0];
256 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
257 OS << OpStr << *Operands[i];
262 SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
265 ScalarEvolution &SE) const {
266 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
268 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
269 if (H != getOperand(i)) {
270 SmallVector<const SCEV *, 8> NewOps;
271 NewOps.reserve(getNumOperands());
272 for (unsigned j = 0; j != i; ++j)
273 NewOps.push_back(getOperand(j));
275 for (++i; i != e; ++i)
276 NewOps.push_back(getOperand(i)->
277 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
279 if (isa<SCEVAddExpr>(this))
280 return SE.getAddExpr(NewOps);
281 else if (isa<SCEVMulExpr>(this))
282 return SE.getMulExpr(NewOps);
283 else if (isa<SCEVSMaxExpr>(this))
284 return SE.getSMaxExpr(NewOps);
285 else if (isa<SCEVUMaxExpr>(this))
286 return SE.getUMaxExpr(NewOps);
288 llvm_unreachable("Unknown commutative expr!");
294 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
295 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
296 if (!getOperand(i)->dominates(BB, DT))
302 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
303 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
306 void SCEVUDivExpr::print(raw_ostream &OS) const {
307 OS << "(" << *LHS << " /u " << *RHS << ")";
310 const Type *SCEVUDivExpr::getType() const {
311 // In most cases the types of LHS and RHS will be the same, but in some
312 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
313 // depend on the type for correctness, but handling types carefully can
314 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
315 // a pointer type than the RHS, so use the RHS' type here.
316 return RHS->getType();
320 SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
322 ScalarEvolution &SE) const {
323 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
325 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
326 if (H != getOperand(i)) {
327 SmallVector<const SCEV *, 8> NewOps;
328 NewOps.reserve(getNumOperands());
329 for (unsigned j = 0; j != i; ++j)
330 NewOps.push_back(getOperand(j));
332 for (++i; i != e; ++i)
333 NewOps.push_back(getOperand(i)->
334 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
336 return SE.getAddRecExpr(NewOps, L);
343 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
344 // Add recurrences are never invariant in the function-body (null loop).
348 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
349 if (QueryLoop->contains(L->getHeader()))
352 // This recurrence is variant w.r.t. QueryLoop if any of its operands
354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
355 if (!getOperand(i)->isLoopInvariant(QueryLoop))
358 // Otherwise it's loop-invariant.
362 void SCEVAddRecExpr::print(raw_ostream &OS) const {
363 OS << "{" << *Operands[0];
364 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
365 OS << ",+," << *Operands[i];
366 OS << "}<" << L->getHeader()->getName() + ">";
369 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
372 // Instructions are never considered invariant in the function body
373 // (null loop) because they are defined within the "loop".
374 if (Instruction *I = dyn_cast<Instruction>(V))
375 return L && !L->contains(I->getParent());
379 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
380 if (Instruction *I = dyn_cast<Instruction>(getValue()))
381 return DT->dominates(I->getParent(), BB);
385 const Type *SCEVUnknown::getType() const {
389 void SCEVUnknown::print(raw_ostream &OS) const {
390 WriteAsOperand(OS, V, false);
393 //===----------------------------------------------------------------------===//
395 //===----------------------------------------------------------------------===//
398 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
399 /// than the complexity of the RHS. This comparator is used to canonicalize
401 class VISIBILITY_HIDDEN SCEVComplexityCompare {
404 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
406 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
407 // Primarily, sort the SCEVs by their getSCEVType().
408 if (LHS->getSCEVType() != RHS->getSCEVType())
409 return LHS->getSCEVType() < RHS->getSCEVType();
411 // Aside from the getSCEVType() ordering, the particular ordering
412 // isn't very important except that it's beneficial to be consistent,
413 // so that (a + b) and (b + a) don't end up as different expressions.
415 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
416 // not as complete as it could be.
417 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
418 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
420 // Order pointer values after integer values. This helps SCEVExpander
422 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
424 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
427 // Compare getValueID values.
428 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
429 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
431 // Sort arguments by their position.
432 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
433 const Argument *RA = cast<Argument>(RU->getValue());
434 return LA->getArgNo() < RA->getArgNo();
437 // For instructions, compare their loop depth, and their opcode.
438 // This is pretty loose.
439 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
440 Instruction *RV = cast<Instruction>(RU->getValue());
442 // Compare loop depths.
443 if (LI->getLoopDepth(LV->getParent()) !=
444 LI->getLoopDepth(RV->getParent()))
445 return LI->getLoopDepth(LV->getParent()) <
446 LI->getLoopDepth(RV->getParent());
449 if (LV->getOpcode() != RV->getOpcode())
450 return LV->getOpcode() < RV->getOpcode();
452 // Compare the number of operands.
453 if (LV->getNumOperands() != RV->getNumOperands())
454 return LV->getNumOperands() < RV->getNumOperands();
460 // Compare constant values.
461 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
462 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
463 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
464 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
465 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
468 // Compare addrec loop depths.
469 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
470 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
471 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
472 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
475 // Lexicographically compare n-ary expressions.
476 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
477 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
478 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
479 if (i >= RC->getNumOperands())
481 if (operator()(LC->getOperand(i), RC->getOperand(i)))
483 if (operator()(RC->getOperand(i), LC->getOperand(i)))
486 return LC->getNumOperands() < RC->getNumOperands();
489 // Lexicographically compare udiv expressions.
490 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
491 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
492 if (operator()(LC->getLHS(), RC->getLHS()))
494 if (operator()(RC->getLHS(), LC->getLHS()))
496 if (operator()(LC->getRHS(), RC->getRHS()))
498 if (operator()(RC->getRHS(), LC->getRHS()))
503 // Compare cast expressions by operand.
504 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
505 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
506 return operator()(LC->getOperand(), RC->getOperand());
509 llvm_unreachable("Unknown SCEV kind!");
515 /// GroupByComplexity - Given a list of SCEV objects, order them by their
516 /// complexity, and group objects of the same complexity together by value.
517 /// When this routine is finished, we know that any duplicates in the vector are
518 /// consecutive and that complexity is monotonically increasing.
520 /// Note that we go take special precautions to ensure that we get determinstic
521 /// results from this routine. In other words, we don't want the results of
522 /// this to depend on where the addresses of various SCEV objects happened to
525 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
527 if (Ops.size() < 2) return; // Noop
528 if (Ops.size() == 2) {
529 // This is the common case, which also happens to be trivially simple.
531 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
532 std::swap(Ops[0], Ops[1]);
536 // Do the rough sort by complexity.
537 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
539 // Now that we are sorted by complexity, group elements of the same
540 // complexity. Note that this is, at worst, N^2, but the vector is likely to
541 // be extremely short in practice. Note that we take this approach because we
542 // do not want to depend on the addresses of the objects we are grouping.
543 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
544 const SCEV *S = Ops[i];
545 unsigned Complexity = S->getSCEVType();
547 // If there are any objects of the same complexity and same value as this
549 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
550 if (Ops[j] == S) { // Found a duplicate.
551 // Move it to immediately after i'th element.
552 std::swap(Ops[i+1], Ops[j]);
553 ++i; // no need to rescan it.
554 if (i == e-2) return; // Done!
562 //===----------------------------------------------------------------------===//
563 // Simple SCEV method implementations
564 //===----------------------------------------------------------------------===//
566 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
568 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
570 const Type* ResultTy) {
571 // Handle the simplest case efficiently.
573 return SE.getTruncateOrZeroExtend(It, ResultTy);
575 // We are using the following formula for BC(It, K):
577 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
579 // Suppose, W is the bitwidth of the return value. We must be prepared for
580 // overflow. Hence, we must assure that the result of our computation is
581 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
582 // safe in modular arithmetic.
584 // However, this code doesn't use exactly that formula; the formula it uses
585 // is something like the following, where T is the number of factors of 2 in
586 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
589 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
591 // This formula is trivially equivalent to the previous formula. However,
592 // this formula can be implemented much more efficiently. The trick is that
593 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
594 // arithmetic. To do exact division in modular arithmetic, all we have
595 // to do is multiply by the inverse. Therefore, this step can be done at
598 // The next issue is how to safely do the division by 2^T. The way this
599 // is done is by doing the multiplication step at a width of at least W + T
600 // bits. This way, the bottom W+T bits of the product are accurate. Then,
601 // when we perform the division by 2^T (which is equivalent to a right shift
602 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
603 // truncated out after the division by 2^T.
605 // In comparison to just directly using the first formula, this technique
606 // is much more efficient; using the first formula requires W * K bits,
607 // but this formula less than W + K bits. Also, the first formula requires
608 // a division step, whereas this formula only requires multiplies and shifts.
610 // It doesn't matter whether the subtraction step is done in the calculation
611 // width or the input iteration count's width; if the subtraction overflows,
612 // the result must be zero anyway. We prefer here to do it in the width of
613 // the induction variable because it helps a lot for certain cases; CodeGen
614 // isn't smart enough to ignore the overflow, which leads to much less
615 // efficient code if the width of the subtraction is wider than the native
618 // (It's possible to not widen at all by pulling out factors of 2 before
619 // the multiplication; for example, K=2 can be calculated as
620 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
621 // extra arithmetic, so it's not an obvious win, and it gets
622 // much more complicated for K > 3.)
624 // Protection from insane SCEVs; this bound is conservative,
625 // but it probably doesn't matter.
627 return SE.getCouldNotCompute();
629 unsigned W = SE.getTypeSizeInBits(ResultTy);
631 // Calculate K! / 2^T and T; we divide out the factors of two before
632 // multiplying for calculating K! / 2^T to avoid overflow.
633 // Other overflow doesn't matter because we only care about the bottom
634 // W bits of the result.
635 APInt OddFactorial(W, 1);
637 for (unsigned i = 3; i <= K; ++i) {
639 unsigned TwoFactors = Mult.countTrailingZeros();
641 Mult = Mult.lshr(TwoFactors);
642 OddFactorial *= Mult;
645 // We need at least W + T bits for the multiplication step
646 unsigned CalculationBits = W + T;
648 // Calcuate 2^T, at width T+W.
649 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
651 // Calculate the multiplicative inverse of K! / 2^T;
652 // this multiplication factor will perform the exact division by
654 APInt Mod = APInt::getSignedMinValue(W+1);
655 APInt MultiplyFactor = OddFactorial.zext(W+1);
656 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
657 MultiplyFactor = MultiplyFactor.trunc(W);
659 // Calculate the product, at width T+W
660 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
661 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
662 for (unsigned i = 1; i != K; ++i) {
663 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
664 Dividend = SE.getMulExpr(Dividend,
665 SE.getTruncateOrZeroExtend(S, CalculationTy));
669 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
671 // Truncate the result, and divide by K! / 2^T.
673 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
674 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
677 /// evaluateAtIteration - Return the value of this chain of recurrences at
678 /// the specified iteration number. We can evaluate this recurrence by
679 /// multiplying each element in the chain by the binomial coefficient
680 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
682 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
684 /// where BC(It, k) stands for binomial coefficient.
686 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
687 ScalarEvolution &SE) const {
688 const SCEV *Result = getStart();
689 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
690 // The computation is correct in the face of overflow provided that the
691 // multiplication is performed _after_ the evaluation of the binomial
693 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
694 if (isa<SCEVCouldNotCompute>(Coeff))
697 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
702 //===----------------------------------------------------------------------===//
703 // SCEV Expression folder implementations
704 //===----------------------------------------------------------------------===//
706 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
708 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
709 "This is not a truncating conversion!");
710 assert(isSCEVable(Ty) &&
711 "This is not a conversion to a SCEVable type!");
712 Ty = getEffectiveSCEVType(Ty);
715 ID.AddInteger(scTruncate);
719 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
721 // Fold if the operand is constant.
722 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
724 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
726 // trunc(trunc(x)) --> trunc(x)
727 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
728 return getTruncateExpr(ST->getOperand(), Ty);
730 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
731 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
732 return getTruncateOrSignExtend(SS->getOperand(), Ty);
734 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
735 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
736 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
738 // If the input value is a chrec scev, truncate the chrec's operands.
739 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
740 SmallVector<const SCEV *, 4> Operands;
741 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
742 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
743 return getAddRecExpr(Operands, AddRec->getLoop());
746 // The cast wasn't folded; create an explicit cast node.
747 // Recompute the insert position, as it may have been invalidated.
748 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
749 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
750 new (S) SCEVTruncateExpr(ID, Op, Ty);
751 UniqueSCEVs.InsertNode(S, IP);
755 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
757 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
758 "This is not an extending conversion!");
759 assert(isSCEVable(Ty) &&
760 "This is not a conversion to a SCEVable type!");
761 Ty = getEffectiveSCEVType(Ty);
763 // Fold if the operand is constant.
764 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
765 const Type *IntTy = getEffectiveSCEVType(Ty);
766 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
767 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
768 return getConstant(cast<ConstantInt>(C));
771 // zext(zext(x)) --> zext(x)
772 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
773 return getZeroExtendExpr(SZ->getOperand(), Ty);
775 // Before doing any expensive analysis, check to see if we've already
776 // computed a SCEV for this Op and Ty.
778 ID.AddInteger(scZeroExtend);
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
784 // If the input value is a chrec scev, and we can prove that the value
785 // did not overflow the old, smaller, value, we can zero extend all of the
786 // operands (often constants). This allows analysis of something like
787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
789 if (AR->isAffine()) {
790 const SCEV *Start = AR->getStart();
791 const SCEV *Step = AR->getStepRecurrence(*this);
792 unsigned BitWidth = getTypeSizeInBits(AR->getType());
793 const Loop *L = AR->getLoop();
795 // Check whether the backedge-taken count is SCEVCouldNotCompute.
796 // Note that this serves two purposes: It filters out loops that are
797 // simply not analyzable, and it covers the case where this code is
798 // being called from within backedge-taken count analysis, such that
799 // attempting to ask for the backedge-taken count would likely result
800 // in infinite recursion. In the later case, the analysis code will
801 // cope with a conservative value, and it will take care to purge
802 // that value once it has finished.
803 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
804 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
805 // Manually compute the final value for AR, checking for
808 // Check whether the backedge-taken count can be losslessly casted to
809 // the addrec's type. The count is always unsigned.
810 const SCEV *CastedMaxBECount =
811 getTruncateOrZeroExtend(MaxBECount, Start->getType());
812 const SCEV *RecastedMaxBECount =
813 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
814 if (MaxBECount == RecastedMaxBECount) {
815 const Type *WideTy = IntegerType::get(BitWidth * 2);
816 // Check whether Start+Step*MaxBECount has no unsigned overflow.
818 getMulExpr(CastedMaxBECount,
819 getTruncateOrZeroExtend(Step, Start->getType()));
820 const SCEV *Add = getAddExpr(Start, ZMul);
821 const SCEV *OperandExtendedAdd =
822 getAddExpr(getZeroExtendExpr(Start, WideTy),
823 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
824 getZeroExtendExpr(Step, WideTy)));
825 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
826 // Return the expression with the addrec on the outside.
827 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
828 getZeroExtendExpr(Step, Ty),
831 // Similar to above, only this time treat the step value as signed.
832 // This covers loops that count down.
834 getMulExpr(CastedMaxBECount,
835 getTruncateOrSignExtend(Step, Start->getType()));
836 Add = getAddExpr(Start, SMul);
838 getAddExpr(getZeroExtendExpr(Start, WideTy),
839 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
840 getSignExtendExpr(Step, WideTy)));
841 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
842 // Return the expression with the addrec on the outside.
843 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
844 getSignExtendExpr(Step, Ty),
848 // If the backedge is guarded by a comparison with the pre-inc value
849 // the addrec is safe. Also, if the entry is guarded by a comparison
850 // with the start value and the backedge is guarded by a comparison
851 // with the post-inc value, the addrec is safe.
852 if (isKnownPositive(Step)) {
853 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
854 getUnsignedRange(Step).getUnsignedMax());
855 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
856 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
857 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
858 AR->getPostIncExpr(*this), N)))
859 // Return the expression with the addrec on the outside.
860 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
861 getZeroExtendExpr(Step, Ty),
863 } else if (isKnownNegative(Step)) {
864 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
865 getSignedRange(Step).getSignedMin());
866 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
867 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
868 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
869 AR->getPostIncExpr(*this), N)))
870 // Return the expression with the addrec on the outside.
871 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
872 getSignExtendExpr(Step, Ty),
878 // The cast wasn't folded; create an explicit cast node.
879 // Recompute the insert position, as it may have been invalidated.
880 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
881 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
882 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
883 UniqueSCEVs.InsertNode(S, IP);
887 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
889 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
890 "This is not an extending conversion!");
891 assert(isSCEVable(Ty) &&
892 "This is not a conversion to a SCEVable type!");
893 Ty = getEffectiveSCEVType(Ty);
895 // Fold if the operand is constant.
896 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
897 const Type *IntTy = getEffectiveSCEVType(Ty);
898 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
899 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
900 return getConstant(cast<ConstantInt>(C));
903 // sext(sext(x)) --> sext(x)
904 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
905 return getSignExtendExpr(SS->getOperand(), Ty);
907 // Before doing any expensive analysis, check to see if we've already
908 // computed a SCEV for this Op and Ty.
910 ID.AddInteger(scSignExtend);
914 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
916 // If the input value is a chrec scev, and we can prove that the value
917 // did not overflow the old, smaller, value, we can sign extend all of the
918 // operands (often constants). This allows analysis of something like
919 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
920 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
921 if (AR->isAffine()) {
922 const SCEV *Start = AR->getStart();
923 const SCEV *Step = AR->getStepRecurrence(*this);
924 unsigned BitWidth = getTypeSizeInBits(AR->getType());
925 const Loop *L = AR->getLoop();
927 // Check whether the backedge-taken count is SCEVCouldNotCompute.
928 // Note that this serves two purposes: It filters out loops that are
929 // simply not analyzable, and it covers the case where this code is
930 // being called from within backedge-taken count analysis, such that
931 // attempting to ask for the backedge-taken count would likely result
932 // in infinite recursion. In the later case, the analysis code will
933 // cope with a conservative value, and it will take care to purge
934 // that value once it has finished.
935 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
936 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
937 // Manually compute the final value for AR, checking for
940 // Check whether the backedge-taken count can be losslessly casted to
941 // the addrec's type. The count is always unsigned.
942 const SCEV *CastedMaxBECount =
943 getTruncateOrZeroExtend(MaxBECount, Start->getType());
944 const SCEV *RecastedMaxBECount =
945 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
946 if (MaxBECount == RecastedMaxBECount) {
947 const Type *WideTy = IntegerType::get(BitWidth * 2);
948 // Check whether Start+Step*MaxBECount has no signed overflow.
950 getMulExpr(CastedMaxBECount,
951 getTruncateOrSignExtend(Step, Start->getType()));
952 const SCEV *Add = getAddExpr(Start, SMul);
953 const SCEV *OperandExtendedAdd =
954 getAddExpr(getSignExtendExpr(Start, WideTy),
955 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
956 getSignExtendExpr(Step, WideTy)));
957 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
964 // If the backedge is guarded by a comparison with the pre-inc value
965 // the addrec is safe. Also, if the entry is guarded by a comparison
966 // with the start value and the backedge is guarded by a comparison
967 // with the post-inc value, the addrec is safe.
968 if (isKnownPositive(Step)) {
969 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
970 getSignedRange(Step).getSignedMax());
971 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
972 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
973 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
974 AR->getPostIncExpr(*this), N)))
975 // Return the expression with the addrec on the outside.
976 return getAddRecExpr(getSignExtendExpr(Start, Ty),
977 getSignExtendExpr(Step, Ty),
979 } else if (isKnownNegative(Step)) {
980 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
981 getSignedRange(Step).getSignedMin());
982 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
983 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
984 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
985 AR->getPostIncExpr(*this), N)))
986 // Return the expression with the addrec on the outside.
987 return getAddRecExpr(getSignExtendExpr(Start, Ty),
988 getSignExtendExpr(Step, Ty),
994 // The cast wasn't folded; create an explicit cast node.
995 // Recompute the insert position, as it may have been invalidated.
996 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
997 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
998 new (S) SCEVSignExtendExpr(ID, Op, Ty);
999 UniqueSCEVs.InsertNode(S, IP);
1003 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1004 /// unspecified bits out to the given type.
1006 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1008 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1009 "This is not an extending conversion!");
1010 assert(isSCEVable(Ty) &&
1011 "This is not a conversion to a SCEVable type!");
1012 Ty = getEffectiveSCEVType(Ty);
1014 // Sign-extend negative constants.
1015 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1016 if (SC->getValue()->getValue().isNegative())
1017 return getSignExtendExpr(Op, Ty);
1019 // Peel off a truncate cast.
1020 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1021 const SCEV *NewOp = T->getOperand();
1022 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1023 return getAnyExtendExpr(NewOp, Ty);
1024 return getTruncateOrNoop(NewOp, Ty);
1027 // Next try a zext cast. If the cast is folded, use it.
1028 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1029 if (!isa<SCEVZeroExtendExpr>(ZExt))
1032 // Next try a sext cast. If the cast is folded, use it.
1033 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1034 if (!isa<SCEVSignExtendExpr>(SExt))
1037 // If the expression is obviously signed, use the sext cast value.
1038 if (isa<SCEVSMaxExpr>(Op))
1041 // Absent any other information, use the zext cast value.
1045 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1046 /// a list of operands to be added under the given scale, update the given
1047 /// map. This is a helper function for getAddRecExpr. As an example of
1048 /// what it does, given a sequence of operands that would form an add
1049 /// expression like this:
1051 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1053 /// where A and B are constants, update the map with these values:
1055 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1057 /// and add 13 + A*B*29 to AccumulatedConstant.
1058 /// This will allow getAddRecExpr to produce this:
1060 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1062 /// This form often exposes folding opportunities that are hidden in
1063 /// the original operand list.
1065 /// Return true iff it appears that any interesting folding opportunities
1066 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1067 /// the common case where no interesting opportunities are present, and
1068 /// is also used as a check to avoid infinite recursion.
1071 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1072 SmallVector<const SCEV *, 8> &NewOps,
1073 APInt &AccumulatedConstant,
1074 const SmallVectorImpl<const SCEV *> &Ops,
1076 ScalarEvolution &SE) {
1077 bool Interesting = false;
1079 // Iterate over the add operands.
1080 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1081 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1082 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1084 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1085 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1086 // A multiplication of a constant with another add; recurse.
1088 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1089 cast<SCEVAddExpr>(Mul->getOperand(1))
1093 // A multiplication of a constant with some other value. Update
1095 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1096 const SCEV *Key = SE.getMulExpr(MulOps);
1097 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1098 M.insert(std::make_pair(Key, NewScale));
1100 NewOps.push_back(Pair.first->first);
1102 Pair.first->second += NewScale;
1103 // The map already had an entry for this value, which may indicate
1104 // a folding opportunity.
1108 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1109 // Pull a buried constant out to the outside.
1110 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1112 AccumulatedConstant += Scale * C->getValue()->getValue();
1114 // An ordinary operand. Update the map.
1115 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1116 M.insert(std::make_pair(Ops[i], Scale));
1118 NewOps.push_back(Pair.first->first);
1120 Pair.first->second += Scale;
1121 // The map already had an entry for this value, which may indicate
1122 // a folding opportunity.
1132 struct APIntCompare {
1133 bool operator()(const APInt &LHS, const APInt &RHS) const {
1134 return LHS.ult(RHS);
1139 /// getAddExpr - Get a canonical add expression, or something simpler if
1141 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1142 assert(!Ops.empty() && "Cannot get empty add!");
1143 if (Ops.size() == 1) return Ops[0];
1145 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1146 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1147 getEffectiveSCEVType(Ops[0]->getType()) &&
1148 "SCEVAddExpr operand types don't match!");
1151 // Sort by complexity, this groups all similar expression types together.
1152 GroupByComplexity(Ops, LI);
1154 // If there are any constants, fold them together.
1156 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1158 assert(Idx < Ops.size());
1159 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1160 // We found two constants, fold them together!
1161 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1162 RHSC->getValue()->getValue());
1163 if (Ops.size() == 2) return Ops[0];
1164 Ops.erase(Ops.begin()+1); // Erase the folded element
1165 LHSC = cast<SCEVConstant>(Ops[0]);
1168 // If we are left with a constant zero being added, strip it off.
1169 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1170 Ops.erase(Ops.begin());
1175 if (Ops.size() == 1) return Ops[0];
1177 // Okay, check to see if the same value occurs in the operand list twice. If
1178 // so, merge them together into an multiply expression. Since we sorted the
1179 // list, these values are required to be adjacent.
1180 const Type *Ty = Ops[0]->getType();
1181 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1182 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1183 // Found a match, merge the two values into a multiply, and add any
1184 // remaining values to the result.
1185 const SCEV *Two = getIntegerSCEV(2, Ty);
1186 const SCEV *Mul = getMulExpr(Ops[i], Two);
1187 if (Ops.size() == 2)
1189 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1191 return getAddExpr(Ops);
1194 // Check for truncates. If all the operands are truncated from the same
1195 // type, see if factoring out the truncate would permit the result to be
1196 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1197 // if the contents of the resulting outer trunc fold to something simple.
1198 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1199 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1200 const Type *DstType = Trunc->getType();
1201 const Type *SrcType = Trunc->getOperand()->getType();
1202 SmallVector<const SCEV *, 8> LargeOps;
1204 // Check all the operands to see if they can be represented in the
1205 // source type of the truncate.
1206 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1208 if (T->getOperand()->getType() != SrcType) {
1212 LargeOps.push_back(T->getOperand());
1213 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1214 // This could be either sign or zero extension, but sign extension
1215 // is much more likely to be foldable here.
1216 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1217 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1218 SmallVector<const SCEV *, 8> LargeMulOps;
1219 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1220 if (const SCEVTruncateExpr *T =
1221 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1222 if (T->getOperand()->getType() != SrcType) {
1226 LargeMulOps.push_back(T->getOperand());
1227 } else if (const SCEVConstant *C =
1228 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1229 // This could be either sign or zero extension, but sign extension
1230 // is much more likely to be foldable here.
1231 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1238 LargeOps.push_back(getMulExpr(LargeMulOps));
1245 // Evaluate the expression in the larger type.
1246 const SCEV *Fold = getAddExpr(LargeOps);
1247 // If it folds to something simple, use it. Otherwise, don't.
1248 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1249 return getTruncateExpr(Fold, DstType);
1253 // Skip past any other cast SCEVs.
1254 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1257 // If there are add operands they would be next.
1258 if (Idx < Ops.size()) {
1259 bool DeletedAdd = false;
1260 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1261 // If we have an add, expand the add operands onto the end of the operands
1263 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1264 Ops.erase(Ops.begin()+Idx);
1268 // If we deleted at least one add, we added operands to the end of the list,
1269 // and they are not necessarily sorted. Recurse to resort and resimplify
1270 // any operands we just aquired.
1272 return getAddExpr(Ops);
1275 // Skip over the add expression until we get to a multiply.
1276 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1279 // Check to see if there are any folding opportunities present with
1280 // operands multiplied by constant values.
1281 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1282 uint64_t BitWidth = getTypeSizeInBits(Ty);
1283 DenseMap<const SCEV *, APInt> M;
1284 SmallVector<const SCEV *, 8> NewOps;
1285 APInt AccumulatedConstant(BitWidth, 0);
1286 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1287 Ops, APInt(BitWidth, 1), *this)) {
1288 // Some interesting folding opportunity is present, so its worthwhile to
1289 // re-generate the operands list. Group the operands by constant scale,
1290 // to avoid multiplying by the same constant scale multiple times.
1291 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1292 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1293 E = NewOps.end(); I != E; ++I)
1294 MulOpLists[M.find(*I)->second].push_back(*I);
1295 // Re-generate the operands list.
1297 if (AccumulatedConstant != 0)
1298 Ops.push_back(getConstant(AccumulatedConstant));
1299 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1300 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1302 Ops.push_back(getMulExpr(getConstant(I->first),
1303 getAddExpr(I->second)));
1305 return getIntegerSCEV(0, Ty);
1306 if (Ops.size() == 1)
1308 return getAddExpr(Ops);
1312 // If we are adding something to a multiply expression, make sure the
1313 // something is not already an operand of the multiply. If so, merge it into
1315 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1316 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1317 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1318 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1319 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1320 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1321 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1322 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1323 if (Mul->getNumOperands() != 2) {
1324 // If the multiply has more than two operands, we must get the
1326 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1327 MulOps.erase(MulOps.begin()+MulOp);
1328 InnerMul = getMulExpr(MulOps);
1330 const SCEV *One = getIntegerSCEV(1, Ty);
1331 const SCEV *AddOne = getAddExpr(InnerMul, One);
1332 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1333 if (Ops.size() == 2) return OuterMul;
1335 Ops.erase(Ops.begin()+AddOp);
1336 Ops.erase(Ops.begin()+Idx-1);
1338 Ops.erase(Ops.begin()+Idx);
1339 Ops.erase(Ops.begin()+AddOp-1);
1341 Ops.push_back(OuterMul);
1342 return getAddExpr(Ops);
1345 // Check this multiply against other multiplies being added together.
1346 for (unsigned OtherMulIdx = Idx+1;
1347 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1349 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1350 // If MulOp occurs in OtherMul, we can fold the two multiplies
1352 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1353 OMulOp != e; ++OMulOp)
1354 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1355 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1356 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1357 if (Mul->getNumOperands() != 2) {
1358 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1360 MulOps.erase(MulOps.begin()+MulOp);
1361 InnerMul1 = getMulExpr(MulOps);
1363 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1364 if (OtherMul->getNumOperands() != 2) {
1365 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1366 OtherMul->op_end());
1367 MulOps.erase(MulOps.begin()+OMulOp);
1368 InnerMul2 = getMulExpr(MulOps);
1370 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1371 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1372 if (Ops.size() == 2) return OuterMul;
1373 Ops.erase(Ops.begin()+Idx);
1374 Ops.erase(Ops.begin()+OtherMulIdx-1);
1375 Ops.push_back(OuterMul);
1376 return getAddExpr(Ops);
1382 // If there are any add recurrences in the operands list, see if any other
1383 // added values are loop invariant. If so, we can fold them into the
1385 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1388 // Scan over all recurrences, trying to fold loop invariants into them.
1389 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1390 // Scan all of the other operands to this add and add them to the vector if
1391 // they are loop invariant w.r.t. the recurrence.
1392 SmallVector<const SCEV *, 8> LIOps;
1393 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1394 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1395 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1396 LIOps.push_back(Ops[i]);
1397 Ops.erase(Ops.begin()+i);
1401 // If we found some loop invariants, fold them into the recurrence.
1402 if (!LIOps.empty()) {
1403 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1404 LIOps.push_back(AddRec->getStart());
1406 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1408 AddRecOps[0] = getAddExpr(LIOps);
1410 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1411 // If all of the other operands were loop invariant, we are done.
1412 if (Ops.size() == 1) return NewRec;
1414 // Otherwise, add the folded AddRec by the non-liv parts.
1415 for (unsigned i = 0;; ++i)
1416 if (Ops[i] == AddRec) {
1420 return getAddExpr(Ops);
1423 // Okay, if there weren't any loop invariants to be folded, check to see if
1424 // there are multiple AddRec's with the same loop induction variable being
1425 // added together. If so, we can fold them.
1426 for (unsigned OtherIdx = Idx+1;
1427 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1428 if (OtherIdx != Idx) {
1429 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1430 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1431 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1432 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1434 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1435 if (i >= NewOps.size()) {
1436 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1437 OtherAddRec->op_end());
1440 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1442 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1444 if (Ops.size() == 2) return NewAddRec;
1446 Ops.erase(Ops.begin()+Idx);
1447 Ops.erase(Ops.begin()+OtherIdx-1);
1448 Ops.push_back(NewAddRec);
1449 return getAddExpr(Ops);
1453 // Otherwise couldn't fold anything into this recurrence. Move onto the
1457 // Okay, it looks like we really DO need an add expr. Check to see if we
1458 // already have one, otherwise create a new one.
1459 FoldingSetNodeID ID;
1460 ID.AddInteger(scAddExpr);
1461 ID.AddInteger(Ops.size());
1462 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1463 ID.AddPointer(Ops[i]);
1465 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1466 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1467 new (S) SCEVAddExpr(ID, Ops);
1468 UniqueSCEVs.InsertNode(S, IP);
1473 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1475 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1476 assert(!Ops.empty() && "Cannot get empty mul!");
1478 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1479 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1480 getEffectiveSCEVType(Ops[0]->getType()) &&
1481 "SCEVMulExpr operand types don't match!");
1484 // Sort by complexity, this groups all similar expression types together.
1485 GroupByComplexity(Ops, LI);
1487 // If there are any constants, fold them together.
1489 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1491 // C1*(C2+V) -> C1*C2 + C1*V
1492 if (Ops.size() == 2)
1493 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1494 if (Add->getNumOperands() == 2 &&
1495 isa<SCEVConstant>(Add->getOperand(0)))
1496 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1497 getMulExpr(LHSC, Add->getOperand(1)));
1501 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1502 // We found two constants, fold them together!
1503 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1504 RHSC->getValue()->getValue());
1505 Ops[0] = getConstant(Fold);
1506 Ops.erase(Ops.begin()+1); // Erase the folded element
1507 if (Ops.size() == 1) return Ops[0];
1508 LHSC = cast<SCEVConstant>(Ops[0]);
1511 // If we are left with a constant one being multiplied, strip it off.
1512 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1513 Ops.erase(Ops.begin());
1515 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1516 // If we have a multiply of zero, it will always be zero.
1521 // Skip over the add expression until we get to a multiply.
1522 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1525 if (Ops.size() == 1)
1528 // If there are mul operands inline them all into this expression.
1529 if (Idx < Ops.size()) {
1530 bool DeletedMul = false;
1531 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1532 // If we have an mul, expand the mul operands onto the end of the operands
1534 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1535 Ops.erase(Ops.begin()+Idx);
1539 // If we deleted at least one mul, we added operands to the end of the list,
1540 // and they are not necessarily sorted. Recurse to resort and resimplify
1541 // any operands we just aquired.
1543 return getMulExpr(Ops);
1546 // If there are any add recurrences in the operands list, see if any other
1547 // added values are loop invariant. If so, we can fold them into the
1549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1552 // Scan over all recurrences, trying to fold loop invariants into them.
1553 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1554 // Scan all of the other operands to this mul and add them to the vector if
1555 // they are loop invariant w.r.t. the recurrence.
1556 SmallVector<const SCEV *, 8> LIOps;
1557 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1558 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1559 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1560 LIOps.push_back(Ops[i]);
1561 Ops.erase(Ops.begin()+i);
1565 // If we found some loop invariants, fold them into the recurrence.
1566 if (!LIOps.empty()) {
1567 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1568 SmallVector<const SCEV *, 4> NewOps;
1569 NewOps.reserve(AddRec->getNumOperands());
1570 if (LIOps.size() == 1) {
1571 const SCEV *Scale = LIOps[0];
1572 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1573 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1575 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1576 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1577 MulOps.push_back(AddRec->getOperand(i));
1578 NewOps.push_back(getMulExpr(MulOps));
1582 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1584 // If all of the other operands were loop invariant, we are done.
1585 if (Ops.size() == 1) return NewRec;
1587 // Otherwise, multiply the folded AddRec by the non-liv parts.
1588 for (unsigned i = 0;; ++i)
1589 if (Ops[i] == AddRec) {
1593 return getMulExpr(Ops);
1596 // Okay, if there weren't any loop invariants to be folded, check to see if
1597 // there are multiple AddRec's with the same loop induction variable being
1598 // multiplied together. If so, we can fold them.
1599 for (unsigned OtherIdx = Idx+1;
1600 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1601 if (OtherIdx != Idx) {
1602 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1603 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1604 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1605 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1606 const SCEV *NewStart = getMulExpr(F->getStart(),
1608 const SCEV *B = F->getStepRecurrence(*this);
1609 const SCEV *D = G->getStepRecurrence(*this);
1610 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1613 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1615 if (Ops.size() == 2) return NewAddRec;
1617 Ops.erase(Ops.begin()+Idx);
1618 Ops.erase(Ops.begin()+OtherIdx-1);
1619 Ops.push_back(NewAddRec);
1620 return getMulExpr(Ops);
1624 // Otherwise couldn't fold anything into this recurrence. Move onto the
1628 // Okay, it looks like we really DO need an mul expr. Check to see if we
1629 // already have one, otherwise create a new one.
1630 FoldingSetNodeID ID;
1631 ID.AddInteger(scMulExpr);
1632 ID.AddInteger(Ops.size());
1633 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1634 ID.AddPointer(Ops[i]);
1636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1637 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1638 new (S) SCEVMulExpr(ID, Ops);
1639 UniqueSCEVs.InsertNode(S, IP);
1643 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1645 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1647 assert(getEffectiveSCEVType(LHS->getType()) ==
1648 getEffectiveSCEVType(RHS->getType()) &&
1649 "SCEVUDivExpr operand types don't match!");
1651 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1652 if (RHSC->getValue()->equalsInt(1))
1653 return LHS; // X udiv 1 --> x
1655 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1657 // Determine if the division can be folded into the operands of
1659 // TODO: Generalize this to non-constants by using known-bits information.
1660 const Type *Ty = LHS->getType();
1661 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1662 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1663 // For non-power-of-two values, effectively round the value up to the
1664 // nearest power of two.
1665 if (!RHSC->getValue()->getValue().isPowerOf2())
1667 const IntegerType *ExtTy =
1668 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1669 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1670 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1671 if (const SCEVConstant *Step =
1672 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1673 if (!Step->getValue()->getValue()
1674 .urem(RHSC->getValue()->getValue()) &&
1675 getZeroExtendExpr(AR, ExtTy) ==
1676 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1677 getZeroExtendExpr(Step, ExtTy),
1679 SmallVector<const SCEV *, 4> Operands;
1680 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1681 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1682 return getAddRecExpr(Operands, AR->getLoop());
1684 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1685 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1686 SmallVector<const SCEV *, 4> Operands;
1687 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1688 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1689 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1690 // Find an operand that's safely divisible.
1691 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1692 const SCEV *Op = M->getOperand(i);
1693 const SCEV *Div = getUDivExpr(Op, RHSC);
1694 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1695 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1696 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1699 return getMulExpr(Operands);
1703 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1704 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1705 SmallVector<const SCEV *, 4> Operands;
1706 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1707 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1708 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1710 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1711 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1712 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1714 Operands.push_back(Op);
1716 if (Operands.size() == A->getNumOperands())
1717 return getAddExpr(Operands);
1721 // Fold if both operands are constant.
1722 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1723 Constant *LHSCV = LHSC->getValue();
1724 Constant *RHSCV = RHSC->getValue();
1725 return getConstant(cast<ConstantInt>(Context->getConstantExprUDiv(LHSCV,
1730 FoldingSetNodeID ID;
1731 ID.AddInteger(scUDivExpr);
1735 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1736 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1737 new (S) SCEVUDivExpr(ID, LHS, RHS);
1738 UniqueSCEVs.InsertNode(S, IP);
1743 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1744 /// Simplify the expression as much as possible.
1745 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1746 const SCEV *Step, const Loop *L) {
1747 SmallVector<const SCEV *, 4> Operands;
1748 Operands.push_back(Start);
1749 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1750 if (StepChrec->getLoop() == L) {
1751 Operands.insert(Operands.end(), StepChrec->op_begin(),
1752 StepChrec->op_end());
1753 return getAddRecExpr(Operands, L);
1756 Operands.push_back(Step);
1757 return getAddRecExpr(Operands, L);
1760 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1761 /// Simplify the expression as much as possible.
1763 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1765 if (Operands.size() == 1) return Operands[0];
1767 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1768 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1769 getEffectiveSCEVType(Operands[0]->getType()) &&
1770 "SCEVAddRecExpr operand types don't match!");
1773 if (Operands.back()->isZero()) {
1774 Operands.pop_back();
1775 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1778 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1779 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1780 const Loop* NestedLoop = NestedAR->getLoop();
1781 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1782 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1783 NestedAR->op_end());
1784 Operands[0] = NestedAR->getStart();
1785 // AddRecs require their operands be loop-invariant with respect to their
1786 // loops. Don't perform this transformation if it would break this
1788 bool AllInvariant = true;
1789 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1790 if (!Operands[i]->isLoopInvariant(L)) {
1791 AllInvariant = false;
1795 NestedOperands[0] = getAddRecExpr(Operands, L);
1796 AllInvariant = true;
1797 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1798 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1799 AllInvariant = false;
1803 // Ok, both add recurrences are valid after the transformation.
1804 return getAddRecExpr(NestedOperands, NestedLoop);
1806 // Reset Operands to its original state.
1807 Operands[0] = NestedAR;
1811 FoldingSetNodeID ID;
1812 ID.AddInteger(scAddRecExpr);
1813 ID.AddInteger(Operands.size());
1814 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1815 ID.AddPointer(Operands[i]);
1818 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1819 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1820 new (S) SCEVAddRecExpr(ID, Operands, L);
1821 UniqueSCEVs.InsertNode(S, IP);
1825 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1827 SmallVector<const SCEV *, 2> Ops;
1830 return getSMaxExpr(Ops);
1834 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1835 assert(!Ops.empty() && "Cannot get empty smax!");
1836 if (Ops.size() == 1) return Ops[0];
1838 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1839 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1840 getEffectiveSCEVType(Ops[0]->getType()) &&
1841 "SCEVSMaxExpr operand types don't match!");
1844 // Sort by complexity, this groups all similar expression types together.
1845 GroupByComplexity(Ops, LI);
1847 // If there are any constants, fold them together.
1849 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1851 assert(Idx < Ops.size());
1852 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1853 // We found two constants, fold them together!
1854 ConstantInt *Fold = ConstantInt::get(
1855 APIntOps::smax(LHSC->getValue()->getValue(),
1856 RHSC->getValue()->getValue()));
1857 Ops[0] = getConstant(Fold);
1858 Ops.erase(Ops.begin()+1); // Erase the folded element
1859 if (Ops.size() == 1) return Ops[0];
1860 LHSC = cast<SCEVConstant>(Ops[0]);
1863 // If we are left with a constant minimum-int, strip it off.
1864 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1865 Ops.erase(Ops.begin());
1867 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1868 // If we have an smax with a constant maximum-int, it will always be
1874 if (Ops.size() == 1) return Ops[0];
1876 // Find the first SMax
1877 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1880 // Check to see if one of the operands is an SMax. If so, expand its operands
1881 // onto our operand list, and recurse to simplify.
1882 if (Idx < Ops.size()) {
1883 bool DeletedSMax = false;
1884 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1885 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1886 Ops.erase(Ops.begin()+Idx);
1891 return getSMaxExpr(Ops);
1894 // Okay, check to see if the same value occurs in the operand list twice. If
1895 // so, delete one. Since we sorted the list, these values are required to
1897 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1898 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1899 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1903 if (Ops.size() == 1) return Ops[0];
1905 assert(!Ops.empty() && "Reduced smax down to nothing!");
1907 // Okay, it looks like we really DO need an smax expr. Check to see if we
1908 // already have one, otherwise create a new one.
1909 FoldingSetNodeID ID;
1910 ID.AddInteger(scSMaxExpr);
1911 ID.AddInteger(Ops.size());
1912 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1913 ID.AddPointer(Ops[i]);
1915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1916 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1917 new (S) SCEVSMaxExpr(ID, Ops);
1918 UniqueSCEVs.InsertNode(S, IP);
1922 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1924 SmallVector<const SCEV *, 2> Ops;
1927 return getUMaxExpr(Ops);
1931 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1932 assert(!Ops.empty() && "Cannot get empty umax!");
1933 if (Ops.size() == 1) return Ops[0];
1935 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1936 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1937 getEffectiveSCEVType(Ops[0]->getType()) &&
1938 "SCEVUMaxExpr operand types don't match!");
1941 // Sort by complexity, this groups all similar expression types together.
1942 GroupByComplexity(Ops, LI);
1944 // If there are any constants, fold them together.
1946 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1948 assert(Idx < Ops.size());
1949 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1950 // We found two constants, fold them together!
1951 ConstantInt *Fold = ConstantInt::get(
1952 APIntOps::umax(LHSC->getValue()->getValue(),
1953 RHSC->getValue()->getValue()));
1954 Ops[0] = getConstant(Fold);
1955 Ops.erase(Ops.begin()+1); // Erase the folded element
1956 if (Ops.size() == 1) return Ops[0];
1957 LHSC = cast<SCEVConstant>(Ops[0]);
1960 // If we are left with a constant minimum-int, strip it off.
1961 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1962 Ops.erase(Ops.begin());
1964 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1965 // If we have an umax with a constant maximum-int, it will always be
1971 if (Ops.size() == 1) return Ops[0];
1973 // Find the first UMax
1974 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1977 // Check to see if one of the operands is a UMax. If so, expand its operands
1978 // onto our operand list, and recurse to simplify.
1979 if (Idx < Ops.size()) {
1980 bool DeletedUMax = false;
1981 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1982 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1983 Ops.erase(Ops.begin()+Idx);
1988 return getUMaxExpr(Ops);
1991 // Okay, check to see if the same value occurs in the operand list twice. If
1992 // so, delete one. Since we sorted the list, these values are required to
1994 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1995 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1996 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2000 if (Ops.size() == 1) return Ops[0];
2002 assert(!Ops.empty() && "Reduced umax down to nothing!");
2004 // Okay, it looks like we really DO need a umax expr. Check to see if we
2005 // already have one, otherwise create a new one.
2006 FoldingSetNodeID ID;
2007 ID.AddInteger(scUMaxExpr);
2008 ID.AddInteger(Ops.size());
2009 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2010 ID.AddPointer(Ops[i]);
2012 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2013 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2014 new (S) SCEVUMaxExpr(ID, Ops);
2015 UniqueSCEVs.InsertNode(S, IP);
2019 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2021 // ~smax(~x, ~y) == smin(x, y).
2022 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2025 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2027 // ~umax(~x, ~y) == umin(x, y)
2028 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2031 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2032 // Don't attempt to do anything other than create a SCEVUnknown object
2033 // here. createSCEV only calls getUnknown after checking for all other
2034 // interesting possibilities, and any other code that calls getUnknown
2035 // is doing so in order to hide a value from SCEV canonicalization.
2037 FoldingSetNodeID ID;
2038 ID.AddInteger(scUnknown);
2041 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2042 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2043 new (S) SCEVUnknown(ID, V);
2044 UniqueSCEVs.InsertNode(S, IP);
2048 //===----------------------------------------------------------------------===//
2049 // Basic SCEV Analysis and PHI Idiom Recognition Code
2052 /// isSCEVable - Test if values of the given type are analyzable within
2053 /// the SCEV framework. This primarily includes integer types, and it
2054 /// can optionally include pointer types if the ScalarEvolution class
2055 /// has access to target-specific information.
2056 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2057 // Integers are always SCEVable.
2058 if (Ty->isInteger())
2061 // Pointers are SCEVable if TargetData information is available
2062 // to provide pointer size information.
2063 if (isa<PointerType>(Ty))
2066 // Otherwise it's not SCEVable.
2070 /// getTypeSizeInBits - Return the size in bits of the specified type,
2071 /// for which isSCEVable must return true.
2072 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2073 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2075 // If we have a TargetData, use it!
2077 return TD->getTypeSizeInBits(Ty);
2079 // Otherwise, we support only integer types.
2080 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2081 return Ty->getPrimitiveSizeInBits();
2084 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2085 /// the given type and which represents how SCEV will treat the given
2086 /// type, for which isSCEVable must return true. For pointer types,
2087 /// this is the pointer-sized integer type.
2088 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2089 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2091 if (Ty->isInteger())
2094 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2095 return TD->getIntPtrType();
2098 const SCEV *ScalarEvolution::getCouldNotCompute() {
2099 return &CouldNotCompute;
2102 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2103 /// expression and create a new one.
2104 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2105 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2107 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2108 if (I != Scalars.end()) return I->second;
2109 const SCEV *S = createSCEV(V);
2110 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2114 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2115 /// specified signed integer value and return a SCEV for the constant.
2116 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2117 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2118 return getConstant(ConstantInt::get(ITy, Val));
2121 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2123 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2124 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2126 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
2128 const Type *Ty = V->getType();
2129 Ty = getEffectiveSCEVType(Ty);
2130 return getMulExpr(V,
2131 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty))));
2134 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2135 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2136 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2138 cast<ConstantInt>(Context->getConstantExprNot(VC->getValue())));
2140 const Type *Ty = V->getType();
2141 Ty = getEffectiveSCEVType(Ty);
2142 const SCEV *AllOnes =
2143 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty)));
2144 return getMinusSCEV(AllOnes, V);
2147 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2149 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2152 return getAddExpr(LHS, getNegativeSCEV(RHS));
2155 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2156 /// input value to the specified type. If the type must be extended, it is zero
2159 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2161 const Type *SrcTy = V->getType();
2162 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2163 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2164 "Cannot truncate or zero extend with non-integer arguments!");
2165 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2166 return V; // No conversion
2167 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2168 return getTruncateExpr(V, Ty);
2169 return getZeroExtendExpr(V, Ty);
2172 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2173 /// input value to the specified type. If the type must be extended, it is sign
2176 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2178 const Type *SrcTy = V->getType();
2179 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2180 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2181 "Cannot truncate or zero extend with non-integer arguments!");
2182 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2183 return V; // No conversion
2184 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2185 return getTruncateExpr(V, Ty);
2186 return getSignExtendExpr(V, Ty);
2189 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2190 /// input value to the specified type. If the type must be extended, it is zero
2191 /// extended. The conversion must not be narrowing.
2193 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2194 const Type *SrcTy = V->getType();
2195 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2196 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2197 "Cannot noop or zero extend with non-integer arguments!");
2198 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2199 "getNoopOrZeroExtend cannot truncate!");
2200 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2201 return V; // No conversion
2202 return getZeroExtendExpr(V, Ty);
2205 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2206 /// input value to the specified type. If the type must be extended, it is sign
2207 /// extended. The conversion must not be narrowing.
2209 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2210 const Type *SrcTy = V->getType();
2211 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2212 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2213 "Cannot noop or sign extend with non-integer arguments!");
2214 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2215 "getNoopOrSignExtend cannot truncate!");
2216 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2217 return V; // No conversion
2218 return getSignExtendExpr(V, Ty);
2221 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2222 /// the input value to the specified type. If the type must be extended,
2223 /// it is extended with unspecified bits. The conversion must not be
2226 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2227 const Type *SrcTy = V->getType();
2228 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2229 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2230 "Cannot noop or any extend with non-integer arguments!");
2231 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2232 "getNoopOrAnyExtend cannot truncate!");
2233 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2234 return V; // No conversion
2235 return getAnyExtendExpr(V, Ty);
2238 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2239 /// input value to the specified type. The conversion must not be widening.
2241 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2242 const Type *SrcTy = V->getType();
2243 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2244 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2245 "Cannot truncate or noop with non-integer arguments!");
2246 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2247 "getTruncateOrNoop cannot extend!");
2248 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2249 return V; // No conversion
2250 return getTruncateExpr(V, Ty);
2253 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2254 /// the types using zero-extension, and then perform a umax operation
2256 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2258 const SCEV *PromotedLHS = LHS;
2259 const SCEV *PromotedRHS = RHS;
2261 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2262 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2264 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2266 return getUMaxExpr(PromotedLHS, PromotedRHS);
2269 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2270 /// the types using zero-extension, and then perform a umin operation
2272 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2274 const SCEV *PromotedLHS = LHS;
2275 const SCEV *PromotedRHS = RHS;
2277 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2278 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2280 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2282 return getUMinExpr(PromotedLHS, PromotedRHS);
2285 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2286 /// the specified instruction and replaces any references to the symbolic value
2287 /// SymName with the specified value. This is used during PHI resolution.
2289 ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2290 const SCEV *SymName,
2291 const SCEV *NewVal) {
2292 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
2293 Scalars.find(SCEVCallbackVH(I, this));
2294 if (SI == Scalars.end()) return;
2297 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2298 if (NV == SI->second) return; // No change.
2300 SI->second = NV; // Update the scalars map!
2302 // Any instruction values that use this instruction might also need to be
2304 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2306 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2309 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2310 /// a loop header, making it a potential recurrence, or it doesn't.
2312 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2313 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2314 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2315 if (L->getHeader() == PN->getParent()) {
2316 // If it lives in the loop header, it has two incoming values, one
2317 // from outside the loop, and one from inside.
2318 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2319 unsigned BackEdge = IncomingEdge^1;
2321 // While we are analyzing this PHI node, handle its value symbolically.
2322 const SCEV *SymbolicName = getUnknown(PN);
2323 assert(Scalars.find(PN) == Scalars.end() &&
2324 "PHI node already processed?");
2325 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2327 // Using this symbolic name for the PHI, analyze the value coming around
2329 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2331 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2332 // has a special value for the first iteration of the loop.
2334 // If the value coming around the backedge is an add with the symbolic
2335 // value we just inserted, then we found a simple induction variable!
2336 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2337 // If there is a single occurrence of the symbolic value, replace it
2338 // with a recurrence.
2339 unsigned FoundIndex = Add->getNumOperands();
2340 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2341 if (Add->getOperand(i) == SymbolicName)
2342 if (FoundIndex == e) {
2347 if (FoundIndex != Add->getNumOperands()) {
2348 // Create an add with everything but the specified operand.
2349 SmallVector<const SCEV *, 8> Ops;
2350 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2351 if (i != FoundIndex)
2352 Ops.push_back(Add->getOperand(i));
2353 const SCEV *Accum = getAddExpr(Ops);
2355 // This is not a valid addrec if the step amount is varying each
2356 // loop iteration, but is not itself an addrec in this loop.
2357 if (Accum->isLoopInvariant(L) ||
2358 (isa<SCEVAddRecExpr>(Accum) &&
2359 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2360 const SCEV *StartVal =
2361 getSCEV(PN->getIncomingValue(IncomingEdge));
2362 const SCEV *PHISCEV =
2363 getAddRecExpr(StartVal, Accum, L);
2365 // Okay, for the entire analysis of this edge we assumed the PHI
2366 // to be symbolic. We now need to go back and update all of the
2367 // entries for the scalars that use the PHI (except for the PHI
2368 // itself) to use the new analyzed value instead of the "symbolic"
2370 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2374 } else if (const SCEVAddRecExpr *AddRec =
2375 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2376 // Otherwise, this could be a loop like this:
2377 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2378 // In this case, j = {1,+,1} and BEValue is j.
2379 // Because the other in-value of i (0) fits the evolution of BEValue
2380 // i really is an addrec evolution.
2381 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2382 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2384 // If StartVal = j.start - j.stride, we can use StartVal as the
2385 // initial step of the addrec evolution.
2386 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2387 AddRec->getOperand(1))) {
2388 const SCEV *PHISCEV =
2389 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2391 // Okay, for the entire analysis of this edge we assumed the PHI
2392 // to be symbolic. We now need to go back and update all of the
2393 // entries for the scalars that use the PHI (except for the PHI
2394 // itself) to use the new analyzed value instead of the "symbolic"
2396 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2402 return SymbolicName;
2405 // It's tempting to recognize PHIs with a unique incoming value, however
2406 // this leads passes like indvars to break LCSSA form. Fortunately, such
2407 // PHIs are rare, as instcombine zaps them.
2409 // If it's not a loop phi, we can't handle it yet.
2410 return getUnknown(PN);
2413 /// createNodeForGEP - Expand GEP instructions into add and multiply
2414 /// operations. This allows them to be analyzed by regular SCEV code.
2416 const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
2418 const Type *IntPtrTy = TD->getIntPtrType();
2419 Value *Base = GEP->getOperand(0);
2420 // Don't attempt to analyze GEPs over unsized objects.
2421 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2422 return getUnknown(GEP);
2423 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2424 gep_type_iterator GTI = gep_type_begin(GEP);
2425 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2429 // Compute the (potentially symbolic) offset in bytes for this index.
2430 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2431 // For a struct, add the member offset.
2432 const StructLayout &SL = *TD->getStructLayout(STy);
2433 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2434 uint64_t Offset = SL.getElementOffset(FieldNo);
2435 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
2437 // For an array, add the element offset, explicitly scaled.
2438 const SCEV *LocalOffset = getSCEV(Index);
2439 if (!isa<PointerType>(LocalOffset->getType()))
2440 // Getelementptr indicies are signed.
2441 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2443 getMulExpr(LocalOffset,
2444 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
2445 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2448 return getAddExpr(getSCEV(Base), TotalOffset);
2451 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2452 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2453 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2454 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2456 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2457 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2458 return C->getValue()->getValue().countTrailingZeros();
2460 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2461 return std::min(GetMinTrailingZeros(T->getOperand()),
2462 (uint32_t)getTypeSizeInBits(T->getType()));
2464 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2465 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2466 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2467 getTypeSizeInBits(E->getType()) : OpRes;
2470 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2471 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2472 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2473 getTypeSizeInBits(E->getType()) : OpRes;
2476 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2477 // The result is the min of all operands results.
2478 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2479 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2480 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2484 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2485 // The result is the sum of all operands results.
2486 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2487 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2488 for (unsigned i = 1, e = M->getNumOperands();
2489 SumOpRes != BitWidth && i != e; ++i)
2490 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2495 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2496 // The result is the min of all operands results.
2497 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2498 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2503 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2504 // The result is the min of all operands results.
2505 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2506 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2507 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2511 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2512 // The result is the min of all operands results.
2513 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2514 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2515 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2519 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2520 // For a SCEVUnknown, ask ValueTracking.
2521 unsigned BitWidth = getTypeSizeInBits(U->getType());
2522 APInt Mask = APInt::getAllOnesValue(BitWidth);
2523 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2524 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2525 return Zeros.countTrailingOnes();
2532 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2535 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2537 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2538 return ConstantRange(C->getValue()->getValue());
2540 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2541 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2542 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2543 X = X.add(getUnsignedRange(Add->getOperand(i)));
2547 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2548 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2549 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2550 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2554 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2555 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2556 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2557 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2561 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2562 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2563 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2564 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2568 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2569 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2570 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2574 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2575 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2576 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2579 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2580 ConstantRange X = getUnsignedRange(SExt->getOperand());
2581 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2584 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2585 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2586 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2589 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2591 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2592 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2593 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2594 if (!Trip) return FullSet;
2596 // TODO: non-affine addrec
2597 if (AddRec->isAffine()) {
2598 const Type *Ty = AddRec->getType();
2599 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2600 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2601 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2603 const SCEV *Start = AddRec->getStart();
2604 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2606 // Check for overflow.
2607 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2610 ConstantRange StartRange = getUnsignedRange(Start);
2611 ConstantRange EndRange = getUnsignedRange(End);
2612 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2613 EndRange.getUnsignedMin());
2614 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2615 EndRange.getUnsignedMax());
2616 if (Min.isMinValue() && Max.isMaxValue())
2617 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2618 return ConstantRange(Min, Max+1);
2623 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2624 // For a SCEVUnknown, ask ValueTracking.
2625 unsigned BitWidth = getTypeSizeInBits(U->getType());
2626 APInt Mask = APInt::getAllOnesValue(BitWidth);
2627 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2628 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2629 return ConstantRange(Ones, ~Zeros);
2635 /// getSignedRange - Determine the signed range for a particular SCEV.
2638 ScalarEvolution::getSignedRange(const SCEV *S) {
2640 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2641 return ConstantRange(C->getValue()->getValue());
2643 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2644 ConstantRange X = getSignedRange(Add->getOperand(0));
2645 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2646 X = X.add(getSignedRange(Add->getOperand(i)));
2650 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2651 ConstantRange X = getSignedRange(Mul->getOperand(0));
2652 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2653 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2657 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2658 ConstantRange X = getSignedRange(SMax->getOperand(0));
2659 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2660 X = X.smax(getSignedRange(SMax->getOperand(i)));
2664 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2665 ConstantRange X = getSignedRange(UMax->getOperand(0));
2666 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2667 X = X.umax(getSignedRange(UMax->getOperand(i)));
2671 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2672 ConstantRange X = getSignedRange(UDiv->getLHS());
2673 ConstantRange Y = getSignedRange(UDiv->getRHS());
2677 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2678 ConstantRange X = getSignedRange(ZExt->getOperand());
2679 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2682 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2683 ConstantRange X = getSignedRange(SExt->getOperand());
2684 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2687 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2688 ConstantRange X = getSignedRange(Trunc->getOperand());
2689 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2692 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2694 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2695 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2696 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2697 if (!Trip) return FullSet;
2699 // TODO: non-affine addrec
2700 if (AddRec->isAffine()) {
2701 const Type *Ty = AddRec->getType();
2702 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2703 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2704 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2706 const SCEV *Start = AddRec->getStart();
2707 const SCEV *Step = AddRec->getStepRecurrence(*this);
2708 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2710 // Check for overflow.
2711 if (!(isKnownPositive(Step) &&
2712 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2713 !(isKnownNegative(Step) &&
2714 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2717 ConstantRange StartRange = getSignedRange(Start);
2718 ConstantRange EndRange = getSignedRange(End);
2719 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2720 EndRange.getSignedMin());
2721 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2722 EndRange.getSignedMax());
2723 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2724 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2725 return ConstantRange(Min, Max+1);
2730 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2731 // For a SCEVUnknown, ask ValueTracking.
2732 unsigned BitWidth = getTypeSizeInBits(U->getType());
2733 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2737 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2738 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
2744 /// createSCEV - We know that there is no SCEV for the specified value.
2745 /// Analyze the expression.
2747 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2748 if (!isSCEVable(V->getType()))
2749 return getUnknown(V);
2751 unsigned Opcode = Instruction::UserOp1;
2752 if (Instruction *I = dyn_cast<Instruction>(V))
2753 Opcode = I->getOpcode();
2754 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2755 Opcode = CE->getOpcode();
2756 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2757 return getConstant(CI);
2758 else if (isa<ConstantPointerNull>(V))
2759 return getIntegerSCEV(0, V->getType());
2760 else if (isa<UndefValue>(V))
2761 return getIntegerSCEV(0, V->getType());
2763 return getUnknown(V);
2765 User *U = cast<User>(V);
2767 case Instruction::Add:
2768 return getAddExpr(getSCEV(U->getOperand(0)),
2769 getSCEV(U->getOperand(1)));
2770 case Instruction::Mul:
2771 return getMulExpr(getSCEV(U->getOperand(0)),
2772 getSCEV(U->getOperand(1)));
2773 case Instruction::UDiv:
2774 return getUDivExpr(getSCEV(U->getOperand(0)),
2775 getSCEV(U->getOperand(1)));
2776 case Instruction::Sub:
2777 return getMinusSCEV(getSCEV(U->getOperand(0)),
2778 getSCEV(U->getOperand(1)));
2779 case Instruction::And:
2780 // For an expression like x&255 that merely masks off the high bits,
2781 // use zext(trunc(x)) as the SCEV expression.
2782 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2783 if (CI->isNullValue())
2784 return getSCEV(U->getOperand(1));
2785 if (CI->isAllOnesValue())
2786 return getSCEV(U->getOperand(0));
2787 const APInt &A = CI->getValue();
2789 // Instcombine's ShrinkDemandedConstant may strip bits out of
2790 // constants, obscuring what would otherwise be a low-bits mask.
2791 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2792 // knew about to reconstruct a low-bits mask value.
2793 unsigned LZ = A.countLeadingZeros();
2794 unsigned BitWidth = A.getBitWidth();
2795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2796 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2797 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2799 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2801 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2803 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2804 IntegerType::get(BitWidth - LZ)),
2809 case Instruction::Or:
2810 // If the RHS of the Or is a constant, we may have something like:
2811 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2812 // optimizations will transparently handle this case.
2814 // In order for this transformation to be safe, the LHS must be of the
2815 // form X*(2^n) and the Or constant must be less than 2^n.
2816 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2817 const SCEV *LHS = getSCEV(U->getOperand(0));
2818 const APInt &CIVal = CI->getValue();
2819 if (GetMinTrailingZeros(LHS) >=
2820 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2821 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2824 case Instruction::Xor:
2825 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2826 // If the RHS of the xor is a signbit, then this is just an add.
2827 // Instcombine turns add of signbit into xor as a strength reduction step.
2828 if (CI->getValue().isSignBit())
2829 return getAddExpr(getSCEV(U->getOperand(0)),
2830 getSCEV(U->getOperand(1)));
2832 // If the RHS of xor is -1, then this is a not operation.
2833 if (CI->isAllOnesValue())
2834 return getNotSCEV(getSCEV(U->getOperand(0)));
2836 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2837 // This is a variant of the check for xor with -1, and it handles
2838 // the case where instcombine has trimmed non-demanded bits out
2839 // of an xor with -1.
2840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2841 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2842 if (BO->getOpcode() == Instruction::And &&
2843 LCI->getValue() == CI->getValue())
2844 if (const SCEVZeroExtendExpr *Z =
2845 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2846 const Type *UTy = U->getType();
2847 const SCEV *Z0 = Z->getOperand();
2848 const Type *Z0Ty = Z0->getType();
2849 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2851 // If C is a low-bits mask, the zero extend is zerving to
2852 // mask off the high bits. Complement the operand and
2853 // re-apply the zext.
2854 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2855 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2857 // If C is a single bit, it may be in the sign-bit position
2858 // before the zero-extend. In this case, represent the xor
2859 // using an add, which is equivalent, and re-apply the zext.
2860 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2861 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2863 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2869 case Instruction::Shl:
2870 // Turn shift left of a constant amount into a multiply.
2871 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2872 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2873 Constant *X = ConstantInt::get(
2874 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2875 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2879 case Instruction::LShr:
2880 // Turn logical shift right of a constant into a unsigned divide.
2881 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2882 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2883 Constant *X = ConstantInt::get(
2884 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2885 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2889 case Instruction::AShr:
2890 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2891 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2892 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2893 if (L->getOpcode() == Instruction::Shl &&
2894 L->getOperand(1) == U->getOperand(1)) {
2895 unsigned BitWidth = getTypeSizeInBits(U->getType());
2896 uint64_t Amt = BitWidth - CI->getZExtValue();
2897 if (Amt == BitWidth)
2898 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2900 return getIntegerSCEV(0, U->getType()); // value is undefined
2902 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2903 IntegerType::get(Amt)),
2908 case Instruction::Trunc:
2909 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2911 case Instruction::ZExt:
2912 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2914 case Instruction::SExt:
2915 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2917 case Instruction::BitCast:
2918 // BitCasts are no-op casts so we just eliminate the cast.
2919 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2920 return getSCEV(U->getOperand(0));
2923 case Instruction::IntToPtr:
2924 if (!TD) break; // Without TD we can't analyze pointers.
2925 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2926 TD->getIntPtrType());
2928 case Instruction::PtrToInt:
2929 if (!TD) break; // Without TD we can't analyze pointers.
2930 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2933 case Instruction::GetElementPtr:
2934 if (!TD) break; // Without TD we can't analyze pointers.
2935 return createNodeForGEP(U);
2937 case Instruction::PHI:
2938 return createNodeForPHI(cast<PHINode>(U));
2940 case Instruction::Select:
2941 // This could be a smax or umax that was lowered earlier.
2942 // Try to recover it.
2943 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2944 Value *LHS = ICI->getOperand(0);
2945 Value *RHS = ICI->getOperand(1);
2946 switch (ICI->getPredicate()) {
2947 case ICmpInst::ICMP_SLT:
2948 case ICmpInst::ICMP_SLE:
2949 std::swap(LHS, RHS);
2951 case ICmpInst::ICMP_SGT:
2952 case ICmpInst::ICMP_SGE:
2953 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2954 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2955 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2956 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
2958 case ICmpInst::ICMP_ULT:
2959 case ICmpInst::ICMP_ULE:
2960 std::swap(LHS, RHS);
2962 case ICmpInst::ICMP_UGT:
2963 case ICmpInst::ICMP_UGE:
2964 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2965 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2966 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2967 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
2969 case ICmpInst::ICMP_NE:
2970 // n != 0 ? n : 1 -> umax(n, 1)
2971 if (LHS == U->getOperand(1) &&
2972 isa<ConstantInt>(U->getOperand(2)) &&
2973 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2974 isa<ConstantInt>(RHS) &&
2975 cast<ConstantInt>(RHS)->isZero())
2976 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2978 case ICmpInst::ICMP_EQ:
2979 // n == 0 ? 1 : n -> umax(n, 1)
2980 if (LHS == U->getOperand(2) &&
2981 isa<ConstantInt>(U->getOperand(1)) &&
2982 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2983 isa<ConstantInt>(RHS) &&
2984 cast<ConstantInt>(RHS)->isZero())
2985 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2992 default: // We cannot analyze this expression.
2996 return getUnknown(V);
3001 //===----------------------------------------------------------------------===//
3002 // Iteration Count Computation Code
3005 /// getBackedgeTakenCount - If the specified loop has a predictable
3006 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3007 /// object. The backedge-taken count is the number of times the loop header
3008 /// will be branched to from within the loop. This is one less than the
3009 /// trip count of the loop, since it doesn't count the first iteration,
3010 /// when the header is branched to from outside the loop.
3012 /// Note that it is not valid to call this method on a loop without a
3013 /// loop-invariant backedge-taken count (see
3014 /// hasLoopInvariantBackedgeTakenCount).
3016 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3017 return getBackedgeTakenInfo(L).Exact;
3020 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3021 /// return the least SCEV value that is known never to be less than the
3022 /// actual backedge taken count.
3023 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3024 return getBackedgeTakenInfo(L).Max;
3027 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3028 /// onto the given Worklist.
3030 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3031 BasicBlock *Header = L->getHeader();
3033 // Push all Loop-header PHIs onto the Worklist stack.
3034 for (BasicBlock::iterator I = Header->begin();
3035 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3036 Worklist.push_back(PN);
3039 /// PushDefUseChildren - Push users of the given Instruction
3040 /// onto the given Worklist.
3042 PushDefUseChildren(Instruction *I,
3043 SmallVectorImpl<Instruction *> &Worklist) {
3044 // Push the def-use children onto the Worklist stack.
3045 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3047 Worklist.push_back(cast<Instruction>(UI));
3050 const ScalarEvolution::BackedgeTakenInfo &
3051 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3052 // Initially insert a CouldNotCompute for this loop. If the insertion
3053 // succeeds, procede to actually compute a backedge-taken count and
3054 // update the value. The temporary CouldNotCompute value tells SCEV
3055 // code elsewhere that it shouldn't attempt to request a new
3056 // backedge-taken count, which could result in infinite recursion.
3057 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
3058 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3060 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
3061 if (ItCount.Exact != getCouldNotCompute()) {
3062 assert(ItCount.Exact->isLoopInvariant(L) &&
3063 ItCount.Max->isLoopInvariant(L) &&
3064 "Computed trip count isn't loop invariant for loop!");
3065 ++NumTripCountsComputed;
3067 // Update the value in the map.
3068 Pair.first->second = ItCount;
3070 if (ItCount.Max != getCouldNotCompute())
3071 // Update the value in the map.
3072 Pair.first->second = ItCount;
3073 if (isa<PHINode>(L->getHeader()->begin()))
3074 // Only count loops that have phi nodes as not being computable.
3075 ++NumTripCountsNotComputed;
3078 // Now that we know more about the trip count for this loop, forget any
3079 // existing SCEV values for PHI nodes in this loop since they are only
3080 // conservative estimates made without the benefit of trip count
3081 // information. This is similar to the code in
3082 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3084 if (ItCount.hasAnyInfo()) {
3085 SmallVector<Instruction *, 16> Worklist;
3086 PushLoopPHIs(L, Worklist);
3088 SmallPtrSet<Instruction *, 8> Visited;
3089 while (!Worklist.empty()) {
3090 Instruction *I = Worklist.pop_back_val();
3091 if (!Visited.insert(I)) continue;
3093 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3094 Scalars.find(static_cast<Value *>(I));
3095 if (It != Scalars.end()) {
3096 // SCEVUnknown for a PHI either means that it has an unrecognized
3097 // structure, or it's a PHI that's in the progress of being computed
3098 // by createNodeForPHI. In the former case, additional loop trip
3099 // count information isn't going to change anything. In the later
3100 // case, createNodeForPHI will perform the necessary updates on its
3101 // own when it gets to that point.
3102 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3104 ValuesAtScopes.erase(I);
3105 if (PHINode *PN = dyn_cast<PHINode>(I))
3106 ConstantEvolutionLoopExitValue.erase(PN);
3109 PushDefUseChildren(I, Worklist);
3113 return Pair.first->second;
3116 /// forgetLoopBackedgeTakenCount - This method should be called by the
3117 /// client when it has changed a loop in a way that may effect
3118 /// ScalarEvolution's ability to compute a trip count, or if the loop
3120 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3121 BackedgeTakenCounts.erase(L);
3123 SmallVector<Instruction *, 16> Worklist;
3124 PushLoopPHIs(L, Worklist);
3126 SmallPtrSet<Instruction *, 8> Visited;
3127 while (!Worklist.empty()) {
3128 Instruction *I = Worklist.pop_back_val();
3129 if (!Visited.insert(I)) continue;
3131 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3132 Scalars.find(static_cast<Value *>(I));
3133 if (It != Scalars.end()) {
3135 ValuesAtScopes.erase(I);
3136 if (PHINode *PN = dyn_cast<PHINode>(I))
3137 ConstantEvolutionLoopExitValue.erase(PN);
3140 PushDefUseChildren(I, Worklist);
3144 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3145 /// of the specified loop will execute.
3146 ScalarEvolution::BackedgeTakenInfo
3147 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3148 SmallVector<BasicBlock*, 8> ExitingBlocks;
3149 L->getExitingBlocks(ExitingBlocks);
3151 // Examine all exits and pick the most conservative values.
3152 const SCEV *BECount = getCouldNotCompute();
3153 const SCEV *MaxBECount = getCouldNotCompute();
3154 bool CouldNotComputeBECount = false;
3155 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3156 BackedgeTakenInfo NewBTI =
3157 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3159 if (NewBTI.Exact == getCouldNotCompute()) {
3160 // We couldn't compute an exact value for this exit, so
3161 // we won't be able to compute an exact value for the loop.
3162 CouldNotComputeBECount = true;
3163 BECount = getCouldNotCompute();
3164 } else if (!CouldNotComputeBECount) {
3165 if (BECount == getCouldNotCompute())
3166 BECount = NewBTI.Exact;
3168 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3170 if (MaxBECount == getCouldNotCompute())
3171 MaxBECount = NewBTI.Max;
3172 else if (NewBTI.Max != getCouldNotCompute())
3173 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3176 return BackedgeTakenInfo(BECount, MaxBECount);
3179 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3180 /// of the specified loop will execute if it exits via the specified block.
3181 ScalarEvolution::BackedgeTakenInfo
3182 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3183 BasicBlock *ExitingBlock) {
3185 // Okay, we've chosen an exiting block. See what condition causes us to
3186 // exit at this block.
3188 // FIXME: we should be able to handle switch instructions (with a single exit)
3189 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3190 if (ExitBr == 0) return getCouldNotCompute();
3191 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3193 // At this point, we know we have a conditional branch that determines whether
3194 // the loop is exited. However, we don't know if the branch is executed each
3195 // time through the loop. If not, then the execution count of the branch will
3196 // not be equal to the trip count of the loop.
3198 // Currently we check for this by checking to see if the Exit branch goes to
3199 // the loop header. If so, we know it will always execute the same number of
3200 // times as the loop. We also handle the case where the exit block *is* the
3201 // loop header. This is common for un-rotated loops.
3203 // If both of those tests fail, walk up the unique predecessor chain to the
3204 // header, stopping if there is an edge that doesn't exit the loop. If the
3205 // header is reached, the execution count of the branch will be equal to the
3206 // trip count of the loop.
3208 // More extensive analysis could be done to handle more cases here.
3210 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3211 ExitBr->getSuccessor(1) != L->getHeader() &&
3212 ExitBr->getParent() != L->getHeader()) {
3213 // The simple checks failed, try climbing the unique predecessor chain
3214 // up to the header.
3216 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3217 BasicBlock *Pred = BB->getUniquePredecessor();
3219 return getCouldNotCompute();
3220 TerminatorInst *PredTerm = Pred->getTerminator();
3221 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3222 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3225 // If the predecessor has a successor that isn't BB and isn't
3226 // outside the loop, assume the worst.
3227 if (L->contains(PredSucc))
3228 return getCouldNotCompute();
3230 if (Pred == L->getHeader()) {
3237 return getCouldNotCompute();
3240 // Procede to the next level to examine the exit condition expression.
3241 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3242 ExitBr->getSuccessor(0),
3243 ExitBr->getSuccessor(1));
3246 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3247 /// backedge of the specified loop will execute if its exit condition
3248 /// were a conditional branch of ExitCond, TBB, and FBB.
3249 ScalarEvolution::BackedgeTakenInfo
3250 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3254 // Check if the controlling expression for this loop is an And or Or.
3255 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3256 if (BO->getOpcode() == Instruction::And) {
3257 // Recurse on the operands of the and.
3258 BackedgeTakenInfo BTI0 =
3259 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3260 BackedgeTakenInfo BTI1 =
3261 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3262 const SCEV *BECount = getCouldNotCompute();
3263 const SCEV *MaxBECount = getCouldNotCompute();
3264 if (L->contains(TBB)) {
3265 // Both conditions must be true for the loop to continue executing.
3266 // Choose the less conservative count.
3267 if (BTI0.Exact == getCouldNotCompute() ||
3268 BTI1.Exact == getCouldNotCompute())
3269 BECount = getCouldNotCompute();
3271 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3272 if (BTI0.Max == getCouldNotCompute())
3273 MaxBECount = BTI1.Max;
3274 else if (BTI1.Max == getCouldNotCompute())
3275 MaxBECount = BTI0.Max;
3277 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3279 // Both conditions must be true for the loop to exit.
3280 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3281 if (BTI0.Exact != getCouldNotCompute() &&
3282 BTI1.Exact != getCouldNotCompute())
3283 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3284 if (BTI0.Max != getCouldNotCompute() &&
3285 BTI1.Max != getCouldNotCompute())
3286 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3289 return BackedgeTakenInfo(BECount, MaxBECount);
3291 if (BO->getOpcode() == Instruction::Or) {
3292 // Recurse on the operands of the or.
3293 BackedgeTakenInfo BTI0 =
3294 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3295 BackedgeTakenInfo BTI1 =
3296 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3297 const SCEV *BECount = getCouldNotCompute();
3298 const SCEV *MaxBECount = getCouldNotCompute();
3299 if (L->contains(FBB)) {
3300 // Both conditions must be false for the loop to continue executing.
3301 // Choose the less conservative count.
3302 if (BTI0.Exact == getCouldNotCompute() ||
3303 BTI1.Exact == getCouldNotCompute())
3304 BECount = getCouldNotCompute();
3306 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3307 if (BTI0.Max == getCouldNotCompute())
3308 MaxBECount = BTI1.Max;
3309 else if (BTI1.Max == getCouldNotCompute())
3310 MaxBECount = BTI0.Max;
3312 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3314 // Both conditions must be false for the loop to exit.
3315 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3316 if (BTI0.Exact != getCouldNotCompute() &&
3317 BTI1.Exact != getCouldNotCompute())
3318 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3319 if (BTI0.Max != getCouldNotCompute() &&
3320 BTI1.Max != getCouldNotCompute())
3321 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3324 return BackedgeTakenInfo(BECount, MaxBECount);
3328 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3329 // Procede to the next level to examine the icmp.
3330 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3331 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3333 // If it's not an integer or pointer comparison then compute it the hard way.
3334 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3337 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3338 /// backedge of the specified loop will execute if its exit condition
3339 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3340 ScalarEvolution::BackedgeTakenInfo
3341 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3346 // If the condition was exit on true, convert the condition to exit on false
3347 ICmpInst::Predicate Cond;
3348 if (!L->contains(FBB))
3349 Cond = ExitCond->getPredicate();
3351 Cond = ExitCond->getInversePredicate();
3353 // Handle common loops like: for (X = "string"; *X; ++X)
3354 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3355 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3357 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3358 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3359 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3360 return BackedgeTakenInfo(ItCnt,
3361 isa<SCEVConstant>(ItCnt) ? ItCnt :
3362 getConstant(APInt::getMaxValue(BitWidth)-1));
3366 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3367 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3369 // Try to evaluate any dependencies out of the loop.
3370 LHS = getSCEVAtScope(LHS, L);
3371 RHS = getSCEVAtScope(RHS, L);
3373 // At this point, we would like to compute how many iterations of the
3374 // loop the predicate will return true for these inputs.
3375 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3376 // If there is a loop-invariant, force it into the RHS.
3377 std::swap(LHS, RHS);
3378 Cond = ICmpInst::getSwappedPredicate(Cond);
3381 // If we have a comparison of a chrec against a constant, try to use value
3382 // ranges to answer this query.
3383 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3384 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3385 if (AddRec->getLoop() == L) {
3386 // Form the constant range.
3387 ConstantRange CompRange(
3388 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3390 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3391 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3395 case ICmpInst::ICMP_NE: { // while (X != Y)
3396 // Convert to: while (X-Y != 0)
3397 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3398 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3401 case ICmpInst::ICMP_EQ: {
3402 // Convert to: while (X-Y == 0) // while (X == Y)
3403 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3404 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3407 case ICmpInst::ICMP_SLT: {
3408 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3409 if (BTI.hasAnyInfo()) return BTI;
3412 case ICmpInst::ICMP_SGT: {
3413 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3414 getNotSCEV(RHS), L, true);
3415 if (BTI.hasAnyInfo()) return BTI;
3418 case ICmpInst::ICMP_ULT: {
3419 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3420 if (BTI.hasAnyInfo()) return BTI;
3423 case ICmpInst::ICMP_UGT: {
3424 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3425 getNotSCEV(RHS), L, false);
3426 if (BTI.hasAnyInfo()) return BTI;
3431 errs() << "ComputeBackedgeTakenCount ";
3432 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3433 errs() << "[unsigned] ";
3434 errs() << *LHS << " "
3435 << Instruction::getOpcodeName(Instruction::ICmp)
3436 << " " << *RHS << "\n";
3441 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3444 static ConstantInt *
3445 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3446 ScalarEvolution &SE) {
3447 const SCEV *InVal = SE.getConstant(C);
3448 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3449 assert(isa<SCEVConstant>(Val) &&
3450 "Evaluation of SCEV at constant didn't fold correctly?");
3451 return cast<SCEVConstant>(Val)->getValue();
3454 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3455 /// and a GEP expression (missing the pointer index) indexing into it, return
3456 /// the addressed element of the initializer or null if the index expression is
3459 GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
3460 const std::vector<ConstantInt*> &Indices) {
3461 Constant *Init = GV->getInitializer();
3462 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3463 uint64_t Idx = Indices[i]->getZExtValue();
3464 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3465 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3466 Init = cast<Constant>(CS->getOperand(Idx));
3467 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3468 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3469 Init = cast<Constant>(CA->getOperand(Idx));
3470 } else if (isa<ConstantAggregateZero>(Init)) {
3471 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3472 assert(Idx < STy->getNumElements() && "Bad struct index!");
3473 Init = Context->getNullValue(STy->getElementType(Idx));
3474 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3475 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3476 Init = Context->getNullValue(ATy->getElementType());
3478 llvm_unreachable("Unknown constant aggregate type!");
3482 return 0; // Unknown initializer type
3488 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3489 /// 'icmp op load X, cst', try to see if we can compute the backedge
3490 /// execution count.
3492 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3496 ICmpInst::Predicate predicate) {
3497 if (LI->isVolatile()) return getCouldNotCompute();
3499 // Check to see if the loaded pointer is a getelementptr of a global.
3500 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3501 if (!GEP) return getCouldNotCompute();
3503 // Make sure that it is really a constant global we are gepping, with an
3504 // initializer, and make sure the first IDX is really 0.
3505 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3506 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3507 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3508 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3509 return getCouldNotCompute();
3511 // Okay, we allow one non-constant index into the GEP instruction.
3513 std::vector<ConstantInt*> Indexes;
3514 unsigned VarIdxNum = 0;
3515 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3516 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3517 Indexes.push_back(CI);
3518 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3519 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3520 VarIdx = GEP->getOperand(i);
3522 Indexes.push_back(0);
3525 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3526 // Check to see if X is a loop variant variable value now.
3527 const SCEV *Idx = getSCEV(VarIdx);
3528 Idx = getSCEVAtScope(Idx, L);
3530 // We can only recognize very limited forms of loop index expressions, in
3531 // particular, only affine AddRec's like {C1,+,C2}.
3532 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3533 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3534 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3535 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3536 return getCouldNotCompute();
3538 unsigned MaxSteps = MaxBruteForceIterations;
3539 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3540 ConstantInt *ItCst =
3541 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
3542 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3544 // Form the GEP offset.
3545 Indexes[VarIdxNum] = Val;
3547 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
3548 if (Result == 0) break; // Cannot compute!
3550 // Evaluate the condition for this iteration.
3551 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3552 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3553 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3555 errs() << "\n***\n*** Computed loop count " << *ItCst
3556 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3559 ++NumArrayLenItCounts;
3560 return getConstant(ItCst); // Found terminating iteration!
3563 return getCouldNotCompute();
3567 /// CanConstantFold - Return true if we can constant fold an instruction of the
3568 /// specified type, assuming that all operands were constants.
3569 static bool CanConstantFold(const Instruction *I) {
3570 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3571 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3574 if (const CallInst *CI = dyn_cast<CallInst>(I))
3575 if (const Function *F = CI->getCalledFunction())
3576 return canConstantFoldCallTo(F);
3580 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3581 /// in the loop that V is derived from. We allow arbitrary operations along the
3582 /// way, but the operands of an operation must either be constants or a value
3583 /// derived from a constant PHI. If this expression does not fit with these
3584 /// constraints, return null.
3585 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3586 // If this is not an instruction, or if this is an instruction outside of the
3587 // loop, it can't be derived from a loop PHI.
3588 Instruction *I = dyn_cast<Instruction>(V);
3589 if (I == 0 || !L->contains(I->getParent())) return 0;
3591 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3592 if (L->getHeader() == I->getParent())
3595 // We don't currently keep track of the control flow needed to evaluate
3596 // PHIs, so we cannot handle PHIs inside of loops.
3600 // If we won't be able to constant fold this expression even if the operands
3601 // are constants, return early.
3602 if (!CanConstantFold(I)) return 0;
3604 // Otherwise, we can evaluate this instruction if all of its operands are
3605 // constant or derived from a PHI node themselves.
3607 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3608 if (!(isa<Constant>(I->getOperand(Op)) ||
3609 isa<GlobalValue>(I->getOperand(Op)))) {
3610 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3611 if (P == 0) return 0; // Not evolving from PHI
3615 return 0; // Evolving from multiple different PHIs.
3618 // This is a expression evolving from a constant PHI!
3622 /// EvaluateExpression - Given an expression that passes the
3623 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3624 /// in the loop has the value PHIVal. If we can't fold this expression for some
3625 /// reason, return null.
3626 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3627 if (isa<PHINode>(V)) return PHIVal;
3628 if (Constant *C = dyn_cast<Constant>(V)) return C;
3629 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3630 Instruction *I = cast<Instruction>(V);
3631 LLVMContext *Context = I->getParent()->getContext();
3633 std::vector<Constant*> Operands;
3634 Operands.resize(I->getNumOperands());
3636 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3637 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3638 if (Operands[i] == 0) return 0;
3641 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3642 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3643 &Operands[0], Operands.size(),
3646 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3647 &Operands[0], Operands.size(),
3651 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3652 /// in the header of its containing loop, we know the loop executes a
3653 /// constant number of times, and the PHI node is just a recurrence
3654 /// involving constants, fold it.
3656 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3659 std::map<PHINode*, Constant*>::iterator I =
3660 ConstantEvolutionLoopExitValue.find(PN);
3661 if (I != ConstantEvolutionLoopExitValue.end())
3664 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3665 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3667 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3669 // Since the loop is canonicalized, the PHI node must have two entries. One
3670 // entry must be a constant (coming in from outside of the loop), and the
3671 // second must be derived from the same PHI.
3672 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3673 Constant *StartCST =
3674 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3676 return RetVal = 0; // Must be a constant.
3678 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3679 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3681 return RetVal = 0; // Not derived from same PHI.
3683 // Execute the loop symbolically to determine the exit value.
3684 if (BEs.getActiveBits() >= 32)
3685 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3687 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3688 unsigned IterationNum = 0;
3689 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3690 if (IterationNum == NumIterations)
3691 return RetVal = PHIVal; // Got exit value!
3693 // Compute the value of the PHI node for the next iteration.
3694 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3695 if (NextPHI == PHIVal)
3696 return RetVal = NextPHI; // Stopped evolving!
3698 return 0; // Couldn't evaluate!
3703 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3704 /// constant number of times (the condition evolves only from constants),
3705 /// try to evaluate a few iterations of the loop until we get the exit
3706 /// condition gets a value of ExitWhen (true or false). If we cannot
3707 /// evaluate the trip count of the loop, return getCouldNotCompute().
3709 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3712 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3713 if (PN == 0) return getCouldNotCompute();
3715 // Since the loop is canonicalized, the PHI node must have two entries. One
3716 // entry must be a constant (coming in from outside of the loop), and the
3717 // second must be derived from the same PHI.
3718 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3719 Constant *StartCST =
3720 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3721 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3723 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3724 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3725 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3727 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3728 // the loop symbolically to determine when the condition gets a value of
3730 unsigned IterationNum = 0;
3731 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3732 for (Constant *PHIVal = StartCST;
3733 IterationNum != MaxIterations; ++IterationNum) {
3734 ConstantInt *CondVal =
3735 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3737 // Couldn't symbolically evaluate.
3738 if (!CondVal) return getCouldNotCompute();
3740 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3741 ++NumBruteForceTripCountsComputed;
3742 return getConstant(Type::Int32Ty, IterationNum);
3745 // Compute the value of the PHI node for the next iteration.
3746 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3747 if (NextPHI == 0 || NextPHI == PHIVal)
3748 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3752 // Too many iterations were needed to evaluate.
3753 return getCouldNotCompute();
3756 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3757 /// at the specified scope in the program. The L value specifies a loop
3758 /// nest to evaluate the expression at, where null is the top-level or a
3759 /// specified loop is immediately inside of the loop.
3761 /// This method can be used to compute the exit value for a variable defined
3762 /// in a loop by querying what the value will hold in the parent loop.
3764 /// In the case that a relevant loop exit value cannot be computed, the
3765 /// original value V is returned.
3766 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3767 // FIXME: this should be turned into a virtual method on SCEV!
3769 if (isa<SCEVConstant>(V)) return V;
3771 // If this instruction is evolved from a constant-evolving PHI, compute the
3772 // exit value from the loop without using SCEVs.
3773 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3774 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3775 const Loop *LI = (*this->LI)[I->getParent()];
3776 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3777 if (PHINode *PN = dyn_cast<PHINode>(I))
3778 if (PN->getParent() == LI->getHeader()) {
3779 // Okay, there is no closed form solution for the PHI node. Check
3780 // to see if the loop that contains it has a known backedge-taken
3781 // count. If so, we may be able to force computation of the exit
3783 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3784 if (const SCEVConstant *BTCC =
3785 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3786 // Okay, we know how many times the containing loop executes. If
3787 // this is a constant evolving PHI node, get the final value at
3788 // the specified iteration number.
3789 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3790 BTCC->getValue()->getValue(),
3792 if (RV) return getSCEV(RV);
3796 // Okay, this is an expression that we cannot symbolically evaluate
3797 // into a SCEV. Check to see if it's possible to symbolically evaluate
3798 // the arguments into constants, and if so, try to constant propagate the
3799 // result. This is particularly useful for computing loop exit values.
3800 if (CanConstantFold(I)) {
3801 // Check to see if we've folded this instruction at this loop before.
3802 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3803 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3804 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3806 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3808 std::vector<Constant*> Operands;
3809 Operands.reserve(I->getNumOperands());
3810 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3811 Value *Op = I->getOperand(i);
3812 if (Constant *C = dyn_cast<Constant>(Op)) {
3813 Operands.push_back(C);
3815 // If any of the operands is non-constant and if they are
3816 // non-integer and non-pointer, don't even try to analyze them
3817 // with scev techniques.
3818 if (!isSCEVable(Op->getType()))
3821 const SCEV* OpV = getSCEVAtScope(Op, L);
3822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3823 Constant *C = SC->getValue();
3824 if (C->getType() != Op->getType())
3825 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3829 Operands.push_back(C);
3830 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3831 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3832 if (C->getType() != Op->getType())
3834 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3838 Operands.push_back(C);
3848 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3849 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3850 &Operands[0], Operands.size(),
3853 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3854 &Operands[0], Operands.size(), Context);
3855 Pair.first->second = C;
3860 // This is some other type of SCEVUnknown, just return it.
3864 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3865 // Avoid performing the look-up in the common case where the specified
3866 // expression has no loop-variant portions.
3867 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3868 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3869 if (OpAtScope != Comm->getOperand(i)) {
3870 // Okay, at least one of these operands is loop variant but might be
3871 // foldable. Build a new instance of the folded commutative expression.
3872 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3873 Comm->op_begin()+i);
3874 NewOps.push_back(OpAtScope);
3876 for (++i; i != e; ++i) {
3877 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3878 NewOps.push_back(OpAtScope);
3880 if (isa<SCEVAddExpr>(Comm))
3881 return getAddExpr(NewOps);
3882 if (isa<SCEVMulExpr>(Comm))
3883 return getMulExpr(NewOps);
3884 if (isa<SCEVSMaxExpr>(Comm))
3885 return getSMaxExpr(NewOps);
3886 if (isa<SCEVUMaxExpr>(Comm))
3887 return getUMaxExpr(NewOps);
3888 llvm_unreachable("Unknown commutative SCEV type!");
3891 // If we got here, all operands are loop invariant.
3895 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3896 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3897 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
3898 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3899 return Div; // must be loop invariant
3900 return getUDivExpr(LHS, RHS);
3903 // If this is a loop recurrence for a loop that does not contain L, then we
3904 // are dealing with the final value computed by the loop.
3905 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3906 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3907 // To evaluate this recurrence, we need to know how many times the AddRec
3908 // loop iterates. Compute this now.
3909 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3910 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
3912 // Then, evaluate the AddRec.
3913 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3918 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3919 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3920 if (Op == Cast->getOperand())
3921 return Cast; // must be loop invariant
3922 return getZeroExtendExpr(Op, Cast->getType());
3925 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3926 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3927 if (Op == Cast->getOperand())
3928 return Cast; // must be loop invariant
3929 return getSignExtendExpr(Op, Cast->getType());
3932 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3933 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3934 if (Op == Cast->getOperand())
3935 return Cast; // must be loop invariant
3936 return getTruncateExpr(Op, Cast->getType());
3939 llvm_unreachable("Unknown SCEV type!");
3943 /// getSCEVAtScope - This is a convenience function which does
3944 /// getSCEVAtScope(getSCEV(V), L).
3945 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3946 return getSCEVAtScope(getSCEV(V), L);
3949 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3950 /// following equation:
3952 /// A * X = B (mod N)
3954 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3955 /// A and B isn't important.
3957 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3958 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3959 ScalarEvolution &SE) {
3960 uint32_t BW = A.getBitWidth();
3961 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3962 assert(A != 0 && "A must be non-zero.");
3966 // The gcd of A and N may have only one prime factor: 2. The number of
3967 // trailing zeros in A is its multiplicity
3968 uint32_t Mult2 = A.countTrailingZeros();
3971 // 2. Check if B is divisible by D.
3973 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3974 // is not less than multiplicity of this prime factor for D.
3975 if (B.countTrailingZeros() < Mult2)
3976 return SE.getCouldNotCompute();
3978 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3981 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3982 // bit width during computations.
3983 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3984 APInt Mod(BW + 1, 0);
3985 Mod.set(BW - Mult2); // Mod = N / D
3986 APInt I = AD.multiplicativeInverse(Mod);
3988 // 4. Compute the minimum unsigned root of the equation:
3989 // I * (B / D) mod (N / D)
3990 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3992 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3994 return SE.getConstant(Result.trunc(BW));
3997 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3998 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3999 /// might be the same) or two SCEVCouldNotCompute objects.
4001 static std::pair<const SCEV *,const SCEV *>
4002 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4003 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4004 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4005 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4006 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4008 // We currently can only solve this if the coefficients are constants.
4009 if (!LC || !MC || !NC) {
4010 const SCEV *CNC = SE.getCouldNotCompute();
4011 return std::make_pair(CNC, CNC);
4014 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4015 const APInt &L = LC->getValue()->getValue();
4016 const APInt &M = MC->getValue()->getValue();
4017 const APInt &N = NC->getValue()->getValue();
4018 APInt Two(BitWidth, 2);
4019 APInt Four(BitWidth, 4);
4022 using namespace APIntOps;
4024 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4025 // The B coefficient is M-N/2
4029 // The A coefficient is N/2
4030 APInt A(N.sdiv(Two));
4032 // Compute the B^2-4ac term.
4035 SqrtTerm -= Four * (A * C);
4037 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4038 // integer value or else APInt::sqrt() will assert.
4039 APInt SqrtVal(SqrtTerm.sqrt());
4041 // Compute the two solutions for the quadratic formula.
4042 // The divisions must be performed as signed divisions.
4044 APInt TwoA( A << 1 );
4045 if (TwoA.isMinValue()) {
4046 const SCEV *CNC = SE.getCouldNotCompute();
4047 return std::make_pair(CNC, CNC);
4050 LLVMContext *Context = SE.getContext();
4052 ConstantInt *Solution1 =
4053 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4054 ConstantInt *Solution2 =
4055 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
4057 return std::make_pair(SE.getConstant(Solution1),
4058 SE.getConstant(Solution2));
4059 } // end APIntOps namespace
4062 /// HowFarToZero - Return the number of times a backedge comparing the specified
4063 /// value to zero will execute. If not computable, return CouldNotCompute.
4064 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4065 // If the value is a constant
4066 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4067 // If the value is already zero, the branch will execute zero times.
4068 if (C->getValue()->isZero()) return C;
4069 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4072 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4073 if (!AddRec || AddRec->getLoop() != L)
4074 return getCouldNotCompute();
4076 if (AddRec->isAffine()) {
4077 // If this is an affine expression, the execution count of this branch is
4078 // the minimum unsigned root of the following equation:
4080 // Start + Step*N = 0 (mod 2^BW)
4084 // Step*N = -Start (mod 2^BW)
4086 // where BW is the common bit width of Start and Step.
4088 // Get the initial value for the loop.
4089 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4090 L->getParentLoop());
4091 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4092 L->getParentLoop());
4094 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4095 // For now we handle only constant steps.
4097 // First, handle unitary steps.
4098 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4099 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4100 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4101 return Start; // N = Start (as unsigned)
4103 // Then, try to solve the above equation provided that Start is constant.
4104 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4105 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4106 -StartC->getValue()->getValue(),
4109 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4110 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4111 // the quadratic equation to solve it.
4112 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4114 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4115 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4118 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4119 << " sol#2: " << *R2 << "\n";
4121 // Pick the smallest positive root value.
4122 if (ConstantInt *CB =
4123 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
4124 R1->getValue(), R2->getValue()))) {
4125 if (CB->getZExtValue() == false)
4126 std::swap(R1, R2); // R1 is the minimum root now.
4128 // We can only use this value if the chrec ends up with an exact zero
4129 // value at this index. When solving for "X*X != 5", for example, we
4130 // should not accept a root of 2.
4131 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4133 return R1; // We found a quadratic root!
4138 return getCouldNotCompute();
4141 /// HowFarToNonZero - Return the number of times a backedge checking the
4142 /// specified value for nonzero will execute. If not computable, return
4144 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4145 // Loops that look like: while (X == 0) are very strange indeed. We don't
4146 // handle them yet except for the trivial case. This could be expanded in the
4147 // future as needed.
4149 // If the value is a constant, check to see if it is known to be non-zero
4150 // already. If so, the backedge will execute zero times.
4151 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4152 if (!C->getValue()->isNullValue())
4153 return getIntegerSCEV(0, C->getType());
4154 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4157 // We could implement others, but I really doubt anyone writes loops like
4158 // this, and if they did, they would already be constant folded.
4159 return getCouldNotCompute();
4162 /// getLoopPredecessor - If the given loop's header has exactly one unique
4163 /// predecessor outside the loop, return it. Otherwise return null.
4165 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4166 BasicBlock *Header = L->getHeader();
4167 BasicBlock *Pred = 0;
4168 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4170 if (!L->contains(*PI)) {
4171 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4177 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4178 /// (which may not be an immediate predecessor) which has exactly one
4179 /// successor from which BB is reachable, or null if no such block is
4183 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4184 // If the block has a unique predecessor, then there is no path from the
4185 // predecessor to the block that does not go through the direct edge
4186 // from the predecessor to the block.
4187 if (BasicBlock *Pred = BB->getSinglePredecessor())
4190 // A loop's header is defined to be a block that dominates the loop.
4191 // If the header has a unique predecessor outside the loop, it must be
4192 // a block that has exactly one successor that can reach the loop.
4193 if (Loop *L = LI->getLoopFor(BB))
4194 return getLoopPredecessor(L);
4199 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4200 /// testing whether two expressions are equal, however for the purposes of
4201 /// looking for a condition guarding a loop, it can be useful to be a little
4202 /// more general, since a front-end may have replicated the controlling
4205 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4206 // Quick check to see if they are the same SCEV.
4207 if (A == B) return true;
4209 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4210 // two different instructions with the same value. Check for this case.
4211 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4212 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4213 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4214 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4215 if (AI->isIdenticalTo(BI))
4218 // Otherwise assume they may have a different value.
4222 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4223 return getSignedRange(S).getSignedMax().isNegative();
4226 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4227 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4230 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4231 return !getSignedRange(S).getSignedMin().isNegative();
4234 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4235 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4238 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4239 return isKnownNegative(S) || isKnownPositive(S);
4242 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4243 const SCEV *LHS, const SCEV *RHS) {
4245 if (HasSameValue(LHS, RHS))
4246 return ICmpInst::isTrueWhenEqual(Pred);
4250 assert(0 && "Unexpected ICmpInst::Predicate value!");
4252 case ICmpInst::ICMP_SGT:
4253 Pred = ICmpInst::ICMP_SLT;
4254 std::swap(LHS, RHS);
4255 case ICmpInst::ICMP_SLT: {
4256 ConstantRange LHSRange = getSignedRange(LHS);
4257 ConstantRange RHSRange = getSignedRange(RHS);
4258 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4260 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4263 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4264 ConstantRange DiffRange = getUnsignedRange(Diff);
4265 if (isKnownNegative(Diff)) {
4266 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4268 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4270 } else if (isKnownPositive(Diff)) {
4271 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4273 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4278 case ICmpInst::ICMP_SGE:
4279 Pred = ICmpInst::ICMP_SLE;
4280 std::swap(LHS, RHS);
4281 case ICmpInst::ICMP_SLE: {
4282 ConstantRange LHSRange = getSignedRange(LHS);
4283 ConstantRange RHSRange = getSignedRange(RHS);
4284 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4286 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4289 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4290 ConstantRange DiffRange = getUnsignedRange(Diff);
4291 if (isKnownNonPositive(Diff)) {
4292 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4294 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4296 } else if (isKnownNonNegative(Diff)) {
4297 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4299 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4304 case ICmpInst::ICMP_UGT:
4305 Pred = ICmpInst::ICMP_ULT;
4306 std::swap(LHS, RHS);
4307 case ICmpInst::ICMP_ULT: {
4308 ConstantRange LHSRange = getUnsignedRange(LHS);
4309 ConstantRange RHSRange = getUnsignedRange(RHS);
4310 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4312 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4315 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4316 ConstantRange DiffRange = getUnsignedRange(Diff);
4317 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4319 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4323 case ICmpInst::ICMP_UGE:
4324 Pred = ICmpInst::ICMP_ULE;
4325 std::swap(LHS, RHS);
4326 case ICmpInst::ICMP_ULE: {
4327 ConstantRange LHSRange = getUnsignedRange(LHS);
4328 ConstantRange RHSRange = getUnsignedRange(RHS);
4329 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4331 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4334 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4335 ConstantRange DiffRange = getUnsignedRange(Diff);
4336 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4338 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4342 case ICmpInst::ICMP_NE: {
4343 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4345 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4348 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4349 if (isKnownNonZero(Diff))
4353 case ICmpInst::ICMP_EQ:
4359 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4360 /// protected by a conditional between LHS and RHS. This is used to
4361 /// to eliminate casts.
4363 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4364 ICmpInst::Predicate Pred,
4365 const SCEV *LHS, const SCEV *RHS) {
4366 // Interpret a null as meaning no loop, where there is obviously no guard
4367 // (interprocedural conditions notwithstanding).
4368 if (!L) return true;
4370 BasicBlock *Latch = L->getLoopLatch();
4374 BranchInst *LoopContinuePredicate =
4375 dyn_cast<BranchInst>(Latch->getTerminator());
4376 if (!LoopContinuePredicate ||
4377 LoopContinuePredicate->isUnconditional())
4381 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4382 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4385 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4386 /// by a conditional between LHS and RHS. This is used to help avoid max
4387 /// expressions in loop trip counts, and to eliminate casts.
4389 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4390 ICmpInst::Predicate Pred,
4391 const SCEV *LHS, const SCEV *RHS) {
4392 // Interpret a null as meaning no loop, where there is obviously no guard
4393 // (interprocedural conditions notwithstanding).
4394 if (!L) return false;
4396 BasicBlock *Predecessor = getLoopPredecessor(L);
4397 BasicBlock *PredecessorDest = L->getHeader();
4399 // Starting at the loop predecessor, climb up the predecessor chain, as long
4400 // as there are predecessors that can be found that have unique successors
4401 // leading to the original header.
4403 PredecessorDest = Predecessor,
4404 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4406 BranchInst *LoopEntryPredicate =
4407 dyn_cast<BranchInst>(Predecessor->getTerminator());
4408 if (!LoopEntryPredicate ||
4409 LoopEntryPredicate->isUnconditional())
4412 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4413 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4420 /// isNecessaryCond - Test whether the condition described by Pred, LHS,
4421 /// and RHS is a necessary condition for the given Cond value to evaluate
4423 bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4424 ICmpInst::Predicate Pred,
4425 const SCEV *LHS, const SCEV *RHS,
4427 // Recursivly handle And and Or conditions.
4428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4429 if (BO->getOpcode() == Instruction::And) {
4431 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4432 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4433 } else if (BO->getOpcode() == Instruction::Or) {
4435 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4436 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4440 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4441 if (!ICI) return false;
4443 // Now that we found a conditional branch that dominates the loop, check to
4444 // see if it is the comparison we are looking for.
4445 Value *PreCondLHS = ICI->getOperand(0);
4446 Value *PreCondRHS = ICI->getOperand(1);
4447 ICmpInst::Predicate FoundPred;
4449 FoundPred = ICI->getInversePredicate();
4451 FoundPred = ICI->getPredicate();
4453 if (FoundPred == Pred)
4454 ; // An exact match.
4455 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4456 // The actual condition is beyond sufficient.
4457 FoundPred = ICmpInst::ICMP_NE;
4458 // NE is symmetric but the original comparison may not be. Swap
4459 // the operands if necessary so that they match below.
4460 if (isa<SCEVConstant>(LHS))
4461 std::swap(PreCondLHS, PreCondRHS);
4463 // Check a few special cases.
4464 switch (FoundPred) {
4465 case ICmpInst::ICMP_UGT:
4466 if (Pred == ICmpInst::ICMP_ULT) {
4467 std::swap(PreCondLHS, PreCondRHS);
4468 FoundPred = ICmpInst::ICMP_ULT;
4472 case ICmpInst::ICMP_SGT:
4473 if (Pred == ICmpInst::ICMP_SLT) {
4474 std::swap(PreCondLHS, PreCondRHS);
4475 FoundPred = ICmpInst::ICMP_SLT;
4479 case ICmpInst::ICMP_NE:
4480 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4481 // so check for this case by checking if the NE is comparing against
4482 // a minimum or maximum constant.
4483 if (!ICmpInst::isTrueWhenEqual(Pred))
4484 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4485 const APInt &A = C->getValue()->getValue();
4487 case ICmpInst::ICMP_SLT:
4488 if (A.isMaxSignedValue()) break;
4490 case ICmpInst::ICMP_SGT:
4491 if (A.isMinSignedValue()) break;
4493 case ICmpInst::ICMP_ULT:
4494 if (A.isMaxValue()) break;
4496 case ICmpInst::ICMP_UGT:
4497 if (A.isMinValue()) break;
4503 // NE is symmetric but the original comparison may not be. Swap
4504 // the operands if necessary so that they match below.
4505 if (isa<SCEVConstant>(LHS))
4506 std::swap(PreCondLHS, PreCondRHS);
4511 // We weren't able to reconcile the condition.
4515 assert(Pred == FoundPred && "Conditions were not reconciled!");
4517 // Bail if the ICmp's operands' types are wider than the needed type
4518 // before attempting to call getSCEV on them. This avoids infinite
4519 // recursion, since the analysis of widening casts can require loop
4520 // exit condition information for overflow checking, which would
4522 if (getTypeSizeInBits(LHS->getType()) <
4523 getTypeSizeInBits(PreCondLHS->getType()))
4526 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4527 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4529 // Balance the types. The case where FoundLHS' type is wider than
4530 // LHS' type is checked for above.
4531 if (getTypeSizeInBits(LHS->getType()) >
4532 getTypeSizeInBits(FoundLHS->getType())) {
4533 if (CmpInst::isSigned(Pred)) {
4534 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4535 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4537 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4538 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4542 return isNecessaryCondOperands(Pred, LHS, RHS,
4543 FoundLHS, FoundRHS) ||
4544 // ~x < ~y --> x > y
4545 isNecessaryCondOperands(Pred, LHS, RHS,
4546 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4549 /// isNecessaryCondOperands - Test whether the condition described by Pred,
4550 /// LHS, and RHS is a necessary condition for the condition described by
4551 /// Pred, FoundLHS, and FoundRHS to evaluate to true.
4553 ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4554 const SCEV *LHS, const SCEV *RHS,
4555 const SCEV *FoundLHS,
4556 const SCEV *FoundRHS) {
4559 case ICmpInst::ICMP_SLT:
4560 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4561 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4564 case ICmpInst::ICMP_SGT:
4565 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4566 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4569 case ICmpInst::ICMP_ULT:
4570 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4571 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4574 case ICmpInst::ICMP_UGT:
4575 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4576 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4584 /// getBECount - Subtract the end and start values and divide by the step,
4585 /// rounding up, to get the number of times the backedge is executed. Return
4586 /// CouldNotCompute if an intermediate computation overflows.
4587 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4590 const Type *Ty = Start->getType();
4591 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4592 const SCEV *Diff = getMinusSCEV(End, Start);
4593 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4595 // Add an adjustment to the difference between End and Start so that
4596 // the division will effectively round up.
4597 const SCEV *Add = getAddExpr(Diff, RoundUp);
4599 // Check Add for unsigned overflow.
4600 // TODO: More sophisticated things could be done here.
4601 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
4602 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4603 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4604 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4605 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4606 return getCouldNotCompute();
4608 return getUDivExpr(Add, Step);
4611 /// HowManyLessThans - Return the number of times a backedge containing the
4612 /// specified less-than comparison will execute. If not computable, return
4613 /// CouldNotCompute.
4614 ScalarEvolution::BackedgeTakenInfo
4615 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4616 const Loop *L, bool isSigned) {
4617 // Only handle: "ADDREC < LoopInvariant".
4618 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4620 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4621 if (!AddRec || AddRec->getLoop() != L)
4622 return getCouldNotCompute();
4624 if (AddRec->isAffine()) {
4625 // FORNOW: We only support unit strides.
4626 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4627 const SCEV *Step = AddRec->getStepRecurrence(*this);
4629 // TODO: handle non-constant strides.
4630 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4631 if (!CStep || CStep->isZero())
4632 return getCouldNotCompute();
4633 if (CStep->isOne()) {
4634 // With unit stride, the iteration never steps past the limit value.
4635 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4636 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4637 // Test whether a positive iteration iteration can step past the limit
4638 // value and past the maximum value for its type in a single step.
4640 APInt Max = APInt::getSignedMaxValue(BitWidth);
4641 if ((Max - CStep->getValue()->getValue())
4642 .slt(CLimit->getValue()->getValue()))
4643 return getCouldNotCompute();
4645 APInt Max = APInt::getMaxValue(BitWidth);
4646 if ((Max - CStep->getValue()->getValue())
4647 .ult(CLimit->getValue()->getValue()))
4648 return getCouldNotCompute();
4651 // TODO: handle non-constant limit values below.
4652 return getCouldNotCompute();
4654 // TODO: handle negative strides below.
4655 return getCouldNotCompute();
4657 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4658 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4659 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4660 // treat m-n as signed nor unsigned due to overflow possibility.
4662 // First, we get the value of the LHS in the first iteration: n
4663 const SCEV *Start = AddRec->getOperand(0);
4665 // Determine the minimum constant start value.
4666 const SCEV *MinStart = getConstant(isSigned ?
4667 getSignedRange(Start).getSignedMin() :
4668 getUnsignedRange(Start).getUnsignedMin());
4670 // If we know that the condition is true in order to enter the loop,
4671 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4672 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4673 // the division must round up.
4674 const SCEV *End = RHS;
4675 if (!isLoopGuardedByCond(L,
4676 isSigned ? ICmpInst::ICMP_SLT :
4678 getMinusSCEV(Start, Step), RHS))
4679 End = isSigned ? getSMaxExpr(RHS, Start)
4680 : getUMaxExpr(RHS, Start);
4682 // Determine the maximum constant end value.
4683 const SCEV *MaxEnd = getConstant(isSigned ?
4684 getSignedRange(End).getSignedMax() :
4685 getUnsignedRange(End).getUnsignedMax());
4687 // Finally, we subtract these two values and divide, rounding up, to get
4688 // the number of times the backedge is executed.
4689 const SCEV *BECount = getBECount(Start, End, Step);
4691 // The maximum backedge count is similar, except using the minimum start
4692 // value and the maximum end value.
4693 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
4695 return BackedgeTakenInfo(BECount, MaxBECount);
4698 return getCouldNotCompute();
4701 /// getNumIterationsInRange - Return the number of iterations of this loop that
4702 /// produce values in the specified constant range. Another way of looking at
4703 /// this is that it returns the first iteration number where the value is not in
4704 /// the condition, thus computing the exit count. If the iteration count can't
4705 /// be computed, an instance of SCEVCouldNotCompute is returned.
4706 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4707 ScalarEvolution &SE) const {
4708 if (Range.isFullSet()) // Infinite loop.
4709 return SE.getCouldNotCompute();
4711 // If the start is a non-zero constant, shift the range to simplify things.
4712 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4713 if (!SC->getValue()->isZero()) {
4714 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4715 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4716 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4717 if (const SCEVAddRecExpr *ShiftedAddRec =
4718 dyn_cast<SCEVAddRecExpr>(Shifted))
4719 return ShiftedAddRec->getNumIterationsInRange(
4720 Range.subtract(SC->getValue()->getValue()), SE);
4721 // This is strange and shouldn't happen.
4722 return SE.getCouldNotCompute();
4725 // The only time we can solve this is when we have all constant indices.
4726 // Otherwise, we cannot determine the overflow conditions.
4727 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4728 if (!isa<SCEVConstant>(getOperand(i)))
4729 return SE.getCouldNotCompute();
4732 // Okay at this point we know that all elements of the chrec are constants and
4733 // that the start element is zero.
4735 // First check to see if the range contains zero. If not, the first
4737 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4738 if (!Range.contains(APInt(BitWidth, 0)))
4739 return SE.getIntegerSCEV(0, getType());
4742 // If this is an affine expression then we have this situation:
4743 // Solve {0,+,A} in Range === Ax in Range
4745 // We know that zero is in the range. If A is positive then we know that
4746 // the upper value of the range must be the first possible exit value.
4747 // If A is negative then the lower of the range is the last possible loop
4748 // value. Also note that we already checked for a full range.
4749 APInt One(BitWidth,1);
4750 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4751 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4753 // The exit value should be (End+A)/A.
4754 APInt ExitVal = (End + A).udiv(A);
4755 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
4757 // Evaluate at the exit value. If we really did fall out of the valid
4758 // range, then we computed our trip count, otherwise wrap around or other
4759 // things must have happened.
4760 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4761 if (Range.contains(Val->getValue()))
4762 return SE.getCouldNotCompute(); // Something strange happened
4764 // Ensure that the previous value is in the range. This is a sanity check.
4765 assert(Range.contains(
4766 EvaluateConstantChrecAtConstant(this,
4767 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
4768 "Linear scev computation is off in a bad way!");
4769 return SE.getConstant(ExitValue);
4770 } else if (isQuadratic()) {
4771 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4772 // quadratic equation to solve it. To do this, we must frame our problem in
4773 // terms of figuring out when zero is crossed, instead of when
4774 // Range.getUpper() is crossed.
4775 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
4776 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4777 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4779 // Next, solve the constructed addrec
4780 std::pair<const SCEV *,const SCEV *> Roots =
4781 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4782 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4783 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4785 // Pick the smallest positive root value.
4786 if (ConstantInt *CB =
4787 dyn_cast<ConstantInt>(
4788 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4789 R1->getValue(), R2->getValue()))) {
4790 if (CB->getZExtValue() == false)
4791 std::swap(R1, R2); // R1 is the minimum root now.
4793 // Make sure the root is not off by one. The returned iteration should
4794 // not be in the range, but the previous one should be. When solving
4795 // for "X*X < 5", for example, we should not return a root of 2.
4796 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4799 if (Range.contains(R1Val->getValue())) {
4800 // The next iteration must be out of the range...
4801 ConstantInt *NextVal =
4802 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
4804 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4805 if (!Range.contains(R1Val->getValue()))
4806 return SE.getConstant(NextVal);
4807 return SE.getCouldNotCompute(); // Something strange happened
4810 // If R1 was not in the range, then it is a good return value. Make
4811 // sure that R1-1 WAS in the range though, just in case.
4812 ConstantInt *NextVal =
4813 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
4814 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4815 if (Range.contains(R1Val->getValue()))
4817 return SE.getCouldNotCompute(); // Something strange happened
4822 return SE.getCouldNotCompute();
4827 //===----------------------------------------------------------------------===//
4828 // SCEVCallbackVH Class Implementation
4829 //===----------------------------------------------------------------------===//
4831 void ScalarEvolution::SCEVCallbackVH::deleted() {
4832 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
4833 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4834 SE->ConstantEvolutionLoopExitValue.erase(PN);
4835 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4836 SE->ValuesAtScopes.erase(I);
4837 SE->Scalars.erase(getValPtr());
4838 // this now dangles!
4841 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
4842 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
4844 // Forget all the expressions associated with users of the old value,
4845 // so that future queries will recompute the expressions using the new
4847 SmallVector<User *, 16> Worklist;
4848 SmallPtrSet<User *, 8> Visited;
4849 Value *Old = getValPtr();
4850 bool DeleteOld = false;
4851 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4853 Worklist.push_back(*UI);
4854 while (!Worklist.empty()) {
4855 User *U = Worklist.pop_back_val();
4856 // Deleting the Old value will cause this to dangle. Postpone
4857 // that until everything else is done.
4862 if (!Visited.insert(U))
4864 if (PHINode *PN = dyn_cast<PHINode>(U))
4865 SE->ConstantEvolutionLoopExitValue.erase(PN);
4866 if (Instruction *I = dyn_cast<Instruction>(U))
4867 SE->ValuesAtScopes.erase(I);
4868 SE->Scalars.erase(U);
4869 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4871 Worklist.push_back(*UI);
4873 // Delete the Old value if it (indirectly) references itself.
4875 if (PHINode *PN = dyn_cast<PHINode>(Old))
4876 SE->ConstantEvolutionLoopExitValue.erase(PN);
4877 if (Instruction *I = dyn_cast<Instruction>(Old))
4878 SE->ValuesAtScopes.erase(I);
4879 SE->Scalars.erase(Old);
4880 // this now dangles!
4885 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
4886 : CallbackVH(V), SE(se) {}
4888 //===----------------------------------------------------------------------===//
4889 // ScalarEvolution Class Implementation
4890 //===----------------------------------------------------------------------===//
4892 ScalarEvolution::ScalarEvolution()
4893 : FunctionPass(&ID) {
4896 bool ScalarEvolution::runOnFunction(Function &F) {
4898 LI = &getAnalysis<LoopInfo>();
4899 TD = getAnalysisIfAvailable<TargetData>();
4903 void ScalarEvolution::releaseMemory() {
4905 BackedgeTakenCounts.clear();
4906 ConstantEvolutionLoopExitValue.clear();
4907 ValuesAtScopes.clear();
4908 UniqueSCEVs.clear();
4909 SCEVAllocator.Reset();
4912 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4913 AU.setPreservesAll();
4914 AU.addRequiredTransitive<LoopInfo>();
4917 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
4918 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
4921 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
4923 // Print all inner loops first
4924 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4925 PrintLoopInfo(OS, SE, *I);
4927 OS << "Loop " << L->getHeader()->getName() << ": ";
4929 SmallVector<BasicBlock*, 8> ExitBlocks;
4930 L->getExitBlocks(ExitBlocks);
4931 if (ExitBlocks.size() != 1)
4932 OS << "<multiple exits> ";
4934 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4935 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4937 OS << "Unpredictable backedge-taken count. ";
4941 OS << "Loop " << L->getHeader()->getName() << ": ";
4943 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4944 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4946 OS << "Unpredictable max backedge-taken count. ";
4952 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4953 // ScalarEvolution's implementaiton of the print method is to print
4954 // out SCEV values of all instructions that are interesting. Doing
4955 // this potentially causes it to create new SCEV objects though,
4956 // which technically conflicts with the const qualifier. This isn't
4957 // observable from outside the class though, so casting away the
4958 // const isn't dangerous.
4959 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4961 OS << "Classifying expressions for: " << F->getName() << "\n";
4962 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4963 if (isSCEVable(I->getType())) {
4966 const SCEV *SV = SE.getSCEV(&*I);
4969 const Loop *L = LI->getLoopFor((*I).getParent());
4971 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
4978 OS << "\t\t" "Exits: ";
4979 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
4980 if (!ExitValue->isLoopInvariant(L)) {
4981 OS << "<<Unknown>>";
4990 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4991 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4992 PrintLoopInfo(OS, &SE, *I);
4995 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4996 raw_os_ostream OS(o);