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(Context->getConstantInt(Val));
198 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
200 Context->getConstantInt(cast<IntegerType>(Ty), V, isSigned));
203 const Type *SCEVConstant::getType() const { return V->getType(); }
205 void SCEVConstant::print(raw_ostream &OS) const {
206 WriteAsOperand(OS, V, false);
209 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
210 unsigned SCEVTy, const SCEV *op, const Type *ty)
211 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
213 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
214 return Op->dominates(BB, DT);
217 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
218 const SCEV *op, const Type *ty)
219 : SCEVCastExpr(ID, scTruncate, op, ty) {
220 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
221 (Ty->isInteger() || isa<PointerType>(Ty)) &&
222 "Cannot truncate non-integer value!");
225 void SCEVTruncateExpr::print(raw_ostream &OS) const {
226 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
229 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
230 const SCEV *op, const Type *ty)
231 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
234 "Cannot zero extend non-integer value!");
237 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
238 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
241 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
242 const SCEV *op, const Type *ty)
243 : SCEVCastExpr(ID, scSignExtend, op, ty) {
244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
246 "Cannot sign extend non-integer value!");
249 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
250 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
253 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
263 SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
266 ScalarEvolution &SE) const {
267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
270 if (H != getOperand(i)) {
271 SmallVector<const SCEV *, 8> NewOps;
272 NewOps.reserve(getNumOperands());
273 for (unsigned j = 0; j != i; ++j)
274 NewOps.push_back(getOperand(j));
276 for (++i; i != e; ++i)
277 NewOps.push_back(getOperand(i)->
278 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
280 if (isa<SCEVAddExpr>(this))
281 return SE.getAddExpr(NewOps);
282 else if (isa<SCEVMulExpr>(this))
283 return SE.getMulExpr(NewOps);
284 else if (isa<SCEVSMaxExpr>(this))
285 return SE.getSMaxExpr(NewOps);
286 else if (isa<SCEVUMaxExpr>(this))
287 return SE.getUMaxExpr(NewOps);
289 llvm_unreachable("Unknown commutative expr!");
295 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
296 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
297 if (!getOperand(i)->dominates(BB, DT))
303 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
304 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
307 void SCEVUDivExpr::print(raw_ostream &OS) const {
308 OS << "(" << *LHS << " /u " << *RHS << ")";
311 const Type *SCEVUDivExpr::getType() const {
312 // In most cases the types of LHS and RHS will be the same, but in some
313 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
314 // depend on the type for correctness, but handling types carefully can
315 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
316 // a pointer type than the RHS, so use the RHS' type here.
317 return RHS->getType();
321 SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
323 ScalarEvolution &SE) const {
324 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
326 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
327 if (H != getOperand(i)) {
328 SmallVector<const SCEV *, 8> NewOps;
329 NewOps.reserve(getNumOperands());
330 for (unsigned j = 0; j != i; ++j)
331 NewOps.push_back(getOperand(j));
333 for (++i; i != e; ++i)
334 NewOps.push_back(getOperand(i)->
335 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
337 return SE.getAddRecExpr(NewOps, L);
344 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
345 // Add recurrences are never invariant in the function-body (null loop).
349 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
350 if (QueryLoop->contains(L->getHeader()))
353 // This recurrence is variant w.r.t. QueryLoop if any of its operands
355 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
356 if (!getOperand(i)->isLoopInvariant(QueryLoop))
359 // Otherwise it's loop-invariant.
363 void SCEVAddRecExpr::print(raw_ostream &OS) const {
364 OS << "{" << *Operands[0];
365 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
366 OS << ",+," << *Operands[i];
367 OS << "}<" << L->getHeader()->getName() + ">";
370 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
371 // All non-instruction values are loop invariant. All instructions are loop
372 // invariant if they are not contained in the specified loop.
373 // Instructions are never considered invariant in the function body
374 // (null loop) because they are defined within the "loop".
375 if (Instruction *I = dyn_cast<Instruction>(V))
376 return L && !L->contains(I->getParent());
380 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
381 if (Instruction *I = dyn_cast<Instruction>(getValue()))
382 return DT->dominates(I->getParent(), BB);
386 const Type *SCEVUnknown::getType() const {
390 void SCEVUnknown::print(raw_ostream &OS) const {
391 WriteAsOperand(OS, V, false);
394 //===----------------------------------------------------------------------===//
396 //===----------------------------------------------------------------------===//
399 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
400 /// than the complexity of the RHS. This comparator is used to canonicalize
402 class VISIBILITY_HIDDEN SCEVComplexityCompare {
405 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
407 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
408 // Primarily, sort the SCEVs by their getSCEVType().
409 if (LHS->getSCEVType() != RHS->getSCEVType())
410 return LHS->getSCEVType() < RHS->getSCEVType();
412 // Aside from the getSCEVType() ordering, the particular ordering
413 // isn't very important except that it's beneficial to be consistent,
414 // so that (a + b) and (b + a) don't end up as different expressions.
416 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
417 // not as complete as it could be.
418 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
419 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
421 // Order pointer values after integer values. This helps SCEVExpander
423 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
425 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
428 // Compare getValueID values.
429 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
430 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
432 // Sort arguments by their position.
433 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
434 const Argument *RA = cast<Argument>(RU->getValue());
435 return LA->getArgNo() < RA->getArgNo();
438 // For instructions, compare their loop depth, and their opcode.
439 // This is pretty loose.
440 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
441 Instruction *RV = cast<Instruction>(RU->getValue());
443 // Compare loop depths.
444 if (LI->getLoopDepth(LV->getParent()) !=
445 LI->getLoopDepth(RV->getParent()))
446 return LI->getLoopDepth(LV->getParent()) <
447 LI->getLoopDepth(RV->getParent());
450 if (LV->getOpcode() != RV->getOpcode())
451 return LV->getOpcode() < RV->getOpcode();
453 // Compare the number of operands.
454 if (LV->getNumOperands() != RV->getNumOperands())
455 return LV->getNumOperands() < RV->getNumOperands();
461 // Compare constant values.
462 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
463 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
464 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
465 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
466 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
469 // Compare addrec loop depths.
470 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
471 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
472 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
473 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
476 // Lexicographically compare n-ary expressions.
477 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
478 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
479 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
480 if (i >= RC->getNumOperands())
482 if (operator()(LC->getOperand(i), RC->getOperand(i)))
484 if (operator()(RC->getOperand(i), LC->getOperand(i)))
487 return LC->getNumOperands() < RC->getNumOperands();
490 // Lexicographically compare udiv expressions.
491 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
492 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
493 if (operator()(LC->getLHS(), RC->getLHS()))
495 if (operator()(RC->getLHS(), LC->getLHS()))
497 if (operator()(LC->getRHS(), RC->getRHS()))
499 if (operator()(RC->getRHS(), LC->getRHS()))
504 // Compare cast expressions by operand.
505 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
506 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
507 return operator()(LC->getOperand(), RC->getOperand());
510 llvm_unreachable("Unknown SCEV kind!");
516 /// GroupByComplexity - Given a list of SCEV objects, order them by their
517 /// complexity, and group objects of the same complexity together by value.
518 /// When this routine is finished, we know that any duplicates in the vector are
519 /// consecutive and that complexity is monotonically increasing.
521 /// Note that we go take special precautions to ensure that we get determinstic
522 /// results from this routine. In other words, we don't want the results of
523 /// this to depend on where the addresses of various SCEV objects happened to
526 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
528 if (Ops.size() < 2) return; // Noop
529 if (Ops.size() == 2) {
530 // This is the common case, which also happens to be trivially simple.
532 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
533 std::swap(Ops[0], Ops[1]);
537 // Do the rough sort by complexity.
538 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
540 // Now that we are sorted by complexity, group elements of the same
541 // complexity. Note that this is, at worst, N^2, but the vector is likely to
542 // be extremely short in practice. Note that we take this approach because we
543 // do not want to depend on the addresses of the objects we are grouping.
544 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
545 const SCEV *S = Ops[i];
546 unsigned Complexity = S->getSCEVType();
548 // If there are any objects of the same complexity and same value as this
550 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
551 if (Ops[j] == S) { // Found a duplicate.
552 // Move it to immediately after i'th element.
553 std::swap(Ops[i+1], Ops[j]);
554 ++i; // no need to rescan it.
555 if (i == e-2) return; // Done!
563 //===----------------------------------------------------------------------===//
564 // Simple SCEV method implementations
565 //===----------------------------------------------------------------------===//
567 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
569 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
571 const Type* ResultTy) {
572 // Handle the simplest case efficiently.
574 return SE.getTruncateOrZeroExtend(It, ResultTy);
576 // We are using the following formula for BC(It, K):
578 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
580 // Suppose, W is the bitwidth of the return value. We must be prepared for
581 // overflow. Hence, we must assure that the result of our computation is
582 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
583 // safe in modular arithmetic.
585 // However, this code doesn't use exactly that formula; the formula it uses
586 // is something like the following, where T is the number of factors of 2 in
587 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
590 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
592 // This formula is trivially equivalent to the previous formula. However,
593 // this formula can be implemented much more efficiently. The trick is that
594 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
595 // arithmetic. To do exact division in modular arithmetic, all we have
596 // to do is multiply by the inverse. Therefore, this step can be done at
599 // The next issue is how to safely do the division by 2^T. The way this
600 // is done is by doing the multiplication step at a width of at least W + T
601 // bits. This way, the bottom W+T bits of the product are accurate. Then,
602 // when we perform the division by 2^T (which is equivalent to a right shift
603 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
604 // truncated out after the division by 2^T.
606 // In comparison to just directly using the first formula, this technique
607 // is much more efficient; using the first formula requires W * K bits,
608 // but this formula less than W + K bits. Also, the first formula requires
609 // a division step, whereas this formula only requires multiplies and shifts.
611 // It doesn't matter whether the subtraction step is done in the calculation
612 // width or the input iteration count's width; if the subtraction overflows,
613 // the result must be zero anyway. We prefer here to do it in the width of
614 // the induction variable because it helps a lot for certain cases; CodeGen
615 // isn't smart enough to ignore the overflow, which leads to much less
616 // efficient code if the width of the subtraction is wider than the native
619 // (It's possible to not widen at all by pulling out factors of 2 before
620 // the multiplication; for example, K=2 can be calculated as
621 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
622 // extra arithmetic, so it's not an obvious win, and it gets
623 // much more complicated for K > 3.)
625 // Protection from insane SCEVs; this bound is conservative,
626 // but it probably doesn't matter.
628 return SE.getCouldNotCompute();
630 unsigned W = SE.getTypeSizeInBits(ResultTy);
632 // Calculate K! / 2^T and T; we divide out the factors of two before
633 // multiplying for calculating K! / 2^T to avoid overflow.
634 // Other overflow doesn't matter because we only care about the bottom
635 // W bits of the result.
636 APInt OddFactorial(W, 1);
638 for (unsigned i = 3; i <= K; ++i) {
640 unsigned TwoFactors = Mult.countTrailingZeros();
642 Mult = Mult.lshr(TwoFactors);
643 OddFactorial *= Mult;
646 // We need at least W + T bits for the multiplication step
647 unsigned CalculationBits = W + T;
649 // Calcuate 2^T, at width T+W.
650 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
652 // Calculate the multiplicative inverse of K! / 2^T;
653 // this multiplication factor will perform the exact division by
655 APInt Mod = APInt::getSignedMinValue(W+1);
656 APInt MultiplyFactor = OddFactorial.zext(W+1);
657 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
658 MultiplyFactor = MultiplyFactor.trunc(W);
660 // Calculate the product, at width T+W
661 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
662 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
663 for (unsigned i = 1; i != K; ++i) {
664 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
665 Dividend = SE.getMulExpr(Dividend,
666 SE.getTruncateOrZeroExtend(S, CalculationTy));
670 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
672 // Truncate the result, and divide by K! / 2^T.
674 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
675 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
678 /// evaluateAtIteration - Return the value of this chain of recurrences at
679 /// the specified iteration number. We can evaluate this recurrence by
680 /// multiplying each element in the chain by the binomial coefficient
681 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
683 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
685 /// where BC(It, k) stands for binomial coefficient.
687 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
688 ScalarEvolution &SE) const {
689 const SCEV *Result = getStart();
690 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
691 // The computation is correct in the face of overflow provided that the
692 // multiplication is performed _after_ the evaluation of the binomial
694 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
695 if (isa<SCEVCouldNotCompute>(Coeff))
698 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
703 //===----------------------------------------------------------------------===//
704 // SCEV Expression folder implementations
705 //===----------------------------------------------------------------------===//
707 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
709 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
710 "This is not a truncating conversion!");
711 assert(isSCEVable(Ty) &&
712 "This is not a conversion to a SCEVable type!");
713 Ty = getEffectiveSCEVType(Ty);
716 ID.AddInteger(scTruncate);
720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
722 // Fold if the operand is constant.
723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
725 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
727 // trunc(trunc(x)) --> trunc(x)
728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
729 return getTruncateExpr(ST->getOperand(), Ty);
731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
739 // If the input value is a chrec scev, truncate the chrec's operands.
740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
741 SmallVector<const SCEV *, 4> Operands;
742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
747 // The cast wasn't folded; create an explicit cast node.
748 // Recompute the insert position, as it may have been invalidated.
749 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
750 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
751 new (S) SCEVTruncateExpr(ID, Op, Ty);
752 UniqueSCEVs.InsertNode(S, IP);
756 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
758 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
759 "This is not an extending conversion!");
760 assert(isSCEVable(Ty) &&
761 "This is not a conversion to a SCEVable type!");
762 Ty = getEffectiveSCEVType(Ty);
764 // Fold if the operand is constant.
765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
766 const Type *IntTy = getEffectiveSCEVType(Ty);
767 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
768 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
769 return getConstant(cast<ConstantInt>(C));
772 // zext(zext(x)) --> zext(x)
773 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
774 return getZeroExtendExpr(SZ->getOperand(), Ty);
776 // Before doing any expensive analysis, check to see if we've already
777 // computed a SCEV for this Op and Ty.
779 ID.AddInteger(scZeroExtend);
783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
785 // If the input value is a chrec scev, and we can prove that the value
786 // did not overflow the old, smaller, value, we can zero extend all of the
787 // operands (often constants). This allows analysis of something like
788 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
790 if (AR->isAffine()) {
791 const SCEV *Start = AR->getStart();
792 const SCEV *Step = AR->getStepRecurrence(*this);
793 unsigned BitWidth = getTypeSizeInBits(AR->getType());
794 const Loop *L = AR->getLoop();
796 // Check whether the backedge-taken count is SCEVCouldNotCompute.
797 // Note that this serves two purposes: It filters out loops that are
798 // simply not analyzable, and it covers the case where this code is
799 // being called from within backedge-taken count analysis, such that
800 // attempting to ask for the backedge-taken count would likely result
801 // in infinite recursion. In the later case, the analysis code will
802 // cope with a conservative value, and it will take care to purge
803 // that value once it has finished.
804 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
805 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
806 // Manually compute the final value for AR, checking for
809 // Check whether the backedge-taken count can be losslessly casted to
810 // the addrec's type. The count is always unsigned.
811 const SCEV *CastedMaxBECount =
812 getTruncateOrZeroExtend(MaxBECount, Start->getType());
813 const SCEV *RecastedMaxBECount =
814 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
815 if (MaxBECount == RecastedMaxBECount) {
816 const Type *WideTy = IntegerType::get(BitWidth * 2);
817 // Check whether Start+Step*MaxBECount has no unsigned overflow.
819 getMulExpr(CastedMaxBECount,
820 getTruncateOrZeroExtend(Step, Start->getType()));
821 const SCEV *Add = getAddExpr(Start, ZMul);
822 const SCEV *OperandExtendedAdd =
823 getAddExpr(getZeroExtendExpr(Start, WideTy),
824 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
825 getZeroExtendExpr(Step, WideTy)));
826 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
827 // Return the expression with the addrec on the outside.
828 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
829 getZeroExtendExpr(Step, Ty),
832 // Similar to above, only this time treat the step value as signed.
833 // This covers loops that count down.
835 getMulExpr(CastedMaxBECount,
836 getTruncateOrSignExtend(Step, Start->getType()));
837 Add = getAddExpr(Start, SMul);
839 getAddExpr(getZeroExtendExpr(Start, WideTy),
840 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
841 getSignExtendExpr(Step, WideTy)));
842 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
843 // Return the expression with the addrec on the outside.
844 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
845 getSignExtendExpr(Step, Ty),
849 // If the backedge is guarded by a comparison with the pre-inc value
850 // the addrec is safe. Also, if the entry is guarded by a comparison
851 // with the start value and the backedge is guarded by a comparison
852 // with the post-inc value, the addrec is safe.
853 if (isKnownPositive(Step)) {
854 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
855 getUnsignedRange(Step).getUnsignedMax());
856 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
857 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
858 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
859 AR->getPostIncExpr(*this), N)))
860 // Return the expression with the addrec on the outside.
861 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
862 getZeroExtendExpr(Step, Ty),
864 } else if (isKnownNegative(Step)) {
865 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
866 getSignedRange(Step).getSignedMin());
867 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
868 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
869 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
870 AR->getPostIncExpr(*this), N)))
871 // Return the expression with the addrec on the outside.
872 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
873 getSignExtendExpr(Step, Ty),
879 // The cast wasn't folded; create an explicit cast node.
880 // Recompute the insert position, as it may have been invalidated.
881 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
882 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
883 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
884 UniqueSCEVs.InsertNode(S, IP);
888 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
890 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
891 "This is not an extending conversion!");
892 assert(isSCEVable(Ty) &&
893 "This is not a conversion to a SCEVable type!");
894 Ty = getEffectiveSCEVType(Ty);
896 // Fold if the operand is constant.
897 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
898 const Type *IntTy = getEffectiveSCEVType(Ty);
899 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
900 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
901 return getConstant(cast<ConstantInt>(C));
904 // sext(sext(x)) --> sext(x)
905 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
906 return getSignExtendExpr(SS->getOperand(), Ty);
908 // Before doing any expensive analysis, check to see if we've already
909 // computed a SCEV for this Op and Ty.
911 ID.AddInteger(scSignExtend);
915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
917 // If the input value is a chrec scev, and we can prove that the value
918 // did not overflow the old, smaller, value, we can sign extend all of the
919 // operands (often constants). This allows analysis of something like
920 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
921 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
922 if (AR->isAffine()) {
923 const SCEV *Start = AR->getStart();
924 const SCEV *Step = AR->getStepRecurrence(*this);
925 unsigned BitWidth = getTypeSizeInBits(AR->getType());
926 const Loop *L = AR->getLoop();
928 // Check whether the backedge-taken count is SCEVCouldNotCompute.
929 // Note that this serves two purposes: It filters out loops that are
930 // simply not analyzable, and it covers the case where this code is
931 // being called from within backedge-taken count analysis, such that
932 // attempting to ask for the backedge-taken count would likely result
933 // in infinite recursion. In the later case, the analysis code will
934 // cope with a conservative value, and it will take care to purge
935 // that value once it has finished.
936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
937 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
938 // Manually compute the final value for AR, checking for
941 // Check whether the backedge-taken count can be losslessly casted to
942 // the addrec's type. The count is always unsigned.
943 const SCEV *CastedMaxBECount =
944 getTruncateOrZeroExtend(MaxBECount, Start->getType());
945 const SCEV *RecastedMaxBECount =
946 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
947 if (MaxBECount == RecastedMaxBECount) {
948 const Type *WideTy = IntegerType::get(BitWidth * 2);
949 // Check whether Start+Step*MaxBECount has no signed overflow.
951 getMulExpr(CastedMaxBECount,
952 getTruncateOrSignExtend(Step, Start->getType()));
953 const SCEV *Add = getAddExpr(Start, SMul);
954 const SCEV *OperandExtendedAdd =
955 getAddExpr(getSignExtendExpr(Start, WideTy),
956 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
957 getSignExtendExpr(Step, WideTy)));
958 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
959 // Return the expression with the addrec on the outside.
960 return getAddRecExpr(getSignExtendExpr(Start, Ty),
961 getSignExtendExpr(Step, Ty),
964 // Similar to above, only this time treat the step value as unsigned.
965 // This covers loops that count up with an unsigned step.
967 getMulExpr(CastedMaxBECount,
968 getTruncateOrZeroExtend(Step, Start->getType()));
969 Add = getAddExpr(Start, UMul);
971 getAddExpr(getZeroExtendExpr(Start, WideTy),
972 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
973 getZeroExtendExpr(Step, WideTy)));
974 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
975 // Return the expression with the addrec on the outside.
976 return getAddRecExpr(getSignExtendExpr(Start, Ty),
977 getZeroExtendExpr(Step, Ty),
981 // If the backedge is guarded by a comparison with the pre-inc value
982 // the addrec is safe. Also, if the entry is guarded by a comparison
983 // with the start value and the backedge is guarded by a comparison
984 // with the post-inc value, the addrec is safe.
985 if (isKnownPositive(Step)) {
986 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
987 getSignedRange(Step).getSignedMax());
988 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
989 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
990 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
991 AR->getPostIncExpr(*this), N)))
992 // Return the expression with the addrec on the outside.
993 return getAddRecExpr(getSignExtendExpr(Start, Ty),
994 getSignExtendExpr(Step, Ty),
996 } else if (isKnownNegative(Step)) {
997 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
998 getSignedRange(Step).getSignedMin());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1000 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1002 AR->getPostIncExpr(*this), N)))
1003 // Return the expression with the addrec on the outside.
1004 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1005 getSignExtendExpr(Step, Ty),
1011 // The cast wasn't folded; create an explicit cast node.
1012 // Recompute the insert position, as it may have been invalidated.
1013 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1014 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1015 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1016 UniqueSCEVs.InsertNode(S, IP);
1020 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1021 /// unspecified bits out to the given type.
1023 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1025 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1026 "This is not an extending conversion!");
1027 assert(isSCEVable(Ty) &&
1028 "This is not a conversion to a SCEVable type!");
1029 Ty = getEffectiveSCEVType(Ty);
1031 // Sign-extend negative constants.
1032 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1033 if (SC->getValue()->getValue().isNegative())
1034 return getSignExtendExpr(Op, Ty);
1036 // Peel off a truncate cast.
1037 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1038 const SCEV *NewOp = T->getOperand();
1039 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1040 return getAnyExtendExpr(NewOp, Ty);
1041 return getTruncateOrNoop(NewOp, Ty);
1044 // Next try a zext cast. If the cast is folded, use it.
1045 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1046 if (!isa<SCEVZeroExtendExpr>(ZExt))
1049 // Next try a sext cast. If the cast is folded, use it.
1050 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1051 if (!isa<SCEVSignExtendExpr>(SExt))
1054 // If the expression is obviously signed, use the sext cast value.
1055 if (isa<SCEVSMaxExpr>(Op))
1058 // Absent any other information, use the zext cast value.
1062 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1063 /// a list of operands to be added under the given scale, update the given
1064 /// map. This is a helper function for getAddRecExpr. As an example of
1065 /// what it does, given a sequence of operands that would form an add
1066 /// expression like this:
1068 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1070 /// where A and B are constants, update the map with these values:
1072 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1074 /// and add 13 + A*B*29 to AccumulatedConstant.
1075 /// This will allow getAddRecExpr to produce this:
1077 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1079 /// This form often exposes folding opportunities that are hidden in
1080 /// the original operand list.
1082 /// Return true iff it appears that any interesting folding opportunities
1083 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1084 /// the common case where no interesting opportunities are present, and
1085 /// is also used as a check to avoid infinite recursion.
1088 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1089 SmallVector<const SCEV *, 8> &NewOps,
1090 APInt &AccumulatedConstant,
1091 const SmallVectorImpl<const SCEV *> &Ops,
1093 ScalarEvolution &SE) {
1094 bool Interesting = false;
1096 // Iterate over the add operands.
1097 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1098 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1099 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1101 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1102 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1103 // A multiplication of a constant with another add; recurse.
1105 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1106 cast<SCEVAddExpr>(Mul->getOperand(1))
1110 // A multiplication of a constant with some other value. Update
1112 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1113 const SCEV *Key = SE.getMulExpr(MulOps);
1114 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1115 M.insert(std::make_pair(Key, NewScale));
1117 NewOps.push_back(Pair.first->first);
1119 Pair.first->second += NewScale;
1120 // The map already had an entry for this value, which may indicate
1121 // a folding opportunity.
1125 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1126 // Pull a buried constant out to the outside.
1127 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1129 AccumulatedConstant += Scale * C->getValue()->getValue();
1131 // An ordinary operand. Update the map.
1132 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1133 M.insert(std::make_pair(Ops[i], Scale));
1135 NewOps.push_back(Pair.first->first);
1137 Pair.first->second += Scale;
1138 // The map already had an entry for this value, which may indicate
1139 // a folding opportunity.
1149 struct APIntCompare {
1150 bool operator()(const APInt &LHS, const APInt &RHS) const {
1151 return LHS.ult(RHS);
1156 /// getAddExpr - Get a canonical add expression, or something simpler if
1158 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1159 assert(!Ops.empty() && "Cannot get empty add!");
1160 if (Ops.size() == 1) return Ops[0];
1162 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1163 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1164 getEffectiveSCEVType(Ops[0]->getType()) &&
1165 "SCEVAddExpr operand types don't match!");
1168 // Sort by complexity, this groups all similar expression types together.
1169 GroupByComplexity(Ops, LI);
1171 // If there are any constants, fold them together.
1173 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1175 assert(Idx < Ops.size());
1176 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1177 // We found two constants, fold them together!
1178 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1179 RHSC->getValue()->getValue());
1180 if (Ops.size() == 2) return Ops[0];
1181 Ops.erase(Ops.begin()+1); // Erase the folded element
1182 LHSC = cast<SCEVConstant>(Ops[0]);
1185 // If we are left with a constant zero being added, strip it off.
1186 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1187 Ops.erase(Ops.begin());
1192 if (Ops.size() == 1) return Ops[0];
1194 // Okay, check to see if the same value occurs in the operand list twice. If
1195 // so, merge them together into an multiply expression. Since we sorted the
1196 // list, these values are required to be adjacent.
1197 const Type *Ty = Ops[0]->getType();
1198 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1199 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1200 // Found a match, merge the two values into a multiply, and add any
1201 // remaining values to the result.
1202 const SCEV *Two = getIntegerSCEV(2, Ty);
1203 const SCEV *Mul = getMulExpr(Ops[i], Two);
1204 if (Ops.size() == 2)
1206 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1208 return getAddExpr(Ops);
1211 // Check for truncates. If all the operands are truncated from the same
1212 // type, see if factoring out the truncate would permit the result to be
1213 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1214 // if the contents of the resulting outer trunc fold to something simple.
1215 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1216 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1217 const Type *DstType = Trunc->getType();
1218 const Type *SrcType = Trunc->getOperand()->getType();
1219 SmallVector<const SCEV *, 8> LargeOps;
1221 // Check all the operands to see if they can be represented in the
1222 // source type of the truncate.
1223 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1224 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1225 if (T->getOperand()->getType() != SrcType) {
1229 LargeOps.push_back(T->getOperand());
1230 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1231 // This could be either sign or zero extension, but sign extension
1232 // is much more likely to be foldable here.
1233 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1234 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1235 SmallVector<const SCEV *, 8> LargeMulOps;
1236 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1237 if (const SCEVTruncateExpr *T =
1238 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1239 if (T->getOperand()->getType() != SrcType) {
1243 LargeMulOps.push_back(T->getOperand());
1244 } else if (const SCEVConstant *C =
1245 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1246 // This could be either sign or zero extension, but sign extension
1247 // is much more likely to be foldable here.
1248 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1255 LargeOps.push_back(getMulExpr(LargeMulOps));
1262 // Evaluate the expression in the larger type.
1263 const SCEV *Fold = getAddExpr(LargeOps);
1264 // If it folds to something simple, use it. Otherwise, don't.
1265 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1266 return getTruncateExpr(Fold, DstType);
1270 // Skip past any other cast SCEVs.
1271 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1274 // If there are add operands they would be next.
1275 if (Idx < Ops.size()) {
1276 bool DeletedAdd = false;
1277 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1278 // If we have an add, expand the add operands onto the end of the operands
1280 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1281 Ops.erase(Ops.begin()+Idx);
1285 // If we deleted at least one add, we added operands to the end of the list,
1286 // and they are not necessarily sorted. Recurse to resort and resimplify
1287 // any operands we just aquired.
1289 return getAddExpr(Ops);
1292 // Skip over the add expression until we get to a multiply.
1293 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1296 // Check to see if there are any folding opportunities present with
1297 // operands multiplied by constant values.
1298 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1299 uint64_t BitWidth = getTypeSizeInBits(Ty);
1300 DenseMap<const SCEV *, APInt> M;
1301 SmallVector<const SCEV *, 8> NewOps;
1302 APInt AccumulatedConstant(BitWidth, 0);
1303 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1304 Ops, APInt(BitWidth, 1), *this)) {
1305 // Some interesting folding opportunity is present, so its worthwhile to
1306 // re-generate the operands list. Group the operands by constant scale,
1307 // to avoid multiplying by the same constant scale multiple times.
1308 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1309 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1310 E = NewOps.end(); I != E; ++I)
1311 MulOpLists[M.find(*I)->second].push_back(*I);
1312 // Re-generate the operands list.
1314 if (AccumulatedConstant != 0)
1315 Ops.push_back(getConstant(AccumulatedConstant));
1316 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1317 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1319 Ops.push_back(getMulExpr(getConstant(I->first),
1320 getAddExpr(I->second)));
1322 return getIntegerSCEV(0, Ty);
1323 if (Ops.size() == 1)
1325 return getAddExpr(Ops);
1329 // If we are adding something to a multiply expression, make sure the
1330 // something is not already an operand of the multiply. If so, merge it into
1332 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1333 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1334 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1335 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1336 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1337 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1338 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1339 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1340 if (Mul->getNumOperands() != 2) {
1341 // If the multiply has more than two operands, we must get the
1343 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1344 MulOps.erase(MulOps.begin()+MulOp);
1345 InnerMul = getMulExpr(MulOps);
1347 const SCEV *One = getIntegerSCEV(1, Ty);
1348 const SCEV *AddOne = getAddExpr(InnerMul, One);
1349 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1350 if (Ops.size() == 2) return OuterMul;
1352 Ops.erase(Ops.begin()+AddOp);
1353 Ops.erase(Ops.begin()+Idx-1);
1355 Ops.erase(Ops.begin()+Idx);
1356 Ops.erase(Ops.begin()+AddOp-1);
1358 Ops.push_back(OuterMul);
1359 return getAddExpr(Ops);
1362 // Check this multiply against other multiplies being added together.
1363 for (unsigned OtherMulIdx = Idx+1;
1364 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1366 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1367 // If MulOp occurs in OtherMul, we can fold the two multiplies
1369 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1370 OMulOp != e; ++OMulOp)
1371 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1372 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1373 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1374 if (Mul->getNumOperands() != 2) {
1375 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1377 MulOps.erase(MulOps.begin()+MulOp);
1378 InnerMul1 = getMulExpr(MulOps);
1380 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1381 if (OtherMul->getNumOperands() != 2) {
1382 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1383 OtherMul->op_end());
1384 MulOps.erase(MulOps.begin()+OMulOp);
1385 InnerMul2 = getMulExpr(MulOps);
1387 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1388 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1389 if (Ops.size() == 2) return OuterMul;
1390 Ops.erase(Ops.begin()+Idx);
1391 Ops.erase(Ops.begin()+OtherMulIdx-1);
1392 Ops.push_back(OuterMul);
1393 return getAddExpr(Ops);
1399 // If there are any add recurrences in the operands list, see if any other
1400 // added values are loop invariant. If so, we can fold them into the
1402 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1405 // Scan over all recurrences, trying to fold loop invariants into them.
1406 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1407 // Scan all of the other operands to this add and add them to the vector if
1408 // they are loop invariant w.r.t. the recurrence.
1409 SmallVector<const SCEV *, 8> LIOps;
1410 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1411 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1412 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1413 LIOps.push_back(Ops[i]);
1414 Ops.erase(Ops.begin()+i);
1418 // If we found some loop invariants, fold them into the recurrence.
1419 if (!LIOps.empty()) {
1420 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1421 LIOps.push_back(AddRec->getStart());
1423 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1425 AddRecOps[0] = getAddExpr(LIOps);
1427 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1428 // If all of the other operands were loop invariant, we are done.
1429 if (Ops.size() == 1) return NewRec;
1431 // Otherwise, add the folded AddRec by the non-liv parts.
1432 for (unsigned i = 0;; ++i)
1433 if (Ops[i] == AddRec) {
1437 return getAddExpr(Ops);
1440 // Okay, if there weren't any loop invariants to be folded, check to see if
1441 // there are multiple AddRec's with the same loop induction variable being
1442 // added together. If so, we can fold them.
1443 for (unsigned OtherIdx = Idx+1;
1444 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1445 if (OtherIdx != Idx) {
1446 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1447 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1448 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1449 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1451 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1452 if (i >= NewOps.size()) {
1453 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1454 OtherAddRec->op_end());
1457 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1459 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1461 if (Ops.size() == 2) return NewAddRec;
1463 Ops.erase(Ops.begin()+Idx);
1464 Ops.erase(Ops.begin()+OtherIdx-1);
1465 Ops.push_back(NewAddRec);
1466 return getAddExpr(Ops);
1470 // Otherwise couldn't fold anything into this recurrence. Move onto the
1474 // Okay, it looks like we really DO need an add expr. Check to see if we
1475 // already have one, otherwise create a new one.
1476 FoldingSetNodeID ID;
1477 ID.AddInteger(scAddExpr);
1478 ID.AddInteger(Ops.size());
1479 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1480 ID.AddPointer(Ops[i]);
1482 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1483 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1484 new (S) SCEVAddExpr(ID, Ops);
1485 UniqueSCEVs.InsertNode(S, IP);
1490 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1492 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1493 assert(!Ops.empty() && "Cannot get empty mul!");
1495 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1496 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1497 getEffectiveSCEVType(Ops[0]->getType()) &&
1498 "SCEVMulExpr operand types don't match!");
1501 // Sort by complexity, this groups all similar expression types together.
1502 GroupByComplexity(Ops, LI);
1504 // If there are any constants, fold them together.
1506 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1508 // C1*(C2+V) -> C1*C2 + C1*V
1509 if (Ops.size() == 2)
1510 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1511 if (Add->getNumOperands() == 2 &&
1512 isa<SCEVConstant>(Add->getOperand(0)))
1513 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1514 getMulExpr(LHSC, Add->getOperand(1)));
1518 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1519 // We found two constants, fold them together!
1520 ConstantInt *Fold = Context->getConstantInt(LHSC->getValue()->getValue() *
1521 RHSC->getValue()->getValue());
1522 Ops[0] = getConstant(Fold);
1523 Ops.erase(Ops.begin()+1); // Erase the folded element
1524 if (Ops.size() == 1) return Ops[0];
1525 LHSC = cast<SCEVConstant>(Ops[0]);
1528 // If we are left with a constant one being multiplied, strip it off.
1529 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1530 Ops.erase(Ops.begin());
1532 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1533 // If we have a multiply of zero, it will always be zero.
1538 // Skip over the add expression until we get to a multiply.
1539 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1542 if (Ops.size() == 1)
1545 // If there are mul operands inline them all into this expression.
1546 if (Idx < Ops.size()) {
1547 bool DeletedMul = false;
1548 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1549 // If we have an mul, expand the mul operands onto the end of the operands
1551 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1552 Ops.erase(Ops.begin()+Idx);
1556 // If we deleted at least one mul, we added operands to the end of the list,
1557 // and they are not necessarily sorted. Recurse to resort and resimplify
1558 // any operands we just aquired.
1560 return getMulExpr(Ops);
1563 // If there are any add recurrences in the operands list, see if any other
1564 // added values are loop invariant. If so, we can fold them into the
1566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1569 // Scan over all recurrences, trying to fold loop invariants into them.
1570 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1571 // Scan all of the other operands to this mul and add them to the vector if
1572 // they are loop invariant w.r.t. the recurrence.
1573 SmallVector<const SCEV *, 8> LIOps;
1574 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1575 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1576 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1577 LIOps.push_back(Ops[i]);
1578 Ops.erase(Ops.begin()+i);
1582 // If we found some loop invariants, fold them into the recurrence.
1583 if (!LIOps.empty()) {
1584 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1585 SmallVector<const SCEV *, 4> NewOps;
1586 NewOps.reserve(AddRec->getNumOperands());
1587 if (LIOps.size() == 1) {
1588 const SCEV *Scale = LIOps[0];
1589 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1590 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1592 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1593 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1594 MulOps.push_back(AddRec->getOperand(i));
1595 NewOps.push_back(getMulExpr(MulOps));
1599 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1601 // If all of the other operands were loop invariant, we are done.
1602 if (Ops.size() == 1) return NewRec;
1604 // Otherwise, multiply the folded AddRec by the non-liv parts.
1605 for (unsigned i = 0;; ++i)
1606 if (Ops[i] == AddRec) {
1610 return getMulExpr(Ops);
1613 // Okay, if there weren't any loop invariants to be folded, check to see if
1614 // there are multiple AddRec's with the same loop induction variable being
1615 // multiplied together. If so, we can fold them.
1616 for (unsigned OtherIdx = Idx+1;
1617 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1618 if (OtherIdx != Idx) {
1619 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1620 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1621 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1622 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1623 const SCEV *NewStart = getMulExpr(F->getStart(),
1625 const SCEV *B = F->getStepRecurrence(*this);
1626 const SCEV *D = G->getStepRecurrence(*this);
1627 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1630 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1632 if (Ops.size() == 2) return NewAddRec;
1634 Ops.erase(Ops.begin()+Idx);
1635 Ops.erase(Ops.begin()+OtherIdx-1);
1636 Ops.push_back(NewAddRec);
1637 return getMulExpr(Ops);
1641 // Otherwise couldn't fold anything into this recurrence. Move onto the
1645 // Okay, it looks like we really DO need an mul expr. Check to see if we
1646 // already have one, otherwise create a new one.
1647 FoldingSetNodeID ID;
1648 ID.AddInteger(scMulExpr);
1649 ID.AddInteger(Ops.size());
1650 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1651 ID.AddPointer(Ops[i]);
1653 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1654 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1655 new (S) SCEVMulExpr(ID, Ops);
1656 UniqueSCEVs.InsertNode(S, IP);
1660 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1662 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1664 assert(getEffectiveSCEVType(LHS->getType()) ==
1665 getEffectiveSCEVType(RHS->getType()) &&
1666 "SCEVUDivExpr operand types don't match!");
1668 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1669 if (RHSC->getValue()->equalsInt(1))
1670 return LHS; // X udiv 1 --> x
1672 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1674 // Determine if the division can be folded into the operands of
1676 // TODO: Generalize this to non-constants by using known-bits information.
1677 const Type *Ty = LHS->getType();
1678 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1679 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1680 // For non-power-of-two values, effectively round the value up to the
1681 // nearest power of two.
1682 if (!RHSC->getValue()->getValue().isPowerOf2())
1684 const IntegerType *ExtTy =
1685 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1686 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1688 if (const SCEVConstant *Step =
1689 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1690 if (!Step->getValue()->getValue()
1691 .urem(RHSC->getValue()->getValue()) &&
1692 getZeroExtendExpr(AR, ExtTy) ==
1693 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1694 getZeroExtendExpr(Step, ExtTy),
1696 SmallVector<const SCEV *, 4> Operands;
1697 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1698 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1699 return getAddRecExpr(Operands, AR->getLoop());
1701 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1702 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1703 SmallVector<const SCEV *, 4> Operands;
1704 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1705 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1706 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1707 // Find an operand that's safely divisible.
1708 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1709 const SCEV *Op = M->getOperand(i);
1710 const SCEV *Div = getUDivExpr(Op, RHSC);
1711 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1712 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1713 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1716 return getMulExpr(Operands);
1720 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1721 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1722 SmallVector<const SCEV *, 4> Operands;
1723 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1724 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1725 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1727 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1728 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1729 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1731 Operands.push_back(Op);
1733 if (Operands.size() == A->getNumOperands())
1734 return getAddExpr(Operands);
1738 // Fold if both operands are constant.
1739 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1740 Constant *LHSCV = LHSC->getValue();
1741 Constant *RHSCV = RHSC->getValue();
1742 return getConstant(cast<ConstantInt>(Context->getConstantExprUDiv(LHSCV,
1747 FoldingSetNodeID ID;
1748 ID.AddInteger(scUDivExpr);
1752 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1753 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1754 new (S) SCEVUDivExpr(ID, LHS, RHS);
1755 UniqueSCEVs.InsertNode(S, IP);
1760 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1761 /// Simplify the expression as much as possible.
1762 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1763 const SCEV *Step, const Loop *L) {
1764 SmallVector<const SCEV *, 4> Operands;
1765 Operands.push_back(Start);
1766 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1767 if (StepChrec->getLoop() == L) {
1768 Operands.insert(Operands.end(), StepChrec->op_begin(),
1769 StepChrec->op_end());
1770 return getAddRecExpr(Operands, L);
1773 Operands.push_back(Step);
1774 return getAddRecExpr(Operands, L);
1777 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1778 /// Simplify the expression as much as possible.
1780 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1782 if (Operands.size() == 1) return Operands[0];
1784 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1785 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1786 getEffectiveSCEVType(Operands[0]->getType()) &&
1787 "SCEVAddRecExpr operand types don't match!");
1790 if (Operands.back()->isZero()) {
1791 Operands.pop_back();
1792 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1795 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1796 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1797 const Loop* NestedLoop = NestedAR->getLoop();
1798 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1799 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1800 NestedAR->op_end());
1801 Operands[0] = NestedAR->getStart();
1802 // AddRecs require their operands be loop-invariant with respect to their
1803 // loops. Don't perform this transformation if it would break this
1805 bool AllInvariant = true;
1806 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1807 if (!Operands[i]->isLoopInvariant(L)) {
1808 AllInvariant = false;
1812 NestedOperands[0] = getAddRecExpr(Operands, L);
1813 AllInvariant = true;
1814 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1815 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1816 AllInvariant = false;
1820 // Ok, both add recurrences are valid after the transformation.
1821 return getAddRecExpr(NestedOperands, NestedLoop);
1823 // Reset Operands to its original state.
1824 Operands[0] = NestedAR;
1828 FoldingSetNodeID ID;
1829 ID.AddInteger(scAddRecExpr);
1830 ID.AddInteger(Operands.size());
1831 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1832 ID.AddPointer(Operands[i]);
1835 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1836 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1837 new (S) SCEVAddRecExpr(ID, Operands, L);
1838 UniqueSCEVs.InsertNode(S, IP);
1842 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1844 SmallVector<const SCEV *, 2> Ops;
1847 return getSMaxExpr(Ops);
1851 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1852 assert(!Ops.empty() && "Cannot get empty smax!");
1853 if (Ops.size() == 1) return Ops[0];
1855 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1856 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1857 getEffectiveSCEVType(Ops[0]->getType()) &&
1858 "SCEVSMaxExpr operand types don't match!");
1861 // Sort by complexity, this groups all similar expression types together.
1862 GroupByComplexity(Ops, LI);
1864 // If there are any constants, fold them together.
1866 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1868 assert(Idx < Ops.size());
1869 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1870 // We found two constants, fold them together!
1871 ConstantInt *Fold = Context->getConstantInt(
1872 APIntOps::smax(LHSC->getValue()->getValue(),
1873 RHSC->getValue()->getValue()));
1874 Ops[0] = getConstant(Fold);
1875 Ops.erase(Ops.begin()+1); // Erase the folded element
1876 if (Ops.size() == 1) return Ops[0];
1877 LHSC = cast<SCEVConstant>(Ops[0]);
1880 // If we are left with a constant minimum-int, strip it off.
1881 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1882 Ops.erase(Ops.begin());
1884 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1885 // If we have an smax with a constant maximum-int, it will always be
1891 if (Ops.size() == 1) return Ops[0];
1893 // Find the first SMax
1894 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1897 // Check to see if one of the operands is an SMax. If so, expand its operands
1898 // onto our operand list, and recurse to simplify.
1899 if (Idx < Ops.size()) {
1900 bool DeletedSMax = false;
1901 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1902 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1903 Ops.erase(Ops.begin()+Idx);
1908 return getSMaxExpr(Ops);
1911 // Okay, check to see if the same value occurs in the operand list twice. If
1912 // so, delete one. Since we sorted the list, these values are required to
1914 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1915 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1916 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1920 if (Ops.size() == 1) return Ops[0];
1922 assert(!Ops.empty() && "Reduced smax down to nothing!");
1924 // Okay, it looks like we really DO need an smax expr. Check to see if we
1925 // already have one, otherwise create a new one.
1926 FoldingSetNodeID ID;
1927 ID.AddInteger(scSMaxExpr);
1928 ID.AddInteger(Ops.size());
1929 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1930 ID.AddPointer(Ops[i]);
1932 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1933 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1934 new (S) SCEVSMaxExpr(ID, Ops);
1935 UniqueSCEVs.InsertNode(S, IP);
1939 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1941 SmallVector<const SCEV *, 2> Ops;
1944 return getUMaxExpr(Ops);
1948 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1949 assert(!Ops.empty() && "Cannot get empty umax!");
1950 if (Ops.size() == 1) return Ops[0];
1952 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1953 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1954 getEffectiveSCEVType(Ops[0]->getType()) &&
1955 "SCEVUMaxExpr operand types don't match!");
1958 // Sort by complexity, this groups all similar expression types together.
1959 GroupByComplexity(Ops, LI);
1961 // If there are any constants, fold them together.
1963 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1965 assert(Idx < Ops.size());
1966 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1967 // We found two constants, fold them together!
1968 ConstantInt *Fold = Context->getConstantInt(
1969 APIntOps::umax(LHSC->getValue()->getValue(),
1970 RHSC->getValue()->getValue()));
1971 Ops[0] = getConstant(Fold);
1972 Ops.erase(Ops.begin()+1); // Erase the folded element
1973 if (Ops.size() == 1) return Ops[0];
1974 LHSC = cast<SCEVConstant>(Ops[0]);
1977 // If we are left with a constant minimum-int, strip it off.
1978 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1979 Ops.erase(Ops.begin());
1981 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1982 // If we have an umax with a constant maximum-int, it will always be
1988 if (Ops.size() == 1) return Ops[0];
1990 // Find the first UMax
1991 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1994 // Check to see if one of the operands is a UMax. If so, expand its operands
1995 // onto our operand list, and recurse to simplify.
1996 if (Idx < Ops.size()) {
1997 bool DeletedUMax = false;
1998 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1999 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2000 Ops.erase(Ops.begin()+Idx);
2005 return getUMaxExpr(Ops);
2008 // Okay, check to see if the same value occurs in the operand list twice. If
2009 // so, delete one. Since we sorted the list, these values are required to
2011 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2012 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2013 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2017 if (Ops.size() == 1) return Ops[0];
2019 assert(!Ops.empty() && "Reduced umax down to nothing!");
2021 // Okay, it looks like we really DO need a umax expr. Check to see if we
2022 // already have one, otherwise create a new one.
2023 FoldingSetNodeID ID;
2024 ID.AddInteger(scUMaxExpr);
2025 ID.AddInteger(Ops.size());
2026 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2027 ID.AddPointer(Ops[i]);
2029 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2030 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2031 new (S) SCEVUMaxExpr(ID, Ops);
2032 UniqueSCEVs.InsertNode(S, IP);
2036 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2038 // ~smax(~x, ~y) == smin(x, y).
2039 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2042 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2044 // ~umax(~x, ~y) == umin(x, y)
2045 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2048 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2049 // Don't attempt to do anything other than create a SCEVUnknown object
2050 // here. createSCEV only calls getUnknown after checking for all other
2051 // interesting possibilities, and any other code that calls getUnknown
2052 // is doing so in order to hide a value from SCEV canonicalization.
2054 FoldingSetNodeID ID;
2055 ID.AddInteger(scUnknown);
2058 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2059 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2060 new (S) SCEVUnknown(ID, V);
2061 UniqueSCEVs.InsertNode(S, IP);
2065 //===----------------------------------------------------------------------===//
2066 // Basic SCEV Analysis and PHI Idiom Recognition Code
2069 /// isSCEVable - Test if values of the given type are analyzable within
2070 /// the SCEV framework. This primarily includes integer types, and it
2071 /// can optionally include pointer types if the ScalarEvolution class
2072 /// has access to target-specific information.
2073 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2074 // Integers are always SCEVable.
2075 if (Ty->isInteger())
2078 // Pointers are SCEVable if TargetData information is available
2079 // to provide pointer size information.
2080 if (isa<PointerType>(Ty))
2083 // Otherwise it's not SCEVable.
2087 /// getTypeSizeInBits - Return the size in bits of the specified type,
2088 /// for which isSCEVable must return true.
2089 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2090 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2092 // If we have a TargetData, use it!
2094 return TD->getTypeSizeInBits(Ty);
2096 // Otherwise, we support only integer types.
2097 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2098 return Ty->getPrimitiveSizeInBits();
2101 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2102 /// the given type and which represents how SCEV will treat the given
2103 /// type, for which isSCEVable must return true. For pointer types,
2104 /// this is the pointer-sized integer type.
2105 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2106 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2108 if (Ty->isInteger())
2111 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2112 return TD->getIntPtrType();
2115 const SCEV *ScalarEvolution::getCouldNotCompute() {
2116 return &CouldNotCompute;
2119 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2120 /// expression and create a new one.
2121 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2122 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2124 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2125 if (I != Scalars.end()) return I->second;
2126 const SCEV *S = createSCEV(V);
2127 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2131 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2132 /// specified signed integer value and return a SCEV for the constant.
2133 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2134 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2135 return getConstant(Context->getConstantInt(ITy, Val));
2138 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2140 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2141 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2143 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
2145 const Type *Ty = V->getType();
2146 Ty = getEffectiveSCEVType(Ty);
2147 return getMulExpr(V,
2148 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty))));
2151 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2152 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2153 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2155 cast<ConstantInt>(Context->getConstantExprNot(VC->getValue())));
2157 const Type *Ty = V->getType();
2158 Ty = getEffectiveSCEVType(Ty);
2159 const SCEV *AllOnes =
2160 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty)));
2161 return getMinusSCEV(AllOnes, V);
2164 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2166 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2169 return getAddExpr(LHS, getNegativeSCEV(RHS));
2172 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2173 /// input value to the specified type. If the type must be extended, it is zero
2176 ScalarEvolution::getTruncateOrZeroExtend(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 getZeroExtendExpr(V, Ty);
2189 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2190 /// input value to the specified type. If the type must be extended, it is sign
2193 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2195 const Type *SrcTy = V->getType();
2196 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2197 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2198 "Cannot truncate or zero extend with non-integer arguments!");
2199 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2200 return V; // No conversion
2201 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2202 return getTruncateExpr(V, Ty);
2203 return getSignExtendExpr(V, Ty);
2206 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2207 /// input value to the specified type. If the type must be extended, it is zero
2208 /// extended. The conversion must not be narrowing.
2210 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2211 const Type *SrcTy = V->getType();
2212 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2213 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2214 "Cannot noop or zero extend with non-integer arguments!");
2215 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2216 "getNoopOrZeroExtend cannot truncate!");
2217 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2218 return V; // No conversion
2219 return getZeroExtendExpr(V, Ty);
2222 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2223 /// input value to the specified type. If the type must be extended, it is sign
2224 /// extended. The conversion must not be narrowing.
2226 ScalarEvolution::getNoopOrSignExtend(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 sign extend with non-integer arguments!");
2231 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2232 "getNoopOrSignExtend cannot truncate!");
2233 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2234 return V; // No conversion
2235 return getSignExtendExpr(V, Ty);
2238 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2239 /// the input value to the specified type. If the type must be extended,
2240 /// it is extended with unspecified bits. The conversion must not be
2243 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2244 const Type *SrcTy = V->getType();
2245 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2246 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2247 "Cannot noop or any extend with non-integer arguments!");
2248 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2249 "getNoopOrAnyExtend cannot truncate!");
2250 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2251 return V; // No conversion
2252 return getAnyExtendExpr(V, Ty);
2255 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2256 /// input value to the specified type. The conversion must not be widening.
2258 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2259 const Type *SrcTy = V->getType();
2260 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2261 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2262 "Cannot truncate or noop with non-integer arguments!");
2263 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2264 "getTruncateOrNoop cannot extend!");
2265 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2266 return V; // No conversion
2267 return getTruncateExpr(V, Ty);
2270 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2271 /// the types using zero-extension, and then perform a umax operation
2273 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2275 const SCEV *PromotedLHS = LHS;
2276 const SCEV *PromotedRHS = RHS;
2278 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2279 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2281 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2283 return getUMaxExpr(PromotedLHS, PromotedRHS);
2286 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2287 /// the types using zero-extension, and then perform a umin operation
2289 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2291 const SCEV *PromotedLHS = LHS;
2292 const SCEV *PromotedRHS = RHS;
2294 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2295 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2297 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2299 return getUMinExpr(PromotedLHS, PromotedRHS);
2302 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2303 /// the specified instruction and replaces any references to the symbolic value
2304 /// SymName with the specified value. This is used during PHI resolution.
2306 ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2307 const SCEV *SymName,
2308 const SCEV *NewVal) {
2309 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
2310 Scalars.find(SCEVCallbackVH(I, this));
2311 if (SI == Scalars.end()) return;
2314 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2315 if (NV == SI->second) return; // No change.
2317 SI->second = NV; // Update the scalars map!
2319 // Any instruction values that use this instruction might also need to be
2321 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2323 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2326 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2327 /// a loop header, making it a potential recurrence, or it doesn't.
2329 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2330 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2331 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2332 if (L->getHeader() == PN->getParent()) {
2333 // If it lives in the loop header, it has two incoming values, one
2334 // from outside the loop, and one from inside.
2335 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2336 unsigned BackEdge = IncomingEdge^1;
2338 // While we are analyzing this PHI node, handle its value symbolically.
2339 const SCEV *SymbolicName = getUnknown(PN);
2340 assert(Scalars.find(PN) == Scalars.end() &&
2341 "PHI node already processed?");
2342 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2344 // Using this symbolic name for the PHI, analyze the value coming around
2346 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2348 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2349 // has a special value for the first iteration of the loop.
2351 // If the value coming around the backedge is an add with the symbolic
2352 // value we just inserted, then we found a simple induction variable!
2353 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2354 // If there is a single occurrence of the symbolic value, replace it
2355 // with a recurrence.
2356 unsigned FoundIndex = Add->getNumOperands();
2357 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2358 if (Add->getOperand(i) == SymbolicName)
2359 if (FoundIndex == e) {
2364 if (FoundIndex != Add->getNumOperands()) {
2365 // Create an add with everything but the specified operand.
2366 SmallVector<const SCEV *, 8> Ops;
2367 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2368 if (i != FoundIndex)
2369 Ops.push_back(Add->getOperand(i));
2370 const SCEV *Accum = getAddExpr(Ops);
2372 // This is not a valid addrec if the step amount is varying each
2373 // loop iteration, but is not itself an addrec in this loop.
2374 if (Accum->isLoopInvariant(L) ||
2375 (isa<SCEVAddRecExpr>(Accum) &&
2376 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2377 const SCEV *StartVal =
2378 getSCEV(PN->getIncomingValue(IncomingEdge));
2379 const SCEV *PHISCEV =
2380 getAddRecExpr(StartVal, Accum, L);
2382 // Okay, for the entire analysis of this edge we assumed the PHI
2383 // to be symbolic. We now need to go back and update all of the
2384 // entries for the scalars that use the PHI (except for the PHI
2385 // itself) to use the new analyzed value instead of the "symbolic"
2387 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2391 } else if (const SCEVAddRecExpr *AddRec =
2392 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2393 // Otherwise, this could be a loop like this:
2394 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2395 // In this case, j = {1,+,1} and BEValue is j.
2396 // Because the other in-value of i (0) fits the evolution of BEValue
2397 // i really is an addrec evolution.
2398 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2399 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2401 // If StartVal = j.start - j.stride, we can use StartVal as the
2402 // initial step of the addrec evolution.
2403 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2404 AddRec->getOperand(1))) {
2405 const SCEV *PHISCEV =
2406 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2408 // Okay, for the entire analysis of this edge we assumed the PHI
2409 // to be symbolic. We now need to go back and update all of the
2410 // entries for the scalars that use the PHI (except for the PHI
2411 // itself) to use the new analyzed value instead of the "symbolic"
2413 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2419 return SymbolicName;
2422 // It's tempting to recognize PHIs with a unique incoming value, however
2423 // this leads passes like indvars to break LCSSA form. Fortunately, such
2424 // PHIs are rare, as instcombine zaps them.
2426 // If it's not a loop phi, we can't handle it yet.
2427 return getUnknown(PN);
2430 /// createNodeForGEP - Expand GEP instructions into add and multiply
2431 /// operations. This allows them to be analyzed by regular SCEV code.
2433 const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
2435 const Type *IntPtrTy = TD->getIntPtrType();
2436 Value *Base = GEP->getOperand(0);
2437 // Don't attempt to analyze GEPs over unsized objects.
2438 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2439 return getUnknown(GEP);
2440 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2441 gep_type_iterator GTI = gep_type_begin(GEP);
2442 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2446 // Compute the (potentially symbolic) offset in bytes for this index.
2447 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2448 // For a struct, add the member offset.
2449 const StructLayout &SL = *TD->getStructLayout(STy);
2450 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2451 uint64_t Offset = SL.getElementOffset(FieldNo);
2452 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
2454 // For an array, add the element offset, explicitly scaled.
2455 const SCEV *LocalOffset = getSCEV(Index);
2456 if (!isa<PointerType>(LocalOffset->getType()))
2457 // Getelementptr indicies are signed.
2458 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2460 getMulExpr(LocalOffset,
2461 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
2462 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2465 return getAddExpr(getSCEV(Base), TotalOffset);
2468 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2469 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2470 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2471 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2473 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2474 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2475 return C->getValue()->getValue().countTrailingZeros();
2477 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2478 return std::min(GetMinTrailingZeros(T->getOperand()),
2479 (uint32_t)getTypeSizeInBits(T->getType()));
2481 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2482 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2483 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2484 getTypeSizeInBits(E->getType()) : OpRes;
2487 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2488 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2489 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2490 getTypeSizeInBits(E->getType()) : OpRes;
2493 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2494 // The result is the min of all operands results.
2495 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2496 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2497 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2501 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2502 // The result is the sum of all operands results.
2503 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2504 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2505 for (unsigned i = 1, e = M->getNumOperands();
2506 SumOpRes != BitWidth && i != e; ++i)
2507 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2512 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2513 // The result is the min of all operands results.
2514 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2515 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2516 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2520 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2521 // The result is the min of all operands results.
2522 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2523 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2524 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2528 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2529 // The result is the min of all operands results.
2530 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2531 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2532 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2536 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2537 // For a SCEVUnknown, ask ValueTracking.
2538 unsigned BitWidth = getTypeSizeInBits(U->getType());
2539 APInt Mask = APInt::getAllOnesValue(BitWidth);
2540 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2541 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2542 return Zeros.countTrailingOnes();
2549 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2552 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2554 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2555 return ConstantRange(C->getValue()->getValue());
2557 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2558 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2559 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2560 X = X.add(getUnsignedRange(Add->getOperand(i)));
2564 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2565 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2566 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2567 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2571 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2572 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2573 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2574 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2578 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2579 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2580 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2581 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2585 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2586 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2587 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2591 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2592 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2593 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2596 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2597 ConstantRange X = getUnsignedRange(SExt->getOperand());
2598 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2601 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2602 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2603 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2606 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2608 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2609 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2610 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2611 if (!Trip) return FullSet;
2613 // TODO: non-affine addrec
2614 if (AddRec->isAffine()) {
2615 const Type *Ty = AddRec->getType();
2616 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2617 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2618 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2620 const SCEV *Start = AddRec->getStart();
2621 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2623 // Check for overflow.
2624 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2627 ConstantRange StartRange = getUnsignedRange(Start);
2628 ConstantRange EndRange = getUnsignedRange(End);
2629 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2630 EndRange.getUnsignedMin());
2631 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2632 EndRange.getUnsignedMax());
2633 if (Min.isMinValue() && Max.isMaxValue())
2634 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2635 return ConstantRange(Min, Max+1);
2640 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2641 // For a SCEVUnknown, ask ValueTracking.
2642 unsigned BitWidth = getTypeSizeInBits(U->getType());
2643 APInt Mask = APInt::getAllOnesValue(BitWidth);
2644 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2645 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2646 return ConstantRange(Ones, ~Zeros);
2652 /// getSignedRange - Determine the signed range for a particular SCEV.
2655 ScalarEvolution::getSignedRange(const SCEV *S) {
2657 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2658 return ConstantRange(C->getValue()->getValue());
2660 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2661 ConstantRange X = getSignedRange(Add->getOperand(0));
2662 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2663 X = X.add(getSignedRange(Add->getOperand(i)));
2667 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2668 ConstantRange X = getSignedRange(Mul->getOperand(0));
2669 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2670 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2674 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2675 ConstantRange X = getSignedRange(SMax->getOperand(0));
2676 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2677 X = X.smax(getSignedRange(SMax->getOperand(i)));
2681 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2682 ConstantRange X = getSignedRange(UMax->getOperand(0));
2683 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2684 X = X.umax(getSignedRange(UMax->getOperand(i)));
2688 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2689 ConstantRange X = getSignedRange(UDiv->getLHS());
2690 ConstantRange Y = getSignedRange(UDiv->getRHS());
2694 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2695 ConstantRange X = getSignedRange(ZExt->getOperand());
2696 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2699 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2700 ConstantRange X = getSignedRange(SExt->getOperand());
2701 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2704 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2705 ConstantRange X = getSignedRange(Trunc->getOperand());
2706 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2709 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2711 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2712 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2713 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2714 if (!Trip) return FullSet;
2716 // TODO: non-affine addrec
2717 if (AddRec->isAffine()) {
2718 const Type *Ty = AddRec->getType();
2719 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2720 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2721 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2723 const SCEV *Start = AddRec->getStart();
2724 const SCEV *Step = AddRec->getStepRecurrence(*this);
2725 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2727 // Check for overflow.
2728 if (!(isKnownPositive(Step) &&
2729 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2730 !(isKnownNegative(Step) &&
2731 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2734 ConstantRange StartRange = getSignedRange(Start);
2735 ConstantRange EndRange = getSignedRange(End);
2736 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2737 EndRange.getSignedMin());
2738 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2739 EndRange.getSignedMax());
2740 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2741 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2742 return ConstantRange(Min, Max+1);
2747 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2748 // For a SCEVUnknown, ask ValueTracking.
2749 unsigned BitWidth = getTypeSizeInBits(U->getType());
2750 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2754 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2755 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
2761 /// createSCEV - We know that there is no SCEV for the specified value.
2762 /// Analyze the expression.
2764 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2765 if (!isSCEVable(V->getType()))
2766 return getUnknown(V);
2768 unsigned Opcode = Instruction::UserOp1;
2769 if (Instruction *I = dyn_cast<Instruction>(V))
2770 Opcode = I->getOpcode();
2771 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2772 Opcode = CE->getOpcode();
2773 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2774 return getConstant(CI);
2775 else if (isa<ConstantPointerNull>(V))
2776 return getIntegerSCEV(0, V->getType());
2777 else if (isa<UndefValue>(V))
2778 return getIntegerSCEV(0, V->getType());
2780 return getUnknown(V);
2782 User *U = cast<User>(V);
2784 case Instruction::Add:
2785 return getAddExpr(getSCEV(U->getOperand(0)),
2786 getSCEV(U->getOperand(1)));
2787 case Instruction::Mul:
2788 return getMulExpr(getSCEV(U->getOperand(0)),
2789 getSCEV(U->getOperand(1)));
2790 case Instruction::UDiv:
2791 return getUDivExpr(getSCEV(U->getOperand(0)),
2792 getSCEV(U->getOperand(1)));
2793 case Instruction::Sub:
2794 return getMinusSCEV(getSCEV(U->getOperand(0)),
2795 getSCEV(U->getOperand(1)));
2796 case Instruction::And:
2797 // For an expression like x&255 that merely masks off the high bits,
2798 // use zext(trunc(x)) as the SCEV expression.
2799 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2800 if (CI->isNullValue())
2801 return getSCEV(U->getOperand(1));
2802 if (CI->isAllOnesValue())
2803 return getSCEV(U->getOperand(0));
2804 const APInt &A = CI->getValue();
2806 // Instcombine's ShrinkDemandedConstant may strip bits out of
2807 // constants, obscuring what would otherwise be a low-bits mask.
2808 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2809 // knew about to reconstruct a low-bits mask value.
2810 unsigned LZ = A.countLeadingZeros();
2811 unsigned BitWidth = A.getBitWidth();
2812 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2813 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2814 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2816 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2818 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2820 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2821 IntegerType::get(BitWidth - LZ)),
2826 case Instruction::Or:
2827 // If the RHS of the Or is a constant, we may have something like:
2828 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2829 // optimizations will transparently handle this case.
2831 // In order for this transformation to be safe, the LHS must be of the
2832 // form X*(2^n) and the Or constant must be less than 2^n.
2833 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2834 const SCEV *LHS = getSCEV(U->getOperand(0));
2835 const APInt &CIVal = CI->getValue();
2836 if (GetMinTrailingZeros(LHS) >=
2837 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2838 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2841 case Instruction::Xor:
2842 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2843 // If the RHS of the xor is a signbit, then this is just an add.
2844 // Instcombine turns add of signbit into xor as a strength reduction step.
2845 if (CI->getValue().isSignBit())
2846 return getAddExpr(getSCEV(U->getOperand(0)),
2847 getSCEV(U->getOperand(1)));
2849 // If the RHS of xor is -1, then this is a not operation.
2850 if (CI->isAllOnesValue())
2851 return getNotSCEV(getSCEV(U->getOperand(0)));
2853 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2854 // This is a variant of the check for xor with -1, and it handles
2855 // the case where instcombine has trimmed non-demanded bits out
2856 // of an xor with -1.
2857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2858 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2859 if (BO->getOpcode() == Instruction::And &&
2860 LCI->getValue() == CI->getValue())
2861 if (const SCEVZeroExtendExpr *Z =
2862 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2863 const Type *UTy = U->getType();
2864 const SCEV *Z0 = Z->getOperand();
2865 const Type *Z0Ty = Z0->getType();
2866 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2868 // If C is a low-bits mask, the zero extend is zerving to
2869 // mask off the high bits. Complement the operand and
2870 // re-apply the zext.
2871 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2872 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2874 // If C is a single bit, it may be in the sign-bit position
2875 // before the zero-extend. In this case, represent the xor
2876 // using an add, which is equivalent, and re-apply the zext.
2877 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2878 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2880 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2886 case Instruction::Shl:
2887 // Turn shift left of a constant amount into a multiply.
2888 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2889 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2890 Constant *X = Context->getConstantInt(
2891 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2892 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2896 case Instruction::LShr:
2897 // Turn logical shift right of a constant into a unsigned divide.
2898 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2899 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2900 Constant *X = Context->getConstantInt(
2901 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2902 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2906 case Instruction::AShr:
2907 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2908 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2909 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2910 if (L->getOpcode() == Instruction::Shl &&
2911 L->getOperand(1) == U->getOperand(1)) {
2912 unsigned BitWidth = getTypeSizeInBits(U->getType());
2913 uint64_t Amt = BitWidth - CI->getZExtValue();
2914 if (Amt == BitWidth)
2915 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2917 return getIntegerSCEV(0, U->getType()); // value is undefined
2919 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2920 IntegerType::get(Amt)),
2925 case Instruction::Trunc:
2926 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2928 case Instruction::ZExt:
2929 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2931 case Instruction::SExt:
2932 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2934 case Instruction::BitCast:
2935 // BitCasts are no-op casts so we just eliminate the cast.
2936 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2937 return getSCEV(U->getOperand(0));
2940 case Instruction::IntToPtr:
2941 if (!TD) break; // Without TD we can't analyze pointers.
2942 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2943 TD->getIntPtrType());
2945 case Instruction::PtrToInt:
2946 if (!TD) break; // Without TD we can't analyze pointers.
2947 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2950 case Instruction::GetElementPtr:
2951 if (!TD) break; // Without TD we can't analyze pointers.
2952 return createNodeForGEP(U);
2954 case Instruction::PHI:
2955 return createNodeForPHI(cast<PHINode>(U));
2957 case Instruction::Select:
2958 // This could be a smax or umax that was lowered earlier.
2959 // Try to recover it.
2960 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2961 Value *LHS = ICI->getOperand(0);
2962 Value *RHS = ICI->getOperand(1);
2963 switch (ICI->getPredicate()) {
2964 case ICmpInst::ICMP_SLT:
2965 case ICmpInst::ICMP_SLE:
2966 std::swap(LHS, RHS);
2968 case ICmpInst::ICMP_SGT:
2969 case ICmpInst::ICMP_SGE:
2970 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2971 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2972 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2973 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
2975 case ICmpInst::ICMP_ULT:
2976 case ICmpInst::ICMP_ULE:
2977 std::swap(LHS, RHS);
2979 case ICmpInst::ICMP_UGT:
2980 case ICmpInst::ICMP_UGE:
2981 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2982 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2983 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2984 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
2986 case ICmpInst::ICMP_NE:
2987 // n != 0 ? n : 1 -> umax(n, 1)
2988 if (LHS == U->getOperand(1) &&
2989 isa<ConstantInt>(U->getOperand(2)) &&
2990 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2991 isa<ConstantInt>(RHS) &&
2992 cast<ConstantInt>(RHS)->isZero())
2993 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2995 case ICmpInst::ICMP_EQ:
2996 // n == 0 ? 1 : n -> umax(n, 1)
2997 if (LHS == U->getOperand(2) &&
2998 isa<ConstantInt>(U->getOperand(1)) &&
2999 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3000 isa<ConstantInt>(RHS) &&
3001 cast<ConstantInt>(RHS)->isZero())
3002 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3009 default: // We cannot analyze this expression.
3013 return getUnknown(V);
3018 //===----------------------------------------------------------------------===//
3019 // Iteration Count Computation Code
3022 /// getBackedgeTakenCount - If the specified loop has a predictable
3023 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3024 /// object. The backedge-taken count is the number of times the loop header
3025 /// will be branched to from within the loop. This is one less than the
3026 /// trip count of the loop, since it doesn't count the first iteration,
3027 /// when the header is branched to from outside the loop.
3029 /// Note that it is not valid to call this method on a loop without a
3030 /// loop-invariant backedge-taken count (see
3031 /// hasLoopInvariantBackedgeTakenCount).
3033 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3034 return getBackedgeTakenInfo(L).Exact;
3037 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3038 /// return the least SCEV value that is known never to be less than the
3039 /// actual backedge taken count.
3040 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3041 return getBackedgeTakenInfo(L).Max;
3044 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3045 /// onto the given Worklist.
3047 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3048 BasicBlock *Header = L->getHeader();
3050 // Push all Loop-header PHIs onto the Worklist stack.
3051 for (BasicBlock::iterator I = Header->begin();
3052 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3053 Worklist.push_back(PN);
3056 /// PushDefUseChildren - Push users of the given Instruction
3057 /// onto the given Worklist.
3059 PushDefUseChildren(Instruction *I,
3060 SmallVectorImpl<Instruction *> &Worklist) {
3061 // Push the def-use children onto the Worklist stack.
3062 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3064 Worklist.push_back(cast<Instruction>(UI));
3067 const ScalarEvolution::BackedgeTakenInfo &
3068 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3069 // Initially insert a CouldNotCompute for this loop. If the insertion
3070 // succeeds, procede to actually compute a backedge-taken count and
3071 // update the value. The temporary CouldNotCompute value tells SCEV
3072 // code elsewhere that it shouldn't attempt to request a new
3073 // backedge-taken count, which could result in infinite recursion.
3074 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
3075 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3077 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
3078 if (ItCount.Exact != getCouldNotCompute()) {
3079 assert(ItCount.Exact->isLoopInvariant(L) &&
3080 ItCount.Max->isLoopInvariant(L) &&
3081 "Computed trip count isn't loop invariant for loop!");
3082 ++NumTripCountsComputed;
3084 // Update the value in the map.
3085 Pair.first->second = ItCount;
3087 if (ItCount.Max != getCouldNotCompute())
3088 // Update the value in the map.
3089 Pair.first->second = ItCount;
3090 if (isa<PHINode>(L->getHeader()->begin()))
3091 // Only count loops that have phi nodes as not being computable.
3092 ++NumTripCountsNotComputed;
3095 // Now that we know more about the trip count for this loop, forget any
3096 // existing SCEV values for PHI nodes in this loop since they are only
3097 // conservative estimates made without the benefit of trip count
3098 // information. This is similar to the code in
3099 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3101 if (ItCount.hasAnyInfo()) {
3102 SmallVector<Instruction *, 16> Worklist;
3103 PushLoopPHIs(L, Worklist);
3105 SmallPtrSet<Instruction *, 8> Visited;
3106 while (!Worklist.empty()) {
3107 Instruction *I = Worklist.pop_back_val();
3108 if (!Visited.insert(I)) continue;
3110 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3111 Scalars.find(static_cast<Value *>(I));
3112 if (It != Scalars.end()) {
3113 // SCEVUnknown for a PHI either means that it has an unrecognized
3114 // structure, or it's a PHI that's in the progress of being computed
3115 // by createNodeForPHI. In the former case, additional loop trip
3116 // count information isn't going to change anything. In the later
3117 // case, createNodeForPHI will perform the necessary updates on its
3118 // own when it gets to that point.
3119 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3121 ValuesAtScopes.erase(I);
3122 if (PHINode *PN = dyn_cast<PHINode>(I))
3123 ConstantEvolutionLoopExitValue.erase(PN);
3126 PushDefUseChildren(I, Worklist);
3130 return Pair.first->second;
3133 /// forgetLoopBackedgeTakenCount - This method should be called by the
3134 /// client when it has changed a loop in a way that may effect
3135 /// ScalarEvolution's ability to compute a trip count, or if the loop
3137 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3138 BackedgeTakenCounts.erase(L);
3140 SmallVector<Instruction *, 16> Worklist;
3141 PushLoopPHIs(L, Worklist);
3143 SmallPtrSet<Instruction *, 8> Visited;
3144 while (!Worklist.empty()) {
3145 Instruction *I = Worklist.pop_back_val();
3146 if (!Visited.insert(I)) continue;
3148 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3149 Scalars.find(static_cast<Value *>(I));
3150 if (It != Scalars.end()) {
3152 ValuesAtScopes.erase(I);
3153 if (PHINode *PN = dyn_cast<PHINode>(I))
3154 ConstantEvolutionLoopExitValue.erase(PN);
3157 PushDefUseChildren(I, Worklist);
3161 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3162 /// of the specified loop will execute.
3163 ScalarEvolution::BackedgeTakenInfo
3164 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3165 SmallVector<BasicBlock*, 8> ExitingBlocks;
3166 L->getExitingBlocks(ExitingBlocks);
3168 // Examine all exits and pick the most conservative values.
3169 const SCEV *BECount = getCouldNotCompute();
3170 const SCEV *MaxBECount = getCouldNotCompute();
3171 bool CouldNotComputeBECount = false;
3172 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3173 BackedgeTakenInfo NewBTI =
3174 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3176 if (NewBTI.Exact == getCouldNotCompute()) {
3177 // We couldn't compute an exact value for this exit, so
3178 // we won't be able to compute an exact value for the loop.
3179 CouldNotComputeBECount = true;
3180 BECount = getCouldNotCompute();
3181 } else if (!CouldNotComputeBECount) {
3182 if (BECount == getCouldNotCompute())
3183 BECount = NewBTI.Exact;
3185 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3187 if (MaxBECount == getCouldNotCompute())
3188 MaxBECount = NewBTI.Max;
3189 else if (NewBTI.Max != getCouldNotCompute())
3190 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3193 return BackedgeTakenInfo(BECount, MaxBECount);
3196 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3197 /// of the specified loop will execute if it exits via the specified block.
3198 ScalarEvolution::BackedgeTakenInfo
3199 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3200 BasicBlock *ExitingBlock) {
3202 // Okay, we've chosen an exiting block. See what condition causes us to
3203 // exit at this block.
3205 // FIXME: we should be able to handle switch instructions (with a single exit)
3206 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3207 if (ExitBr == 0) return getCouldNotCompute();
3208 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3210 // At this point, we know we have a conditional branch that determines whether
3211 // the loop is exited. However, we don't know if the branch is executed each
3212 // time through the loop. If not, then the execution count of the branch will
3213 // not be equal to the trip count of the loop.
3215 // Currently we check for this by checking to see if the Exit branch goes to
3216 // the loop header. If so, we know it will always execute the same number of
3217 // times as the loop. We also handle the case where the exit block *is* the
3218 // loop header. This is common for un-rotated loops.
3220 // If both of those tests fail, walk up the unique predecessor chain to the
3221 // header, stopping if there is an edge that doesn't exit the loop. If the
3222 // header is reached, the execution count of the branch will be equal to the
3223 // trip count of the loop.
3225 // More extensive analysis could be done to handle more cases here.
3227 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3228 ExitBr->getSuccessor(1) != L->getHeader() &&
3229 ExitBr->getParent() != L->getHeader()) {
3230 // The simple checks failed, try climbing the unique predecessor chain
3231 // up to the header.
3233 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3234 BasicBlock *Pred = BB->getUniquePredecessor();
3236 return getCouldNotCompute();
3237 TerminatorInst *PredTerm = Pred->getTerminator();
3238 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3239 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3242 // If the predecessor has a successor that isn't BB and isn't
3243 // outside the loop, assume the worst.
3244 if (L->contains(PredSucc))
3245 return getCouldNotCompute();
3247 if (Pred == L->getHeader()) {
3254 return getCouldNotCompute();
3257 // Procede to the next level to examine the exit condition expression.
3258 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3259 ExitBr->getSuccessor(0),
3260 ExitBr->getSuccessor(1));
3263 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3264 /// backedge of the specified loop will execute if its exit condition
3265 /// were a conditional branch of ExitCond, TBB, and FBB.
3266 ScalarEvolution::BackedgeTakenInfo
3267 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3271 // Check if the controlling expression for this loop is an And or Or.
3272 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3273 if (BO->getOpcode() == Instruction::And) {
3274 // Recurse on the operands of the and.
3275 BackedgeTakenInfo BTI0 =
3276 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3277 BackedgeTakenInfo BTI1 =
3278 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3279 const SCEV *BECount = getCouldNotCompute();
3280 const SCEV *MaxBECount = getCouldNotCompute();
3281 if (L->contains(TBB)) {
3282 // Both conditions must be true for the loop to continue executing.
3283 // Choose the less conservative count.
3284 if (BTI0.Exact == getCouldNotCompute() ||
3285 BTI1.Exact == getCouldNotCompute())
3286 BECount = getCouldNotCompute();
3288 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3289 if (BTI0.Max == getCouldNotCompute())
3290 MaxBECount = BTI1.Max;
3291 else if (BTI1.Max == getCouldNotCompute())
3292 MaxBECount = BTI0.Max;
3294 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3296 // Both conditions must be true for the loop to exit.
3297 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3298 if (BTI0.Exact != getCouldNotCompute() &&
3299 BTI1.Exact != getCouldNotCompute())
3300 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3301 if (BTI0.Max != getCouldNotCompute() &&
3302 BTI1.Max != getCouldNotCompute())
3303 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3306 return BackedgeTakenInfo(BECount, MaxBECount);
3308 if (BO->getOpcode() == Instruction::Or) {
3309 // Recurse on the operands of the or.
3310 BackedgeTakenInfo BTI0 =
3311 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3312 BackedgeTakenInfo BTI1 =
3313 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3314 const SCEV *BECount = getCouldNotCompute();
3315 const SCEV *MaxBECount = getCouldNotCompute();
3316 if (L->contains(FBB)) {
3317 // Both conditions must be false for the loop to continue executing.
3318 // Choose the less conservative count.
3319 if (BTI0.Exact == getCouldNotCompute() ||
3320 BTI1.Exact == getCouldNotCompute())
3321 BECount = getCouldNotCompute();
3323 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3324 if (BTI0.Max == getCouldNotCompute())
3325 MaxBECount = BTI1.Max;
3326 else if (BTI1.Max == getCouldNotCompute())
3327 MaxBECount = BTI0.Max;
3329 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3331 // Both conditions must be false for the loop to exit.
3332 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3333 if (BTI0.Exact != getCouldNotCompute() &&
3334 BTI1.Exact != getCouldNotCompute())
3335 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3336 if (BTI0.Max != getCouldNotCompute() &&
3337 BTI1.Max != getCouldNotCompute())
3338 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3341 return BackedgeTakenInfo(BECount, MaxBECount);
3345 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3346 // Procede to the next level to examine the icmp.
3347 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3348 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3350 // If it's not an integer or pointer comparison then compute it the hard way.
3351 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3354 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3355 /// backedge of the specified loop will execute if its exit condition
3356 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3357 ScalarEvolution::BackedgeTakenInfo
3358 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3363 // If the condition was exit on true, convert the condition to exit on false
3364 ICmpInst::Predicate Cond;
3365 if (!L->contains(FBB))
3366 Cond = ExitCond->getPredicate();
3368 Cond = ExitCond->getInversePredicate();
3370 // Handle common loops like: for (X = "string"; *X; ++X)
3371 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3372 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3374 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3375 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3376 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3377 return BackedgeTakenInfo(ItCnt,
3378 isa<SCEVConstant>(ItCnt) ? ItCnt :
3379 getConstant(APInt::getMaxValue(BitWidth)-1));
3383 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3384 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3386 // Try to evaluate any dependencies out of the loop.
3387 LHS = getSCEVAtScope(LHS, L);
3388 RHS = getSCEVAtScope(RHS, L);
3390 // At this point, we would like to compute how many iterations of the
3391 // loop the predicate will return true for these inputs.
3392 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3393 // If there is a loop-invariant, force it into the RHS.
3394 std::swap(LHS, RHS);
3395 Cond = ICmpInst::getSwappedPredicate(Cond);
3398 // If we have a comparison of a chrec against a constant, try to use value
3399 // ranges to answer this query.
3400 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3401 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3402 if (AddRec->getLoop() == L) {
3403 // Form the constant range.
3404 ConstantRange CompRange(
3405 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3407 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3408 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3412 case ICmpInst::ICMP_NE: { // while (X != Y)
3413 // Convert to: while (X-Y != 0)
3414 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3415 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3418 case ICmpInst::ICMP_EQ: {
3419 // Convert to: while (X-Y == 0) // while (X == Y)
3420 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3421 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3424 case ICmpInst::ICMP_SLT: {
3425 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3426 if (BTI.hasAnyInfo()) return BTI;
3429 case ICmpInst::ICMP_SGT: {
3430 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3431 getNotSCEV(RHS), L, true);
3432 if (BTI.hasAnyInfo()) return BTI;
3435 case ICmpInst::ICMP_ULT: {
3436 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3437 if (BTI.hasAnyInfo()) return BTI;
3440 case ICmpInst::ICMP_UGT: {
3441 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3442 getNotSCEV(RHS), L, false);
3443 if (BTI.hasAnyInfo()) return BTI;
3448 errs() << "ComputeBackedgeTakenCount ";
3449 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3450 errs() << "[unsigned] ";
3451 errs() << *LHS << " "
3452 << Instruction::getOpcodeName(Instruction::ICmp)
3453 << " " << *RHS << "\n";
3458 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3461 static ConstantInt *
3462 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3463 ScalarEvolution &SE) {
3464 const SCEV *InVal = SE.getConstant(C);
3465 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3466 assert(isa<SCEVConstant>(Val) &&
3467 "Evaluation of SCEV at constant didn't fold correctly?");
3468 return cast<SCEVConstant>(Val)->getValue();
3471 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3472 /// and a GEP expression (missing the pointer index) indexing into it, return
3473 /// the addressed element of the initializer or null if the index expression is
3476 GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
3477 const std::vector<ConstantInt*> &Indices) {
3478 Constant *Init = GV->getInitializer();
3479 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3480 uint64_t Idx = Indices[i]->getZExtValue();
3481 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3482 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3483 Init = cast<Constant>(CS->getOperand(Idx));
3484 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3485 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3486 Init = cast<Constant>(CA->getOperand(Idx));
3487 } else if (isa<ConstantAggregateZero>(Init)) {
3488 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3489 assert(Idx < STy->getNumElements() && "Bad struct index!");
3490 Init = Context->getNullValue(STy->getElementType(Idx));
3491 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3492 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3493 Init = Context->getNullValue(ATy->getElementType());
3495 llvm_unreachable("Unknown constant aggregate type!");
3499 return 0; // Unknown initializer type
3505 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3506 /// 'icmp op load X, cst', try to see if we can compute the backedge
3507 /// execution count.
3509 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3513 ICmpInst::Predicate predicate) {
3514 if (LI->isVolatile()) return getCouldNotCompute();
3516 // Check to see if the loaded pointer is a getelementptr of a global.
3517 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3518 if (!GEP) return getCouldNotCompute();
3520 // Make sure that it is really a constant global we are gepping, with an
3521 // initializer, and make sure the first IDX is really 0.
3522 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3523 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3524 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3525 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3526 return getCouldNotCompute();
3528 // Okay, we allow one non-constant index into the GEP instruction.
3530 std::vector<ConstantInt*> Indexes;
3531 unsigned VarIdxNum = 0;
3532 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3533 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3534 Indexes.push_back(CI);
3535 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3536 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3537 VarIdx = GEP->getOperand(i);
3539 Indexes.push_back(0);
3542 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3543 // Check to see if X is a loop variant variable value now.
3544 const SCEV *Idx = getSCEV(VarIdx);
3545 Idx = getSCEVAtScope(Idx, L);
3547 // We can only recognize very limited forms of loop index expressions, in
3548 // particular, only affine AddRec's like {C1,+,C2}.
3549 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3550 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3551 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3552 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3553 return getCouldNotCompute();
3555 unsigned MaxSteps = MaxBruteForceIterations;
3556 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3557 ConstantInt *ItCst = Context->getConstantInt(
3558 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3559 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3561 // Form the GEP offset.
3562 Indexes[VarIdxNum] = Val;
3564 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
3565 if (Result == 0) break; // Cannot compute!
3567 // Evaluate the condition for this iteration.
3568 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3569 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3570 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3572 errs() << "\n***\n*** Computed loop count " << *ItCst
3573 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3576 ++NumArrayLenItCounts;
3577 return getConstant(ItCst); // Found terminating iteration!
3580 return getCouldNotCompute();
3584 /// CanConstantFold - Return true if we can constant fold an instruction of the
3585 /// specified type, assuming that all operands were constants.
3586 static bool CanConstantFold(const Instruction *I) {
3587 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3588 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3591 if (const CallInst *CI = dyn_cast<CallInst>(I))
3592 if (const Function *F = CI->getCalledFunction())
3593 return canConstantFoldCallTo(F);
3597 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3598 /// in the loop that V is derived from. We allow arbitrary operations along the
3599 /// way, but the operands of an operation must either be constants or a value
3600 /// derived from a constant PHI. If this expression does not fit with these
3601 /// constraints, return null.
3602 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3603 // If this is not an instruction, or if this is an instruction outside of the
3604 // loop, it can't be derived from a loop PHI.
3605 Instruction *I = dyn_cast<Instruction>(V);
3606 if (I == 0 || !L->contains(I->getParent())) return 0;
3608 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3609 if (L->getHeader() == I->getParent())
3612 // We don't currently keep track of the control flow needed to evaluate
3613 // PHIs, so we cannot handle PHIs inside of loops.
3617 // If we won't be able to constant fold this expression even if the operands
3618 // are constants, return early.
3619 if (!CanConstantFold(I)) return 0;
3621 // Otherwise, we can evaluate this instruction if all of its operands are
3622 // constant or derived from a PHI node themselves.
3624 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3625 if (!(isa<Constant>(I->getOperand(Op)) ||
3626 isa<GlobalValue>(I->getOperand(Op)))) {
3627 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3628 if (P == 0) return 0; // Not evolving from PHI
3632 return 0; // Evolving from multiple different PHIs.
3635 // This is a expression evolving from a constant PHI!
3639 /// EvaluateExpression - Given an expression that passes the
3640 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3641 /// in the loop has the value PHIVal. If we can't fold this expression for some
3642 /// reason, return null.
3643 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3644 if (isa<PHINode>(V)) return PHIVal;
3645 if (Constant *C = dyn_cast<Constant>(V)) return C;
3646 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3647 Instruction *I = cast<Instruction>(V);
3648 LLVMContext *Context = I->getParent()->getContext();
3650 std::vector<Constant*> Operands;
3651 Operands.resize(I->getNumOperands());
3653 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3654 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3655 if (Operands[i] == 0) return 0;
3658 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3659 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3660 &Operands[0], Operands.size(),
3663 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3664 &Operands[0], Operands.size(),
3668 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3669 /// in the header of its containing loop, we know the loop executes a
3670 /// constant number of times, and the PHI node is just a recurrence
3671 /// involving constants, fold it.
3673 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3676 std::map<PHINode*, Constant*>::iterator I =
3677 ConstantEvolutionLoopExitValue.find(PN);
3678 if (I != ConstantEvolutionLoopExitValue.end())
3681 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3682 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3684 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3686 // Since the loop is canonicalized, the PHI node must have two entries. One
3687 // entry must be a constant (coming in from outside of the loop), and the
3688 // second must be derived from the same PHI.
3689 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3690 Constant *StartCST =
3691 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3693 return RetVal = 0; // Must be a constant.
3695 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3696 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3698 return RetVal = 0; // Not derived from same PHI.
3700 // Execute the loop symbolically to determine the exit value.
3701 if (BEs.getActiveBits() >= 32)
3702 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3704 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3705 unsigned IterationNum = 0;
3706 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3707 if (IterationNum == NumIterations)
3708 return RetVal = PHIVal; // Got exit value!
3710 // Compute the value of the PHI node for the next iteration.
3711 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3712 if (NextPHI == PHIVal)
3713 return RetVal = NextPHI; // Stopped evolving!
3715 return 0; // Couldn't evaluate!
3720 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3721 /// constant number of times (the condition evolves only from constants),
3722 /// try to evaluate a few iterations of the loop until we get the exit
3723 /// condition gets a value of ExitWhen (true or false). If we cannot
3724 /// evaluate the trip count of the loop, return getCouldNotCompute().
3726 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3729 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3730 if (PN == 0) return getCouldNotCompute();
3732 // Since the loop is canonicalized, the PHI node must have two entries. One
3733 // entry must be a constant (coming in from outside of the loop), and the
3734 // second must be derived from the same PHI.
3735 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3736 Constant *StartCST =
3737 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3738 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3740 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3741 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3742 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3744 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3745 // the loop symbolically to determine when the condition gets a value of
3747 unsigned IterationNum = 0;
3748 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3749 for (Constant *PHIVal = StartCST;
3750 IterationNum != MaxIterations; ++IterationNum) {
3751 ConstantInt *CondVal =
3752 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3754 // Couldn't symbolically evaluate.
3755 if (!CondVal) return getCouldNotCompute();
3757 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3758 ++NumBruteForceTripCountsComputed;
3759 return getConstant(Type::Int32Ty, IterationNum);
3762 // Compute the value of the PHI node for the next iteration.
3763 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3764 if (NextPHI == 0 || NextPHI == PHIVal)
3765 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3769 // Too many iterations were needed to evaluate.
3770 return getCouldNotCompute();
3773 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3774 /// at the specified scope in the program. The L value specifies a loop
3775 /// nest to evaluate the expression at, where null is the top-level or a
3776 /// specified loop is immediately inside of the loop.
3778 /// This method can be used to compute the exit value for a variable defined
3779 /// in a loop by querying what the value will hold in the parent loop.
3781 /// In the case that a relevant loop exit value cannot be computed, the
3782 /// original value V is returned.
3783 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3784 // FIXME: this should be turned into a virtual method on SCEV!
3786 if (isa<SCEVConstant>(V)) return V;
3788 // If this instruction is evolved from a constant-evolving PHI, compute the
3789 // exit value from the loop without using SCEVs.
3790 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3791 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3792 const Loop *LI = (*this->LI)[I->getParent()];
3793 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3794 if (PHINode *PN = dyn_cast<PHINode>(I))
3795 if (PN->getParent() == LI->getHeader()) {
3796 // Okay, there is no closed form solution for the PHI node. Check
3797 // to see if the loop that contains it has a known backedge-taken
3798 // count. If so, we may be able to force computation of the exit
3800 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3801 if (const SCEVConstant *BTCC =
3802 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3803 // Okay, we know how many times the containing loop executes. If
3804 // this is a constant evolving PHI node, get the final value at
3805 // the specified iteration number.
3806 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3807 BTCC->getValue()->getValue(),
3809 if (RV) return getSCEV(RV);
3813 // Okay, this is an expression that we cannot symbolically evaluate
3814 // into a SCEV. Check to see if it's possible to symbolically evaluate
3815 // the arguments into constants, and if so, try to constant propagate the
3816 // result. This is particularly useful for computing loop exit values.
3817 if (CanConstantFold(I)) {
3818 // Check to see if we've folded this instruction at this loop before.
3819 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3820 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3821 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3823 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3825 std::vector<Constant*> Operands;
3826 Operands.reserve(I->getNumOperands());
3827 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3828 Value *Op = I->getOperand(i);
3829 if (Constant *C = dyn_cast<Constant>(Op)) {
3830 Operands.push_back(C);
3832 // If any of the operands is non-constant and if they are
3833 // non-integer and non-pointer, don't even try to analyze them
3834 // with scev techniques.
3835 if (!isSCEVable(Op->getType()))
3838 const SCEV* OpV = getSCEVAtScope(Op, L);
3839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3840 Constant *C = SC->getValue();
3841 if (C->getType() != Op->getType())
3842 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3846 Operands.push_back(C);
3847 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3848 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3849 if (C->getType() != Op->getType())
3851 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3855 Operands.push_back(C);
3865 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3866 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3867 &Operands[0], Operands.size(),
3870 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3871 &Operands[0], Operands.size(), Context);
3872 Pair.first->second = C;
3877 // This is some other type of SCEVUnknown, just return it.
3881 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3882 // Avoid performing the look-up in the common case where the specified
3883 // expression has no loop-variant portions.
3884 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3885 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3886 if (OpAtScope != Comm->getOperand(i)) {
3887 // Okay, at least one of these operands is loop variant but might be
3888 // foldable. Build a new instance of the folded commutative expression.
3889 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3890 Comm->op_begin()+i);
3891 NewOps.push_back(OpAtScope);
3893 for (++i; i != e; ++i) {
3894 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3895 NewOps.push_back(OpAtScope);
3897 if (isa<SCEVAddExpr>(Comm))
3898 return getAddExpr(NewOps);
3899 if (isa<SCEVMulExpr>(Comm))
3900 return getMulExpr(NewOps);
3901 if (isa<SCEVSMaxExpr>(Comm))
3902 return getSMaxExpr(NewOps);
3903 if (isa<SCEVUMaxExpr>(Comm))
3904 return getUMaxExpr(NewOps);
3905 llvm_unreachable("Unknown commutative SCEV type!");
3908 // If we got here, all operands are loop invariant.
3912 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3913 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3914 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
3915 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3916 return Div; // must be loop invariant
3917 return getUDivExpr(LHS, RHS);
3920 // If this is a loop recurrence for a loop that does not contain L, then we
3921 // are dealing with the final value computed by the loop.
3922 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3923 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3924 // To evaluate this recurrence, we need to know how many times the AddRec
3925 // loop iterates. Compute this now.
3926 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3927 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
3929 // Then, evaluate the AddRec.
3930 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3935 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3936 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3937 if (Op == Cast->getOperand())
3938 return Cast; // must be loop invariant
3939 return getZeroExtendExpr(Op, Cast->getType());
3942 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3943 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3944 if (Op == Cast->getOperand())
3945 return Cast; // must be loop invariant
3946 return getSignExtendExpr(Op, Cast->getType());
3949 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3950 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3951 if (Op == Cast->getOperand())
3952 return Cast; // must be loop invariant
3953 return getTruncateExpr(Op, Cast->getType());
3956 llvm_unreachable("Unknown SCEV type!");
3960 /// getSCEVAtScope - This is a convenience function which does
3961 /// getSCEVAtScope(getSCEV(V), L).
3962 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3963 return getSCEVAtScope(getSCEV(V), L);
3966 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3967 /// following equation:
3969 /// A * X = B (mod N)
3971 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3972 /// A and B isn't important.
3974 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3975 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3976 ScalarEvolution &SE) {
3977 uint32_t BW = A.getBitWidth();
3978 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3979 assert(A != 0 && "A must be non-zero.");
3983 // The gcd of A and N may have only one prime factor: 2. The number of
3984 // trailing zeros in A is its multiplicity
3985 uint32_t Mult2 = A.countTrailingZeros();
3988 // 2. Check if B is divisible by D.
3990 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3991 // is not less than multiplicity of this prime factor for D.
3992 if (B.countTrailingZeros() < Mult2)
3993 return SE.getCouldNotCompute();
3995 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3998 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3999 // bit width during computations.
4000 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4001 APInt Mod(BW + 1, 0);
4002 Mod.set(BW - Mult2); // Mod = N / D
4003 APInt I = AD.multiplicativeInverse(Mod);
4005 // 4. Compute the minimum unsigned root of the equation:
4006 // I * (B / D) mod (N / D)
4007 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4009 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4011 return SE.getConstant(Result.trunc(BW));
4014 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4015 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4016 /// might be the same) or two SCEVCouldNotCompute objects.
4018 static std::pair<const SCEV *,const SCEV *>
4019 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4020 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4021 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4022 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4023 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4025 // We currently can only solve this if the coefficients are constants.
4026 if (!LC || !MC || !NC) {
4027 const SCEV *CNC = SE.getCouldNotCompute();
4028 return std::make_pair(CNC, CNC);
4031 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4032 const APInt &L = LC->getValue()->getValue();
4033 const APInt &M = MC->getValue()->getValue();
4034 const APInt &N = NC->getValue()->getValue();
4035 APInt Two(BitWidth, 2);
4036 APInt Four(BitWidth, 4);
4039 using namespace APIntOps;
4041 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4042 // The B coefficient is M-N/2
4046 // The A coefficient is N/2
4047 APInt A(N.sdiv(Two));
4049 // Compute the B^2-4ac term.
4052 SqrtTerm -= Four * (A * C);
4054 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4055 // integer value or else APInt::sqrt() will assert.
4056 APInt SqrtVal(SqrtTerm.sqrt());
4058 // Compute the two solutions for the quadratic formula.
4059 // The divisions must be performed as signed divisions.
4061 APInt TwoA( A << 1 );
4062 if (TwoA.isMinValue()) {
4063 const SCEV *CNC = SE.getCouldNotCompute();
4064 return std::make_pair(CNC, CNC);
4067 LLVMContext *Context = SE.getContext();
4069 ConstantInt *Solution1 =
4070 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4071 ConstantInt *Solution2 =
4072 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
4074 return std::make_pair(SE.getConstant(Solution1),
4075 SE.getConstant(Solution2));
4076 } // end APIntOps namespace
4079 /// HowFarToZero - Return the number of times a backedge comparing the specified
4080 /// value to zero will execute. If not computable, return CouldNotCompute.
4081 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4082 // If the value is a constant
4083 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4084 // If the value is already zero, the branch will execute zero times.
4085 if (C->getValue()->isZero()) return C;
4086 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4089 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4090 if (!AddRec || AddRec->getLoop() != L)
4091 return getCouldNotCompute();
4093 if (AddRec->isAffine()) {
4094 // If this is an affine expression, the execution count of this branch is
4095 // the minimum unsigned root of the following equation:
4097 // Start + Step*N = 0 (mod 2^BW)
4101 // Step*N = -Start (mod 2^BW)
4103 // where BW is the common bit width of Start and Step.
4105 // Get the initial value for the loop.
4106 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4107 L->getParentLoop());
4108 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4109 L->getParentLoop());
4111 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4112 // For now we handle only constant steps.
4114 // First, handle unitary steps.
4115 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4116 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4117 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4118 return Start; // N = Start (as unsigned)
4120 // Then, try to solve the above equation provided that Start is constant.
4121 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4122 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4123 -StartC->getValue()->getValue(),
4126 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4127 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4128 // the quadratic equation to solve it.
4129 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4131 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4132 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4135 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4136 << " sol#2: " << *R2 << "\n";
4138 // Pick the smallest positive root value.
4139 if (ConstantInt *CB =
4140 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
4141 R1->getValue(), R2->getValue()))) {
4142 if (CB->getZExtValue() == false)
4143 std::swap(R1, R2); // R1 is the minimum root now.
4145 // We can only use this value if the chrec ends up with an exact zero
4146 // value at this index. When solving for "X*X != 5", for example, we
4147 // should not accept a root of 2.
4148 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4150 return R1; // We found a quadratic root!
4155 return getCouldNotCompute();
4158 /// HowFarToNonZero - Return the number of times a backedge checking the
4159 /// specified value for nonzero will execute. If not computable, return
4161 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4162 // Loops that look like: while (X == 0) are very strange indeed. We don't
4163 // handle them yet except for the trivial case. This could be expanded in the
4164 // future as needed.
4166 // If the value is a constant, check to see if it is known to be non-zero
4167 // already. If so, the backedge will execute zero times.
4168 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4169 if (!C->getValue()->isNullValue())
4170 return getIntegerSCEV(0, C->getType());
4171 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4174 // We could implement others, but I really doubt anyone writes loops like
4175 // this, and if they did, they would already be constant folded.
4176 return getCouldNotCompute();
4179 /// getLoopPredecessor - If the given loop's header has exactly one unique
4180 /// predecessor outside the loop, return it. Otherwise return null.
4182 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4183 BasicBlock *Header = L->getHeader();
4184 BasicBlock *Pred = 0;
4185 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4187 if (!L->contains(*PI)) {
4188 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4194 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4195 /// (which may not be an immediate predecessor) which has exactly one
4196 /// successor from which BB is reachable, or null if no such block is
4200 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4201 // If the block has a unique predecessor, then there is no path from the
4202 // predecessor to the block that does not go through the direct edge
4203 // from the predecessor to the block.
4204 if (BasicBlock *Pred = BB->getSinglePredecessor())
4207 // A loop's header is defined to be a block that dominates the loop.
4208 // If the header has a unique predecessor outside the loop, it must be
4209 // a block that has exactly one successor that can reach the loop.
4210 if (Loop *L = LI->getLoopFor(BB))
4211 return getLoopPredecessor(L);
4216 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4217 /// testing whether two expressions are equal, however for the purposes of
4218 /// looking for a condition guarding a loop, it can be useful to be a little
4219 /// more general, since a front-end may have replicated the controlling
4222 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4223 // Quick check to see if they are the same SCEV.
4224 if (A == B) return true;
4226 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4227 // two different instructions with the same value. Check for this case.
4228 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4229 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4230 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4231 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4232 if (AI->isIdenticalTo(BI))
4235 // Otherwise assume they may have a different value.
4239 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4240 return getSignedRange(S).getSignedMax().isNegative();
4243 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4244 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4247 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4248 return !getSignedRange(S).getSignedMin().isNegative();
4251 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4252 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4255 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4256 return isKnownNegative(S) || isKnownPositive(S);
4259 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4260 const SCEV *LHS, const SCEV *RHS) {
4262 if (HasSameValue(LHS, RHS))
4263 return ICmpInst::isTrueWhenEqual(Pred);
4267 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4269 case ICmpInst::ICMP_SGT:
4270 Pred = ICmpInst::ICMP_SLT;
4271 std::swap(LHS, RHS);
4272 case ICmpInst::ICMP_SLT: {
4273 ConstantRange LHSRange = getSignedRange(LHS);
4274 ConstantRange RHSRange = getSignedRange(RHS);
4275 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4277 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4280 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4281 ConstantRange DiffRange = getUnsignedRange(Diff);
4282 if (isKnownNegative(Diff)) {
4283 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4285 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4287 } else if (isKnownPositive(Diff)) {
4288 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4290 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4295 case ICmpInst::ICMP_SGE:
4296 Pred = ICmpInst::ICMP_SLE;
4297 std::swap(LHS, RHS);
4298 case ICmpInst::ICMP_SLE: {
4299 ConstantRange LHSRange = getSignedRange(LHS);
4300 ConstantRange RHSRange = getSignedRange(RHS);
4301 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4303 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4306 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4307 ConstantRange DiffRange = getUnsignedRange(Diff);
4308 if (isKnownNonPositive(Diff)) {
4309 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4311 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4313 } else if (isKnownNonNegative(Diff)) {
4314 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4316 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4321 case ICmpInst::ICMP_UGT:
4322 Pred = ICmpInst::ICMP_ULT;
4323 std::swap(LHS, RHS);
4324 case ICmpInst::ICMP_ULT: {
4325 ConstantRange LHSRange = getUnsignedRange(LHS);
4326 ConstantRange RHSRange = getUnsignedRange(RHS);
4327 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4329 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4332 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4333 ConstantRange DiffRange = getUnsignedRange(Diff);
4334 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4336 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4340 case ICmpInst::ICMP_UGE:
4341 Pred = ICmpInst::ICMP_ULE;
4342 std::swap(LHS, RHS);
4343 case ICmpInst::ICMP_ULE: {
4344 ConstantRange LHSRange = getUnsignedRange(LHS);
4345 ConstantRange RHSRange = getUnsignedRange(RHS);
4346 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4348 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4351 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4352 ConstantRange DiffRange = getUnsignedRange(Diff);
4353 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4355 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4359 case ICmpInst::ICMP_NE: {
4360 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4362 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4365 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4366 if (isKnownNonZero(Diff))
4370 case ICmpInst::ICMP_EQ:
4376 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4377 /// protected by a conditional between LHS and RHS. This is used to
4378 /// to eliminate casts.
4380 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4381 ICmpInst::Predicate Pred,
4382 const SCEV *LHS, const SCEV *RHS) {
4383 // Interpret a null as meaning no loop, where there is obviously no guard
4384 // (interprocedural conditions notwithstanding).
4385 if (!L) return true;
4387 BasicBlock *Latch = L->getLoopLatch();
4391 BranchInst *LoopContinuePredicate =
4392 dyn_cast<BranchInst>(Latch->getTerminator());
4393 if (!LoopContinuePredicate ||
4394 LoopContinuePredicate->isUnconditional())
4398 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4399 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4402 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4403 /// by a conditional between LHS and RHS. This is used to help avoid max
4404 /// expressions in loop trip counts, and to eliminate casts.
4406 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4407 ICmpInst::Predicate Pred,
4408 const SCEV *LHS, const SCEV *RHS) {
4409 // Interpret a null as meaning no loop, where there is obviously no guard
4410 // (interprocedural conditions notwithstanding).
4411 if (!L) return false;
4413 BasicBlock *Predecessor = getLoopPredecessor(L);
4414 BasicBlock *PredecessorDest = L->getHeader();
4416 // Starting at the loop predecessor, climb up the predecessor chain, as long
4417 // as there are predecessors that can be found that have unique successors
4418 // leading to the original header.
4420 PredecessorDest = Predecessor,
4421 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4423 BranchInst *LoopEntryPredicate =
4424 dyn_cast<BranchInst>(Predecessor->getTerminator());
4425 if (!LoopEntryPredicate ||
4426 LoopEntryPredicate->isUnconditional())
4429 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4430 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4437 /// isNecessaryCond - Test whether the condition described by Pred, LHS,
4438 /// and RHS is a necessary condition for the given Cond value to evaluate
4440 bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4441 ICmpInst::Predicate Pred,
4442 const SCEV *LHS, const SCEV *RHS,
4444 // Recursivly handle And and Or conditions.
4445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4446 if (BO->getOpcode() == Instruction::And) {
4448 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4449 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4450 } else if (BO->getOpcode() == Instruction::Or) {
4452 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4453 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4457 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4458 if (!ICI) return false;
4460 // Now that we found a conditional branch that dominates the loop, check to
4461 // see if it is the comparison we are looking for.
4462 Value *PreCondLHS = ICI->getOperand(0);
4463 Value *PreCondRHS = ICI->getOperand(1);
4464 ICmpInst::Predicate FoundPred;
4466 FoundPred = ICI->getInversePredicate();
4468 FoundPred = ICI->getPredicate();
4470 if (FoundPred == Pred)
4471 ; // An exact match.
4472 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4473 // The actual condition is beyond sufficient.
4474 FoundPred = ICmpInst::ICMP_NE;
4475 // NE is symmetric but the original comparison may not be. Swap
4476 // the operands if necessary so that they match below.
4477 if (isa<SCEVConstant>(LHS))
4478 std::swap(PreCondLHS, PreCondRHS);
4480 // Check a few special cases.
4481 switch (FoundPred) {
4482 case ICmpInst::ICMP_UGT:
4483 if (Pred == ICmpInst::ICMP_ULT) {
4484 std::swap(PreCondLHS, PreCondRHS);
4485 FoundPred = ICmpInst::ICMP_ULT;
4489 case ICmpInst::ICMP_SGT:
4490 if (Pred == ICmpInst::ICMP_SLT) {
4491 std::swap(PreCondLHS, PreCondRHS);
4492 FoundPred = ICmpInst::ICMP_SLT;
4496 case ICmpInst::ICMP_NE:
4497 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4498 // so check for this case by checking if the NE is comparing against
4499 // a minimum or maximum constant.
4500 if (!ICmpInst::isTrueWhenEqual(Pred))
4501 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4502 const APInt &A = C->getValue()->getValue();
4504 case ICmpInst::ICMP_SLT:
4505 if (A.isMaxSignedValue()) break;
4507 case ICmpInst::ICMP_SGT:
4508 if (A.isMinSignedValue()) break;
4510 case ICmpInst::ICMP_ULT:
4511 if (A.isMaxValue()) break;
4513 case ICmpInst::ICMP_UGT:
4514 if (A.isMinValue()) break;
4520 // NE is symmetric but the original comparison may not be. Swap
4521 // the operands if necessary so that they match below.
4522 if (isa<SCEVConstant>(LHS))
4523 std::swap(PreCondLHS, PreCondRHS);
4528 // We weren't able to reconcile the condition.
4532 assert(Pred == FoundPred && "Conditions were not reconciled!");
4534 // Bail if the ICmp's operands' types are wider than the needed type
4535 // before attempting to call getSCEV on them. This avoids infinite
4536 // recursion, since the analysis of widening casts can require loop
4537 // exit condition information for overflow checking, which would
4539 if (getTypeSizeInBits(LHS->getType()) <
4540 getTypeSizeInBits(PreCondLHS->getType()))
4543 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4544 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4546 // Balance the types. The case where FoundLHS' type is wider than
4547 // LHS' type is checked for above.
4548 if (getTypeSizeInBits(LHS->getType()) >
4549 getTypeSizeInBits(FoundLHS->getType())) {
4550 if (CmpInst::isSigned(Pred)) {
4551 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4552 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4554 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4555 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4559 return isNecessaryCondOperands(Pred, LHS, RHS,
4560 FoundLHS, FoundRHS) ||
4561 // ~x < ~y --> x > y
4562 isNecessaryCondOperands(Pred, LHS, RHS,
4563 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4566 /// isNecessaryCondOperands - Test whether the condition described by Pred,
4567 /// LHS, and RHS is a necessary condition for the condition described by
4568 /// Pred, FoundLHS, and FoundRHS to evaluate to true.
4570 ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4571 const SCEV *LHS, const SCEV *RHS,
4572 const SCEV *FoundLHS,
4573 const SCEV *FoundRHS) {
4575 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4576 case ICmpInst::ICMP_EQ:
4577 case ICmpInst::ICMP_NE:
4578 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4581 case ICmpInst::ICMP_SLT:
4582 case ICmpInst::ICMP_SLE:
4583 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4584 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4587 case ICmpInst::ICMP_SGT:
4588 case ICmpInst::ICMP_SGE:
4589 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4590 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4593 case ICmpInst::ICMP_ULT:
4594 case ICmpInst::ICMP_ULE:
4595 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4596 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4599 case ICmpInst::ICMP_UGT:
4600 case ICmpInst::ICMP_UGE:
4601 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4602 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4610 /// getBECount - Subtract the end and start values and divide by the step,
4611 /// rounding up, to get the number of times the backedge is executed. Return
4612 /// CouldNotCompute if an intermediate computation overflows.
4613 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4616 const Type *Ty = Start->getType();
4617 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4618 const SCEV *Diff = getMinusSCEV(End, Start);
4619 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4621 // Add an adjustment to the difference between End and Start so that
4622 // the division will effectively round up.
4623 const SCEV *Add = getAddExpr(Diff, RoundUp);
4625 // Check Add for unsigned overflow.
4626 // TODO: More sophisticated things could be done here.
4627 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
4628 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4629 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4630 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4631 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4632 return getCouldNotCompute();
4634 return getUDivExpr(Add, Step);
4637 /// HowManyLessThans - Return the number of times a backedge containing the
4638 /// specified less-than comparison will execute. If not computable, return
4639 /// CouldNotCompute.
4640 ScalarEvolution::BackedgeTakenInfo
4641 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4642 const Loop *L, bool isSigned) {
4643 // Only handle: "ADDREC < LoopInvariant".
4644 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4646 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4647 if (!AddRec || AddRec->getLoop() != L)
4648 return getCouldNotCompute();
4650 if (AddRec->isAffine()) {
4651 // FORNOW: We only support unit strides.
4652 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4653 const SCEV *Step = AddRec->getStepRecurrence(*this);
4655 // TODO: handle non-constant strides.
4656 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4657 if (!CStep || CStep->isZero())
4658 return getCouldNotCompute();
4659 if (CStep->isOne()) {
4660 // With unit stride, the iteration never steps past the limit value.
4661 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4662 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4663 // Test whether a positive iteration iteration can step past the limit
4664 // value and past the maximum value for its type in a single step.
4666 APInt Max = APInt::getSignedMaxValue(BitWidth);
4667 if ((Max - CStep->getValue()->getValue())
4668 .slt(CLimit->getValue()->getValue()))
4669 return getCouldNotCompute();
4671 APInt Max = APInt::getMaxValue(BitWidth);
4672 if ((Max - CStep->getValue()->getValue())
4673 .ult(CLimit->getValue()->getValue()))
4674 return getCouldNotCompute();
4677 // TODO: handle non-constant limit values below.
4678 return getCouldNotCompute();
4680 // TODO: handle negative strides below.
4681 return getCouldNotCompute();
4683 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4684 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4685 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4686 // treat m-n as signed nor unsigned due to overflow possibility.
4688 // First, we get the value of the LHS in the first iteration: n
4689 const SCEV *Start = AddRec->getOperand(0);
4691 // Determine the minimum constant start value.
4692 const SCEV *MinStart = getConstant(isSigned ?
4693 getSignedRange(Start).getSignedMin() :
4694 getUnsignedRange(Start).getUnsignedMin());
4696 // If we know that the condition is true in order to enter the loop,
4697 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4698 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4699 // the division must round up.
4700 const SCEV *End = RHS;
4701 if (!isLoopGuardedByCond(L,
4702 isSigned ? ICmpInst::ICMP_SLT :
4704 getMinusSCEV(Start, Step), RHS))
4705 End = isSigned ? getSMaxExpr(RHS, Start)
4706 : getUMaxExpr(RHS, Start);
4708 // Determine the maximum constant end value.
4709 const SCEV *MaxEnd = getConstant(isSigned ?
4710 getSignedRange(End).getSignedMax() :
4711 getUnsignedRange(End).getUnsignedMax());
4713 // Finally, we subtract these two values and divide, rounding up, to get
4714 // the number of times the backedge is executed.
4715 const SCEV *BECount = getBECount(Start, End, Step);
4717 // The maximum backedge count is similar, except using the minimum start
4718 // value and the maximum end value.
4719 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
4721 return BackedgeTakenInfo(BECount, MaxBECount);
4724 return getCouldNotCompute();
4727 /// getNumIterationsInRange - Return the number of iterations of this loop that
4728 /// produce values in the specified constant range. Another way of looking at
4729 /// this is that it returns the first iteration number where the value is not in
4730 /// the condition, thus computing the exit count. If the iteration count can't
4731 /// be computed, an instance of SCEVCouldNotCompute is returned.
4732 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4733 ScalarEvolution &SE) const {
4734 if (Range.isFullSet()) // Infinite loop.
4735 return SE.getCouldNotCompute();
4737 // If the start is a non-zero constant, shift the range to simplify things.
4738 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4739 if (!SC->getValue()->isZero()) {
4740 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4741 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4742 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4743 if (const SCEVAddRecExpr *ShiftedAddRec =
4744 dyn_cast<SCEVAddRecExpr>(Shifted))
4745 return ShiftedAddRec->getNumIterationsInRange(
4746 Range.subtract(SC->getValue()->getValue()), SE);
4747 // This is strange and shouldn't happen.
4748 return SE.getCouldNotCompute();
4751 // The only time we can solve this is when we have all constant indices.
4752 // Otherwise, we cannot determine the overflow conditions.
4753 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4754 if (!isa<SCEVConstant>(getOperand(i)))
4755 return SE.getCouldNotCompute();
4758 // Okay at this point we know that all elements of the chrec are constants and
4759 // that the start element is zero.
4761 // First check to see if the range contains zero. If not, the first
4763 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4764 if (!Range.contains(APInt(BitWidth, 0)))
4765 return SE.getIntegerSCEV(0, getType());
4768 // If this is an affine expression then we have this situation:
4769 // Solve {0,+,A} in Range === Ax in Range
4771 // We know that zero is in the range. If A is positive then we know that
4772 // the upper value of the range must be the first possible exit value.
4773 // If A is negative then the lower of the range is the last possible loop
4774 // value. Also note that we already checked for a full range.
4775 APInt One(BitWidth,1);
4776 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4777 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4779 // The exit value should be (End+A)/A.
4780 APInt ExitVal = (End + A).udiv(A);
4781 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
4783 // Evaluate at the exit value. If we really did fall out of the valid
4784 // range, then we computed our trip count, otherwise wrap around or other
4785 // things must have happened.
4786 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4787 if (Range.contains(Val->getValue()))
4788 return SE.getCouldNotCompute(); // Something strange happened
4790 // Ensure that the previous value is in the range. This is a sanity check.
4791 assert(Range.contains(
4792 EvaluateConstantChrecAtConstant(this,
4793 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
4794 "Linear scev computation is off in a bad way!");
4795 return SE.getConstant(ExitValue);
4796 } else if (isQuadratic()) {
4797 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4798 // quadratic equation to solve it. To do this, we must frame our problem in
4799 // terms of figuring out when zero is crossed, instead of when
4800 // Range.getUpper() is crossed.
4801 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
4802 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4803 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4805 // Next, solve the constructed addrec
4806 std::pair<const SCEV *,const SCEV *> Roots =
4807 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4808 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4809 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4811 // Pick the smallest positive root value.
4812 if (ConstantInt *CB =
4813 dyn_cast<ConstantInt>(
4814 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4815 R1->getValue(), R2->getValue()))) {
4816 if (CB->getZExtValue() == false)
4817 std::swap(R1, R2); // R1 is the minimum root now.
4819 // Make sure the root is not off by one. The returned iteration should
4820 // not be in the range, but the previous one should be. When solving
4821 // for "X*X < 5", for example, we should not return a root of 2.
4822 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4825 if (Range.contains(R1Val->getValue())) {
4826 // The next iteration must be out of the range...
4827 ConstantInt *NextVal =
4828 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
4830 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4831 if (!Range.contains(R1Val->getValue()))
4832 return SE.getConstant(NextVal);
4833 return SE.getCouldNotCompute(); // Something strange happened
4836 // If R1 was not in the range, then it is a good return value. Make
4837 // sure that R1-1 WAS in the range though, just in case.
4838 ConstantInt *NextVal =
4839 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
4840 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4841 if (Range.contains(R1Val->getValue()))
4843 return SE.getCouldNotCompute(); // Something strange happened
4848 return SE.getCouldNotCompute();
4853 //===----------------------------------------------------------------------===//
4854 // SCEVCallbackVH Class Implementation
4855 //===----------------------------------------------------------------------===//
4857 void ScalarEvolution::SCEVCallbackVH::deleted() {
4858 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
4859 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4860 SE->ConstantEvolutionLoopExitValue.erase(PN);
4861 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4862 SE->ValuesAtScopes.erase(I);
4863 SE->Scalars.erase(getValPtr());
4864 // this now dangles!
4867 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
4868 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
4870 // Forget all the expressions associated with users of the old value,
4871 // so that future queries will recompute the expressions using the new
4873 SmallVector<User *, 16> Worklist;
4874 SmallPtrSet<User *, 8> Visited;
4875 Value *Old = getValPtr();
4876 bool DeleteOld = false;
4877 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4879 Worklist.push_back(*UI);
4880 while (!Worklist.empty()) {
4881 User *U = Worklist.pop_back_val();
4882 // Deleting the Old value will cause this to dangle. Postpone
4883 // that until everything else is done.
4888 if (!Visited.insert(U))
4890 if (PHINode *PN = dyn_cast<PHINode>(U))
4891 SE->ConstantEvolutionLoopExitValue.erase(PN);
4892 if (Instruction *I = dyn_cast<Instruction>(U))
4893 SE->ValuesAtScopes.erase(I);
4894 SE->Scalars.erase(U);
4895 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4897 Worklist.push_back(*UI);
4899 // Delete the Old value if it (indirectly) references itself.
4901 if (PHINode *PN = dyn_cast<PHINode>(Old))
4902 SE->ConstantEvolutionLoopExitValue.erase(PN);
4903 if (Instruction *I = dyn_cast<Instruction>(Old))
4904 SE->ValuesAtScopes.erase(I);
4905 SE->Scalars.erase(Old);
4906 // this now dangles!
4911 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
4912 : CallbackVH(V), SE(se) {}
4914 //===----------------------------------------------------------------------===//
4915 // ScalarEvolution Class Implementation
4916 //===----------------------------------------------------------------------===//
4918 ScalarEvolution::ScalarEvolution()
4919 : FunctionPass(&ID) {
4922 bool ScalarEvolution::runOnFunction(Function &F) {
4924 LI = &getAnalysis<LoopInfo>();
4925 TD = getAnalysisIfAvailable<TargetData>();
4929 void ScalarEvolution::releaseMemory() {
4931 BackedgeTakenCounts.clear();
4932 ConstantEvolutionLoopExitValue.clear();
4933 ValuesAtScopes.clear();
4934 UniqueSCEVs.clear();
4935 SCEVAllocator.Reset();
4938 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4939 AU.setPreservesAll();
4940 AU.addRequiredTransitive<LoopInfo>();
4943 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
4944 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
4947 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
4949 // Print all inner loops first
4950 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4951 PrintLoopInfo(OS, SE, *I);
4953 OS << "Loop " << L->getHeader()->getName() << ": ";
4955 SmallVector<BasicBlock*, 8> ExitBlocks;
4956 L->getExitBlocks(ExitBlocks);
4957 if (ExitBlocks.size() != 1)
4958 OS << "<multiple exits> ";
4960 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4961 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4963 OS << "Unpredictable backedge-taken count. ";
4967 OS << "Loop " << L->getHeader()->getName() << ": ";
4969 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4970 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4972 OS << "Unpredictable max backedge-taken count. ";
4978 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4979 // ScalarEvolution's implementaiton of the print method is to print
4980 // out SCEV values of all instructions that are interesting. Doing
4981 // this potentially causes it to create new SCEV objects though,
4982 // which technically conflicts with the const qualifier. This isn't
4983 // observable from outside the class though, so casting away the
4984 // const isn't dangerous.
4985 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4987 OS << "Classifying expressions for: " << F->getName() << "\n";
4988 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4989 if (isSCEVable(I->getType())) {
4992 const SCEV *SV = SE.getSCEV(&*I);
4995 const Loop *L = LI->getLoopFor((*I).getParent());
4997 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5004 OS << "\t\t" "Exits: ";
5005 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5006 if (!ExitValue->isLoopInvariant(L)) {
5007 OS << "<<Unknown>>";
5016 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5017 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5018 PrintLoopInfo(OS, &SE, *I);
5021 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5022 raw_os_ostream OS(o);