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/GetElementPtrTypeIterator.h"
79 #include "llvm/Support/InstIterator.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/ADT/Statistic.h"
83 #include "llvm/ADT/STLExtras.h"
87 STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89 STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91 STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93 STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
96 static cl::opt<unsigned>
97 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant "
103 static RegisterPass<ScalarEvolution>
104 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
105 char ScalarEvolution::ID = 0;
107 //===----------------------------------------------------------------------===//
108 // SCEV class definitions
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
112 // Implementation of the SCEV class.
117 void SCEV::dump() const {
122 void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
127 bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
133 bool SCEV::isOne() const {
134 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
135 return SC->getValue()->isOne();
139 bool SCEV::isAllOnesValue() const {
140 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
141 return SC->getValue()->isAllOnesValue();
145 SCEVCouldNotCompute::SCEVCouldNotCompute() :
146 SCEV(scCouldNotCompute) {}
148 void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
153 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
157 const Type *SCEVCouldNotCompute::getType() const {
158 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
162 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
163 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
168 SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
171 ScalarEvolution &SE) const {
175 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
176 OS << "***COULDNOTCOMPUTE***";
179 bool SCEVCouldNotCompute::classof(const SCEV *S) {
180 return S->getSCEVType() == scCouldNotCompute;
183 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
185 ID.AddInteger(scConstant);
188 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
189 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
190 new (S) SCEVConstant(V);
191 UniqueSCEVs.InsertNode(S, IP);
195 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
196 return getConstant(ConstantInt::get(Val));
200 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
201 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
204 void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
205 ID.AddInteger(scConstant);
209 const Type *SCEVConstant::getType() const { return V->getType(); }
211 void SCEVConstant::print(raw_ostream &OS) const {
212 WriteAsOperand(OS, V, false);
215 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
216 const SCEV *op, const Type *ty)
217 : SCEV(SCEVTy), Op(op), Ty(ty) {}
219 void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
220 ID.AddInteger(getSCEVType());
225 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
226 return Op->dominates(BB, DT);
229 SCEVTruncateExpr::SCEVTruncateExpr(const SCEV *op, const Type *ty)
230 : SCEVCastExpr(scTruncate, op, ty) {
231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
233 "Cannot truncate non-integer value!");
236 void SCEVTruncateExpr::print(raw_ostream &OS) const {
237 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
240 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV *op, const Type *ty)
241 : SCEVCastExpr(scZeroExtend, op, ty) {
242 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
243 (Ty->isInteger() || isa<PointerType>(Ty)) &&
244 "Cannot zero extend non-integer value!");
247 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
248 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
251 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV *op, const Type *ty)
252 : SCEVCastExpr(scSignExtend, op, ty) {
253 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
254 (Ty->isInteger() || isa<PointerType>(Ty)) &&
255 "Cannot sign extend non-integer value!");
258 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
259 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
262 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
263 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
264 const char *OpStr = getOperationStr();
265 OS << "(" << *Operands[0];
266 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
267 OS << OpStr << *Operands[i];
272 SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
275 ScalarEvolution &SE) const {
276 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
278 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
279 if (H != getOperand(i)) {
280 SmallVector<const SCEV *, 8> NewOps;
281 NewOps.reserve(getNumOperands());
282 for (unsigned j = 0; j != i; ++j)
283 NewOps.push_back(getOperand(j));
285 for (++i; i != e; ++i)
286 NewOps.push_back(getOperand(i)->
287 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
289 if (isa<SCEVAddExpr>(this))
290 return SE.getAddExpr(NewOps);
291 else if (isa<SCEVMulExpr>(this))
292 return SE.getMulExpr(NewOps);
293 else if (isa<SCEVSMaxExpr>(this))
294 return SE.getSMaxExpr(NewOps);
295 else if (isa<SCEVUMaxExpr>(this))
296 return SE.getUMaxExpr(NewOps);
298 assert(0 && "Unknown commutative expr!");
304 void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
305 ID.AddInteger(getSCEVType());
306 ID.AddInteger(Operands.size());
307 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
308 ID.AddPointer(Operands[i]);
311 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
313 if (!getOperand(i)->dominates(BB, DT))
319 void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
320 ID.AddInteger(scUDivExpr);
325 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
329 void SCEVUDivExpr::print(raw_ostream &OS) const {
330 OS << "(" << *LHS << " /u " << *RHS << ")";
333 const Type *SCEVUDivExpr::getType() const {
334 // In most cases the types of LHS and RHS will be the same, but in some
335 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
336 // depend on the type for correctness, but handling types carefully can
337 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
338 // a pointer type than the RHS, so use the RHS' type here.
339 return RHS->getType();
342 void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
343 ID.AddInteger(scAddRecExpr);
344 ID.AddInteger(Operands.size());
345 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
346 ID.AddPointer(Operands[i]);
351 SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
353 ScalarEvolution &SE) const {
354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
356 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
357 if (H != getOperand(i)) {
358 SmallVector<const SCEV *, 8> NewOps;
359 NewOps.reserve(getNumOperands());
360 for (unsigned j = 0; j != i; ++j)
361 NewOps.push_back(getOperand(j));
363 for (++i; i != e; ++i)
364 NewOps.push_back(getOperand(i)->
365 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
367 return SE.getAddRecExpr(NewOps, L);
374 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
375 // Add recurrences are never invariant in the function-body (null loop).
379 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
380 if (QueryLoop->contains(L->getHeader()))
383 // This recurrence is variant w.r.t. QueryLoop if any of its operands
385 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
386 if (!getOperand(i)->isLoopInvariant(QueryLoop))
389 // Otherwise it's loop-invariant.
393 void SCEVAddRecExpr::print(raw_ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
400 void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
401 ID.AddInteger(scUnknown);
405 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 // Instructions are never considered invariant in the function body
409 // (null loop) because they are defined within the "loop".
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return L && !L->contains(I->getParent());
415 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
416 if (Instruction *I = dyn_cast<Instruction>(getValue()))
417 return DT->dominates(I->getParent(), BB);
421 const Type *SCEVUnknown::getType() const {
425 void SCEVUnknown::print(raw_ostream &OS) const {
426 WriteAsOperand(OS, V, false);
429 //===----------------------------------------------------------------------===//
431 //===----------------------------------------------------------------------===//
434 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
435 /// than the complexity of the RHS. This comparator is used to canonicalize
437 class VISIBILITY_HIDDEN SCEVComplexityCompare {
440 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
442 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
443 // Primarily, sort the SCEVs by their getSCEVType().
444 if (LHS->getSCEVType() != RHS->getSCEVType())
445 return LHS->getSCEVType() < RHS->getSCEVType();
447 // Aside from the getSCEVType() ordering, the particular ordering
448 // isn't very important except that it's beneficial to be consistent,
449 // so that (a + b) and (b + a) don't end up as different expressions.
451 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
452 // not as complete as it could be.
453 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
454 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
456 // Order pointer values after integer values. This helps SCEVExpander
458 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
460 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
463 // Compare getValueID values.
464 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
465 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
467 // Sort arguments by their position.
468 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
469 const Argument *RA = cast<Argument>(RU->getValue());
470 return LA->getArgNo() < RA->getArgNo();
473 // For instructions, compare their loop depth, and their opcode.
474 // This is pretty loose.
475 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
476 Instruction *RV = cast<Instruction>(RU->getValue());
478 // Compare loop depths.
479 if (LI->getLoopDepth(LV->getParent()) !=
480 LI->getLoopDepth(RV->getParent()))
481 return LI->getLoopDepth(LV->getParent()) <
482 LI->getLoopDepth(RV->getParent());
485 if (LV->getOpcode() != RV->getOpcode())
486 return LV->getOpcode() < RV->getOpcode();
488 // Compare the number of operands.
489 if (LV->getNumOperands() != RV->getNumOperands())
490 return LV->getNumOperands() < RV->getNumOperands();
496 // Compare constant values.
497 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
498 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
499 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
500 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
501 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
504 // Compare addrec loop depths.
505 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
506 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
507 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
508 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
511 // Lexicographically compare n-ary expressions.
512 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
513 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
514 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
515 if (i >= RC->getNumOperands())
517 if (operator()(LC->getOperand(i), RC->getOperand(i)))
519 if (operator()(RC->getOperand(i), LC->getOperand(i)))
522 return LC->getNumOperands() < RC->getNumOperands();
525 // Lexicographically compare udiv expressions.
526 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
527 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
528 if (operator()(LC->getLHS(), RC->getLHS()))
530 if (operator()(RC->getLHS(), LC->getLHS()))
532 if (operator()(LC->getRHS(), RC->getRHS()))
534 if (operator()(RC->getRHS(), LC->getRHS()))
539 // Compare cast expressions by operand.
540 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
541 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
542 return operator()(LC->getOperand(), RC->getOperand());
545 assert(0 && "Unknown SCEV kind!");
551 /// GroupByComplexity - Given a list of SCEV objects, order them by their
552 /// complexity, and group objects of the same complexity together by value.
553 /// When this routine is finished, we know that any duplicates in the vector are
554 /// consecutive and that complexity is monotonically increasing.
556 /// Note that we go take special precautions to ensure that we get determinstic
557 /// results from this routine. In other words, we don't want the results of
558 /// this to depend on where the addresses of various SCEV objects happened to
561 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
563 if (Ops.size() < 2) return; // Noop
564 if (Ops.size() == 2) {
565 // This is the common case, which also happens to be trivially simple.
567 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
568 std::swap(Ops[0], Ops[1]);
572 // Do the rough sort by complexity.
573 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
575 // Now that we are sorted by complexity, group elements of the same
576 // complexity. Note that this is, at worst, N^2, but the vector is likely to
577 // be extremely short in practice. Note that we take this approach because we
578 // do not want to depend on the addresses of the objects we are grouping.
579 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
580 const SCEV *S = Ops[i];
581 unsigned Complexity = S->getSCEVType();
583 // If there are any objects of the same complexity and same value as this
585 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
586 if (Ops[j] == S) { // Found a duplicate.
587 // Move it to immediately after i'th element.
588 std::swap(Ops[i+1], Ops[j]);
589 ++i; // no need to rescan it.
590 if (i == e-2) return; // Done!
598 //===----------------------------------------------------------------------===//
599 // Simple SCEV method implementations
600 //===----------------------------------------------------------------------===//
602 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
604 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
606 const Type* ResultTy) {
607 // Handle the simplest case efficiently.
609 return SE.getTruncateOrZeroExtend(It, ResultTy);
611 // We are using the following formula for BC(It, K):
613 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
615 // Suppose, W is the bitwidth of the return value. We must be prepared for
616 // overflow. Hence, we must assure that the result of our computation is
617 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
618 // safe in modular arithmetic.
620 // However, this code doesn't use exactly that formula; the formula it uses
621 // is something like the following, where T is the number of factors of 2 in
622 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
625 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
627 // This formula is trivially equivalent to the previous formula. However,
628 // this formula can be implemented much more efficiently. The trick is that
629 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
630 // arithmetic. To do exact division in modular arithmetic, all we have
631 // to do is multiply by the inverse. Therefore, this step can be done at
634 // The next issue is how to safely do the division by 2^T. The way this
635 // is done is by doing the multiplication step at a width of at least W + T
636 // bits. This way, the bottom W+T bits of the product are accurate. Then,
637 // when we perform the division by 2^T (which is equivalent to a right shift
638 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
639 // truncated out after the division by 2^T.
641 // In comparison to just directly using the first formula, this technique
642 // is much more efficient; using the first formula requires W * K bits,
643 // but this formula less than W + K bits. Also, the first formula requires
644 // a division step, whereas this formula only requires multiplies and shifts.
646 // It doesn't matter whether the subtraction step is done in the calculation
647 // width or the input iteration count's width; if the subtraction overflows,
648 // the result must be zero anyway. We prefer here to do it in the width of
649 // the induction variable because it helps a lot for certain cases; CodeGen
650 // isn't smart enough to ignore the overflow, which leads to much less
651 // efficient code if the width of the subtraction is wider than the native
654 // (It's possible to not widen at all by pulling out factors of 2 before
655 // the multiplication; for example, K=2 can be calculated as
656 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
657 // extra arithmetic, so it's not an obvious win, and it gets
658 // much more complicated for K > 3.)
660 // Protection from insane SCEVs; this bound is conservative,
661 // but it probably doesn't matter.
663 return SE.getCouldNotCompute();
665 unsigned W = SE.getTypeSizeInBits(ResultTy);
667 // Calculate K! / 2^T and T; we divide out the factors of two before
668 // multiplying for calculating K! / 2^T to avoid overflow.
669 // Other overflow doesn't matter because we only care about the bottom
670 // W bits of the result.
671 APInt OddFactorial(W, 1);
673 for (unsigned i = 3; i <= K; ++i) {
675 unsigned TwoFactors = Mult.countTrailingZeros();
677 Mult = Mult.lshr(TwoFactors);
678 OddFactorial *= Mult;
681 // We need at least W + T bits for the multiplication step
682 unsigned CalculationBits = W + T;
684 // Calcuate 2^T, at width T+W.
685 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
687 // Calculate the multiplicative inverse of K! / 2^T;
688 // this multiplication factor will perform the exact division by
690 APInt Mod = APInt::getSignedMinValue(W+1);
691 APInt MultiplyFactor = OddFactorial.zext(W+1);
692 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
693 MultiplyFactor = MultiplyFactor.trunc(W);
695 // Calculate the product, at width T+W
696 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
697 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
698 for (unsigned i = 1; i != K; ++i) {
699 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
700 Dividend = SE.getMulExpr(Dividend,
701 SE.getTruncateOrZeroExtend(S, CalculationTy));
705 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
707 // Truncate the result, and divide by K! / 2^T.
709 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
710 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
713 /// evaluateAtIteration - Return the value of this chain of recurrences at
714 /// the specified iteration number. We can evaluate this recurrence by
715 /// multiplying each element in the chain by the binomial coefficient
716 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
718 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
720 /// where BC(It, k) stands for binomial coefficient.
722 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
723 ScalarEvolution &SE) const {
724 const SCEV *Result = getStart();
725 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
726 // The computation is correct in the face of overflow provided that the
727 // multiplication is performed _after_ the evaluation of the binomial
729 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
730 if (isa<SCEVCouldNotCompute>(Coeff))
733 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
738 //===----------------------------------------------------------------------===//
739 // SCEV Expression folder implementations
740 //===----------------------------------------------------------------------===//
742 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
744 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
745 "This is not a truncating conversion!");
746 assert(isSCEVable(Ty) &&
747 "This is not a conversion to a SCEVable type!");
748 Ty = getEffectiveSCEVType(Ty);
750 // Fold if the operand is constant.
751 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
753 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
755 // trunc(trunc(x)) --> trunc(x)
756 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
757 return getTruncateExpr(ST->getOperand(), Ty);
759 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
760 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
761 return getTruncateOrSignExtend(SS->getOperand(), Ty);
763 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
764 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
765 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
767 // If the input value is a chrec scev, truncate the chrec's operands.
768 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
769 SmallVector<const SCEV *, 4> Operands;
770 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
771 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
772 return getAddRecExpr(Operands, AddRec->getLoop());
776 ID.AddInteger(scTruncate);
780 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
781 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
782 new (S) SCEVTruncateExpr(Op, Ty);
783 UniqueSCEVs.InsertNode(S, IP);
787 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
789 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
790 "This is not an extending conversion!");
791 assert(isSCEVable(Ty) &&
792 "This is not a conversion to a SCEVable type!");
793 Ty = getEffectiveSCEVType(Ty);
795 // Fold if the operand is constant.
796 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
797 const Type *IntTy = getEffectiveSCEVType(Ty);
798 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
799 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
800 return getConstant(cast<ConstantInt>(C));
803 // zext(zext(x)) --> zext(x)
804 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
805 return getZeroExtendExpr(SZ->getOperand(), Ty);
807 // If the input value is a chrec scev, and we can prove that the value
808 // did not overflow the old, smaller, value, we can zero extend all of the
809 // operands (often constants). This allows analysis of something like
810 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
811 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
812 if (AR->isAffine()) {
813 // Check whether the backedge-taken count is SCEVCouldNotCompute.
814 // Note that this serves two purposes: It filters out loops that are
815 // simply not analyzable, and it covers the case where this code is
816 // being called from within backedge-taken count analysis, such that
817 // attempting to ask for the backedge-taken count would likely result
818 // in infinite recursion. In the later case, the analysis code will
819 // cope with a conservative value, and it will take care to purge
820 // that value once it has finished.
821 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
822 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
823 // Manually compute the final value for AR, checking for
825 const SCEV *Start = AR->getStart();
826 const SCEV *Step = AR->getStepRecurrence(*this);
828 // Check whether the backedge-taken count can be losslessly casted to
829 // the addrec's type. The count is always unsigned.
830 const SCEV *CastedMaxBECount =
831 getTruncateOrZeroExtend(MaxBECount, Start->getType());
832 const SCEV *RecastedMaxBECount =
833 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
834 if (MaxBECount == RecastedMaxBECount) {
836 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
837 // Check whether Start+Step*MaxBECount has no unsigned overflow.
839 getMulExpr(CastedMaxBECount,
840 getTruncateOrZeroExtend(Step, Start->getType()));
841 const SCEV *Add = getAddExpr(Start, ZMul);
842 const SCEV *OperandExtendedAdd =
843 getAddExpr(getZeroExtendExpr(Start, WideTy),
844 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
845 getZeroExtendExpr(Step, WideTy)));
846 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
847 // Return the expression with the addrec on the outside.
848 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
849 getZeroExtendExpr(Step, Ty),
852 // Similar to above, only this time treat the step value as signed.
853 // This covers loops that count down.
855 getMulExpr(CastedMaxBECount,
856 getTruncateOrSignExtend(Step, Start->getType()));
857 Add = getAddExpr(Start, SMul);
859 getAddExpr(getZeroExtendExpr(Start, WideTy),
860 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
861 getSignExtendExpr(Step, WideTy)));
862 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
863 // Return the expression with the addrec on the outside.
864 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
865 getSignExtendExpr(Step, Ty),
872 ID.AddInteger(scZeroExtend);
876 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
877 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
878 new (S) SCEVZeroExtendExpr(Op, Ty);
879 UniqueSCEVs.InsertNode(S, IP);
883 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
886 "This is not an extending conversion!");
887 assert(isSCEVable(Ty) &&
888 "This is not a conversion to a SCEVable type!");
889 Ty = getEffectiveSCEVType(Ty);
891 // Fold if the operand is constant.
892 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
893 const Type *IntTy = getEffectiveSCEVType(Ty);
894 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
895 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
896 return getConstant(cast<ConstantInt>(C));
899 // sext(sext(x)) --> sext(x)
900 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
901 return getSignExtendExpr(SS->getOperand(), Ty);
903 // If the input value is a chrec scev, and we can prove that the value
904 // did not overflow the old, smaller, value, we can sign extend all of the
905 // operands (often constants). This allows analysis of something like
906 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
907 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
908 if (AR->isAffine()) {
909 // Check whether the backedge-taken count is SCEVCouldNotCompute.
910 // Note that this serves two purposes: It filters out loops that are
911 // simply not analyzable, and it covers the case where this code is
912 // being called from within backedge-taken count analysis, such that
913 // attempting to ask for the backedge-taken count would likely result
914 // in infinite recursion. In the later case, the analysis code will
915 // cope with a conservative value, and it will take care to purge
916 // that value once it has finished.
917 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
918 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
919 // Manually compute the final value for AR, checking for
921 const SCEV *Start = AR->getStart();
922 const SCEV *Step = AR->getStepRecurrence(*this);
924 // Check whether the backedge-taken count can be losslessly casted to
925 // the addrec's type. The count is always unsigned.
926 const SCEV *CastedMaxBECount =
927 getTruncateOrZeroExtend(MaxBECount, Start->getType());
928 const SCEV *RecastedMaxBECount =
929 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
930 if (MaxBECount == RecastedMaxBECount) {
932 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
933 // Check whether Start+Step*MaxBECount has no signed overflow.
935 getMulExpr(CastedMaxBECount,
936 getTruncateOrSignExtend(Step, Start->getType()));
937 const SCEV *Add = getAddExpr(Start, SMul);
938 const SCEV *OperandExtendedAdd =
939 getAddExpr(getSignExtendExpr(Start, WideTy),
940 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
941 getSignExtendExpr(Step, WideTy)));
942 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
943 // Return the expression with the addrec on the outside.
944 return getAddRecExpr(getSignExtendExpr(Start, Ty),
945 getSignExtendExpr(Step, Ty),
952 ID.AddInteger(scSignExtend);
956 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
957 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
958 new (S) SCEVSignExtendExpr(Op, Ty);
959 UniqueSCEVs.InsertNode(S, IP);
963 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
964 /// unspecified bits out to the given type.
966 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
968 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
969 "This is not an extending conversion!");
970 assert(isSCEVable(Ty) &&
971 "This is not a conversion to a SCEVable type!");
972 Ty = getEffectiveSCEVType(Ty);
974 // Sign-extend negative constants.
975 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
976 if (SC->getValue()->getValue().isNegative())
977 return getSignExtendExpr(Op, Ty);
979 // Peel off a truncate cast.
980 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
981 const SCEV *NewOp = T->getOperand();
982 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
983 return getAnyExtendExpr(NewOp, Ty);
984 return getTruncateOrNoop(NewOp, Ty);
987 // Next try a zext cast. If the cast is folded, use it.
988 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
989 if (!isa<SCEVZeroExtendExpr>(ZExt))
992 // Next try a sext cast. If the cast is folded, use it.
993 const SCEV *SExt = getSignExtendExpr(Op, Ty);
994 if (!isa<SCEVSignExtendExpr>(SExt))
997 // If the expression is obviously signed, use the sext cast value.
998 if (isa<SCEVSMaxExpr>(Op))
1001 // Absent any other information, use the zext cast value.
1005 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1006 /// a list of operands to be added under the given scale, update the given
1007 /// map. This is a helper function for getAddRecExpr. As an example of
1008 /// what it does, given a sequence of operands that would form an add
1009 /// expression like this:
1011 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1013 /// where A and B are constants, update the map with these values:
1015 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1017 /// and add 13 + A*B*29 to AccumulatedConstant.
1018 /// This will allow getAddRecExpr to produce this:
1020 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1022 /// This form often exposes folding opportunities that are hidden in
1023 /// the original operand list.
1025 /// Return true iff it appears that any interesting folding opportunities
1026 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1027 /// the common case where no interesting opportunities are present, and
1028 /// is also used as a check to avoid infinite recursion.
1031 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1032 SmallVector<const SCEV *, 8> &NewOps,
1033 APInt &AccumulatedConstant,
1034 const SmallVectorImpl<const SCEV *> &Ops,
1036 ScalarEvolution &SE) {
1037 bool Interesting = false;
1039 // Iterate over the add operands.
1040 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1041 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1042 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1044 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1045 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1046 // A multiplication of a constant with another add; recurse.
1048 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1049 cast<SCEVAddExpr>(Mul->getOperand(1))
1053 // A multiplication of a constant with some other value. Update
1055 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1056 const SCEV *Key = SE.getMulExpr(MulOps);
1057 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1058 M.insert(std::make_pair(Key, NewScale));
1060 NewOps.push_back(Pair.first->first);
1062 Pair.first->second += NewScale;
1063 // The map already had an entry for this value, which may indicate
1064 // a folding opportunity.
1068 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1069 // Pull a buried constant out to the outside.
1070 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1072 AccumulatedConstant += Scale * C->getValue()->getValue();
1074 // An ordinary operand. Update the map.
1075 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1076 M.insert(std::make_pair(Ops[i], Scale));
1078 NewOps.push_back(Pair.first->first);
1080 Pair.first->second += Scale;
1081 // The map already had an entry for this value, which may indicate
1082 // a folding opportunity.
1092 struct APIntCompare {
1093 bool operator()(const APInt &LHS, const APInt &RHS) const {
1094 return LHS.ult(RHS);
1099 /// getAddExpr - Get a canonical add expression, or something simpler if
1101 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1102 assert(!Ops.empty() && "Cannot get empty add!");
1103 if (Ops.size() == 1) return Ops[0];
1105 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1106 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1107 getEffectiveSCEVType(Ops[0]->getType()) &&
1108 "SCEVAddExpr operand types don't match!");
1111 // Sort by complexity, this groups all similar expression types together.
1112 GroupByComplexity(Ops, LI);
1114 // If there are any constants, fold them together.
1116 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1118 assert(Idx < Ops.size());
1119 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1120 // We found two constants, fold them together!
1121 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1122 RHSC->getValue()->getValue());
1123 if (Ops.size() == 2) return Ops[0];
1124 Ops.erase(Ops.begin()+1); // Erase the folded element
1125 LHSC = cast<SCEVConstant>(Ops[0]);
1128 // If we are left with a constant zero being added, strip it off.
1129 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1130 Ops.erase(Ops.begin());
1135 if (Ops.size() == 1) return Ops[0];
1137 // Okay, check to see if the same value occurs in the operand list twice. If
1138 // so, merge them together into an multiply expression. Since we sorted the
1139 // list, these values are required to be adjacent.
1140 const Type *Ty = Ops[0]->getType();
1141 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1142 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1143 // Found a match, merge the two values into a multiply, and add any
1144 // remaining values to the result.
1145 const SCEV *Two = getIntegerSCEV(2, Ty);
1146 const SCEV *Mul = getMulExpr(Ops[i], Two);
1147 if (Ops.size() == 2)
1149 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1151 return getAddExpr(Ops);
1154 // Check for truncates. If all the operands are truncated from the same
1155 // type, see if factoring out the truncate would permit the result to be
1156 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1157 // if the contents of the resulting outer trunc fold to something simple.
1158 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1159 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1160 const Type *DstType = Trunc->getType();
1161 const Type *SrcType = Trunc->getOperand()->getType();
1162 SmallVector<const SCEV *, 8> LargeOps;
1164 // Check all the operands to see if they can be represented in the
1165 // source type of the truncate.
1166 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1167 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1168 if (T->getOperand()->getType() != SrcType) {
1172 LargeOps.push_back(T->getOperand());
1173 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1174 // This could be either sign or zero extension, but sign extension
1175 // is much more likely to be foldable here.
1176 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1177 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1178 SmallVector<const SCEV *, 8> LargeMulOps;
1179 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1180 if (const SCEVTruncateExpr *T =
1181 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1182 if (T->getOperand()->getType() != SrcType) {
1186 LargeMulOps.push_back(T->getOperand());
1187 } else if (const SCEVConstant *C =
1188 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1189 // This could be either sign or zero extension, but sign extension
1190 // is much more likely to be foldable here.
1191 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1198 LargeOps.push_back(getMulExpr(LargeMulOps));
1205 // Evaluate the expression in the larger type.
1206 const SCEV *Fold = getAddExpr(LargeOps);
1207 // If it folds to something simple, use it. Otherwise, don't.
1208 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1209 return getTruncateExpr(Fold, DstType);
1213 // Skip past any other cast SCEVs.
1214 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1217 // If there are add operands they would be next.
1218 if (Idx < Ops.size()) {
1219 bool DeletedAdd = false;
1220 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1221 // If we have an add, expand the add operands onto the end of the operands
1223 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1224 Ops.erase(Ops.begin()+Idx);
1228 // If we deleted at least one add, we added operands to the end of the list,
1229 // and they are not necessarily sorted. Recurse to resort and resimplify
1230 // any operands we just aquired.
1232 return getAddExpr(Ops);
1235 // Skip over the add expression until we get to a multiply.
1236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1239 // Check to see if there are any folding opportunities present with
1240 // operands multiplied by constant values.
1241 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1242 uint64_t BitWidth = getTypeSizeInBits(Ty);
1243 DenseMap<const SCEV *, APInt> M;
1244 SmallVector<const SCEV *, 8> NewOps;
1245 APInt AccumulatedConstant(BitWidth, 0);
1246 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1247 Ops, APInt(BitWidth, 1), *this)) {
1248 // Some interesting folding opportunity is present, so its worthwhile to
1249 // re-generate the operands list. Group the operands by constant scale,
1250 // to avoid multiplying by the same constant scale multiple times.
1251 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1252 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1253 E = NewOps.end(); I != E; ++I)
1254 MulOpLists[M.find(*I)->second].push_back(*I);
1255 // Re-generate the operands list.
1257 if (AccumulatedConstant != 0)
1258 Ops.push_back(getConstant(AccumulatedConstant));
1259 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1260 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1262 Ops.push_back(getMulExpr(getConstant(I->first),
1263 getAddExpr(I->second)));
1265 return getIntegerSCEV(0, Ty);
1266 if (Ops.size() == 1)
1268 return getAddExpr(Ops);
1272 // If we are adding something to a multiply expression, make sure the
1273 // something is not already an operand of the multiply. If so, merge it into
1275 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1276 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1277 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1278 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1279 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1280 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1281 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1282 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1283 if (Mul->getNumOperands() != 2) {
1284 // If the multiply has more than two operands, we must get the
1286 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1287 MulOps.erase(MulOps.begin()+MulOp);
1288 InnerMul = getMulExpr(MulOps);
1290 const SCEV *One = getIntegerSCEV(1, Ty);
1291 const SCEV *AddOne = getAddExpr(InnerMul, One);
1292 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1293 if (Ops.size() == 2) return OuterMul;
1295 Ops.erase(Ops.begin()+AddOp);
1296 Ops.erase(Ops.begin()+Idx-1);
1298 Ops.erase(Ops.begin()+Idx);
1299 Ops.erase(Ops.begin()+AddOp-1);
1301 Ops.push_back(OuterMul);
1302 return getAddExpr(Ops);
1305 // Check this multiply against other multiplies being added together.
1306 for (unsigned OtherMulIdx = Idx+1;
1307 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1309 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1310 // If MulOp occurs in OtherMul, we can fold the two multiplies
1312 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1313 OMulOp != e; ++OMulOp)
1314 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1315 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1316 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1317 if (Mul->getNumOperands() != 2) {
1318 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1320 MulOps.erase(MulOps.begin()+MulOp);
1321 InnerMul1 = getMulExpr(MulOps);
1323 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1324 if (OtherMul->getNumOperands() != 2) {
1325 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1326 OtherMul->op_end());
1327 MulOps.erase(MulOps.begin()+OMulOp);
1328 InnerMul2 = getMulExpr(MulOps);
1330 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1331 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1332 if (Ops.size() == 2) return OuterMul;
1333 Ops.erase(Ops.begin()+Idx);
1334 Ops.erase(Ops.begin()+OtherMulIdx-1);
1335 Ops.push_back(OuterMul);
1336 return getAddExpr(Ops);
1342 // If there are any add recurrences in the operands list, see if any other
1343 // added values are loop invariant. If so, we can fold them into the
1345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1348 // Scan over all recurrences, trying to fold loop invariants into them.
1349 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1350 // Scan all of the other operands to this add and add them to the vector if
1351 // they are loop invariant w.r.t. the recurrence.
1352 SmallVector<const SCEV *, 8> LIOps;
1353 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1354 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1355 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1356 LIOps.push_back(Ops[i]);
1357 Ops.erase(Ops.begin()+i);
1361 // If we found some loop invariants, fold them into the recurrence.
1362 if (!LIOps.empty()) {
1363 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1364 LIOps.push_back(AddRec->getStart());
1366 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1368 AddRecOps[0] = getAddExpr(LIOps);
1370 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1371 // If all of the other operands were loop invariant, we are done.
1372 if (Ops.size() == 1) return NewRec;
1374 // Otherwise, add the folded AddRec by the non-liv parts.
1375 for (unsigned i = 0;; ++i)
1376 if (Ops[i] == AddRec) {
1380 return getAddExpr(Ops);
1383 // Okay, if there weren't any loop invariants to be folded, check to see if
1384 // there are multiple AddRec's with the same loop induction variable being
1385 // added together. If so, we can fold them.
1386 for (unsigned OtherIdx = Idx+1;
1387 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1388 if (OtherIdx != Idx) {
1389 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1390 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1391 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1392 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1394 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1395 if (i >= NewOps.size()) {
1396 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1397 OtherAddRec->op_end());
1400 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1402 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1404 if (Ops.size() == 2) return NewAddRec;
1406 Ops.erase(Ops.begin()+Idx);
1407 Ops.erase(Ops.begin()+OtherIdx-1);
1408 Ops.push_back(NewAddRec);
1409 return getAddExpr(Ops);
1413 // Otherwise couldn't fold anything into this recurrence. Move onto the
1417 // Okay, it looks like we really DO need an add expr. Check to see if we
1418 // already have one, otherwise create a new one.
1419 FoldingSetNodeID ID;
1420 ID.AddInteger(scAddExpr);
1421 ID.AddInteger(Ops.size());
1422 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1423 ID.AddPointer(Ops[i]);
1425 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1426 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1427 new (S) SCEVAddExpr(Ops);
1428 UniqueSCEVs.InsertNode(S, IP);
1433 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1435 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1436 assert(!Ops.empty() && "Cannot get empty mul!");
1438 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1439 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1440 getEffectiveSCEVType(Ops[0]->getType()) &&
1441 "SCEVMulExpr operand types don't match!");
1444 // Sort by complexity, this groups all similar expression types together.
1445 GroupByComplexity(Ops, LI);
1447 // If there are any constants, fold them together.
1449 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1451 // C1*(C2+V) -> C1*C2 + C1*V
1452 if (Ops.size() == 2)
1453 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1454 if (Add->getNumOperands() == 2 &&
1455 isa<SCEVConstant>(Add->getOperand(0)))
1456 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1457 getMulExpr(LHSC, Add->getOperand(1)));
1461 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1462 // We found two constants, fold them together!
1463 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1464 RHSC->getValue()->getValue());
1465 Ops[0] = getConstant(Fold);
1466 Ops.erase(Ops.begin()+1); // Erase the folded element
1467 if (Ops.size() == 1) return Ops[0];
1468 LHSC = cast<SCEVConstant>(Ops[0]);
1471 // If we are left with a constant one being multiplied, strip it off.
1472 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1473 Ops.erase(Ops.begin());
1475 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1476 // If we have a multiply of zero, it will always be zero.
1481 // Skip over the add expression until we get to a multiply.
1482 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1485 if (Ops.size() == 1)
1488 // If there are mul operands inline them all into this expression.
1489 if (Idx < Ops.size()) {
1490 bool DeletedMul = false;
1491 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1492 // If we have an mul, expand the mul operands onto the end of the operands
1494 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1495 Ops.erase(Ops.begin()+Idx);
1499 // If we deleted at least one mul, we added operands to the end of the list,
1500 // and they are not necessarily sorted. Recurse to resort and resimplify
1501 // any operands we just aquired.
1503 return getMulExpr(Ops);
1506 // If there are any add recurrences in the operands list, see if any other
1507 // added values are loop invariant. If so, we can fold them into the
1509 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1512 // Scan over all recurrences, trying to fold loop invariants into them.
1513 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1514 // Scan all of the other operands to this mul and add them to the vector if
1515 // they are loop invariant w.r.t. the recurrence.
1516 SmallVector<const SCEV *, 8> LIOps;
1517 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1518 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1519 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1520 LIOps.push_back(Ops[i]);
1521 Ops.erase(Ops.begin()+i);
1525 // If we found some loop invariants, fold them into the recurrence.
1526 if (!LIOps.empty()) {
1527 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1528 SmallVector<const SCEV *, 4> NewOps;
1529 NewOps.reserve(AddRec->getNumOperands());
1530 if (LIOps.size() == 1) {
1531 const SCEV *Scale = LIOps[0];
1532 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1533 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1535 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1536 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1537 MulOps.push_back(AddRec->getOperand(i));
1538 NewOps.push_back(getMulExpr(MulOps));
1542 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1544 // If all of the other operands were loop invariant, we are done.
1545 if (Ops.size() == 1) return NewRec;
1547 // Otherwise, multiply the folded AddRec by the non-liv parts.
1548 for (unsigned i = 0;; ++i)
1549 if (Ops[i] == AddRec) {
1553 return getMulExpr(Ops);
1556 // Okay, if there weren't any loop invariants to be folded, check to see if
1557 // there are multiple AddRec's with the same loop induction variable being
1558 // multiplied together. If so, we can fold them.
1559 for (unsigned OtherIdx = Idx+1;
1560 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1561 if (OtherIdx != Idx) {
1562 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1563 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1564 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1565 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1566 const SCEV *NewStart = getMulExpr(F->getStart(),
1568 const SCEV *B = F->getStepRecurrence(*this);
1569 const SCEV *D = G->getStepRecurrence(*this);
1570 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1573 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1575 if (Ops.size() == 2) return NewAddRec;
1577 Ops.erase(Ops.begin()+Idx);
1578 Ops.erase(Ops.begin()+OtherIdx-1);
1579 Ops.push_back(NewAddRec);
1580 return getMulExpr(Ops);
1584 // Otherwise couldn't fold anything into this recurrence. Move onto the
1588 // Okay, it looks like we really DO need an mul expr. Check to see if we
1589 // already have one, otherwise create a new one.
1590 FoldingSetNodeID ID;
1591 ID.AddInteger(scMulExpr);
1592 ID.AddInteger(Ops.size());
1593 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1594 ID.AddPointer(Ops[i]);
1596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1597 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1598 new (S) SCEVMulExpr(Ops);
1599 UniqueSCEVs.InsertNode(S, IP);
1603 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1605 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1607 assert(getEffectiveSCEVType(LHS->getType()) ==
1608 getEffectiveSCEVType(RHS->getType()) &&
1609 "SCEVUDivExpr operand types don't match!");
1611 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1612 if (RHSC->getValue()->equalsInt(1))
1613 return LHS; // X udiv 1 --> x
1615 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1617 // Determine if the division can be folded into the operands of
1619 // TODO: Generalize this to non-constants by using known-bits information.
1620 const Type *Ty = LHS->getType();
1621 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1622 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1623 // For non-power-of-two values, effectively round the value up to the
1624 // nearest power of two.
1625 if (!RHSC->getValue()->getValue().isPowerOf2())
1627 const IntegerType *ExtTy =
1628 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1629 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1630 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1631 if (const SCEVConstant *Step =
1632 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1633 if (!Step->getValue()->getValue()
1634 .urem(RHSC->getValue()->getValue()) &&
1635 getZeroExtendExpr(AR, ExtTy) ==
1636 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1637 getZeroExtendExpr(Step, ExtTy),
1639 SmallVector<const SCEV *, 4> Operands;
1640 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1641 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1642 return getAddRecExpr(Operands, AR->getLoop());
1644 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1645 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1646 SmallVector<const SCEV *, 4> Operands;
1647 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1648 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1649 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1650 // Find an operand that's safely divisible.
1651 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1652 const SCEV *Op = M->getOperand(i);
1653 const SCEV *Div = getUDivExpr(Op, RHSC);
1654 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1655 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1656 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1659 return getMulExpr(Operands);
1663 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1664 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1665 SmallVector<const SCEV *, 4> Operands;
1666 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1667 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1668 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1670 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1671 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1672 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1674 Operands.push_back(Op);
1676 if (Operands.size() == A->getNumOperands())
1677 return getAddExpr(Operands);
1681 // Fold if both operands are constant.
1682 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1683 Constant *LHSCV = LHSC->getValue();
1684 Constant *RHSCV = RHSC->getValue();
1685 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1690 FoldingSetNodeID ID;
1691 ID.AddInteger(scUDivExpr);
1695 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1696 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1697 new (S) SCEVUDivExpr(LHS, RHS);
1698 UniqueSCEVs.InsertNode(S, IP);
1703 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1704 /// Simplify the expression as much as possible.
1705 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1706 const SCEV *Step, const Loop *L) {
1707 SmallVector<const SCEV *, 4> Operands;
1708 Operands.push_back(Start);
1709 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1710 if (StepChrec->getLoop() == L) {
1711 Operands.insert(Operands.end(), StepChrec->op_begin(),
1712 StepChrec->op_end());
1713 return getAddRecExpr(Operands, L);
1716 Operands.push_back(Step);
1717 return getAddRecExpr(Operands, L);
1720 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1721 /// Simplify the expression as much as possible.
1723 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1725 if (Operands.size() == 1) return Operands[0];
1727 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1728 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1729 getEffectiveSCEVType(Operands[0]->getType()) &&
1730 "SCEVAddRecExpr operand types don't match!");
1733 if (Operands.back()->isZero()) {
1734 Operands.pop_back();
1735 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1738 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1739 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1740 const Loop* NestedLoop = NestedAR->getLoop();
1741 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1742 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1743 NestedAR->op_end());
1744 Operands[0] = NestedAR->getStart();
1745 // AddRecs require their operands be loop-invariant with respect to their
1746 // loops. Don't perform this transformation if it would break this
1748 bool AllInvariant = true;
1749 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1750 if (!Operands[i]->isLoopInvariant(L)) {
1751 AllInvariant = false;
1755 NestedOperands[0] = getAddRecExpr(Operands, L);
1756 AllInvariant = true;
1757 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1758 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1759 AllInvariant = false;
1763 // Ok, both add recurrences are valid after the transformation.
1764 return getAddRecExpr(NestedOperands, NestedLoop);
1766 // Reset Operands to its original state.
1767 Operands[0] = NestedAR;
1771 FoldingSetNodeID ID;
1772 ID.AddInteger(scAddRecExpr);
1773 ID.AddInteger(Operands.size());
1774 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1775 ID.AddPointer(Operands[i]);
1778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1780 new (S) SCEVAddRecExpr(Operands, L);
1781 UniqueSCEVs.InsertNode(S, IP);
1785 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1787 SmallVector<const SCEV *, 2> Ops;
1790 return getSMaxExpr(Ops);
1794 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1795 assert(!Ops.empty() && "Cannot get empty smax!");
1796 if (Ops.size() == 1) return Ops[0];
1798 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1799 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1800 getEffectiveSCEVType(Ops[0]->getType()) &&
1801 "SCEVSMaxExpr operand types don't match!");
1804 // Sort by complexity, this groups all similar expression types together.
1805 GroupByComplexity(Ops, LI);
1807 // If there are any constants, fold them together.
1809 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1811 assert(Idx < Ops.size());
1812 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1813 // We found two constants, fold them together!
1814 ConstantInt *Fold = ConstantInt::get(
1815 APIntOps::smax(LHSC->getValue()->getValue(),
1816 RHSC->getValue()->getValue()));
1817 Ops[0] = getConstant(Fold);
1818 Ops.erase(Ops.begin()+1); // Erase the folded element
1819 if (Ops.size() == 1) return Ops[0];
1820 LHSC = cast<SCEVConstant>(Ops[0]);
1823 // If we are left with a constant minimum-int, strip it off.
1824 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1825 Ops.erase(Ops.begin());
1827 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1828 // If we have an smax with a constant maximum-int, it will always be
1834 if (Ops.size() == 1) return Ops[0];
1836 // Find the first SMax
1837 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1840 // Check to see if one of the operands is an SMax. If so, expand its operands
1841 // onto our operand list, and recurse to simplify.
1842 if (Idx < Ops.size()) {
1843 bool DeletedSMax = false;
1844 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1845 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1846 Ops.erase(Ops.begin()+Idx);
1851 return getSMaxExpr(Ops);
1854 // Okay, check to see if the same value occurs in the operand list twice. If
1855 // so, delete one. Since we sorted the list, these values are required to
1857 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1858 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1859 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1863 if (Ops.size() == 1) return Ops[0];
1865 assert(!Ops.empty() && "Reduced smax down to nothing!");
1867 // Okay, it looks like we really DO need an smax expr. Check to see if we
1868 // already have one, otherwise create a new one.
1869 FoldingSetNodeID ID;
1870 ID.AddInteger(scSMaxExpr);
1871 ID.AddInteger(Ops.size());
1872 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1873 ID.AddPointer(Ops[i]);
1875 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1876 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1877 new (S) SCEVSMaxExpr(Ops);
1878 UniqueSCEVs.InsertNode(S, IP);
1882 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1884 SmallVector<const SCEV *, 2> Ops;
1887 return getUMaxExpr(Ops);
1891 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1892 assert(!Ops.empty() && "Cannot get empty umax!");
1893 if (Ops.size() == 1) return Ops[0];
1895 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1896 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1897 getEffectiveSCEVType(Ops[0]->getType()) &&
1898 "SCEVUMaxExpr operand types don't match!");
1901 // Sort by complexity, this groups all similar expression types together.
1902 GroupByComplexity(Ops, LI);
1904 // If there are any constants, fold them together.
1906 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1908 assert(Idx < Ops.size());
1909 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1910 // We found two constants, fold them together!
1911 ConstantInt *Fold = ConstantInt::get(
1912 APIntOps::umax(LHSC->getValue()->getValue(),
1913 RHSC->getValue()->getValue()));
1914 Ops[0] = getConstant(Fold);
1915 Ops.erase(Ops.begin()+1); // Erase the folded element
1916 if (Ops.size() == 1) return Ops[0];
1917 LHSC = cast<SCEVConstant>(Ops[0]);
1920 // If we are left with a constant minimum-int, strip it off.
1921 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1922 Ops.erase(Ops.begin());
1924 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1925 // If we have an umax with a constant maximum-int, it will always be
1931 if (Ops.size() == 1) return Ops[0];
1933 // Find the first UMax
1934 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1937 // Check to see if one of the operands is a UMax. If so, expand its operands
1938 // onto our operand list, and recurse to simplify.
1939 if (Idx < Ops.size()) {
1940 bool DeletedUMax = false;
1941 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1942 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1943 Ops.erase(Ops.begin()+Idx);
1948 return getUMaxExpr(Ops);
1951 // Okay, check to see if the same value occurs in the operand list twice. If
1952 // so, delete one. Since we sorted the list, these values are required to
1954 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1955 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1956 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1960 if (Ops.size() == 1) return Ops[0];
1962 assert(!Ops.empty() && "Reduced umax down to nothing!");
1964 // Okay, it looks like we really DO need a umax expr. Check to see if we
1965 // already have one, otherwise create a new one.
1966 FoldingSetNodeID ID;
1967 ID.AddInteger(scUMaxExpr);
1968 ID.AddInteger(Ops.size());
1969 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1970 ID.AddPointer(Ops[i]);
1972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1973 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1974 new (S) SCEVUMaxExpr(Ops);
1975 UniqueSCEVs.InsertNode(S, IP);
1979 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1981 // ~smax(~x, ~y) == smin(x, y).
1982 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1985 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1987 // ~umax(~x, ~y) == umin(x, y)
1988 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1991 const SCEV *ScalarEvolution::getUnknown(Value *V) {
1992 // Don't attempt to do anything other than create a SCEVUnknown object
1993 // here. createSCEV only calls getUnknown after checking for all other
1994 // interesting possibilities, and any other code that calls getUnknown
1995 // is doing so in order to hide a value from SCEV canonicalization.
1997 FoldingSetNodeID ID;
1998 ID.AddInteger(scUnknown);
2001 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2002 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2003 new (S) SCEVUnknown(V);
2004 UniqueSCEVs.InsertNode(S, IP);
2008 //===----------------------------------------------------------------------===//
2009 // Basic SCEV Analysis and PHI Idiom Recognition Code
2012 /// isSCEVable - Test if values of the given type are analyzable within
2013 /// the SCEV framework. This primarily includes integer types, and it
2014 /// can optionally include pointer types if the ScalarEvolution class
2015 /// has access to target-specific information.
2016 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2017 // Integers are always SCEVable.
2018 if (Ty->isInteger())
2021 // Pointers are SCEVable if TargetData information is available
2022 // to provide pointer size information.
2023 if (isa<PointerType>(Ty))
2026 // Otherwise it's not SCEVable.
2030 /// getTypeSizeInBits - Return the size in bits of the specified type,
2031 /// for which isSCEVable must return true.
2032 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2033 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2035 // If we have a TargetData, use it!
2037 return TD->getTypeSizeInBits(Ty);
2039 // Otherwise, we support only integer types.
2040 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2041 return Ty->getPrimitiveSizeInBits();
2044 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2045 /// the given type and which represents how SCEV will treat the given
2046 /// type, for which isSCEVable must return true. For pointer types,
2047 /// this is the pointer-sized integer type.
2048 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2049 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2051 if (Ty->isInteger())
2054 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2055 return TD->getIntPtrType();
2058 const SCEV *ScalarEvolution::getCouldNotCompute() {
2059 return &CouldNotCompute;
2062 /// hasSCEV - Return true if the SCEV for this value has already been
2064 bool ScalarEvolution::hasSCEV(Value *V) const {
2065 return Scalars.count(V);
2068 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2069 /// expression and create a new one.
2070 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2071 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2073 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2074 if (I != Scalars.end()) return I->second;
2075 const SCEV *S = createSCEV(V);
2076 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2080 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2081 /// specified signed integer value and return a SCEV for the constant.
2082 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2083 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2084 return getConstant(ConstantInt::get(ITy, Val));
2087 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2089 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2090 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2091 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2093 const Type *Ty = V->getType();
2094 Ty = getEffectiveSCEVType(Ty);
2095 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
2098 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2099 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2100 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2101 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2103 const Type *Ty = V->getType();
2104 Ty = getEffectiveSCEVType(Ty);
2105 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
2106 return getMinusSCEV(AllOnes, V);
2109 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2111 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2114 return getAddExpr(LHS, getNegativeSCEV(RHS));
2117 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2118 /// input value to the specified type. If the type must be extended, it is zero
2121 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2123 const Type *SrcTy = V->getType();
2124 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2125 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2126 "Cannot truncate or zero extend with non-integer arguments!");
2127 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2128 return V; // No conversion
2129 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2130 return getTruncateExpr(V, Ty);
2131 return getZeroExtendExpr(V, Ty);
2134 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2135 /// input value to the specified type. If the type must be extended, it is sign
2138 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2140 const Type *SrcTy = V->getType();
2141 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2142 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2143 "Cannot truncate or zero extend with non-integer arguments!");
2144 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2145 return V; // No conversion
2146 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2147 return getTruncateExpr(V, Ty);
2148 return getSignExtendExpr(V, Ty);
2151 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2152 /// input value to the specified type. If the type must be extended, it is zero
2153 /// extended. The conversion must not be narrowing.
2155 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2156 const Type *SrcTy = V->getType();
2157 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2158 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2159 "Cannot noop or zero extend with non-integer arguments!");
2160 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2161 "getNoopOrZeroExtend cannot truncate!");
2162 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2163 return V; // No conversion
2164 return getZeroExtendExpr(V, Ty);
2167 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2168 /// input value to the specified type. If the type must be extended, it is sign
2169 /// extended. The conversion must not be narrowing.
2171 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2172 const Type *SrcTy = V->getType();
2173 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2174 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2175 "Cannot noop or sign extend with non-integer arguments!");
2176 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2177 "getNoopOrSignExtend cannot truncate!");
2178 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2179 return V; // No conversion
2180 return getSignExtendExpr(V, Ty);
2183 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2184 /// the input value to the specified type. If the type must be extended,
2185 /// it is extended with unspecified bits. The conversion must not be
2188 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2189 const Type *SrcTy = V->getType();
2190 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2191 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2192 "Cannot noop or any extend with non-integer arguments!");
2193 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2194 "getNoopOrAnyExtend cannot truncate!");
2195 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2196 return V; // No conversion
2197 return getAnyExtendExpr(V, Ty);
2200 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2201 /// input value to the specified type. The conversion must not be widening.
2203 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2204 const Type *SrcTy = V->getType();
2205 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2206 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2207 "Cannot truncate or noop with non-integer arguments!");
2208 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2209 "getTruncateOrNoop cannot extend!");
2210 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2211 return V; // No conversion
2212 return getTruncateExpr(V, Ty);
2215 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2216 /// the types using zero-extension, and then perform a umax operation
2218 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2220 const SCEV *PromotedLHS = LHS;
2221 const SCEV *PromotedRHS = RHS;
2223 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2224 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2226 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2228 return getUMaxExpr(PromotedLHS, PromotedRHS);
2231 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2232 /// the types using zero-extension, and then perform a umin operation
2234 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2236 const SCEV *PromotedLHS = LHS;
2237 const SCEV *PromotedRHS = RHS;
2239 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2240 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2242 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2244 return getUMinExpr(PromotedLHS, PromotedRHS);
2247 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2248 /// the specified instruction and replaces any references to the symbolic value
2249 /// SymName with the specified value. This is used during PHI resolution.
2251 ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2252 const SCEV *SymName,
2253 const SCEV *NewVal) {
2254 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
2255 Scalars.find(SCEVCallbackVH(I, this));
2256 if (SI == Scalars.end()) return;
2259 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2260 if (NV == SI->second) return; // No change.
2262 SI->second = NV; // Update the scalars map!
2264 // Any instruction values that use this instruction might also need to be
2266 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2268 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2271 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2272 /// a loop header, making it a potential recurrence, or it doesn't.
2274 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2275 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2276 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2277 if (L->getHeader() == PN->getParent()) {
2278 // If it lives in the loop header, it has two incoming values, one
2279 // from outside the loop, and one from inside.
2280 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2281 unsigned BackEdge = IncomingEdge^1;
2283 // While we are analyzing this PHI node, handle its value symbolically.
2284 const SCEV *SymbolicName = getUnknown(PN);
2285 assert(Scalars.find(PN) == Scalars.end() &&
2286 "PHI node already processed?");
2287 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2289 // Using this symbolic name for the PHI, analyze the value coming around
2291 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2293 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2294 // has a special value for the first iteration of the loop.
2296 // If the value coming around the backedge is an add with the symbolic
2297 // value we just inserted, then we found a simple induction variable!
2298 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2299 // If there is a single occurrence of the symbolic value, replace it
2300 // with a recurrence.
2301 unsigned FoundIndex = Add->getNumOperands();
2302 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2303 if (Add->getOperand(i) == SymbolicName)
2304 if (FoundIndex == e) {
2309 if (FoundIndex != Add->getNumOperands()) {
2310 // Create an add with everything but the specified operand.
2311 SmallVector<const SCEV *, 8> Ops;
2312 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2313 if (i != FoundIndex)
2314 Ops.push_back(Add->getOperand(i));
2315 const SCEV *Accum = getAddExpr(Ops);
2317 // This is not a valid addrec if the step amount is varying each
2318 // loop iteration, but is not itself an addrec in this loop.
2319 if (Accum->isLoopInvariant(L) ||
2320 (isa<SCEVAddRecExpr>(Accum) &&
2321 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2322 const SCEV *StartVal =
2323 getSCEV(PN->getIncomingValue(IncomingEdge));
2324 const SCEV *PHISCEV =
2325 getAddRecExpr(StartVal, Accum, L);
2327 // Okay, for the entire analysis of this edge we assumed the PHI
2328 // to be symbolic. We now need to go back and update all of the
2329 // entries for the scalars that use the PHI (except for the PHI
2330 // itself) to use the new analyzed value instead of the "symbolic"
2332 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2336 } else if (const SCEVAddRecExpr *AddRec =
2337 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2338 // Otherwise, this could be a loop like this:
2339 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2340 // In this case, j = {1,+,1} and BEValue is j.
2341 // Because the other in-value of i (0) fits the evolution of BEValue
2342 // i really is an addrec evolution.
2343 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2344 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2346 // If StartVal = j.start - j.stride, we can use StartVal as the
2347 // initial step of the addrec evolution.
2348 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2349 AddRec->getOperand(1))) {
2350 const SCEV *PHISCEV =
2351 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2353 // Okay, for the entire analysis of this edge we assumed the PHI
2354 // to be symbolic. We now need to go back and update all of the
2355 // entries for the scalars that use the PHI (except for the PHI
2356 // itself) to use the new analyzed value instead of the "symbolic"
2358 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2364 return SymbolicName;
2367 // If it's not a loop phi, we can't handle it yet.
2368 return getUnknown(PN);
2371 /// createNodeForGEP - Expand GEP instructions into add and multiply
2372 /// operations. This allows them to be analyzed by regular SCEV code.
2374 const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
2376 const Type *IntPtrTy = TD->getIntPtrType();
2377 Value *Base = GEP->getOperand(0);
2378 // Don't attempt to analyze GEPs over unsized objects.
2379 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2380 return getUnknown(GEP);
2381 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2382 gep_type_iterator GTI = gep_type_begin(GEP);
2383 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2387 // Compute the (potentially symbolic) offset in bytes for this index.
2388 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2389 // For a struct, add the member offset.
2390 const StructLayout &SL = *TD->getStructLayout(STy);
2391 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2392 uint64_t Offset = SL.getElementOffset(FieldNo);
2393 TotalOffset = getAddExpr(TotalOffset,
2394 getIntegerSCEV(Offset, IntPtrTy));
2396 // For an array, add the element offset, explicitly scaled.
2397 const SCEV *LocalOffset = getSCEV(Index);
2398 if (!isa<PointerType>(LocalOffset->getType()))
2399 // Getelementptr indicies are signed.
2400 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2403 getMulExpr(LocalOffset,
2404 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2406 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2409 return getAddExpr(getSCEV(Base), TotalOffset);
2412 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2413 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2414 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2415 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2417 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2418 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2419 return C->getValue()->getValue().countTrailingZeros();
2421 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2422 return std::min(GetMinTrailingZeros(T->getOperand()),
2423 (uint32_t)getTypeSizeInBits(T->getType()));
2425 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2426 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2427 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2428 getTypeSizeInBits(E->getType()) : OpRes;
2431 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2432 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2433 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2434 getTypeSizeInBits(E->getType()) : OpRes;
2437 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2438 // The result is the min of all operands results.
2439 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2440 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2441 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2445 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2446 // The result is the sum of all operands results.
2447 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2448 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2449 for (unsigned i = 1, e = M->getNumOperands();
2450 SumOpRes != BitWidth && i != e; ++i)
2451 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2456 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2457 // The result is the min of all operands results.
2458 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2459 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2460 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2464 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2465 // The result is the min of all operands results.
2466 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2467 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2468 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2472 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2473 // The result is the min of all operands results.
2474 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2475 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2476 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2480 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2481 // For a SCEVUnknown, ask ValueTracking.
2482 unsigned BitWidth = getTypeSizeInBits(U->getType());
2483 APInt Mask = APInt::getAllOnesValue(BitWidth);
2484 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2485 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2486 return Zeros.countTrailingOnes();
2494 ScalarEvolution::GetMinLeadingZeros(const SCEV *S) {
2495 // TODO: Handle other SCEV expression types here.
2497 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2498 return C->getValue()->getValue().countLeadingZeros();
2500 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2501 // A zero-extension cast adds zero bits.
2502 return GetMinLeadingZeros(C->getOperand()) +
2503 (getTypeSizeInBits(C->getType()) -
2504 getTypeSizeInBits(C->getOperand()->getType()));
2507 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2508 // For a SCEVUnknown, ask ValueTracking.
2509 unsigned BitWidth = getTypeSizeInBits(U->getType());
2510 APInt Mask = APInt::getAllOnesValue(BitWidth);
2511 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2512 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2513 return Zeros.countLeadingOnes();
2520 ScalarEvolution::GetMinSignBits(const SCEV *S) {
2521 // TODO: Handle other SCEV expression types here.
2523 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2524 const APInt &A = C->getValue()->getValue();
2525 return A.isNegative() ? A.countLeadingOnes() :
2526 A.countLeadingZeros();
2529 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2530 // A sign-extension cast adds sign bits.
2531 return GetMinSignBits(C->getOperand()) +
2532 (getTypeSizeInBits(C->getType()) -
2533 getTypeSizeInBits(C->getOperand()->getType()));
2536 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2537 unsigned BitWidth = getTypeSizeInBits(A->getType());
2539 // Special case decrementing a value (ADD X, -1):
2540 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2541 if (CRHS->isAllOnesValue()) {
2542 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2543 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2544 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2546 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2548 if (LZ == BitWidth - 1)
2551 // If we are subtracting one from a positive number, there is no carry
2552 // out of the result.
2554 return GetMinSignBits(OtherOpsAdd);
2557 // Add can have at most one carry bit. Thus we know that the output
2558 // is, at worst, one more bit than the inputs.
2559 unsigned Min = BitWidth;
2560 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2561 unsigned N = GetMinSignBits(A->getOperand(i));
2562 Min = std::min(Min, N) - 1;
2563 if (Min == 0) return 1;
2568 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2569 // For a SCEVUnknown, ask ValueTracking.
2570 return ComputeNumSignBits(U->getValue(), TD);
2576 /// createSCEV - We know that there is no SCEV for the specified value.
2577 /// Analyze the expression.
2579 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2580 if (!isSCEVable(V->getType()))
2581 return getUnknown(V);
2583 unsigned Opcode = Instruction::UserOp1;
2584 if (Instruction *I = dyn_cast<Instruction>(V))
2585 Opcode = I->getOpcode();
2586 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2587 Opcode = CE->getOpcode();
2588 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2589 return getConstant(CI);
2590 else if (isa<ConstantPointerNull>(V))
2591 return getIntegerSCEV(0, V->getType());
2592 else if (isa<UndefValue>(V))
2593 return getIntegerSCEV(0, V->getType());
2595 return getUnknown(V);
2597 User *U = cast<User>(V);
2599 case Instruction::Add:
2600 return getAddExpr(getSCEV(U->getOperand(0)),
2601 getSCEV(U->getOperand(1)));
2602 case Instruction::Mul:
2603 return getMulExpr(getSCEV(U->getOperand(0)),
2604 getSCEV(U->getOperand(1)));
2605 case Instruction::UDiv:
2606 return getUDivExpr(getSCEV(U->getOperand(0)),
2607 getSCEV(U->getOperand(1)));
2608 case Instruction::Sub:
2609 return getMinusSCEV(getSCEV(U->getOperand(0)),
2610 getSCEV(U->getOperand(1)));
2611 case Instruction::And:
2612 // For an expression like x&255 that merely masks off the high bits,
2613 // use zext(trunc(x)) as the SCEV expression.
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2615 if (CI->isNullValue())
2616 return getSCEV(U->getOperand(1));
2617 if (CI->isAllOnesValue())
2618 return getSCEV(U->getOperand(0));
2619 const APInt &A = CI->getValue();
2621 // Instcombine's ShrinkDemandedConstant may strip bits out of
2622 // constants, obscuring what would otherwise be a low-bits mask.
2623 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2624 // knew about to reconstruct a low-bits mask value.
2625 unsigned LZ = A.countLeadingZeros();
2626 unsigned BitWidth = A.getBitWidth();
2627 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2628 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2629 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2631 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2633 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2635 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2636 IntegerType::get(BitWidth - LZ)),
2641 case Instruction::Or:
2642 // If the RHS of the Or is a constant, we may have something like:
2643 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2644 // optimizations will transparently handle this case.
2646 // In order for this transformation to be safe, the LHS must be of the
2647 // form X*(2^n) and the Or constant must be less than 2^n.
2648 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2649 const SCEV *LHS = getSCEV(U->getOperand(0));
2650 const APInt &CIVal = CI->getValue();
2651 if (GetMinTrailingZeros(LHS) >=
2652 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2653 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2656 case Instruction::Xor:
2657 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2658 // If the RHS of the xor is a signbit, then this is just an add.
2659 // Instcombine turns add of signbit into xor as a strength reduction step.
2660 if (CI->getValue().isSignBit())
2661 return getAddExpr(getSCEV(U->getOperand(0)),
2662 getSCEV(U->getOperand(1)));
2664 // If the RHS of xor is -1, then this is a not operation.
2665 if (CI->isAllOnesValue())
2666 return getNotSCEV(getSCEV(U->getOperand(0)));
2668 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2669 // This is a variant of the check for xor with -1, and it handles
2670 // the case where instcombine has trimmed non-demanded bits out
2671 // of an xor with -1.
2672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2673 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2674 if (BO->getOpcode() == Instruction::And &&
2675 LCI->getValue() == CI->getValue())
2676 if (const SCEVZeroExtendExpr *Z =
2677 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2678 const Type *UTy = U->getType();
2679 const SCEV *Z0 = Z->getOperand();
2680 const Type *Z0Ty = Z0->getType();
2681 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2683 // If C is a low-bits mask, the zero extend is zerving to
2684 // mask off the high bits. Complement the operand and
2685 // re-apply the zext.
2686 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2687 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2689 // If C is a single bit, it may be in the sign-bit position
2690 // before the zero-extend. In this case, represent the xor
2691 // using an add, which is equivalent, and re-apply the zext.
2692 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2693 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2695 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2701 case Instruction::Shl:
2702 // Turn shift left of a constant amount into a multiply.
2703 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2704 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2705 Constant *X = ConstantInt::get(
2706 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2707 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2711 case Instruction::LShr:
2712 // Turn logical shift right of a constant into a unsigned divide.
2713 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2714 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2715 Constant *X = ConstantInt::get(
2716 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2717 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2721 case Instruction::AShr:
2722 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2723 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2724 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2725 if (L->getOpcode() == Instruction::Shl &&
2726 L->getOperand(1) == U->getOperand(1)) {
2727 unsigned BitWidth = getTypeSizeInBits(U->getType());
2728 uint64_t Amt = BitWidth - CI->getZExtValue();
2729 if (Amt == BitWidth)
2730 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2732 return getIntegerSCEV(0, U->getType()); // value is undefined
2734 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2735 IntegerType::get(Amt)),
2740 case Instruction::Trunc:
2741 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2743 case Instruction::ZExt:
2744 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2746 case Instruction::SExt:
2747 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2749 case Instruction::BitCast:
2750 // BitCasts are no-op casts so we just eliminate the cast.
2751 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2752 return getSCEV(U->getOperand(0));
2755 case Instruction::IntToPtr:
2756 if (!TD) break; // Without TD we can't analyze pointers.
2757 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2758 TD->getIntPtrType());
2760 case Instruction::PtrToInt:
2761 if (!TD) break; // Without TD we can't analyze pointers.
2762 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2765 case Instruction::GetElementPtr:
2766 if (!TD) break; // Without TD we can't analyze pointers.
2767 return createNodeForGEP(U);
2769 case Instruction::PHI:
2770 return createNodeForPHI(cast<PHINode>(U));
2772 case Instruction::Select:
2773 // This could be a smax or umax that was lowered earlier.
2774 // Try to recover it.
2775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2776 Value *LHS = ICI->getOperand(0);
2777 Value *RHS = ICI->getOperand(1);
2778 switch (ICI->getPredicate()) {
2779 case ICmpInst::ICMP_SLT:
2780 case ICmpInst::ICMP_SLE:
2781 std::swap(LHS, RHS);
2783 case ICmpInst::ICMP_SGT:
2784 case ICmpInst::ICMP_SGE:
2785 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2786 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2787 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2788 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
2790 case ICmpInst::ICMP_ULT:
2791 case ICmpInst::ICMP_ULE:
2792 std::swap(LHS, RHS);
2794 case ICmpInst::ICMP_UGT:
2795 case ICmpInst::ICMP_UGE:
2796 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2797 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2798 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2799 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
2801 case ICmpInst::ICMP_NE:
2802 // n != 0 ? n : 1 -> umax(n, 1)
2803 if (LHS == U->getOperand(1) &&
2804 isa<ConstantInt>(U->getOperand(2)) &&
2805 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2806 isa<ConstantInt>(RHS) &&
2807 cast<ConstantInt>(RHS)->isZero())
2808 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2810 case ICmpInst::ICMP_EQ:
2811 // n == 0 ? 1 : n -> umax(n, 1)
2812 if (LHS == U->getOperand(2) &&
2813 isa<ConstantInt>(U->getOperand(1)) &&
2814 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2815 isa<ConstantInt>(RHS) &&
2816 cast<ConstantInt>(RHS)->isZero())
2817 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2824 default: // We cannot analyze this expression.
2828 return getUnknown(V);
2833 //===----------------------------------------------------------------------===//
2834 // Iteration Count Computation Code
2837 /// getBackedgeTakenCount - If the specified loop has a predictable
2838 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2839 /// object. The backedge-taken count is the number of times the loop header
2840 /// will be branched to from within the loop. This is one less than the
2841 /// trip count of the loop, since it doesn't count the first iteration,
2842 /// when the header is branched to from outside the loop.
2844 /// Note that it is not valid to call this method on a loop without a
2845 /// loop-invariant backedge-taken count (see
2846 /// hasLoopInvariantBackedgeTakenCount).
2848 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2849 return getBackedgeTakenInfo(L).Exact;
2852 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2853 /// return the least SCEV value that is known never to be less than the
2854 /// actual backedge taken count.
2855 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2856 return getBackedgeTakenInfo(L).Max;
2859 const ScalarEvolution::BackedgeTakenInfo &
2860 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2861 // Initially insert a CouldNotCompute for this loop. If the insertion
2862 // succeeds, procede to actually compute a backedge-taken count and
2863 // update the value. The temporary CouldNotCompute value tells SCEV
2864 // code elsewhere that it shouldn't attempt to request a new
2865 // backedge-taken count, which could result in infinite recursion.
2866 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2867 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2869 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2870 if (ItCount.Exact != getCouldNotCompute()) {
2871 assert(ItCount.Exact->isLoopInvariant(L) &&
2872 ItCount.Max->isLoopInvariant(L) &&
2873 "Computed trip count isn't loop invariant for loop!");
2874 ++NumTripCountsComputed;
2876 // Update the value in the map.
2877 Pair.first->second = ItCount;
2879 if (ItCount.Max != getCouldNotCompute())
2880 // Update the value in the map.
2881 Pair.first->second = ItCount;
2882 if (isa<PHINode>(L->getHeader()->begin()))
2883 // Only count loops that have phi nodes as not being computable.
2884 ++NumTripCountsNotComputed;
2887 // Now that we know more about the trip count for this loop, forget any
2888 // existing SCEV values for PHI nodes in this loop since they are only
2889 // conservative estimates made without the benefit
2890 // of trip count information.
2891 if (ItCount.hasAnyInfo())
2894 return Pair.first->second;
2897 /// forgetLoopBackedgeTakenCount - This method should be called by the
2898 /// client when it has changed a loop in a way that may effect
2899 /// ScalarEvolution's ability to compute a trip count, or if the loop
2901 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2902 BackedgeTakenCounts.erase(L);
2906 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2907 /// PHI nodes in the given loop. This is used when the trip count of
2908 /// the loop may have changed.
2909 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2910 BasicBlock *Header = L->getHeader();
2912 // Push all Loop-header PHIs onto the Worklist stack, except those
2913 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2914 // a PHI either means that it has an unrecognized structure, or it's
2915 // a PHI that's in the progress of being computed by createNodeForPHI.
2916 // In the former case, additional loop trip count information isn't
2917 // going to change anything. In the later case, createNodeForPHI will
2918 // perform the necessary updates on its own when it gets to that point.
2919 SmallVector<Instruction *, 16> Worklist;
2920 for (BasicBlock::iterator I = Header->begin();
2921 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2922 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2923 Scalars.find((Value*)I);
2924 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2925 Worklist.push_back(PN);
2928 while (!Worklist.empty()) {
2929 Instruction *I = Worklist.pop_back_val();
2930 if (Scalars.erase(I))
2931 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2933 Worklist.push_back(cast<Instruction>(UI));
2937 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2938 /// of the specified loop will execute.
2939 ScalarEvolution::BackedgeTakenInfo
2940 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2941 SmallVector<BasicBlock*, 8> ExitingBlocks;
2942 L->getExitingBlocks(ExitingBlocks);
2944 // Examine all exits and pick the most conservative values.
2945 const SCEV *BECount = getCouldNotCompute();
2946 const SCEV *MaxBECount = getCouldNotCompute();
2947 bool CouldNotComputeBECount = false;
2948 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2949 BackedgeTakenInfo NewBTI =
2950 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
2952 if (NewBTI.Exact == getCouldNotCompute()) {
2953 // We couldn't compute an exact value for this exit, so
2954 // we won't be able to compute an exact value for the loop.
2955 CouldNotComputeBECount = true;
2956 BECount = getCouldNotCompute();
2957 } else if (!CouldNotComputeBECount) {
2958 if (BECount == getCouldNotCompute())
2959 BECount = NewBTI.Exact;
2961 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
2963 if (MaxBECount == getCouldNotCompute())
2964 MaxBECount = NewBTI.Max;
2965 else if (NewBTI.Max != getCouldNotCompute())
2966 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
2969 return BackedgeTakenInfo(BECount, MaxBECount);
2972 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2973 /// of the specified loop will execute if it exits via the specified block.
2974 ScalarEvolution::BackedgeTakenInfo
2975 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2976 BasicBlock *ExitingBlock) {
2978 // Okay, we've chosen an exiting block. See what condition causes us to
2979 // exit at this block.
2981 // FIXME: we should be able to handle switch instructions (with a single exit)
2982 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2983 if (ExitBr == 0) return getCouldNotCompute();
2984 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2986 // At this point, we know we have a conditional branch that determines whether
2987 // the loop is exited. However, we don't know if the branch is executed each
2988 // time through the loop. If not, then the execution count of the branch will
2989 // not be equal to the trip count of the loop.
2991 // Currently we check for this by checking to see if the Exit branch goes to
2992 // the loop header. If so, we know it will always execute the same number of
2993 // times as the loop. We also handle the case where the exit block *is* the
2994 // loop header. This is common for un-rotated loops.
2996 // If both of those tests fail, walk up the unique predecessor chain to the
2997 // header, stopping if there is an edge that doesn't exit the loop. If the
2998 // header is reached, the execution count of the branch will be equal to the
2999 // trip count of the loop.
3001 // More extensive analysis could be done to handle more cases here.
3003 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3004 ExitBr->getSuccessor(1) != L->getHeader() &&
3005 ExitBr->getParent() != L->getHeader()) {
3006 // The simple checks failed, try climbing the unique predecessor chain
3007 // up to the header.
3009 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3010 BasicBlock *Pred = BB->getUniquePredecessor();
3012 return getCouldNotCompute();
3013 TerminatorInst *PredTerm = Pred->getTerminator();
3014 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3015 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3018 // If the predecessor has a successor that isn't BB and isn't
3019 // outside the loop, assume the worst.
3020 if (L->contains(PredSucc))
3021 return getCouldNotCompute();
3023 if (Pred == L->getHeader()) {
3030 return getCouldNotCompute();
3033 // Procede to the next level to examine the exit condition expression.
3034 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3035 ExitBr->getSuccessor(0),
3036 ExitBr->getSuccessor(1));
3039 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3040 /// backedge of the specified loop will execute if its exit condition
3041 /// were a conditional branch of ExitCond, TBB, and FBB.
3042 ScalarEvolution::BackedgeTakenInfo
3043 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3047 // Check if the controlling expression for this loop is an And or Or.
3048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3049 if (BO->getOpcode() == Instruction::And) {
3050 // Recurse on the operands of the and.
3051 BackedgeTakenInfo BTI0 =
3052 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3053 BackedgeTakenInfo BTI1 =
3054 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3055 const SCEV *BECount = getCouldNotCompute();
3056 const SCEV *MaxBECount = getCouldNotCompute();
3057 if (L->contains(TBB)) {
3058 // Both conditions must be true for the loop to continue executing.
3059 // Choose the less conservative count.
3060 if (BTI0.Exact == getCouldNotCompute() ||
3061 BTI1.Exact == getCouldNotCompute())
3062 BECount = getCouldNotCompute();
3064 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3065 if (BTI0.Max == getCouldNotCompute())
3066 MaxBECount = BTI1.Max;
3067 else if (BTI1.Max == getCouldNotCompute())
3068 MaxBECount = BTI0.Max;
3070 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3072 // Both conditions must be true for the loop to exit.
3073 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3074 if (BTI0.Exact != getCouldNotCompute() &&
3075 BTI1.Exact != getCouldNotCompute())
3076 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3077 if (BTI0.Max != getCouldNotCompute() &&
3078 BTI1.Max != getCouldNotCompute())
3079 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3082 return BackedgeTakenInfo(BECount, MaxBECount);
3084 if (BO->getOpcode() == Instruction::Or) {
3085 // Recurse on the operands of the or.
3086 BackedgeTakenInfo BTI0 =
3087 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3088 BackedgeTakenInfo BTI1 =
3089 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3090 const SCEV *BECount = getCouldNotCompute();
3091 const SCEV *MaxBECount = getCouldNotCompute();
3092 if (L->contains(FBB)) {
3093 // Both conditions must be false for the loop to continue executing.
3094 // Choose the less conservative count.
3095 if (BTI0.Exact == getCouldNotCompute() ||
3096 BTI1.Exact == getCouldNotCompute())
3097 BECount = getCouldNotCompute();
3099 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3100 if (BTI0.Max == getCouldNotCompute())
3101 MaxBECount = BTI1.Max;
3102 else if (BTI1.Max == getCouldNotCompute())
3103 MaxBECount = BTI0.Max;
3105 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3107 // Both conditions must be false for the loop to exit.
3108 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3109 if (BTI0.Exact != getCouldNotCompute() &&
3110 BTI1.Exact != getCouldNotCompute())
3111 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3112 if (BTI0.Max != getCouldNotCompute() &&
3113 BTI1.Max != getCouldNotCompute())
3114 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3117 return BackedgeTakenInfo(BECount, MaxBECount);
3121 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3122 // Procede to the next level to examine the icmp.
3123 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3124 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3126 // If it's not an integer or pointer comparison then compute it the hard way.
3127 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3130 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3131 /// backedge of the specified loop will execute if its exit condition
3132 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3133 ScalarEvolution::BackedgeTakenInfo
3134 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3139 // If the condition was exit on true, convert the condition to exit on false
3140 ICmpInst::Predicate Cond;
3141 if (!L->contains(FBB))
3142 Cond = ExitCond->getPredicate();
3144 Cond = ExitCond->getInversePredicate();
3146 // Handle common loops like: for (X = "string"; *X; ++X)
3147 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3148 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3150 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3151 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3152 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3153 return BackedgeTakenInfo(ItCnt,
3154 isa<SCEVConstant>(ItCnt) ? ItCnt :
3155 getConstant(APInt::getMaxValue(BitWidth)-1));
3159 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3160 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3162 // Try to evaluate any dependencies out of the loop.
3163 LHS = getSCEVAtScope(LHS, L);
3164 RHS = getSCEVAtScope(RHS, L);
3166 // At this point, we would like to compute how many iterations of the
3167 // loop the predicate will return true for these inputs.
3168 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3169 // If there is a loop-invariant, force it into the RHS.
3170 std::swap(LHS, RHS);
3171 Cond = ICmpInst::getSwappedPredicate(Cond);
3174 // If we have a comparison of a chrec against a constant, try to use value
3175 // ranges to answer this query.
3176 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3177 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3178 if (AddRec->getLoop() == L) {
3179 // Form the constant range.
3180 ConstantRange CompRange(
3181 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3183 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3184 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3188 case ICmpInst::ICMP_NE: { // while (X != Y)
3189 // Convert to: while (X-Y != 0)
3190 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3191 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3194 case ICmpInst::ICMP_EQ: {
3195 // Convert to: while (X-Y == 0) // while (X == Y)
3196 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3197 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3200 case ICmpInst::ICMP_SLT: {
3201 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3202 if (BTI.hasAnyInfo()) return BTI;
3205 case ICmpInst::ICMP_SGT: {
3206 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3207 getNotSCEV(RHS), L, true);
3208 if (BTI.hasAnyInfo()) return BTI;
3211 case ICmpInst::ICMP_ULT: {
3212 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3213 if (BTI.hasAnyInfo()) return BTI;
3216 case ICmpInst::ICMP_UGT: {
3217 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3218 getNotSCEV(RHS), L, false);
3219 if (BTI.hasAnyInfo()) return BTI;
3224 errs() << "ComputeBackedgeTakenCount ";
3225 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3226 errs() << "[unsigned] ";
3227 errs() << *LHS << " "
3228 << Instruction::getOpcodeName(Instruction::ICmp)
3229 << " " << *RHS << "\n";
3234 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3237 static ConstantInt *
3238 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3239 ScalarEvolution &SE) {
3240 const SCEV *InVal = SE.getConstant(C);
3241 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3242 assert(isa<SCEVConstant>(Val) &&
3243 "Evaluation of SCEV at constant didn't fold correctly?");
3244 return cast<SCEVConstant>(Val)->getValue();
3247 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3248 /// and a GEP expression (missing the pointer index) indexing into it, return
3249 /// the addressed element of the initializer or null if the index expression is
3252 GetAddressedElementFromGlobal(GlobalVariable *GV,
3253 const std::vector<ConstantInt*> &Indices) {
3254 Constant *Init = GV->getInitializer();
3255 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3256 uint64_t Idx = Indices[i]->getZExtValue();
3257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3258 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3259 Init = cast<Constant>(CS->getOperand(Idx));
3260 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3261 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3262 Init = cast<Constant>(CA->getOperand(Idx));
3263 } else if (isa<ConstantAggregateZero>(Init)) {
3264 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3265 assert(Idx < STy->getNumElements() && "Bad struct index!");
3266 Init = Constant::getNullValue(STy->getElementType(Idx));
3267 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3268 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3269 Init = Constant::getNullValue(ATy->getElementType());
3271 assert(0 && "Unknown constant aggregate type!");
3275 return 0; // Unknown initializer type
3281 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3282 /// 'icmp op load X, cst', try to see if we can compute the backedge
3283 /// execution count.
3285 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3289 ICmpInst::Predicate predicate) {
3290 if (LI->isVolatile()) return getCouldNotCompute();
3292 // Check to see if the loaded pointer is a getelementptr of a global.
3293 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3294 if (!GEP) return getCouldNotCompute();
3296 // Make sure that it is really a constant global we are gepping, with an
3297 // initializer, and make sure the first IDX is really 0.
3298 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3299 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3300 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3301 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3302 return getCouldNotCompute();
3304 // Okay, we allow one non-constant index into the GEP instruction.
3306 std::vector<ConstantInt*> Indexes;
3307 unsigned VarIdxNum = 0;
3308 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3309 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3310 Indexes.push_back(CI);
3311 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3312 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3313 VarIdx = GEP->getOperand(i);
3315 Indexes.push_back(0);
3318 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3319 // Check to see if X is a loop variant variable value now.
3320 const SCEV *Idx = getSCEV(VarIdx);
3321 Idx = getSCEVAtScope(Idx, L);
3323 // We can only recognize very limited forms of loop index expressions, in
3324 // particular, only affine AddRec's like {C1,+,C2}.
3325 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3326 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3327 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3328 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3329 return getCouldNotCompute();
3331 unsigned MaxSteps = MaxBruteForceIterations;
3332 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3333 ConstantInt *ItCst =
3334 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
3335 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3337 // Form the GEP offset.
3338 Indexes[VarIdxNum] = Val;
3340 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3341 if (Result == 0) break; // Cannot compute!
3343 // Evaluate the condition for this iteration.
3344 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3345 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3346 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3348 errs() << "\n***\n*** Computed loop count " << *ItCst
3349 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3352 ++NumArrayLenItCounts;
3353 return getConstant(ItCst); // Found terminating iteration!
3356 return getCouldNotCompute();
3360 /// CanConstantFold - Return true if we can constant fold an instruction of the
3361 /// specified type, assuming that all operands were constants.
3362 static bool CanConstantFold(const Instruction *I) {
3363 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3364 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3367 if (const CallInst *CI = dyn_cast<CallInst>(I))
3368 if (const Function *F = CI->getCalledFunction())
3369 return canConstantFoldCallTo(F);
3373 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3374 /// in the loop that V is derived from. We allow arbitrary operations along the
3375 /// way, but the operands of an operation must either be constants or a value
3376 /// derived from a constant PHI. If this expression does not fit with these
3377 /// constraints, return null.
3378 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3379 // If this is not an instruction, or if this is an instruction outside of the
3380 // loop, it can't be derived from a loop PHI.
3381 Instruction *I = dyn_cast<Instruction>(V);
3382 if (I == 0 || !L->contains(I->getParent())) return 0;
3384 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3385 if (L->getHeader() == I->getParent())
3388 // We don't currently keep track of the control flow needed to evaluate
3389 // PHIs, so we cannot handle PHIs inside of loops.
3393 // If we won't be able to constant fold this expression even if the operands
3394 // are constants, return early.
3395 if (!CanConstantFold(I)) return 0;
3397 // Otherwise, we can evaluate this instruction if all of its operands are
3398 // constant or derived from a PHI node themselves.
3400 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3401 if (!(isa<Constant>(I->getOperand(Op)) ||
3402 isa<GlobalValue>(I->getOperand(Op)))) {
3403 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3404 if (P == 0) return 0; // Not evolving from PHI
3408 return 0; // Evolving from multiple different PHIs.
3411 // This is a expression evolving from a constant PHI!
3415 /// EvaluateExpression - Given an expression that passes the
3416 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3417 /// in the loop has the value PHIVal. If we can't fold this expression for some
3418 /// reason, return null.
3419 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3420 if (isa<PHINode>(V)) return PHIVal;
3421 if (Constant *C = dyn_cast<Constant>(V)) return C;
3422 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3423 Instruction *I = cast<Instruction>(V);
3424 LLVMContext *Context = I->getParent()->getContext();
3426 std::vector<Constant*> Operands;
3427 Operands.resize(I->getNumOperands());
3429 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3430 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3431 if (Operands[i] == 0) return 0;
3434 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3435 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3436 &Operands[0], Operands.size(),
3439 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3440 &Operands[0], Operands.size(),
3444 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3445 /// in the header of its containing loop, we know the loop executes a
3446 /// constant number of times, and the PHI node is just a recurrence
3447 /// involving constants, fold it.
3449 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3452 std::map<PHINode*, Constant*>::iterator I =
3453 ConstantEvolutionLoopExitValue.find(PN);
3454 if (I != ConstantEvolutionLoopExitValue.end())
3457 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3458 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3460 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3462 // Since the loop is canonicalized, the PHI node must have two entries. One
3463 // entry must be a constant (coming in from outside of the loop), and the
3464 // second must be derived from the same PHI.
3465 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3466 Constant *StartCST =
3467 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3469 return RetVal = 0; // Must be a constant.
3471 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3472 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3474 return RetVal = 0; // Not derived from same PHI.
3476 // Execute the loop symbolically to determine the exit value.
3477 if (BEs.getActiveBits() >= 32)
3478 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3480 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3481 unsigned IterationNum = 0;
3482 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3483 if (IterationNum == NumIterations)
3484 return RetVal = PHIVal; // Got exit value!
3486 // Compute the value of the PHI node for the next iteration.
3487 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3488 if (NextPHI == PHIVal)
3489 return RetVal = NextPHI; // Stopped evolving!
3491 return 0; // Couldn't evaluate!
3496 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3497 /// constant number of times (the condition evolves only from constants),
3498 /// try to evaluate a few iterations of the loop until we get the exit
3499 /// condition gets a value of ExitWhen (true or false). If we cannot
3500 /// evaluate the trip count of the loop, return getCouldNotCompute().
3502 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3505 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3506 if (PN == 0) return getCouldNotCompute();
3508 // Since the loop is canonicalized, the PHI node must have two entries. One
3509 // entry must be a constant (coming in from outside of the loop), and the
3510 // second must be derived from the same PHI.
3511 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3512 Constant *StartCST =
3513 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3514 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3516 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3517 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3518 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3520 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3521 // the loop symbolically to determine when the condition gets a value of
3523 unsigned IterationNum = 0;
3524 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3525 for (Constant *PHIVal = StartCST;
3526 IterationNum != MaxIterations; ++IterationNum) {
3527 ConstantInt *CondVal =
3528 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3530 // Couldn't symbolically evaluate.
3531 if (!CondVal) return getCouldNotCompute();
3533 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3534 ++NumBruteForceTripCountsComputed;
3535 return getConstant(Type::Int32Ty, IterationNum);
3538 // Compute the value of the PHI node for the next iteration.
3539 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3540 if (NextPHI == 0 || NextPHI == PHIVal)
3541 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3545 // Too many iterations were needed to evaluate.
3546 return getCouldNotCompute();
3549 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3550 /// at the specified scope in the program. The L value specifies a loop
3551 /// nest to evaluate the expression at, where null is the top-level or a
3552 /// specified loop is immediately inside of the loop.
3554 /// This method can be used to compute the exit value for a variable defined
3555 /// in a loop by querying what the value will hold in the parent loop.
3557 /// In the case that a relevant loop exit value cannot be computed, the
3558 /// original value V is returned.
3559 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3560 // FIXME: this should be turned into a virtual method on SCEV!
3562 if (isa<SCEVConstant>(V)) return V;
3564 // If this instruction is evolved from a constant-evolving PHI, compute the
3565 // exit value from the loop without using SCEVs.
3566 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3567 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3568 const Loop *LI = (*this->LI)[I->getParent()];
3569 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3570 if (PHINode *PN = dyn_cast<PHINode>(I))
3571 if (PN->getParent() == LI->getHeader()) {
3572 // Okay, there is no closed form solution for the PHI node. Check
3573 // to see if the loop that contains it has a known backedge-taken
3574 // count. If so, we may be able to force computation of the exit
3576 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3577 if (const SCEVConstant *BTCC =
3578 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3579 // Okay, we know how many times the containing loop executes. If
3580 // this is a constant evolving PHI node, get the final value at
3581 // the specified iteration number.
3582 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3583 BTCC->getValue()->getValue(),
3585 if (RV) return getSCEV(RV);
3589 // Okay, this is an expression that we cannot symbolically evaluate
3590 // into a SCEV. Check to see if it's possible to symbolically evaluate
3591 // the arguments into constants, and if so, try to constant propagate the
3592 // result. This is particularly useful for computing loop exit values.
3593 if (CanConstantFold(I)) {
3594 // Check to see if we've folded this instruction at this loop before.
3595 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3596 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3597 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3599 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3601 std::vector<Constant*> Operands;
3602 Operands.reserve(I->getNumOperands());
3603 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3604 Value *Op = I->getOperand(i);
3605 if (Constant *C = dyn_cast<Constant>(Op)) {
3606 Operands.push_back(C);
3608 // If any of the operands is non-constant and if they are
3609 // non-integer and non-pointer, don't even try to analyze them
3610 // with scev techniques.
3611 if (!isSCEVable(Op->getType()))
3614 const SCEV *OpV = getSCEVAtScope(getSCEV(Op), L);
3615 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3616 Constant *C = SC->getValue();
3617 if (C->getType() != Op->getType())
3618 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3622 Operands.push_back(C);
3623 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3624 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3625 if (C->getType() != Op->getType())
3627 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3631 Operands.push_back(C);
3641 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3642 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3643 &Operands[0], Operands.size(),
3646 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3647 &Operands[0], Operands.size(), Context);
3648 Pair.first->second = C;
3653 // This is some other type of SCEVUnknown, just return it.
3657 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3658 // Avoid performing the look-up in the common case where the specified
3659 // expression has no loop-variant portions.
3660 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3661 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3662 if (OpAtScope != Comm->getOperand(i)) {
3663 // Okay, at least one of these operands is loop variant but might be
3664 // foldable. Build a new instance of the folded commutative expression.
3665 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3666 Comm->op_begin()+i);
3667 NewOps.push_back(OpAtScope);
3669 for (++i; i != e; ++i) {
3670 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3671 NewOps.push_back(OpAtScope);
3673 if (isa<SCEVAddExpr>(Comm))
3674 return getAddExpr(NewOps);
3675 if (isa<SCEVMulExpr>(Comm))
3676 return getMulExpr(NewOps);
3677 if (isa<SCEVSMaxExpr>(Comm))
3678 return getSMaxExpr(NewOps);
3679 if (isa<SCEVUMaxExpr>(Comm))
3680 return getUMaxExpr(NewOps);
3681 assert(0 && "Unknown commutative SCEV type!");
3684 // If we got here, all operands are loop invariant.
3688 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3689 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3690 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
3691 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3692 return Div; // must be loop invariant
3693 return getUDivExpr(LHS, RHS);
3696 // If this is a loop recurrence for a loop that does not contain L, then we
3697 // are dealing with the final value computed by the loop.
3698 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3699 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3700 // To evaluate this recurrence, we need to know how many times the AddRec
3701 // loop iterates. Compute this now.
3702 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3703 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
3705 // Then, evaluate the AddRec.
3706 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3711 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3712 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3713 if (Op == Cast->getOperand())
3714 return Cast; // must be loop invariant
3715 return getZeroExtendExpr(Op, Cast->getType());
3718 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3719 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3720 if (Op == Cast->getOperand())
3721 return Cast; // must be loop invariant
3722 return getSignExtendExpr(Op, Cast->getType());
3725 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3726 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
3727 if (Op == Cast->getOperand())
3728 return Cast; // must be loop invariant
3729 return getTruncateExpr(Op, Cast->getType());
3732 assert(0 && "Unknown SCEV type!");
3736 /// getSCEVAtScope - This is a convenience function which does
3737 /// getSCEVAtScope(getSCEV(V), L).
3738 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3739 return getSCEVAtScope(getSCEV(V), L);
3742 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3743 /// following equation:
3745 /// A * X = B (mod N)
3747 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3748 /// A and B isn't important.
3750 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3751 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3752 ScalarEvolution &SE) {
3753 uint32_t BW = A.getBitWidth();
3754 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3755 assert(A != 0 && "A must be non-zero.");
3759 // The gcd of A and N may have only one prime factor: 2. The number of
3760 // trailing zeros in A is its multiplicity
3761 uint32_t Mult2 = A.countTrailingZeros();
3764 // 2. Check if B is divisible by D.
3766 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3767 // is not less than multiplicity of this prime factor for D.
3768 if (B.countTrailingZeros() < Mult2)
3769 return SE.getCouldNotCompute();
3771 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3774 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3775 // bit width during computations.
3776 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3777 APInt Mod(BW + 1, 0);
3778 Mod.set(BW - Mult2); // Mod = N / D
3779 APInt I = AD.multiplicativeInverse(Mod);
3781 // 4. Compute the minimum unsigned root of the equation:
3782 // I * (B / D) mod (N / D)
3783 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3785 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3787 return SE.getConstant(Result.trunc(BW));
3790 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3791 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3792 /// might be the same) or two SCEVCouldNotCompute objects.
3794 static std::pair<const SCEV *,const SCEV *>
3795 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3796 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3797 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3798 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3799 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3801 // We currently can only solve this if the coefficients are constants.
3802 if (!LC || !MC || !NC) {
3803 const SCEV *CNC = SE.getCouldNotCompute();
3804 return std::make_pair(CNC, CNC);
3807 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3808 const APInt &L = LC->getValue()->getValue();
3809 const APInt &M = MC->getValue()->getValue();
3810 const APInt &N = NC->getValue()->getValue();
3811 APInt Two(BitWidth, 2);
3812 APInt Four(BitWidth, 4);
3815 using namespace APIntOps;
3817 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3818 // The B coefficient is M-N/2
3822 // The A coefficient is N/2
3823 APInt A(N.sdiv(Two));
3825 // Compute the B^2-4ac term.
3828 SqrtTerm -= Four * (A * C);
3830 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3831 // integer value or else APInt::sqrt() will assert.
3832 APInt SqrtVal(SqrtTerm.sqrt());
3834 // Compute the two solutions for the quadratic formula.
3835 // The divisions must be performed as signed divisions.
3837 APInt TwoA( A << 1 );
3838 if (TwoA.isMinValue()) {
3839 const SCEV *CNC = SE.getCouldNotCompute();
3840 return std::make_pair(CNC, CNC);
3843 LLVMContext *Context = SE.getContext();
3845 ConstantInt *Solution1 =
3846 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3847 ConstantInt *Solution2 =
3848 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
3850 return std::make_pair(SE.getConstant(Solution1),
3851 SE.getConstant(Solution2));
3852 } // end APIntOps namespace
3855 /// HowFarToZero - Return the number of times a backedge comparing the specified
3856 /// value to zero will execute. If not computable, return CouldNotCompute.
3857 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3858 // If the value is a constant
3859 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3860 // If the value is already zero, the branch will execute zero times.
3861 if (C->getValue()->isZero()) return C;
3862 return getCouldNotCompute(); // Otherwise it will loop infinitely.
3865 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3866 if (!AddRec || AddRec->getLoop() != L)
3867 return getCouldNotCompute();
3869 if (AddRec->isAffine()) {
3870 // If this is an affine expression, the execution count of this branch is
3871 // the minimum unsigned root of the following equation:
3873 // Start + Step*N = 0 (mod 2^BW)
3877 // Step*N = -Start (mod 2^BW)
3879 // where BW is the common bit width of Start and Step.
3881 // Get the initial value for the loop.
3882 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3883 L->getParentLoop());
3884 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3885 L->getParentLoop());
3887 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3888 // For now we handle only constant steps.
3890 // First, handle unitary steps.
3891 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3892 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3893 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3894 return Start; // N = Start (as unsigned)
3896 // Then, try to solve the above equation provided that Start is constant.
3897 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3898 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3899 -StartC->getValue()->getValue(),
3902 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3903 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3904 // the quadratic equation to solve it.
3905 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
3907 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3908 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3911 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3912 << " sol#2: " << *R2 << "\n";
3914 // Pick the smallest positive root value.
3915 if (ConstantInt *CB =
3916 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
3917 R1->getValue(), R2->getValue()))) {
3918 if (CB->getZExtValue() == false)
3919 std::swap(R1, R2); // R1 is the minimum root now.
3921 // We can only use this value if the chrec ends up with an exact zero
3922 // value at this index. When solving for "X*X != 5", for example, we
3923 // should not accept a root of 2.
3924 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
3926 return R1; // We found a quadratic root!
3931 return getCouldNotCompute();
3934 /// HowFarToNonZero - Return the number of times a backedge checking the
3935 /// specified value for nonzero will execute. If not computable, return
3937 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3938 // Loops that look like: while (X == 0) are very strange indeed. We don't
3939 // handle them yet except for the trivial case. This could be expanded in the
3940 // future as needed.
3942 // If the value is a constant, check to see if it is known to be non-zero
3943 // already. If so, the backedge will execute zero times.
3944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3945 if (!C->getValue()->isNullValue())
3946 return getIntegerSCEV(0, C->getType());
3947 return getCouldNotCompute(); // Otherwise it will loop infinitely.
3950 // We could implement others, but I really doubt anyone writes loops like
3951 // this, and if they did, they would already be constant folded.
3952 return getCouldNotCompute();
3955 /// getLoopPredecessor - If the given loop's header has exactly one unique
3956 /// predecessor outside the loop, return it. Otherwise return null.
3958 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3959 BasicBlock *Header = L->getHeader();
3960 BasicBlock *Pred = 0;
3961 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3963 if (!L->contains(*PI)) {
3964 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3970 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3971 /// (which may not be an immediate predecessor) which has exactly one
3972 /// successor from which BB is reachable, or null if no such block is
3976 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3977 // If the block has a unique predecessor, then there is no path from the
3978 // predecessor to the block that does not go through the direct edge
3979 // from the predecessor to the block.
3980 if (BasicBlock *Pred = BB->getSinglePredecessor())
3983 // A loop's header is defined to be a block that dominates the loop.
3984 // If the header has a unique predecessor outside the loop, it must be
3985 // a block that has exactly one successor that can reach the loop.
3986 if (Loop *L = LI->getLoopFor(BB))
3987 return getLoopPredecessor(L);
3992 /// HasSameValue - SCEV structural equivalence is usually sufficient for
3993 /// testing whether two expressions are equal, however for the purposes of
3994 /// looking for a condition guarding a loop, it can be useful to be a little
3995 /// more general, since a front-end may have replicated the controlling
3998 static bool HasSameValue(const SCEV *A, const SCEV *B) {
3999 // Quick check to see if they are the same SCEV.
4000 if (A == B) return true;
4002 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4003 // two different instructions with the same value. Check for this case.
4004 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4005 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4006 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4007 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4008 if (AI->isIdenticalTo(BI))
4011 // Otherwise assume they may have a different value.
4015 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
4016 /// a conditional between LHS and RHS. This is used to help avoid max
4017 /// expressions in loop trip counts.
4018 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4019 ICmpInst::Predicate Pred,
4020 const SCEV *LHS, const SCEV *RHS) {
4021 // Interpret a null as meaning no loop, where there is obviously no guard
4022 // (interprocedural conditions notwithstanding).
4023 if (!L) return false;
4025 BasicBlock *Predecessor = getLoopPredecessor(L);
4026 BasicBlock *PredecessorDest = L->getHeader();
4028 // Starting at the loop predecessor, climb up the predecessor chain, as long
4029 // as there are predecessors that can be found that have unique successors
4030 // leading to the original header.
4032 PredecessorDest = Predecessor,
4033 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4035 BranchInst *LoopEntryPredicate =
4036 dyn_cast<BranchInst>(Predecessor->getTerminator());
4037 if (!LoopEntryPredicate ||
4038 LoopEntryPredicate->isUnconditional())
4041 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4042 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4049 /// isNecessaryCond - Test whether the given CondValue value is a condition
4050 /// which is at least as strict as the one described by Pred, LHS, and RHS.
4051 bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4052 ICmpInst::Predicate Pred,
4053 const SCEV *LHS, const SCEV *RHS,
4055 // Recursivly handle And and Or conditions.
4056 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4057 if (BO->getOpcode() == Instruction::And) {
4059 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4060 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4061 } else if (BO->getOpcode() == Instruction::Or) {
4063 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4064 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4068 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4069 if (!ICI) return false;
4071 // Now that we found a conditional branch that dominates the loop, check to
4072 // see if it is the comparison we are looking for.
4073 Value *PreCondLHS = ICI->getOperand(0);
4074 Value *PreCondRHS = ICI->getOperand(1);
4075 ICmpInst::Predicate Cond;
4077 Cond = ICI->getInversePredicate();
4079 Cond = ICI->getPredicate();
4082 ; // An exact match.
4083 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4084 ; // The actual condition is beyond sufficient.
4086 // Check a few special cases.
4088 case ICmpInst::ICMP_UGT:
4089 if (Pred == ICmpInst::ICMP_ULT) {
4090 std::swap(PreCondLHS, PreCondRHS);
4091 Cond = ICmpInst::ICMP_ULT;
4095 case ICmpInst::ICMP_SGT:
4096 if (Pred == ICmpInst::ICMP_SLT) {
4097 std::swap(PreCondLHS, PreCondRHS);
4098 Cond = ICmpInst::ICMP_SLT;
4102 case ICmpInst::ICMP_NE:
4103 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4104 // so check for this case by checking if the NE is comparing against
4105 // a minimum or maximum constant.
4106 if (!ICmpInst::isTrueWhenEqual(Pred))
4107 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4108 const APInt &A = CI->getValue();
4110 case ICmpInst::ICMP_SLT:
4111 if (A.isMaxSignedValue()) break;
4113 case ICmpInst::ICMP_SGT:
4114 if (A.isMinSignedValue()) break;
4116 case ICmpInst::ICMP_ULT:
4117 if (A.isMaxValue()) break;
4119 case ICmpInst::ICMP_UGT:
4120 if (A.isMinValue()) break;
4125 Cond = ICmpInst::ICMP_NE;
4126 // NE is symmetric but the original comparison may not be. Swap
4127 // the operands if necessary so that they match below.
4128 if (isa<SCEVConstant>(LHS))
4129 std::swap(PreCondLHS, PreCondRHS);
4134 // We weren't able to reconcile the condition.
4138 if (!PreCondLHS->getType()->isInteger()) return false;
4140 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4141 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4142 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4143 HasSameValue(RHS, PreCondRHSSCEV)) ||
4144 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4145 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4148 /// getBECount - Subtract the end and start values and divide by the step,
4149 /// rounding up, to get the number of times the backedge is executed. Return
4150 /// CouldNotCompute if an intermediate computation overflows.
4151 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4154 const Type *Ty = Start->getType();
4155 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4156 const SCEV *Diff = getMinusSCEV(End, Start);
4157 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4159 // Add an adjustment to the difference between End and Start so that
4160 // the division will effectively round up.
4161 const SCEV *Add = getAddExpr(Diff, RoundUp);
4163 // Check Add for unsigned overflow.
4164 // TODO: More sophisticated things could be done here.
4165 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
4166 const SCEV *OperandExtendedAdd =
4167 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4168 getZeroExtendExpr(RoundUp, WideTy));
4169 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4170 return getCouldNotCompute();
4172 return getUDivExpr(Add, Step);
4175 /// HowManyLessThans - Return the number of times a backedge containing the
4176 /// specified less-than comparison will execute. If not computable, return
4177 /// CouldNotCompute.
4178 ScalarEvolution::BackedgeTakenInfo
4179 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4180 const Loop *L, bool isSigned) {
4181 // Only handle: "ADDREC < LoopInvariant".
4182 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4184 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4185 if (!AddRec || AddRec->getLoop() != L)
4186 return getCouldNotCompute();
4188 if (AddRec->isAffine()) {
4189 // FORNOW: We only support unit strides.
4190 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4191 const SCEV *Step = AddRec->getStepRecurrence(*this);
4193 // TODO: handle non-constant strides.
4194 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4195 if (!CStep || CStep->isZero())
4196 return getCouldNotCompute();
4197 if (CStep->isOne()) {
4198 // With unit stride, the iteration never steps past the limit value.
4199 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4200 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4201 // Test whether a positive iteration iteration can step past the limit
4202 // value and past the maximum value for its type in a single step.
4204 APInt Max = APInt::getSignedMaxValue(BitWidth);
4205 if ((Max - CStep->getValue()->getValue())
4206 .slt(CLimit->getValue()->getValue()))
4207 return getCouldNotCompute();
4209 APInt Max = APInt::getMaxValue(BitWidth);
4210 if ((Max - CStep->getValue()->getValue())
4211 .ult(CLimit->getValue()->getValue()))
4212 return getCouldNotCompute();
4215 // TODO: handle non-constant limit values below.
4216 return getCouldNotCompute();
4218 // TODO: handle negative strides below.
4219 return getCouldNotCompute();
4221 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4222 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4223 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4224 // treat m-n as signed nor unsigned due to overflow possibility.
4226 // First, we get the value of the LHS in the first iteration: n
4227 const SCEV *Start = AddRec->getOperand(0);
4229 // Determine the minimum constant start value.
4230 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
4231 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4232 APInt::getMinValue(BitWidth));
4234 // If we know that the condition is true in order to enter the loop,
4235 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4236 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4237 // the division must round up.
4238 const SCEV *End = RHS;
4239 if (!isLoopGuardedByCond(L,
4240 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4241 getMinusSCEV(Start, Step), RHS))
4242 End = isSigned ? getSMaxExpr(RHS, Start)
4243 : getUMaxExpr(RHS, Start);
4245 // Determine the maximum constant end value.
4246 const SCEV *MaxEnd =
4247 isa<SCEVConstant>(End) ? End :
4248 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4249 .ashr(GetMinSignBits(End) - 1) :
4250 APInt::getMaxValue(BitWidth)
4251 .lshr(GetMinLeadingZeros(End)));
4253 // Finally, we subtract these two values and divide, rounding up, to get
4254 // the number of times the backedge is executed.
4255 const SCEV *BECount = getBECount(Start, End, Step);
4257 // The maximum backedge count is similar, except using the minimum start
4258 // value and the maximum end value.
4259 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
4261 return BackedgeTakenInfo(BECount, MaxBECount);
4264 return getCouldNotCompute();
4267 /// getNumIterationsInRange - Return the number of iterations of this loop that
4268 /// produce values in the specified constant range. Another way of looking at
4269 /// this is that it returns the first iteration number where the value is not in
4270 /// the condition, thus computing the exit count. If the iteration count can't
4271 /// be computed, an instance of SCEVCouldNotCompute is returned.
4272 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4273 ScalarEvolution &SE) const {
4274 if (Range.isFullSet()) // Infinite loop.
4275 return SE.getCouldNotCompute();
4277 // If the start is a non-zero constant, shift the range to simplify things.
4278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4279 if (!SC->getValue()->isZero()) {
4280 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4281 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4282 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4283 if (const SCEVAddRecExpr *ShiftedAddRec =
4284 dyn_cast<SCEVAddRecExpr>(Shifted))
4285 return ShiftedAddRec->getNumIterationsInRange(
4286 Range.subtract(SC->getValue()->getValue()), SE);
4287 // This is strange and shouldn't happen.
4288 return SE.getCouldNotCompute();
4291 // The only time we can solve this is when we have all constant indices.
4292 // Otherwise, we cannot determine the overflow conditions.
4293 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4294 if (!isa<SCEVConstant>(getOperand(i)))
4295 return SE.getCouldNotCompute();
4298 // Okay at this point we know that all elements of the chrec are constants and
4299 // that the start element is zero.
4301 // First check to see if the range contains zero. If not, the first
4303 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4304 if (!Range.contains(APInt(BitWidth, 0)))
4305 return SE.getIntegerSCEV(0, getType());
4308 // If this is an affine expression then we have this situation:
4309 // Solve {0,+,A} in Range === Ax in Range
4311 // We know that zero is in the range. If A is positive then we know that
4312 // the upper value of the range must be the first possible exit value.
4313 // If A is negative then the lower of the range is the last possible loop
4314 // value. Also note that we already checked for a full range.
4315 APInt One(BitWidth,1);
4316 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4317 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4319 // The exit value should be (End+A)/A.
4320 APInt ExitVal = (End + A).udiv(A);
4321 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
4323 // Evaluate at the exit value. If we really did fall out of the valid
4324 // range, then we computed our trip count, otherwise wrap around or other
4325 // things must have happened.
4326 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4327 if (Range.contains(Val->getValue()))
4328 return SE.getCouldNotCompute(); // Something strange happened
4330 // Ensure that the previous value is in the range. This is a sanity check.
4331 assert(Range.contains(
4332 EvaluateConstantChrecAtConstant(this,
4333 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
4334 "Linear scev computation is off in a bad way!");
4335 return SE.getConstant(ExitValue);
4336 } else if (isQuadratic()) {
4337 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4338 // quadratic equation to solve it. To do this, we must frame our problem in
4339 // terms of figuring out when zero is crossed, instead of when
4340 // Range.getUpper() is crossed.
4341 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
4342 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4343 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4345 // Next, solve the constructed addrec
4346 std::pair<const SCEV *,const SCEV *> Roots =
4347 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4348 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4349 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4351 // Pick the smallest positive root value.
4352 if (ConstantInt *CB =
4353 dyn_cast<ConstantInt>(
4354 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4355 R1->getValue(), R2->getValue()))) {
4356 if (CB->getZExtValue() == false)
4357 std::swap(R1, R2); // R1 is the minimum root now.
4359 // Make sure the root is not off by one. The returned iteration should
4360 // not be in the range, but the previous one should be. When solving
4361 // for "X*X < 5", for example, we should not return a root of 2.
4362 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4365 if (Range.contains(R1Val->getValue())) {
4366 // The next iteration must be out of the range...
4367 ConstantInt *NextVal =
4368 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
4370 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4371 if (!Range.contains(R1Val->getValue()))
4372 return SE.getConstant(NextVal);
4373 return SE.getCouldNotCompute(); // Something strange happened
4376 // If R1 was not in the range, then it is a good return value. Make
4377 // sure that R1-1 WAS in the range though, just in case.
4378 ConstantInt *NextVal =
4379 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
4380 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4381 if (Range.contains(R1Val->getValue()))
4383 return SE.getCouldNotCompute(); // Something strange happened
4388 return SE.getCouldNotCompute();
4393 //===----------------------------------------------------------------------===//
4394 // SCEVCallbackVH Class Implementation
4395 //===----------------------------------------------------------------------===//
4397 void ScalarEvolution::SCEVCallbackVH::deleted() {
4398 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4399 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4400 SE->ConstantEvolutionLoopExitValue.erase(PN);
4401 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4402 SE->ValuesAtScopes.erase(I);
4403 SE->Scalars.erase(getValPtr());
4404 // this now dangles!
4407 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
4408 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4410 // Forget all the expressions associated with users of the old value,
4411 // so that future queries will recompute the expressions using the new
4413 SmallVector<User *, 16> Worklist;
4414 Value *Old = getValPtr();
4415 bool DeleteOld = false;
4416 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4418 Worklist.push_back(*UI);
4419 while (!Worklist.empty()) {
4420 User *U = Worklist.pop_back_val();
4421 // Deleting the Old value will cause this to dangle. Postpone
4422 // that until everything else is done.
4427 if (PHINode *PN = dyn_cast<PHINode>(U))
4428 SE->ConstantEvolutionLoopExitValue.erase(PN);
4429 if (Instruction *I = dyn_cast<Instruction>(U))
4430 SE->ValuesAtScopes.erase(I);
4431 if (SE->Scalars.erase(U))
4432 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4434 Worklist.push_back(*UI);
4437 if (PHINode *PN = dyn_cast<PHINode>(Old))
4438 SE->ConstantEvolutionLoopExitValue.erase(PN);
4439 if (Instruction *I = dyn_cast<Instruction>(Old))
4440 SE->ValuesAtScopes.erase(I);
4441 SE->Scalars.erase(Old);
4442 // this now dangles!
4447 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
4448 : CallbackVH(V), SE(se) {}
4450 //===----------------------------------------------------------------------===//
4451 // ScalarEvolution Class Implementation
4452 //===----------------------------------------------------------------------===//
4454 ScalarEvolution::ScalarEvolution()
4455 : FunctionPass(&ID) {
4458 bool ScalarEvolution::runOnFunction(Function &F) {
4460 LI = &getAnalysis<LoopInfo>();
4461 TD = getAnalysisIfAvailable<TargetData>();
4465 void ScalarEvolution::releaseMemory() {
4467 BackedgeTakenCounts.clear();
4468 ConstantEvolutionLoopExitValue.clear();
4469 ValuesAtScopes.clear();
4470 UniqueSCEVs.clear();
4471 SCEVAllocator.Reset();
4474 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4475 AU.setPreservesAll();
4476 AU.addRequiredTransitive<LoopInfo>();
4479 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
4480 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
4483 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
4485 // Print all inner loops first
4486 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4487 PrintLoopInfo(OS, SE, *I);
4489 OS << "Loop " << L->getHeader()->getName() << ": ";
4491 SmallVector<BasicBlock*, 8> ExitBlocks;
4492 L->getExitBlocks(ExitBlocks);
4493 if (ExitBlocks.size() != 1)
4494 OS << "<multiple exits> ";
4496 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4497 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4499 OS << "Unpredictable backedge-taken count. ";
4503 OS << "Loop " << L->getHeader()->getName() << ": ";
4505 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4506 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4508 OS << "Unpredictable max backedge-taken count. ";
4514 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4515 // ScalarEvolution's implementaiton of the print method is to print
4516 // out SCEV values of all instructions that are interesting. Doing
4517 // this potentially causes it to create new SCEV objects though,
4518 // which technically conflicts with the const qualifier. This isn't
4519 // observable from outside the class though (the hasSCEV function
4520 // notwithstanding), so casting away the const isn't dangerous.
4521 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4523 OS << "Classifying expressions for: " << F->getName() << "\n";
4524 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4525 if (isSCEVable(I->getType())) {
4528 const SCEV *SV = SE.getSCEV(&*I);
4531 const Loop *L = LI->getLoopFor((*I).getParent());
4533 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
4540 OS << "\t\t" "Exits: ";
4541 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
4542 if (!ExitValue->isLoopInvariant(L)) {
4543 OS << "<<Unknown>>";
4552 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4553 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4554 PrintLoopInfo(OS, &SE, *I);
4557 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4558 raw_os_ostream OS(o);