1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression. These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
38 //===----------------------------------------------------------------------===//
40 // There are several good references for the techniques used in this analysis.
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 // On computational properties of chains of recurrences
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
59 //===----------------------------------------------------------------------===//
61 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/InstructionSimplify.h"
73 #include "llvm/Analysis/LoopInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/Assembly/Writer.h"
76 #include "llvm/Target/TargetData.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/ConstantRange.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/GetElementPtrTypeIterator.h"
82 #include "llvm/Support/InstIterator.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/ADT/STLExtras.h"
87 #include "llvm/ADT/SmallPtrSet.h"
91 STATISTIC(NumArrayLenItCounts,
92 "Number of trip counts computed with array length");
93 STATISTIC(NumTripCountsComputed,
94 "Number of loops with predictable loop counts");
95 STATISTIC(NumTripCountsNotComputed,
96 "Number of loops without predictable loop counts");
97 STATISTIC(NumBruteForceTripCountsComputed,
98 "Number of loops with trip counts computed by force");
100 static cl::opt<unsigned>
101 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
102 cl::desc("Maximum number of iterations SCEV will "
103 "symbolically execute a constant "
107 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
108 "Scalar Evolution Analysis", false, true)
109 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
111 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
112 "Scalar Evolution Analysis", false, true)
113 char ScalarEvolution::ID = 0;
115 //===----------------------------------------------------------------------===//
116 // SCEV class definitions
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
120 // Implementation of the SCEV class.
123 void SCEV::dump() const {
128 void SCEV::print(raw_ostream &OS) const {
129 switch (getSCEVType()) {
131 WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false);
134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
135 const SCEV *Op = Trunc->getOperand();
136 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
137 << *Trunc->getType() << ")";
141 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
142 const SCEV *Op = ZExt->getOperand();
143 OS << "(zext " << *Op->getType() << " " << *Op << " to "
144 << *ZExt->getType() << ")";
148 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
149 const SCEV *Op = SExt->getOperand();
150 OS << "(sext " << *Op->getType() << " " << *Op << " to "
151 << *SExt->getType() << ")";
155 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
156 OS << "{" << *AR->getOperand(0);
157 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
158 OS << ",+," << *AR->getOperand(i);
160 if (AR->hasNoUnsignedWrap())
162 if (AR->hasNoSignedWrap())
164 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
172 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
173 const char *OpStr = 0;
174 switch (NAry->getSCEVType()) {
175 case scAddExpr: OpStr = " + "; break;
176 case scMulExpr: OpStr = " * "; break;
177 case scUMaxExpr: OpStr = " umax "; break;
178 case scSMaxExpr: OpStr = " smax "; break;
181 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
184 if (llvm::next(I) != E)
191 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
192 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
196 const SCEVUnknown *U = cast<SCEVUnknown>(this);
198 if (U->isSizeOf(AllocTy)) {
199 OS << "sizeof(" << *AllocTy << ")";
202 if (U->isAlignOf(AllocTy)) {
203 OS << "alignof(" << *AllocTy << ")";
209 if (U->isOffsetOf(CTy, FieldNo)) {
210 OS << "offsetof(" << *CTy << ", ";
211 WriteAsOperand(OS, FieldNo, false);
216 // Otherwise just print it normally.
217 WriteAsOperand(OS, U->getValue(), false);
220 case scCouldNotCompute:
221 OS << "***COULDNOTCOMPUTE***";
225 llvm_unreachable("Unknown SCEV kind!");
228 const Type *SCEV::getType() const {
229 switch (getSCEVType()) {
231 return cast<SCEVConstant>(this)->getType();
235 return cast<SCEVCastExpr>(this)->getType();
240 return cast<SCEVNAryExpr>(this)->getType();
242 return cast<SCEVAddExpr>(this)->getType();
244 return cast<SCEVUDivExpr>(this)->getType();
246 return cast<SCEVUnknown>(this)->getType();
247 case scCouldNotCompute:
248 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
252 llvm_unreachable("Unknown SCEV kind!");
256 bool SCEV::isZero() const {
257 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
258 return SC->getValue()->isZero();
262 bool SCEV::isOne() const {
263 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
264 return SC->getValue()->isOne();
268 bool SCEV::isAllOnesValue() const {
269 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
270 return SC->getValue()->isAllOnesValue();
274 SCEVCouldNotCompute::SCEVCouldNotCompute() :
275 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
277 bool SCEVCouldNotCompute::classof(const SCEV *S) {
278 return S->getSCEVType() == scCouldNotCompute;
281 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
283 ID.AddInteger(scConstant);
286 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
287 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
288 UniqueSCEVs.InsertNode(S, IP);
292 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
293 return getConstant(ConstantInt::get(getContext(), Val));
297 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
298 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
299 return getConstant(ConstantInt::get(ITy, V, isSigned));
302 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
303 unsigned SCEVTy, const SCEV *op, const Type *ty)
304 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
306 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
307 const SCEV *op, const Type *ty)
308 : SCEVCastExpr(ID, scTruncate, op, ty) {
309 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
310 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
311 "Cannot truncate non-integer value!");
314 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
315 const SCEV *op, const Type *ty)
316 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
317 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
318 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
319 "Cannot zero extend non-integer value!");
322 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
323 const SCEV *op, const Type *ty)
324 : SCEVCastExpr(ID, scSignExtend, op, ty) {
325 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
326 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
327 "Cannot sign extend non-integer value!");
330 void SCEVUnknown::deleted() {
331 // Clear this SCEVUnknown from various maps.
332 SE->forgetMemoizedResults(this);
334 // Remove this SCEVUnknown from the uniquing map.
335 SE->UniqueSCEVs.RemoveNode(this);
337 // Release the value.
341 void SCEVUnknown::allUsesReplacedWith(Value *New) {
342 // Clear this SCEVUnknown from various maps.
343 SE->forgetMemoizedResults(this);
345 // Remove this SCEVUnknown from the uniquing map.
346 SE->UniqueSCEVs.RemoveNode(this);
348 // Update this SCEVUnknown to point to the new value. This is needed
349 // because there may still be outstanding SCEVs which still point to
354 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
355 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
356 if (VCE->getOpcode() == Instruction::PtrToInt)
357 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
358 if (CE->getOpcode() == Instruction::GetElementPtr &&
359 CE->getOperand(0)->isNullValue() &&
360 CE->getNumOperands() == 2)
361 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
363 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
371 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
372 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
373 if (VCE->getOpcode() == Instruction::PtrToInt)
374 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
375 if (CE->getOpcode() == Instruction::GetElementPtr &&
376 CE->getOperand(0)->isNullValue()) {
378 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
379 if (const StructType *STy = dyn_cast<StructType>(Ty))
380 if (!STy->isPacked() &&
381 CE->getNumOperands() == 3 &&
382 CE->getOperand(1)->isNullValue()) {
383 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
385 STy->getNumElements() == 2 &&
386 STy->getElementType(0)->isIntegerTy(1)) {
387 AllocTy = STy->getElementType(1);
396 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
397 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
398 if (VCE->getOpcode() == Instruction::PtrToInt)
399 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
400 if (CE->getOpcode() == Instruction::GetElementPtr &&
401 CE->getNumOperands() == 3 &&
402 CE->getOperand(0)->isNullValue() &&
403 CE->getOperand(1)->isNullValue()) {
405 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
406 // Ignore vector types here so that ScalarEvolutionExpander doesn't
407 // emit getelementptrs that index into vectors.
408 if (Ty->isStructTy() || Ty->isArrayTy()) {
410 FieldNo = CE->getOperand(2);
418 //===----------------------------------------------------------------------===//
420 //===----------------------------------------------------------------------===//
423 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
424 /// than the complexity of the RHS. This comparator is used to canonicalize
426 class SCEVComplexityCompare {
427 const LoopInfo *const LI;
429 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
431 // Return true or false if LHS is less than, or at least RHS, respectively.
432 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
433 return compare(LHS, RHS) < 0;
436 // Return negative, zero, or positive, if LHS is less than, equal to, or
437 // greater than RHS, respectively. A three-way result allows recursive
438 // comparisons to be more efficient.
439 int compare(const SCEV *LHS, const SCEV *RHS) const {
440 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
444 // Primarily, sort the SCEVs by their getSCEVType().
445 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
447 return (int)LType - (int)RType;
449 // Aside from the getSCEVType() ordering, the particular ordering
450 // isn't very important except that it's beneficial to be consistent,
451 // so that (a + b) and (b + a) don't end up as different expressions.
454 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
455 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
457 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
458 // not as complete as it could be.
459 const Value *LV = LU->getValue(), *RV = RU->getValue();
461 // Order pointer values after integer values. This helps SCEVExpander
463 bool LIsPointer = LV->getType()->isPointerTy(),
464 RIsPointer = RV->getType()->isPointerTy();
465 if (LIsPointer != RIsPointer)
466 return (int)LIsPointer - (int)RIsPointer;
468 // Compare getValueID values.
469 unsigned LID = LV->getValueID(),
470 RID = RV->getValueID();
472 return (int)LID - (int)RID;
474 // Sort arguments by their position.
475 if (const Argument *LA = dyn_cast<Argument>(LV)) {
476 const Argument *RA = cast<Argument>(RV);
477 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
478 return (int)LArgNo - (int)RArgNo;
481 // For instructions, compare their loop depth, and their operand
482 // count. This is pretty loose.
483 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
484 const Instruction *RInst = cast<Instruction>(RV);
486 // Compare loop depths.
487 const BasicBlock *LParent = LInst->getParent(),
488 *RParent = RInst->getParent();
489 if (LParent != RParent) {
490 unsigned LDepth = LI->getLoopDepth(LParent),
491 RDepth = LI->getLoopDepth(RParent);
492 if (LDepth != RDepth)
493 return (int)LDepth - (int)RDepth;
496 // Compare the number of operands.
497 unsigned LNumOps = LInst->getNumOperands(),
498 RNumOps = RInst->getNumOperands();
499 return (int)LNumOps - (int)RNumOps;
506 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
507 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
509 // Compare constant values.
510 const APInt &LA = LC->getValue()->getValue();
511 const APInt &RA = RC->getValue()->getValue();
512 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
513 if (LBitWidth != RBitWidth)
514 return (int)LBitWidth - (int)RBitWidth;
515 return LA.ult(RA) ? -1 : 1;
519 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
520 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
522 // Compare addrec loop depths.
523 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
524 if (LLoop != RLoop) {
525 unsigned LDepth = LLoop->getLoopDepth(),
526 RDepth = RLoop->getLoopDepth();
527 if (LDepth != RDepth)
528 return (int)LDepth - (int)RDepth;
531 // Addrec complexity grows with operand count.
532 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
533 if (LNumOps != RNumOps)
534 return (int)LNumOps - (int)RNumOps;
536 // Lexicographically compare.
537 for (unsigned i = 0; i != LNumOps; ++i) {
538 long X = compare(LA->getOperand(i), RA->getOperand(i));
550 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
551 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
553 // Lexicographically compare n-ary expressions.
554 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
555 for (unsigned i = 0; i != LNumOps; ++i) {
558 long X = compare(LC->getOperand(i), RC->getOperand(i));
562 return (int)LNumOps - (int)RNumOps;
566 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
567 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
569 // Lexicographically compare udiv expressions.
570 long X = compare(LC->getLHS(), RC->getLHS());
573 return compare(LC->getRHS(), RC->getRHS());
579 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
580 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
582 // Compare cast expressions by operand.
583 return compare(LC->getOperand(), RC->getOperand());
590 llvm_unreachable("Unknown SCEV kind!");
596 /// GroupByComplexity - Given a list of SCEV objects, order them by their
597 /// complexity, and group objects of the same complexity together by value.
598 /// When this routine is finished, we know that any duplicates in the vector are
599 /// consecutive and that complexity is monotonically increasing.
601 /// Note that we go take special precautions to ensure that we get deterministic
602 /// results from this routine. In other words, we don't want the results of
603 /// this to depend on where the addresses of various SCEV objects happened to
606 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
608 if (Ops.size() < 2) return; // Noop
609 if (Ops.size() == 2) {
610 // This is the common case, which also happens to be trivially simple.
612 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
613 if (SCEVComplexityCompare(LI)(RHS, LHS))
618 // Do the rough sort by complexity.
619 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
621 // Now that we are sorted by complexity, group elements of the same
622 // complexity. Note that this is, at worst, N^2, but the vector is likely to
623 // be extremely short in practice. Note that we take this approach because we
624 // do not want to depend on the addresses of the objects we are grouping.
625 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
626 const SCEV *S = Ops[i];
627 unsigned Complexity = S->getSCEVType();
629 // If there are any objects of the same complexity and same value as this
631 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
632 if (Ops[j] == S) { // Found a duplicate.
633 // Move it to immediately after i'th element.
634 std::swap(Ops[i+1], Ops[j]);
635 ++i; // no need to rescan it.
636 if (i == e-2) return; // Done!
644 //===----------------------------------------------------------------------===//
645 // Simple SCEV method implementations
646 //===----------------------------------------------------------------------===//
648 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
650 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
652 const Type* ResultTy) {
653 // Handle the simplest case efficiently.
655 return SE.getTruncateOrZeroExtend(It, ResultTy);
657 // We are using the following formula for BC(It, K):
659 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
661 // Suppose, W is the bitwidth of the return value. We must be prepared for
662 // overflow. Hence, we must assure that the result of our computation is
663 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
664 // safe in modular arithmetic.
666 // However, this code doesn't use exactly that formula; the formula it uses
667 // is something like the following, where T is the number of factors of 2 in
668 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
671 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
673 // This formula is trivially equivalent to the previous formula. However,
674 // this formula can be implemented much more efficiently. The trick is that
675 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
676 // arithmetic. To do exact division in modular arithmetic, all we have
677 // to do is multiply by the inverse. Therefore, this step can be done at
680 // The next issue is how to safely do the division by 2^T. The way this
681 // is done is by doing the multiplication step at a width of at least W + T
682 // bits. This way, the bottom W+T bits of the product are accurate. Then,
683 // when we perform the division by 2^T (which is equivalent to a right shift
684 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
685 // truncated out after the division by 2^T.
687 // In comparison to just directly using the first formula, this technique
688 // is much more efficient; using the first formula requires W * K bits,
689 // but this formula less than W + K bits. Also, the first formula requires
690 // a division step, whereas this formula only requires multiplies and shifts.
692 // It doesn't matter whether the subtraction step is done in the calculation
693 // width or the input iteration count's width; if the subtraction overflows,
694 // the result must be zero anyway. We prefer here to do it in the width of
695 // the induction variable because it helps a lot for certain cases; CodeGen
696 // isn't smart enough to ignore the overflow, which leads to much less
697 // efficient code if the width of the subtraction is wider than the native
700 // (It's possible to not widen at all by pulling out factors of 2 before
701 // the multiplication; for example, K=2 can be calculated as
702 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
703 // extra arithmetic, so it's not an obvious win, and it gets
704 // much more complicated for K > 3.)
706 // Protection from insane SCEVs; this bound is conservative,
707 // but it probably doesn't matter.
709 return SE.getCouldNotCompute();
711 unsigned W = SE.getTypeSizeInBits(ResultTy);
713 // Calculate K! / 2^T and T; we divide out the factors of two before
714 // multiplying for calculating K! / 2^T to avoid overflow.
715 // Other overflow doesn't matter because we only care about the bottom
716 // W bits of the result.
717 APInt OddFactorial(W, 1);
719 for (unsigned i = 3; i <= K; ++i) {
721 unsigned TwoFactors = Mult.countTrailingZeros();
723 Mult = Mult.lshr(TwoFactors);
724 OddFactorial *= Mult;
727 // We need at least W + T bits for the multiplication step
728 unsigned CalculationBits = W + T;
730 // Calculate 2^T, at width T+W.
731 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
733 // Calculate the multiplicative inverse of K! / 2^T;
734 // this multiplication factor will perform the exact division by
736 APInt Mod = APInt::getSignedMinValue(W+1);
737 APInt MultiplyFactor = OddFactorial.zext(W+1);
738 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
739 MultiplyFactor = MultiplyFactor.trunc(W);
741 // Calculate the product, at width T+W
742 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
744 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
745 for (unsigned i = 1; i != K; ++i) {
746 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
747 Dividend = SE.getMulExpr(Dividend,
748 SE.getTruncateOrZeroExtend(S, CalculationTy));
752 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
754 // Truncate the result, and divide by K! / 2^T.
756 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
757 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
760 /// evaluateAtIteration - Return the value of this chain of recurrences at
761 /// the specified iteration number. We can evaluate this recurrence by
762 /// multiplying each element in the chain by the binomial coefficient
763 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
765 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
767 /// where BC(It, k) stands for binomial coefficient.
769 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
770 ScalarEvolution &SE) const {
771 const SCEV *Result = getStart();
772 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
773 // The computation is correct in the face of overflow provided that the
774 // multiplication is performed _after_ the evaluation of the binomial
776 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
777 if (isa<SCEVCouldNotCompute>(Coeff))
780 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
785 //===----------------------------------------------------------------------===//
786 // SCEV Expression folder implementations
787 //===----------------------------------------------------------------------===//
789 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
791 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
792 "This is not a truncating conversion!");
793 assert(isSCEVable(Ty) &&
794 "This is not a conversion to a SCEVable type!");
795 Ty = getEffectiveSCEVType(Ty);
798 ID.AddInteger(scTruncate);
802 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
804 // Fold if the operand is constant.
805 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
807 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
808 getEffectiveSCEVType(Ty))));
810 // trunc(trunc(x)) --> trunc(x)
811 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
812 return getTruncateExpr(ST->getOperand(), Ty);
814 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
815 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
816 return getTruncateOrSignExtend(SS->getOperand(), Ty);
818 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
819 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
820 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
822 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
823 // eliminate all the truncates.
824 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
825 SmallVector<const SCEV *, 4> Operands;
826 bool hasTrunc = false;
827 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
828 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
829 hasTrunc = isa<SCEVTruncateExpr>(S);
830 Operands.push_back(S);
833 return getAddExpr(Operands, false, false);
836 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
837 // eliminate all the truncates.
838 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
839 SmallVector<const SCEV *, 4> Operands;
840 bool hasTrunc = false;
841 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
842 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
843 hasTrunc = isa<SCEVTruncateExpr>(S);
844 Operands.push_back(S);
847 return getMulExpr(Operands, false, false);
850 // If the input value is a chrec scev, truncate the chrec's operands.
851 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
852 SmallVector<const SCEV *, 4> Operands;
853 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
854 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
855 return getAddRecExpr(Operands, AddRec->getLoop());
858 // As a special case, fold trunc(undef) to undef. We don't want to
859 // know too much about SCEVUnknowns, but this special case is handy
861 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
862 if (isa<UndefValue>(U->getValue()))
863 return getSCEV(UndefValue::get(Ty));
865 // The cast wasn't folded; create an explicit cast node. We can reuse
866 // the existing insert position since if we get here, we won't have
867 // made any changes which would invalidate it.
868 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
870 UniqueSCEVs.InsertNode(S, IP);
874 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
876 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
877 "This is not an extending conversion!");
878 assert(isSCEVable(Ty) &&
879 "This is not a conversion to a SCEVable type!");
880 Ty = getEffectiveSCEVType(Ty);
882 // Fold if the operand is constant.
883 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
885 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
886 getEffectiveSCEVType(Ty))));
888 // zext(zext(x)) --> zext(x)
889 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
890 return getZeroExtendExpr(SZ->getOperand(), Ty);
892 // Before doing any expensive analysis, check to see if we've already
893 // computed a SCEV for this Op and Ty.
895 ID.AddInteger(scZeroExtend);
899 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
901 // zext(trunc(x)) --> zext(x) or x or trunc(x)
902 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
903 // It's possible the bits taken off by the truncate were all zero bits. If
904 // so, we should be able to simplify this further.
905 const SCEV *X = ST->getOperand();
906 ConstantRange CR = getUnsignedRange(X);
907 unsigned TruncBits = getTypeSizeInBits(ST->getType());
908 unsigned NewBits = getTypeSizeInBits(Ty);
909 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
910 CR.zextOrTrunc(NewBits)))
911 return getTruncateOrZeroExtend(X, Ty);
914 // If the input value is a chrec scev, and we can prove that the value
915 // did not overflow the old, smaller, value, we can zero extend all of the
916 // operands (often constants). This allows analysis of something like
917 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
918 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
919 if (AR->isAffine()) {
920 const SCEV *Start = AR->getStart();
921 const SCEV *Step = AR->getStepRecurrence(*this);
922 unsigned BitWidth = getTypeSizeInBits(AR->getType());
923 const Loop *L = AR->getLoop();
925 // If we have special knowledge that this addrec won't overflow,
926 // we don't need to do any further analysis.
927 if (AR->hasNoUnsignedWrap())
928 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
929 getZeroExtendExpr(Step, Ty),
932 // Check whether the backedge-taken count is SCEVCouldNotCompute.
933 // Note that this serves two purposes: It filters out loops that are
934 // simply not analyzable, and it covers the case where this code is
935 // being called from within backedge-taken count analysis, such that
936 // attempting to ask for the backedge-taken count would likely result
937 // in infinite recursion. In the later case, the analysis code will
938 // cope with a conservative value, and it will take care to purge
939 // that value once it has finished.
940 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
941 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
942 // Manually compute the final value for AR, checking for
945 // Check whether the backedge-taken count can be losslessly casted to
946 // the addrec's type. The count is always unsigned.
947 const SCEV *CastedMaxBECount =
948 getTruncateOrZeroExtend(MaxBECount, Start->getType());
949 const SCEV *RecastedMaxBECount =
950 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
951 if (MaxBECount == RecastedMaxBECount) {
952 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
953 // Check whether Start+Step*MaxBECount has no unsigned overflow.
954 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
955 const SCEV *Add = getAddExpr(Start, ZMul);
956 const SCEV *OperandExtendedAdd =
957 getAddExpr(getZeroExtendExpr(Start, WideTy),
958 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
959 getZeroExtendExpr(Step, WideTy)));
960 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
961 // Return the expression with the addrec on the outside.
962 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
963 getZeroExtendExpr(Step, Ty),
966 // Similar to above, only this time treat the step value as signed.
967 // This covers loops that count down.
968 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
969 Add = getAddExpr(Start, SMul);
971 getAddExpr(getZeroExtendExpr(Start, WideTy),
972 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
973 getSignExtendExpr(Step, WideTy)));
974 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
975 // Return the expression with the addrec on the outside.
976 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
977 getSignExtendExpr(Step, Ty),
981 // If the backedge is guarded by a comparison with the pre-inc value
982 // the addrec is safe. Also, if the entry is guarded by a comparison
983 // with the start value and the backedge is guarded by a comparison
984 // with the post-inc value, the addrec is safe.
985 if (isKnownPositive(Step)) {
986 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
987 getUnsignedRange(Step).getUnsignedMax());
988 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
989 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
990 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
991 AR->getPostIncExpr(*this), N)))
992 // Return the expression with the addrec on the outside.
993 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
994 getZeroExtendExpr(Step, Ty),
996 } else if (isKnownNegative(Step)) {
997 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
998 getSignedRange(Step).getSignedMin());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1002 AR->getPostIncExpr(*this), N)))
1003 // Return the expression with the addrec on the outside.
1004 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1005 getSignExtendExpr(Step, Ty),
1011 // The cast wasn't folded; create an explicit cast node.
1012 // Recompute the insert position, as it may have been invalidated.
1013 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1014 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1016 UniqueSCEVs.InsertNode(S, IP);
1020 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1022 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1023 "This is not an extending conversion!");
1024 assert(isSCEVable(Ty) &&
1025 "This is not a conversion to a SCEVable type!");
1026 Ty = getEffectiveSCEVType(Ty);
1028 // Fold if the operand is constant.
1029 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1031 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1032 getEffectiveSCEVType(Ty))));
1034 // sext(sext(x)) --> sext(x)
1035 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1036 return getSignExtendExpr(SS->getOperand(), Ty);
1038 // sext(zext(x)) --> zext(x)
1039 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1040 return getZeroExtendExpr(SZ->getOperand(), Ty);
1042 // Before doing any expensive analysis, check to see if we've already
1043 // computed a SCEV for this Op and Ty.
1044 FoldingSetNodeID ID;
1045 ID.AddInteger(scSignExtend);
1049 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1051 // If the input value is provably positive, build a zext instead.
1052 if (isKnownNonNegative(Op))
1053 return getZeroExtendExpr(Op, Ty);
1055 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1056 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1057 // It's possible the bits taken off by the truncate were all sign bits. If
1058 // so, we should be able to simplify this further.
1059 const SCEV *X = ST->getOperand();
1060 ConstantRange CR = getSignedRange(X);
1061 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1062 unsigned NewBits = getTypeSizeInBits(Ty);
1063 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1064 CR.sextOrTrunc(NewBits)))
1065 return getTruncateOrSignExtend(X, Ty);
1068 // If the input value is a chrec scev, and we can prove that the value
1069 // did not overflow the old, smaller, value, we can sign extend all of the
1070 // operands (often constants). This allows analysis of something like
1071 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1072 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1073 if (AR->isAffine()) {
1074 const SCEV *Start = AR->getStart();
1075 const SCEV *Step = AR->getStepRecurrence(*this);
1076 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1077 const Loop *L = AR->getLoop();
1079 // If we have special knowledge that this addrec won't overflow,
1080 // we don't need to do any further analysis.
1081 if (AR->hasNoSignedWrap())
1082 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1083 getSignExtendExpr(Step, Ty),
1086 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1087 // Note that this serves two purposes: It filters out loops that are
1088 // simply not analyzable, and it covers the case where this code is
1089 // being called from within backedge-taken count analysis, such that
1090 // attempting to ask for the backedge-taken count would likely result
1091 // in infinite recursion. In the later case, the analysis code will
1092 // cope with a conservative value, and it will take care to purge
1093 // that value once it has finished.
1094 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1095 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1096 // Manually compute the final value for AR, checking for
1099 // Check whether the backedge-taken count can be losslessly casted to
1100 // the addrec's type. The count is always unsigned.
1101 const SCEV *CastedMaxBECount =
1102 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1103 const SCEV *RecastedMaxBECount =
1104 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1105 if (MaxBECount == RecastedMaxBECount) {
1106 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1107 // Check whether Start+Step*MaxBECount has no signed overflow.
1108 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1109 const SCEV *Add = getAddExpr(Start, SMul);
1110 const SCEV *OperandExtendedAdd =
1111 getAddExpr(getSignExtendExpr(Start, WideTy),
1112 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1113 getSignExtendExpr(Step, WideTy)));
1114 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1115 // Return the expression with the addrec on the outside.
1116 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1117 getSignExtendExpr(Step, Ty),
1120 // Similar to above, only this time treat the step value as unsigned.
1121 // This covers loops that count up with an unsigned step.
1122 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1123 Add = getAddExpr(Start, UMul);
1124 OperandExtendedAdd =
1125 getAddExpr(getSignExtendExpr(Start, WideTy),
1126 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1127 getZeroExtendExpr(Step, WideTy)));
1128 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1129 // Return the expression with the addrec on the outside.
1130 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1131 getZeroExtendExpr(Step, Ty),
1135 // If the backedge is guarded by a comparison with the pre-inc value
1136 // the addrec is safe. Also, if the entry is guarded by a comparison
1137 // with the start value and the backedge is guarded by a comparison
1138 // with the post-inc value, the addrec is safe.
1139 if (isKnownPositive(Step)) {
1140 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1141 getSignedRange(Step).getSignedMax());
1142 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1143 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1144 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1145 AR->getPostIncExpr(*this), N)))
1146 // Return the expression with the addrec on the outside.
1147 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1148 getSignExtendExpr(Step, Ty),
1150 } else if (isKnownNegative(Step)) {
1151 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1152 getSignedRange(Step).getSignedMin());
1153 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1154 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1155 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1156 AR->getPostIncExpr(*this), N)))
1157 // Return the expression with the addrec on the outside.
1158 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1159 getSignExtendExpr(Step, Ty),
1165 // The cast wasn't folded; create an explicit cast node.
1166 // Recompute the insert position, as it may have been invalidated.
1167 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1168 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1170 UniqueSCEVs.InsertNode(S, IP);
1174 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1175 /// unspecified bits out to the given type.
1177 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1179 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1180 "This is not an extending conversion!");
1181 assert(isSCEVable(Ty) &&
1182 "This is not a conversion to a SCEVable type!");
1183 Ty = getEffectiveSCEVType(Ty);
1185 // Sign-extend negative constants.
1186 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1187 if (SC->getValue()->getValue().isNegative())
1188 return getSignExtendExpr(Op, Ty);
1190 // Peel off a truncate cast.
1191 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1192 const SCEV *NewOp = T->getOperand();
1193 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1194 return getAnyExtendExpr(NewOp, Ty);
1195 return getTruncateOrNoop(NewOp, Ty);
1198 // Next try a zext cast. If the cast is folded, use it.
1199 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1200 if (!isa<SCEVZeroExtendExpr>(ZExt))
1203 // Next try a sext cast. If the cast is folded, use it.
1204 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1205 if (!isa<SCEVSignExtendExpr>(SExt))
1208 // Force the cast to be folded into the operands of an addrec.
1209 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1210 SmallVector<const SCEV *, 4> Ops;
1211 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1213 Ops.push_back(getAnyExtendExpr(*I, Ty));
1214 return getAddRecExpr(Ops, AR->getLoop());
1217 // As a special case, fold anyext(undef) to undef. We don't want to
1218 // know too much about SCEVUnknowns, but this special case is handy
1220 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1221 if (isa<UndefValue>(U->getValue()))
1222 return getSCEV(UndefValue::get(Ty));
1224 // If the expression is obviously signed, use the sext cast value.
1225 if (isa<SCEVSMaxExpr>(Op))
1228 // Absent any other information, use the zext cast value.
1232 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1233 /// a list of operands to be added under the given scale, update the given
1234 /// map. This is a helper function for getAddRecExpr. As an example of
1235 /// what it does, given a sequence of operands that would form an add
1236 /// expression like this:
1238 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1240 /// where A and B are constants, update the map with these values:
1242 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1244 /// and add 13 + A*B*29 to AccumulatedConstant.
1245 /// This will allow getAddRecExpr to produce this:
1247 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1249 /// This form often exposes folding opportunities that are hidden in
1250 /// the original operand list.
1252 /// Return true iff it appears that any interesting folding opportunities
1253 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1254 /// the common case where no interesting opportunities are present, and
1255 /// is also used as a check to avoid infinite recursion.
1258 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1259 SmallVector<const SCEV *, 8> &NewOps,
1260 APInt &AccumulatedConstant,
1261 const SCEV *const *Ops, size_t NumOperands,
1263 ScalarEvolution &SE) {
1264 bool Interesting = false;
1266 // Iterate over the add operands. They are sorted, with constants first.
1268 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1270 // Pull a buried constant out to the outside.
1271 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1273 AccumulatedConstant += Scale * C->getValue()->getValue();
1276 // Next comes everything else. We're especially interested in multiplies
1277 // here, but they're in the middle, so just visit the rest with one loop.
1278 for (; i != NumOperands; ++i) {
1279 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1280 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1282 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1283 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1284 // A multiplication of a constant with another add; recurse.
1285 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1287 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1288 Add->op_begin(), Add->getNumOperands(),
1291 // A multiplication of a constant with some other value. Update
1293 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1294 const SCEV *Key = SE.getMulExpr(MulOps);
1295 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1296 M.insert(std::make_pair(Key, NewScale));
1298 NewOps.push_back(Pair.first->first);
1300 Pair.first->second += NewScale;
1301 // The map already had an entry for this value, which may indicate
1302 // a folding opportunity.
1307 // An ordinary operand. Update the map.
1308 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1309 M.insert(std::make_pair(Ops[i], Scale));
1311 NewOps.push_back(Pair.first->first);
1313 Pair.first->second += Scale;
1314 // The map already had an entry for this value, which may indicate
1315 // a folding opportunity.
1325 struct APIntCompare {
1326 bool operator()(const APInt &LHS, const APInt &RHS) const {
1327 return LHS.ult(RHS);
1332 /// getAddExpr - Get a canonical add expression, or something simpler if
1334 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1335 bool HasNUW, bool HasNSW) {
1336 assert(!Ops.empty() && "Cannot get empty add!");
1337 if (Ops.size() == 1) return Ops[0];
1339 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1340 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1341 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1342 "SCEVAddExpr operand types don't match!");
1345 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1346 if (!HasNUW && HasNSW) {
1348 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1349 E = Ops.end(); I != E; ++I)
1350 if (!isKnownNonNegative(*I)) {
1354 if (All) HasNUW = true;
1357 // Sort by complexity, this groups all similar expression types together.
1358 GroupByComplexity(Ops, LI);
1360 // If there are any constants, fold them together.
1362 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1364 assert(Idx < Ops.size());
1365 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1366 // We found two constants, fold them together!
1367 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1368 RHSC->getValue()->getValue());
1369 if (Ops.size() == 2) return Ops[0];
1370 Ops.erase(Ops.begin()+1); // Erase the folded element
1371 LHSC = cast<SCEVConstant>(Ops[0]);
1374 // If we are left with a constant zero being added, strip it off.
1375 if (LHSC->getValue()->isZero()) {
1376 Ops.erase(Ops.begin());
1380 if (Ops.size() == 1) return Ops[0];
1383 // Okay, check to see if the same value occurs in the operand list more than
1384 // once. If so, merge them together into an multiply expression. Since we
1385 // sorted the list, these values are required to be adjacent.
1386 const Type *Ty = Ops[0]->getType();
1387 bool FoundMatch = false;
1388 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1389 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1390 // Scan ahead to count how many equal operands there are.
1392 while (i+Count != e && Ops[i+Count] == Ops[i])
1394 // Merge the values into a multiply.
1395 const SCEV *Scale = getConstant(Ty, Count);
1396 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1397 if (Ops.size() == Count)
1400 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1401 --i; e -= Count - 1;
1405 return getAddExpr(Ops, HasNUW, HasNSW);
1407 // Check for truncates. If all the operands are truncated from the same
1408 // type, see if factoring out the truncate would permit the result to be
1409 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1410 // if the contents of the resulting outer trunc fold to something simple.
1411 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1412 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1413 const Type *DstType = Trunc->getType();
1414 const Type *SrcType = Trunc->getOperand()->getType();
1415 SmallVector<const SCEV *, 8> LargeOps;
1417 // Check all the operands to see if they can be represented in the
1418 // source type of the truncate.
1419 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1420 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1421 if (T->getOperand()->getType() != SrcType) {
1425 LargeOps.push_back(T->getOperand());
1426 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1427 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1428 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1429 SmallVector<const SCEV *, 8> LargeMulOps;
1430 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1431 if (const SCEVTruncateExpr *T =
1432 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1433 if (T->getOperand()->getType() != SrcType) {
1437 LargeMulOps.push_back(T->getOperand());
1438 } else if (const SCEVConstant *C =
1439 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1440 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1447 LargeOps.push_back(getMulExpr(LargeMulOps));
1454 // Evaluate the expression in the larger type.
1455 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1456 // If it folds to something simple, use it. Otherwise, don't.
1457 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1458 return getTruncateExpr(Fold, DstType);
1462 // Skip past any other cast SCEVs.
1463 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1466 // If there are add operands they would be next.
1467 if (Idx < Ops.size()) {
1468 bool DeletedAdd = false;
1469 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1470 // If we have an add, expand the add operands onto the end of the operands
1472 Ops.erase(Ops.begin()+Idx);
1473 Ops.append(Add->op_begin(), Add->op_end());
1477 // If we deleted at least one add, we added operands to the end of the list,
1478 // and they are not necessarily sorted. Recurse to resort and resimplify
1479 // any operands we just acquired.
1481 return getAddExpr(Ops);
1484 // Skip over the add expression until we get to a multiply.
1485 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1488 // Check to see if there are any folding opportunities present with
1489 // operands multiplied by constant values.
1490 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1491 uint64_t BitWidth = getTypeSizeInBits(Ty);
1492 DenseMap<const SCEV *, APInt> M;
1493 SmallVector<const SCEV *, 8> NewOps;
1494 APInt AccumulatedConstant(BitWidth, 0);
1495 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1496 Ops.data(), Ops.size(),
1497 APInt(BitWidth, 1), *this)) {
1498 // Some interesting folding opportunity is present, so its worthwhile to
1499 // re-generate the operands list. Group the operands by constant scale,
1500 // to avoid multiplying by the same constant scale multiple times.
1501 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1502 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1503 E = NewOps.end(); I != E; ++I)
1504 MulOpLists[M.find(*I)->second].push_back(*I);
1505 // Re-generate the operands list.
1507 if (AccumulatedConstant != 0)
1508 Ops.push_back(getConstant(AccumulatedConstant));
1509 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1510 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1512 Ops.push_back(getMulExpr(getConstant(I->first),
1513 getAddExpr(I->second)));
1515 return getConstant(Ty, 0);
1516 if (Ops.size() == 1)
1518 return getAddExpr(Ops);
1522 // If we are adding something to a multiply expression, make sure the
1523 // something is not already an operand of the multiply. If so, merge it into
1525 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1526 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1527 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1528 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1529 if (isa<SCEVConstant>(MulOpSCEV))
1531 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1532 if (MulOpSCEV == Ops[AddOp]) {
1533 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1534 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1535 if (Mul->getNumOperands() != 2) {
1536 // If the multiply has more than two operands, we must get the
1538 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1539 Mul->op_begin()+MulOp);
1540 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1541 InnerMul = getMulExpr(MulOps);
1543 const SCEV *One = getConstant(Ty, 1);
1544 const SCEV *AddOne = getAddExpr(One, InnerMul);
1545 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1546 if (Ops.size() == 2) return OuterMul;
1548 Ops.erase(Ops.begin()+AddOp);
1549 Ops.erase(Ops.begin()+Idx-1);
1551 Ops.erase(Ops.begin()+Idx);
1552 Ops.erase(Ops.begin()+AddOp-1);
1554 Ops.push_back(OuterMul);
1555 return getAddExpr(Ops);
1558 // Check this multiply against other multiplies being added together.
1559 for (unsigned OtherMulIdx = Idx+1;
1560 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1562 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1563 // If MulOp occurs in OtherMul, we can fold the two multiplies
1565 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1566 OMulOp != e; ++OMulOp)
1567 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1568 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1569 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1570 if (Mul->getNumOperands() != 2) {
1571 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1572 Mul->op_begin()+MulOp);
1573 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1574 InnerMul1 = getMulExpr(MulOps);
1576 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1577 if (OtherMul->getNumOperands() != 2) {
1578 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1579 OtherMul->op_begin()+OMulOp);
1580 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1581 InnerMul2 = getMulExpr(MulOps);
1583 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1584 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1585 if (Ops.size() == 2) return OuterMul;
1586 Ops.erase(Ops.begin()+Idx);
1587 Ops.erase(Ops.begin()+OtherMulIdx-1);
1588 Ops.push_back(OuterMul);
1589 return getAddExpr(Ops);
1595 // If there are any add recurrences in the operands list, see if any other
1596 // added values are loop invariant. If so, we can fold them into the
1598 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1601 // Scan over all recurrences, trying to fold loop invariants into them.
1602 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1603 // Scan all of the other operands to this add and add them to the vector if
1604 // they are loop invariant w.r.t. the recurrence.
1605 SmallVector<const SCEV *, 8> LIOps;
1606 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1607 const Loop *AddRecLoop = AddRec->getLoop();
1608 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1609 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1610 LIOps.push_back(Ops[i]);
1611 Ops.erase(Ops.begin()+i);
1615 // If we found some loop invariants, fold them into the recurrence.
1616 if (!LIOps.empty()) {
1617 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1618 LIOps.push_back(AddRec->getStart());
1620 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1622 AddRecOps[0] = getAddExpr(LIOps);
1624 // Build the new addrec. Propagate the NUW and NSW flags if both the
1625 // outer add and the inner addrec are guaranteed to have no overflow.
1626 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1627 HasNUW && AddRec->hasNoUnsignedWrap(),
1628 HasNSW && AddRec->hasNoSignedWrap());
1630 // If all of the other operands were loop invariant, we are done.
1631 if (Ops.size() == 1) return NewRec;
1633 // Otherwise, add the folded AddRec by the non-liv parts.
1634 for (unsigned i = 0;; ++i)
1635 if (Ops[i] == AddRec) {
1639 return getAddExpr(Ops);
1642 // Okay, if there weren't any loop invariants to be folded, check to see if
1643 // there are multiple AddRec's with the same loop induction variable being
1644 // added together. If so, we can fold them.
1645 for (unsigned OtherIdx = Idx+1;
1646 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1648 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1649 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1650 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1652 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1654 if (const SCEVAddRecExpr *OtherAddRec =
1655 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1656 if (OtherAddRec->getLoop() == AddRecLoop) {
1657 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1659 if (i >= AddRecOps.size()) {
1660 AddRecOps.append(OtherAddRec->op_begin()+i,
1661 OtherAddRec->op_end());
1664 AddRecOps[i] = getAddExpr(AddRecOps[i],
1665 OtherAddRec->getOperand(i));
1667 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1669 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop);
1670 return getAddExpr(Ops);
1673 // Otherwise couldn't fold anything into this recurrence. Move onto the
1677 // Okay, it looks like we really DO need an add expr. Check to see if we
1678 // already have one, otherwise create a new one.
1679 FoldingSetNodeID ID;
1680 ID.AddInteger(scAddExpr);
1681 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1682 ID.AddPointer(Ops[i]);
1685 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1687 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1688 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1689 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1691 UniqueSCEVs.InsertNode(S, IP);
1693 if (HasNUW) S->setHasNoUnsignedWrap(true);
1694 if (HasNSW) S->setHasNoSignedWrap(true);
1698 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1700 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1701 bool HasNUW, bool HasNSW) {
1702 assert(!Ops.empty() && "Cannot get empty mul!");
1703 if (Ops.size() == 1) return Ops[0];
1705 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1706 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1707 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1708 "SCEVMulExpr operand types don't match!");
1711 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1712 if (!HasNUW && HasNSW) {
1714 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1715 E = Ops.end(); I != E; ++I)
1716 if (!isKnownNonNegative(*I)) {
1720 if (All) HasNUW = true;
1723 // Sort by complexity, this groups all similar expression types together.
1724 GroupByComplexity(Ops, LI);
1726 // If there are any constants, fold them together.
1728 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1730 // C1*(C2+V) -> C1*C2 + C1*V
1731 if (Ops.size() == 2)
1732 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1733 if (Add->getNumOperands() == 2 &&
1734 isa<SCEVConstant>(Add->getOperand(0)))
1735 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1736 getMulExpr(LHSC, Add->getOperand(1)));
1739 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1740 // We found two constants, fold them together!
1741 ConstantInt *Fold = ConstantInt::get(getContext(),
1742 LHSC->getValue()->getValue() *
1743 RHSC->getValue()->getValue());
1744 Ops[0] = getConstant(Fold);
1745 Ops.erase(Ops.begin()+1); // Erase the folded element
1746 if (Ops.size() == 1) return Ops[0];
1747 LHSC = cast<SCEVConstant>(Ops[0]);
1750 // If we are left with a constant one being multiplied, strip it off.
1751 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1752 Ops.erase(Ops.begin());
1754 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1755 // If we have a multiply of zero, it will always be zero.
1757 } else if (Ops[0]->isAllOnesValue()) {
1758 // If we have a mul by -1 of an add, try distributing the -1 among the
1760 if (Ops.size() == 2)
1761 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1762 SmallVector<const SCEV *, 4> NewOps;
1763 bool AnyFolded = false;
1764 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1766 const SCEV *Mul = getMulExpr(Ops[0], *I);
1767 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1768 NewOps.push_back(Mul);
1771 return getAddExpr(NewOps);
1775 if (Ops.size() == 1)
1779 // Skip over the add expression until we get to a multiply.
1780 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1783 // If there are mul operands inline them all into this expression.
1784 if (Idx < Ops.size()) {
1785 bool DeletedMul = false;
1786 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1787 // If we have an mul, expand the mul operands onto the end of the operands
1789 Ops.erase(Ops.begin()+Idx);
1790 Ops.append(Mul->op_begin(), Mul->op_end());
1794 // If we deleted at least one mul, we added operands to the end of the list,
1795 // and they are not necessarily sorted. Recurse to resort and resimplify
1796 // any operands we just acquired.
1798 return getMulExpr(Ops);
1801 // If there are any add recurrences in the operands list, see if any other
1802 // added values are loop invariant. If so, we can fold them into the
1804 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1807 // Scan over all recurrences, trying to fold loop invariants into them.
1808 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1809 // Scan all of the other operands to this mul and add them to the vector if
1810 // they are loop invariant w.r.t. the recurrence.
1811 SmallVector<const SCEV *, 8> LIOps;
1812 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1813 const Loop *AddRecLoop = AddRec->getLoop();
1814 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1815 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1816 LIOps.push_back(Ops[i]);
1817 Ops.erase(Ops.begin()+i);
1821 // If we found some loop invariants, fold them into the recurrence.
1822 if (!LIOps.empty()) {
1823 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1824 SmallVector<const SCEV *, 4> NewOps;
1825 NewOps.reserve(AddRec->getNumOperands());
1826 const SCEV *Scale = getMulExpr(LIOps);
1827 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1828 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1830 // Build the new addrec. Propagate the NUW and NSW flags if both the
1831 // outer mul and the inner addrec are guaranteed to have no overflow.
1832 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop,
1833 HasNUW && AddRec->hasNoUnsignedWrap(),
1834 HasNSW && AddRec->hasNoSignedWrap());
1836 // If all of the other operands were loop invariant, we are done.
1837 if (Ops.size() == 1) return NewRec;
1839 // Otherwise, multiply the folded AddRec by the non-liv parts.
1840 for (unsigned i = 0;; ++i)
1841 if (Ops[i] == AddRec) {
1845 return getMulExpr(Ops);
1848 // Okay, if there weren't any loop invariants to be folded, check to see if
1849 // there are multiple AddRec's with the same loop induction variable being
1850 // multiplied together. If so, we can fold them.
1851 for (unsigned OtherIdx = Idx+1;
1852 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1854 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1855 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1856 // {A*C,+,F*D + G*B + B*D}<L>
1857 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1859 if (const SCEVAddRecExpr *OtherAddRec =
1860 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1861 if (OtherAddRec->getLoop() == AddRecLoop) {
1862 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1863 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1864 const SCEV *B = F->getStepRecurrence(*this);
1865 const SCEV *D = G->getStepRecurrence(*this);
1866 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1869 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1871 if (Ops.size() == 2) return NewAddRec;
1872 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1873 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1875 return getMulExpr(Ops);
1878 // Otherwise couldn't fold anything into this recurrence. Move onto the
1882 // Okay, it looks like we really DO need an mul expr. Check to see if we
1883 // already have one, otherwise create a new one.
1884 FoldingSetNodeID ID;
1885 ID.AddInteger(scMulExpr);
1886 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1887 ID.AddPointer(Ops[i]);
1890 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1892 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1893 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1894 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1896 UniqueSCEVs.InsertNode(S, IP);
1898 if (HasNUW) S->setHasNoUnsignedWrap(true);
1899 if (HasNSW) S->setHasNoSignedWrap(true);
1903 /// getUDivExpr - Get a canonical unsigned division expression, or something
1904 /// simpler if possible.
1905 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1907 assert(getEffectiveSCEVType(LHS->getType()) ==
1908 getEffectiveSCEVType(RHS->getType()) &&
1909 "SCEVUDivExpr operand types don't match!");
1911 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1912 if (RHSC->getValue()->equalsInt(1))
1913 return LHS; // X udiv 1 --> x
1914 // If the denominator is zero, the result of the udiv is undefined. Don't
1915 // try to analyze it, because the resolution chosen here may differ from
1916 // the resolution chosen in other parts of the compiler.
1917 if (!RHSC->getValue()->isZero()) {
1918 // Determine if the division can be folded into the operands of
1920 // TODO: Generalize this to non-constants by using known-bits information.
1921 const Type *Ty = LHS->getType();
1922 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1923 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1924 // For non-power-of-two values, effectively round the value up to the
1925 // nearest power of two.
1926 if (!RHSC->getValue()->getValue().isPowerOf2())
1928 const IntegerType *ExtTy =
1929 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1930 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1931 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1932 if (const SCEVConstant *Step =
1933 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1934 if (!Step->getValue()->getValue()
1935 .urem(RHSC->getValue()->getValue()) &&
1936 getZeroExtendExpr(AR, ExtTy) ==
1937 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1938 getZeroExtendExpr(Step, ExtTy),
1940 SmallVector<const SCEV *, 4> Operands;
1941 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1942 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1943 return getAddRecExpr(Operands, AR->getLoop());
1945 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1946 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1947 SmallVector<const SCEV *, 4> Operands;
1948 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1949 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1950 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1951 // Find an operand that's safely divisible.
1952 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1953 const SCEV *Op = M->getOperand(i);
1954 const SCEV *Div = getUDivExpr(Op, RHSC);
1955 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1956 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1959 return getMulExpr(Operands);
1963 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1964 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1965 SmallVector<const SCEV *, 4> Operands;
1966 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1967 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1968 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1970 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1971 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1972 if (isa<SCEVUDivExpr>(Op) ||
1973 getMulExpr(Op, RHS) != A->getOperand(i))
1975 Operands.push_back(Op);
1977 if (Operands.size() == A->getNumOperands())
1978 return getAddExpr(Operands);
1982 // Fold if both operands are constant.
1983 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1984 Constant *LHSCV = LHSC->getValue();
1985 Constant *RHSCV = RHSC->getValue();
1986 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1992 FoldingSetNodeID ID;
1993 ID.AddInteger(scUDivExpr);
1997 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1998 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2000 UniqueSCEVs.InsertNode(S, IP);
2005 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2006 /// Simplify the expression as much as possible.
2007 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
2008 const SCEV *Step, const Loop *L,
2009 bool HasNUW, bool HasNSW) {
2010 SmallVector<const SCEV *, 4> Operands;
2011 Operands.push_back(Start);
2012 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2013 if (StepChrec->getLoop() == L) {
2014 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2015 return getAddRecExpr(Operands, L);
2018 Operands.push_back(Step);
2019 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
2022 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2023 /// Simplify the expression as much as possible.
2025 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2027 bool HasNUW, bool HasNSW) {
2028 if (Operands.size() == 1) return Operands[0];
2030 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2031 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2032 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2033 "SCEVAddRecExpr operand types don't match!");
2034 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2035 assert(isLoopInvariant(Operands[i], L) &&
2036 "SCEVAddRecExpr operand is not loop-invariant!");
2039 if (Operands.back()->isZero()) {
2040 Operands.pop_back();
2041 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
2044 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2045 // use that information to infer NUW and NSW flags. However, computing a
2046 // BE count requires calling getAddRecExpr, so we may not yet have a
2047 // meaningful BE count at this point (and if we don't, we'd be stuck
2048 // with a SCEVCouldNotCompute as the cached BE count).
2050 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2051 if (!HasNUW && HasNSW) {
2053 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2054 E = Operands.end(); I != E; ++I)
2055 if (!isKnownNonNegative(*I)) {
2059 if (All) HasNUW = true;
2062 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2063 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2064 const Loop *NestedLoop = NestedAR->getLoop();
2065 if (L->contains(NestedLoop) ?
2066 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2067 (!NestedLoop->contains(L) &&
2068 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2069 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2070 NestedAR->op_end());
2071 Operands[0] = NestedAR->getStart();
2072 // AddRecs require their operands be loop-invariant with respect to their
2073 // loops. Don't perform this transformation if it would break this
2075 bool AllInvariant = true;
2076 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2077 if (!isLoopInvariant(Operands[i], L)) {
2078 AllInvariant = false;
2082 NestedOperands[0] = getAddRecExpr(Operands, L);
2083 AllInvariant = true;
2084 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2085 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2086 AllInvariant = false;
2090 // Ok, both add recurrences are valid after the transformation.
2091 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2093 // Reset Operands to its original state.
2094 Operands[0] = NestedAR;
2098 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2099 // already have one, otherwise create a new one.
2100 FoldingSetNodeID ID;
2101 ID.AddInteger(scAddRecExpr);
2102 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2103 ID.AddPointer(Operands[i]);
2107 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2109 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2110 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2111 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2112 O, Operands.size(), L);
2113 UniqueSCEVs.InsertNode(S, IP);
2115 if (HasNUW) S->setHasNoUnsignedWrap(true);
2116 if (HasNSW) S->setHasNoSignedWrap(true);
2120 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2122 SmallVector<const SCEV *, 2> Ops;
2125 return getSMaxExpr(Ops);
2129 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2130 assert(!Ops.empty() && "Cannot get empty smax!");
2131 if (Ops.size() == 1) return Ops[0];
2133 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2134 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2135 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2136 "SCEVSMaxExpr operand types don't match!");
2139 // Sort by complexity, this groups all similar expression types together.
2140 GroupByComplexity(Ops, LI);
2142 // If there are any constants, fold them together.
2144 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2146 assert(Idx < Ops.size());
2147 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2148 // We found two constants, fold them together!
2149 ConstantInt *Fold = ConstantInt::get(getContext(),
2150 APIntOps::smax(LHSC->getValue()->getValue(),
2151 RHSC->getValue()->getValue()));
2152 Ops[0] = getConstant(Fold);
2153 Ops.erase(Ops.begin()+1); // Erase the folded element
2154 if (Ops.size() == 1) return Ops[0];
2155 LHSC = cast<SCEVConstant>(Ops[0]);
2158 // If we are left with a constant minimum-int, strip it off.
2159 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2160 Ops.erase(Ops.begin());
2162 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2163 // If we have an smax with a constant maximum-int, it will always be
2168 if (Ops.size() == 1) return Ops[0];
2171 // Find the first SMax
2172 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2175 // Check to see if one of the operands is an SMax. If so, expand its operands
2176 // onto our operand list, and recurse to simplify.
2177 if (Idx < Ops.size()) {
2178 bool DeletedSMax = false;
2179 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2180 Ops.erase(Ops.begin()+Idx);
2181 Ops.append(SMax->op_begin(), SMax->op_end());
2186 return getSMaxExpr(Ops);
2189 // Okay, check to see if the same value occurs in the operand list twice. If
2190 // so, delete one. Since we sorted the list, these values are required to
2192 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2193 // X smax Y smax Y --> X smax Y
2194 // X smax Y --> X, if X is always greater than Y
2195 if (Ops[i] == Ops[i+1] ||
2196 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2197 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2199 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2200 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2204 if (Ops.size() == 1) return Ops[0];
2206 assert(!Ops.empty() && "Reduced smax down to nothing!");
2208 // Okay, it looks like we really DO need an smax expr. Check to see if we
2209 // already have one, otherwise create a new one.
2210 FoldingSetNodeID ID;
2211 ID.AddInteger(scSMaxExpr);
2212 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2213 ID.AddPointer(Ops[i]);
2215 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2216 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2217 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2218 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2220 UniqueSCEVs.InsertNode(S, IP);
2224 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2226 SmallVector<const SCEV *, 2> Ops;
2229 return getUMaxExpr(Ops);
2233 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2234 assert(!Ops.empty() && "Cannot get empty umax!");
2235 if (Ops.size() == 1) return Ops[0];
2237 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2238 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2239 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2240 "SCEVUMaxExpr operand types don't match!");
2243 // Sort by complexity, this groups all similar expression types together.
2244 GroupByComplexity(Ops, LI);
2246 // If there are any constants, fold them together.
2248 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2250 assert(Idx < Ops.size());
2251 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2252 // We found two constants, fold them together!
2253 ConstantInt *Fold = ConstantInt::get(getContext(),
2254 APIntOps::umax(LHSC->getValue()->getValue(),
2255 RHSC->getValue()->getValue()));
2256 Ops[0] = getConstant(Fold);
2257 Ops.erase(Ops.begin()+1); // Erase the folded element
2258 if (Ops.size() == 1) return Ops[0];
2259 LHSC = cast<SCEVConstant>(Ops[0]);
2262 // If we are left with a constant minimum-int, strip it off.
2263 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2264 Ops.erase(Ops.begin());
2266 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2267 // If we have an umax with a constant maximum-int, it will always be
2272 if (Ops.size() == 1) return Ops[0];
2275 // Find the first UMax
2276 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2279 // Check to see if one of the operands is a UMax. If so, expand its operands
2280 // onto our operand list, and recurse to simplify.
2281 if (Idx < Ops.size()) {
2282 bool DeletedUMax = false;
2283 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2284 Ops.erase(Ops.begin()+Idx);
2285 Ops.append(UMax->op_begin(), UMax->op_end());
2290 return getUMaxExpr(Ops);
2293 // Okay, check to see if the same value occurs in the operand list twice. If
2294 // so, delete one. Since we sorted the list, these values are required to
2296 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2297 // X umax Y umax Y --> X umax Y
2298 // X umax Y --> X, if X is always greater than Y
2299 if (Ops[i] == Ops[i+1] ||
2300 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2301 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2303 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2304 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2308 if (Ops.size() == 1) return Ops[0];
2310 assert(!Ops.empty() && "Reduced umax down to nothing!");
2312 // Okay, it looks like we really DO need a umax expr. Check to see if we
2313 // already have one, otherwise create a new one.
2314 FoldingSetNodeID ID;
2315 ID.AddInteger(scUMaxExpr);
2316 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2317 ID.AddPointer(Ops[i]);
2319 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2320 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2321 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2322 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2324 UniqueSCEVs.InsertNode(S, IP);
2328 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2330 // ~smax(~x, ~y) == smin(x, y).
2331 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2334 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2336 // ~umax(~x, ~y) == umin(x, y)
2337 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2340 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2341 // If we have TargetData, we can bypass creating a target-independent
2342 // constant expression and then folding it back into a ConstantInt.
2343 // This is just a compile-time optimization.
2345 return getConstant(TD->getIntPtrType(getContext()),
2346 TD->getTypeAllocSize(AllocTy));
2348 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2349 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2350 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2352 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2353 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2356 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2357 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2358 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2359 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2361 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2362 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2365 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2367 // If we have TargetData, we can bypass creating a target-independent
2368 // constant expression and then folding it back into a ConstantInt.
2369 // This is just a compile-time optimization.
2371 return getConstant(TD->getIntPtrType(getContext()),
2372 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2374 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2376 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2378 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2379 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2382 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2383 Constant *FieldNo) {
2384 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2386 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2388 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2389 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2392 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2393 // Don't attempt to do anything other than create a SCEVUnknown object
2394 // here. createSCEV only calls getUnknown after checking for all other
2395 // interesting possibilities, and any other code that calls getUnknown
2396 // is doing so in order to hide a value from SCEV canonicalization.
2398 FoldingSetNodeID ID;
2399 ID.AddInteger(scUnknown);
2402 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2403 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2404 "Stale SCEVUnknown in uniquing map!");
2407 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2409 FirstUnknown = cast<SCEVUnknown>(S);
2410 UniqueSCEVs.InsertNode(S, IP);
2414 //===----------------------------------------------------------------------===//
2415 // Basic SCEV Analysis and PHI Idiom Recognition Code
2418 /// isSCEVable - Test if values of the given type are analyzable within
2419 /// the SCEV framework. This primarily includes integer types, and it
2420 /// can optionally include pointer types if the ScalarEvolution class
2421 /// has access to target-specific information.
2422 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2423 // Integers and pointers are always SCEVable.
2424 return Ty->isIntegerTy() || Ty->isPointerTy();
2427 /// getTypeSizeInBits - Return the size in bits of the specified type,
2428 /// for which isSCEVable must return true.
2429 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2430 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2432 // If we have a TargetData, use it!
2434 return TD->getTypeSizeInBits(Ty);
2436 // Integer types have fixed sizes.
2437 if (Ty->isIntegerTy())
2438 return Ty->getPrimitiveSizeInBits();
2440 // The only other support type is pointer. Without TargetData, conservatively
2441 // assume pointers are 64-bit.
2442 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2446 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2447 /// the given type and which represents how SCEV will treat the given
2448 /// type, for which isSCEVable must return true. For pointer types,
2449 /// this is the pointer-sized integer type.
2450 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2451 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2453 if (Ty->isIntegerTy())
2456 // The only other support type is pointer.
2457 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2458 if (TD) return TD->getIntPtrType(getContext());
2460 // Without TargetData, conservatively assume pointers are 64-bit.
2461 return Type::getInt64Ty(getContext());
2464 const SCEV *ScalarEvolution::getCouldNotCompute() {
2465 return &CouldNotCompute;
2468 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2469 /// expression and create a new one.
2470 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2471 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2473 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2474 if (I != ValueExprMap.end()) return I->second;
2475 const SCEV *S = createSCEV(V);
2477 // The process of creating a SCEV for V may have caused other SCEVs
2478 // to have been created, so it's necessary to insert the new entry
2479 // from scratch, rather than trying to remember the insert position
2481 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2485 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2487 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2488 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2490 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2492 const Type *Ty = V->getType();
2493 Ty = getEffectiveSCEVType(Ty);
2494 return getMulExpr(V,
2495 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2498 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2499 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2500 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2502 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2504 const Type *Ty = V->getType();
2505 Ty = getEffectiveSCEVType(Ty);
2506 const SCEV *AllOnes =
2507 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2508 return getMinusSCEV(AllOnes, V);
2511 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1,
2512 /// and thus the HasNUW and HasNSW bits apply to the resultant add, not
2513 /// whether the sub would have overflowed.
2514 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
2515 bool HasNUW, bool HasNSW) {
2516 // Fast path: X - X --> 0.
2518 return getConstant(LHS->getType(), 0);
2521 return getAddExpr(LHS, getNegativeSCEV(RHS), HasNUW, HasNSW);
2524 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2525 /// input value to the specified type. If the type must be extended, it is zero
2528 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, const Type *Ty) {
2529 const Type *SrcTy = V->getType();
2530 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2531 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2532 "Cannot truncate or zero extend with non-integer arguments!");
2533 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2534 return V; // No conversion
2535 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2536 return getTruncateExpr(V, Ty);
2537 return getZeroExtendExpr(V, Ty);
2540 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2541 /// input value to the specified type. If the type must be extended, it is sign
2544 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2546 const Type *SrcTy = V->getType();
2547 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2548 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2549 "Cannot truncate or zero extend with non-integer arguments!");
2550 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2551 return V; // No conversion
2552 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2553 return getTruncateExpr(V, Ty);
2554 return getSignExtendExpr(V, Ty);
2557 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2558 /// input value to the specified type. If the type must be extended, it is zero
2559 /// extended. The conversion must not be narrowing.
2561 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2562 const Type *SrcTy = V->getType();
2563 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2564 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2565 "Cannot noop or zero extend with non-integer arguments!");
2566 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2567 "getNoopOrZeroExtend cannot truncate!");
2568 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2569 return V; // No conversion
2570 return getZeroExtendExpr(V, Ty);
2573 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2574 /// input value to the specified type. If the type must be extended, it is sign
2575 /// extended. The conversion must not be narrowing.
2577 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2578 const Type *SrcTy = V->getType();
2579 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2580 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2581 "Cannot noop or sign extend with non-integer arguments!");
2582 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2583 "getNoopOrSignExtend cannot truncate!");
2584 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2585 return V; // No conversion
2586 return getSignExtendExpr(V, Ty);
2589 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2590 /// the input value to the specified type. If the type must be extended,
2591 /// it is extended with unspecified bits. The conversion must not be
2594 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2595 const Type *SrcTy = V->getType();
2596 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2597 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2598 "Cannot noop or any extend with non-integer arguments!");
2599 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2600 "getNoopOrAnyExtend cannot truncate!");
2601 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2602 return V; // No conversion
2603 return getAnyExtendExpr(V, Ty);
2606 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2607 /// input value to the specified type. The conversion must not be widening.
2609 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2610 const Type *SrcTy = V->getType();
2611 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2612 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2613 "Cannot truncate or noop with non-integer arguments!");
2614 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2615 "getTruncateOrNoop cannot extend!");
2616 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2617 return V; // No conversion
2618 return getTruncateExpr(V, Ty);
2621 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2622 /// the types using zero-extension, and then perform a umax operation
2624 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2626 const SCEV *PromotedLHS = LHS;
2627 const SCEV *PromotedRHS = RHS;
2629 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2630 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2632 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2634 return getUMaxExpr(PromotedLHS, PromotedRHS);
2637 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2638 /// the types using zero-extension, and then perform a umin operation
2640 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2642 const SCEV *PromotedLHS = LHS;
2643 const SCEV *PromotedRHS = RHS;
2645 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2646 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2648 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2650 return getUMinExpr(PromotedLHS, PromotedRHS);
2653 /// PushDefUseChildren - Push users of the given Instruction
2654 /// onto the given Worklist.
2656 PushDefUseChildren(Instruction *I,
2657 SmallVectorImpl<Instruction *> &Worklist) {
2658 // Push the def-use children onto the Worklist stack.
2659 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2661 Worklist.push_back(cast<Instruction>(*UI));
2664 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2665 /// instructions that depend on the given instruction and removes them from
2666 /// the ValueExprMapType map if they reference SymName. This is used during PHI
2669 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2670 SmallVector<Instruction *, 16> Worklist;
2671 PushDefUseChildren(PN, Worklist);
2673 SmallPtrSet<Instruction *, 8> Visited;
2675 while (!Worklist.empty()) {
2676 Instruction *I = Worklist.pop_back_val();
2677 if (!Visited.insert(I)) continue;
2679 ValueExprMapType::iterator It =
2680 ValueExprMap.find(static_cast<Value *>(I));
2681 if (It != ValueExprMap.end()) {
2682 const SCEV *Old = It->second;
2684 // Short-circuit the def-use traversal if the symbolic name
2685 // ceases to appear in expressions.
2686 if (Old != SymName && !hasOperand(Old, SymName))
2689 // SCEVUnknown for a PHI either means that it has an unrecognized
2690 // structure, it's a PHI that's in the progress of being computed
2691 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2692 // additional loop trip count information isn't going to change anything.
2693 // In the second case, createNodeForPHI will perform the necessary
2694 // updates on its own when it gets to that point. In the third, we do
2695 // want to forget the SCEVUnknown.
2696 if (!isa<PHINode>(I) ||
2697 !isa<SCEVUnknown>(Old) ||
2698 (I != PN && Old == SymName)) {
2699 forgetMemoizedResults(Old);
2700 ValueExprMap.erase(It);
2704 PushDefUseChildren(I, Worklist);
2708 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2709 /// a loop header, making it a potential recurrence, or it doesn't.
2711 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2712 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2713 if (L->getHeader() == PN->getParent()) {
2714 // The loop may have multiple entrances or multiple exits; we can analyze
2715 // this phi as an addrec if it has a unique entry value and a unique
2717 Value *BEValueV = 0, *StartValueV = 0;
2718 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2719 Value *V = PN->getIncomingValue(i);
2720 if (L->contains(PN->getIncomingBlock(i))) {
2723 } else if (BEValueV != V) {
2727 } else if (!StartValueV) {
2729 } else if (StartValueV != V) {
2734 if (BEValueV && StartValueV) {
2735 // While we are analyzing this PHI node, handle its value symbolically.
2736 const SCEV *SymbolicName = getUnknown(PN);
2737 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
2738 "PHI node already processed?");
2739 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2741 // Using this symbolic name for the PHI, analyze the value coming around
2743 const SCEV *BEValue = getSCEV(BEValueV);
2745 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2746 // has a special value for the first iteration of the loop.
2748 // If the value coming around the backedge is an add with the symbolic
2749 // value we just inserted, then we found a simple induction variable!
2750 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2751 // If there is a single occurrence of the symbolic value, replace it
2752 // with a recurrence.
2753 unsigned FoundIndex = Add->getNumOperands();
2754 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2755 if (Add->getOperand(i) == SymbolicName)
2756 if (FoundIndex == e) {
2761 if (FoundIndex != Add->getNumOperands()) {
2762 // Create an add with everything but the specified operand.
2763 SmallVector<const SCEV *, 8> Ops;
2764 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2765 if (i != FoundIndex)
2766 Ops.push_back(Add->getOperand(i));
2767 const SCEV *Accum = getAddExpr(Ops);
2769 // This is not a valid addrec if the step amount is varying each
2770 // loop iteration, but is not itself an addrec in this loop.
2771 if (isLoopInvariant(Accum, L) ||
2772 (isa<SCEVAddRecExpr>(Accum) &&
2773 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2774 bool HasNUW = false;
2775 bool HasNSW = false;
2777 // If the increment doesn't overflow, then neither the addrec nor
2778 // the post-increment will overflow.
2779 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2780 if (OBO->hasNoUnsignedWrap())
2782 if (OBO->hasNoSignedWrap())
2784 } else if (const GEPOperator *GEP =
2785 dyn_cast<GEPOperator>(BEValueV)) {
2786 // If the increment is a GEP, then we know it won't perform an
2787 // unsigned overflow, because the address space cannot be
2789 HasNUW |= GEP->isInBounds();
2792 const SCEV *StartVal = getSCEV(StartValueV);
2793 const SCEV *PHISCEV =
2794 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2796 // Since the no-wrap flags are on the increment, they apply to the
2797 // post-incremented value as well.
2798 if (isLoopInvariant(Accum, L))
2799 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2800 Accum, L, HasNUW, HasNSW);
2802 // Okay, for the entire analysis of this edge we assumed the PHI
2803 // to be symbolic. We now need to go back and purge all of the
2804 // entries for the scalars that use the symbolic expression.
2805 ForgetSymbolicName(PN, SymbolicName);
2806 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2810 } else if (const SCEVAddRecExpr *AddRec =
2811 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2812 // Otherwise, this could be a loop like this:
2813 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2814 // In this case, j = {1,+,1} and BEValue is j.
2815 // Because the other in-value of i (0) fits the evolution of BEValue
2816 // i really is an addrec evolution.
2817 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2818 const SCEV *StartVal = getSCEV(StartValueV);
2820 // If StartVal = j.start - j.stride, we can use StartVal as the
2821 // initial step of the addrec evolution.
2822 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2823 AddRec->getOperand(1))) {
2824 const SCEV *PHISCEV =
2825 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2827 // Okay, for the entire analysis of this edge we assumed the PHI
2828 // to be symbolic. We now need to go back and purge all of the
2829 // entries for the scalars that use the symbolic expression.
2830 ForgetSymbolicName(PN, SymbolicName);
2831 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2839 // If the PHI has a single incoming value, follow that value, unless the
2840 // PHI's incoming blocks are in a different loop, in which case doing so
2841 // risks breaking LCSSA form. Instcombine would normally zap these, but
2842 // it doesn't have DominatorTree information, so it may miss cases.
2843 if (Value *V = SimplifyInstruction(PN, TD, DT))
2844 if (LI->replacementPreservesLCSSAForm(PN, V))
2847 // If it's not a loop phi, we can't handle it yet.
2848 return getUnknown(PN);
2851 /// createNodeForGEP - Expand GEP instructions into add and multiply
2852 /// operations. This allows them to be analyzed by regular SCEV code.
2854 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2856 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2857 // Add expression, because the Instruction may be guarded by control flow
2858 // and the no-overflow bits may not be valid for the expression in any
2861 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2862 Value *Base = GEP->getOperand(0);
2863 // Don't attempt to analyze GEPs over unsized objects.
2864 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2865 return getUnknown(GEP);
2866 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2867 gep_type_iterator GTI = gep_type_begin(GEP);
2868 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2872 // Compute the (potentially symbolic) offset in bytes for this index.
2873 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2874 // For a struct, add the member offset.
2875 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2876 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2878 // Add the field offset to the running total offset.
2879 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2881 // For an array, add the element offset, explicitly scaled.
2882 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2883 const SCEV *IndexS = getSCEV(Index);
2884 // Getelementptr indices are signed.
2885 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2887 // Multiply the index by the element size to compute the element offset.
2888 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2890 // Add the element offset to the running total offset.
2891 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2895 // Get the SCEV for the GEP base.
2896 const SCEV *BaseS = getSCEV(Base);
2898 // Add the total offset from all the GEP indices to the base.
2899 return getAddExpr(BaseS, TotalOffset);
2902 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2903 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2904 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2905 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2907 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2908 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2909 return C->getValue()->getValue().countTrailingZeros();
2911 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2912 return std::min(GetMinTrailingZeros(T->getOperand()),
2913 (uint32_t)getTypeSizeInBits(T->getType()));
2915 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2916 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2917 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2918 getTypeSizeInBits(E->getType()) : OpRes;
2921 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2922 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2923 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2924 getTypeSizeInBits(E->getType()) : OpRes;
2927 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2928 // The result is the min of all operands results.
2929 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2930 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2931 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2935 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2936 // The result is the sum of all operands results.
2937 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2938 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2939 for (unsigned i = 1, e = M->getNumOperands();
2940 SumOpRes != BitWidth && i != e; ++i)
2941 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2946 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2947 // The result is the min of all operands results.
2948 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2949 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2950 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2954 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2955 // The result is the min of all operands results.
2956 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2957 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2958 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2962 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2963 // The result is the min of all operands results.
2964 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2965 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2966 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2970 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2971 // For a SCEVUnknown, ask ValueTracking.
2972 unsigned BitWidth = getTypeSizeInBits(U->getType());
2973 APInt Mask = APInt::getAllOnesValue(BitWidth);
2974 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2975 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2976 return Zeros.countTrailingOnes();
2983 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2986 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2987 // See if we've computed this range already.
2988 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
2989 if (I != UnsignedRanges.end())
2992 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2993 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
2995 unsigned BitWidth = getTypeSizeInBits(S->getType());
2996 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2998 // If the value has known zeros, the maximum unsigned value will have those
2999 // known zeros as well.
3000 uint32_t TZ = GetMinTrailingZeros(S);
3002 ConservativeResult =
3003 ConstantRange(APInt::getMinValue(BitWidth),
3004 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3006 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3007 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3008 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3009 X = X.add(getUnsignedRange(Add->getOperand(i)));
3010 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3013 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3014 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3015 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3016 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3017 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3020 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3021 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3022 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3023 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3024 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3027 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3028 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3029 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3030 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3031 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3034 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3035 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3036 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3037 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3040 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3041 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3042 return setUnsignedRange(ZExt,
3043 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3046 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3047 ConstantRange X = getUnsignedRange(SExt->getOperand());
3048 return setUnsignedRange(SExt,
3049 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3052 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3053 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3054 return setUnsignedRange(Trunc,
3055 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3058 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3059 // If there's no unsigned wrap, the value will never be less than its
3061 if (AddRec->hasNoUnsignedWrap())
3062 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3063 if (!C->getValue()->isZero())
3064 ConservativeResult =
3065 ConservativeResult.intersectWith(
3066 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3068 // TODO: non-affine addrec
3069 if (AddRec->isAffine()) {
3070 const Type *Ty = AddRec->getType();
3071 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3072 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3073 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3074 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3076 const SCEV *Start = AddRec->getStart();
3077 const SCEV *Step = AddRec->getStepRecurrence(*this);
3079 ConstantRange StartRange = getUnsignedRange(Start);
3080 ConstantRange StepRange = getSignedRange(Step);
3081 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3082 ConstantRange EndRange =
3083 StartRange.add(MaxBECountRange.multiply(StepRange));
3085 // Check for overflow. This must be done with ConstantRange arithmetic
3086 // because we could be called from within the ScalarEvolution overflow
3088 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3089 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3090 ConstantRange ExtMaxBECountRange =
3091 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3092 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3093 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3095 return setUnsignedRange(AddRec, ConservativeResult);
3097 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3098 EndRange.getUnsignedMin());
3099 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3100 EndRange.getUnsignedMax());
3101 if (Min.isMinValue() && Max.isMaxValue())
3102 return setUnsignedRange(AddRec, ConservativeResult);
3103 return setUnsignedRange(AddRec,
3104 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3108 return setUnsignedRange(AddRec, ConservativeResult);
3111 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3112 // For a SCEVUnknown, ask ValueTracking.
3113 APInt Mask = APInt::getAllOnesValue(BitWidth);
3114 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3115 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3116 if (Ones == ~Zeros + 1)
3117 return setUnsignedRange(U, ConservativeResult);
3118 return setUnsignedRange(U,
3119 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3122 return setUnsignedRange(S, ConservativeResult);
3125 /// getSignedRange - Determine the signed range for a particular SCEV.
3128 ScalarEvolution::getSignedRange(const SCEV *S) {
3129 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3130 if (I != SignedRanges.end())
3133 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3134 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3136 unsigned BitWidth = getTypeSizeInBits(S->getType());
3137 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3139 // If the value has known zeros, the maximum signed value will have those
3140 // known zeros as well.
3141 uint32_t TZ = GetMinTrailingZeros(S);
3143 ConservativeResult =
3144 ConstantRange(APInt::getSignedMinValue(BitWidth),
3145 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3147 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3148 ConstantRange X = getSignedRange(Add->getOperand(0));
3149 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3150 X = X.add(getSignedRange(Add->getOperand(i)));
3151 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3154 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3155 ConstantRange X = getSignedRange(Mul->getOperand(0));
3156 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3157 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3158 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3161 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3162 ConstantRange X = getSignedRange(SMax->getOperand(0));
3163 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3164 X = X.smax(getSignedRange(SMax->getOperand(i)));
3165 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3168 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3169 ConstantRange X = getSignedRange(UMax->getOperand(0));
3170 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3171 X = X.umax(getSignedRange(UMax->getOperand(i)));
3172 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3175 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3176 ConstantRange X = getSignedRange(UDiv->getLHS());
3177 ConstantRange Y = getSignedRange(UDiv->getRHS());
3178 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3181 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3182 ConstantRange X = getSignedRange(ZExt->getOperand());
3183 return setSignedRange(ZExt,
3184 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3187 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3188 ConstantRange X = getSignedRange(SExt->getOperand());
3189 return setSignedRange(SExt,
3190 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3193 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3194 ConstantRange X = getSignedRange(Trunc->getOperand());
3195 return setSignedRange(Trunc,
3196 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3199 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3200 // If there's no signed wrap, and all the operands have the same sign or
3201 // zero, the value won't ever change sign.
3202 if (AddRec->hasNoSignedWrap()) {
3203 bool AllNonNeg = true;
3204 bool AllNonPos = true;
3205 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3206 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3207 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3210 ConservativeResult = ConservativeResult.intersectWith(
3211 ConstantRange(APInt(BitWidth, 0),
3212 APInt::getSignedMinValue(BitWidth)));
3214 ConservativeResult = ConservativeResult.intersectWith(
3215 ConstantRange(APInt::getSignedMinValue(BitWidth),
3216 APInt(BitWidth, 1)));
3219 // TODO: non-affine addrec
3220 if (AddRec->isAffine()) {
3221 const Type *Ty = AddRec->getType();
3222 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3223 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3224 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3225 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3227 const SCEV *Start = AddRec->getStart();
3228 const SCEV *Step = AddRec->getStepRecurrence(*this);
3230 ConstantRange StartRange = getSignedRange(Start);
3231 ConstantRange StepRange = getSignedRange(Step);
3232 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3233 ConstantRange EndRange =
3234 StartRange.add(MaxBECountRange.multiply(StepRange));
3236 // Check for overflow. This must be done with ConstantRange arithmetic
3237 // because we could be called from within the ScalarEvolution overflow
3239 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3240 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3241 ConstantRange ExtMaxBECountRange =
3242 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3243 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3244 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3246 return setSignedRange(AddRec, ConservativeResult);
3248 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3249 EndRange.getSignedMin());
3250 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3251 EndRange.getSignedMax());
3252 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3253 return setSignedRange(AddRec, ConservativeResult);
3254 return setSignedRange(AddRec,
3255 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3259 return setSignedRange(AddRec, ConservativeResult);
3262 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3263 // For a SCEVUnknown, ask ValueTracking.
3264 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3265 return setSignedRange(U, ConservativeResult);
3266 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3268 return setSignedRange(U, ConservativeResult);
3269 return setSignedRange(U, ConservativeResult.intersectWith(
3270 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3271 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3274 return setSignedRange(S, ConservativeResult);
3277 /// createSCEV - We know that there is no SCEV for the specified value.
3278 /// Analyze the expression.
3280 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3281 if (!isSCEVable(V->getType()))
3282 return getUnknown(V);
3284 unsigned Opcode = Instruction::UserOp1;
3285 if (Instruction *I = dyn_cast<Instruction>(V)) {
3286 Opcode = I->getOpcode();
3288 // Don't attempt to analyze instructions in blocks that aren't
3289 // reachable. Such instructions don't matter, and they aren't required
3290 // to obey basic rules for definitions dominating uses which this
3291 // analysis depends on.
3292 if (!DT->isReachableFromEntry(I->getParent()))
3293 return getUnknown(V);
3294 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3295 Opcode = CE->getOpcode();
3296 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3297 return getConstant(CI);
3298 else if (isa<ConstantPointerNull>(V))
3299 return getConstant(V->getType(), 0);
3300 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3301 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3303 return getUnknown(V);
3305 Operator *U = cast<Operator>(V);
3307 case Instruction::Add: {
3308 // The simple thing to do would be to just call getSCEV on both operands
3309 // and call getAddExpr with the result. However if we're looking at a
3310 // bunch of things all added together, this can be quite inefficient,
3311 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3312 // Instead, gather up all the operands and make a single getAddExpr call.
3313 // LLVM IR canonical form means we need only traverse the left operands.
3314 SmallVector<const SCEV *, 4> AddOps;
3315 AddOps.push_back(getSCEV(U->getOperand(1)));
3316 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3317 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3318 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3320 U = cast<Operator>(Op);
3321 const SCEV *Op1 = getSCEV(U->getOperand(1));
3322 if (Opcode == Instruction::Sub)
3323 AddOps.push_back(getNegativeSCEV(Op1));
3325 AddOps.push_back(Op1);
3327 AddOps.push_back(getSCEV(U->getOperand(0)));
3328 return getAddExpr(AddOps);
3330 case Instruction::Mul: {
3331 // See the Add code above.
3332 SmallVector<const SCEV *, 4> MulOps;
3333 MulOps.push_back(getSCEV(U->getOperand(1)));
3334 for (Value *Op = U->getOperand(0);
3335 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3336 Op = U->getOperand(0)) {
3337 U = cast<Operator>(Op);
3338 MulOps.push_back(getSCEV(U->getOperand(1)));
3340 MulOps.push_back(getSCEV(U->getOperand(0)));
3341 return getMulExpr(MulOps);
3343 case Instruction::UDiv:
3344 return getUDivExpr(getSCEV(U->getOperand(0)),
3345 getSCEV(U->getOperand(1)));
3346 case Instruction::Sub:
3347 return getMinusSCEV(getSCEV(U->getOperand(0)),
3348 getSCEV(U->getOperand(1)));
3349 case Instruction::And:
3350 // For an expression like x&255 that merely masks off the high bits,
3351 // use zext(trunc(x)) as the SCEV expression.
3352 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3353 if (CI->isNullValue())
3354 return getSCEV(U->getOperand(1));
3355 if (CI->isAllOnesValue())
3356 return getSCEV(U->getOperand(0));
3357 const APInt &A = CI->getValue();
3359 // Instcombine's ShrinkDemandedConstant may strip bits out of
3360 // constants, obscuring what would otherwise be a low-bits mask.
3361 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3362 // knew about to reconstruct a low-bits mask value.
3363 unsigned LZ = A.countLeadingZeros();
3364 unsigned BitWidth = A.getBitWidth();
3365 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3366 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3367 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3369 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3371 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3373 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3374 IntegerType::get(getContext(), BitWidth - LZ)),
3379 case Instruction::Or:
3380 // If the RHS of the Or is a constant, we may have something like:
3381 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3382 // optimizations will transparently handle this case.
3384 // In order for this transformation to be safe, the LHS must be of the
3385 // form X*(2^n) and the Or constant must be less than 2^n.
3386 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3387 const SCEV *LHS = getSCEV(U->getOperand(0));
3388 const APInt &CIVal = CI->getValue();
3389 if (GetMinTrailingZeros(LHS) >=
3390 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3391 // Build a plain add SCEV.
3392 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3393 // If the LHS of the add was an addrec and it has no-wrap flags,
3394 // transfer the no-wrap flags, since an or won't introduce a wrap.
3395 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3396 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3397 if (OldAR->hasNoUnsignedWrap())
3398 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3399 if (OldAR->hasNoSignedWrap())
3400 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3406 case Instruction::Xor:
3407 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3408 // If the RHS of the xor is a signbit, then this is just an add.
3409 // Instcombine turns add of signbit into xor as a strength reduction step.
3410 if (CI->getValue().isSignBit())
3411 return getAddExpr(getSCEV(U->getOperand(0)),
3412 getSCEV(U->getOperand(1)));
3414 // If the RHS of xor is -1, then this is a not operation.
3415 if (CI->isAllOnesValue())
3416 return getNotSCEV(getSCEV(U->getOperand(0)));
3418 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3419 // This is a variant of the check for xor with -1, and it handles
3420 // the case where instcombine has trimmed non-demanded bits out
3421 // of an xor with -1.
3422 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3423 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3424 if (BO->getOpcode() == Instruction::And &&
3425 LCI->getValue() == CI->getValue())
3426 if (const SCEVZeroExtendExpr *Z =
3427 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3428 const Type *UTy = U->getType();
3429 const SCEV *Z0 = Z->getOperand();
3430 const Type *Z0Ty = Z0->getType();
3431 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3433 // If C is a low-bits mask, the zero extend is serving to
3434 // mask off the high bits. Complement the operand and
3435 // re-apply the zext.
3436 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3437 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3439 // If C is a single bit, it may be in the sign-bit position
3440 // before the zero-extend. In this case, represent the xor
3441 // using an add, which is equivalent, and re-apply the zext.
3442 APInt Trunc = CI->getValue().trunc(Z0TySize);
3443 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3445 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3451 case Instruction::Shl:
3452 // Turn shift left of a constant amount into a multiply.
3453 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3454 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3456 // If the shift count is not less than the bitwidth, the result of
3457 // the shift is undefined. Don't try to analyze it, because the
3458 // resolution chosen here may differ from the resolution chosen in
3459 // other parts of the compiler.
3460 if (SA->getValue().uge(BitWidth))
3463 Constant *X = ConstantInt::get(getContext(),
3464 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3465 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3469 case Instruction::LShr:
3470 // Turn logical shift right of a constant into a unsigned divide.
3471 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3472 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3474 // If the shift count is not less than the bitwidth, the result of
3475 // the shift is undefined. Don't try to analyze it, because the
3476 // resolution chosen here may differ from the resolution chosen in
3477 // other parts of the compiler.
3478 if (SA->getValue().uge(BitWidth))
3481 Constant *X = ConstantInt::get(getContext(),
3482 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3483 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3487 case Instruction::AShr:
3488 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3489 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3490 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3491 if (L->getOpcode() == Instruction::Shl &&
3492 L->getOperand(1) == U->getOperand(1)) {
3493 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3495 // If the shift count is not less than the bitwidth, the result of
3496 // the shift is undefined. Don't try to analyze it, because the
3497 // resolution chosen here may differ from the resolution chosen in
3498 // other parts of the compiler.
3499 if (CI->getValue().uge(BitWidth))
3502 uint64_t Amt = BitWidth - CI->getZExtValue();
3503 if (Amt == BitWidth)
3504 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3506 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3507 IntegerType::get(getContext(),
3513 case Instruction::Trunc:
3514 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3516 case Instruction::ZExt:
3517 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3519 case Instruction::SExt:
3520 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3522 case Instruction::BitCast:
3523 // BitCasts are no-op casts so we just eliminate the cast.
3524 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3525 return getSCEV(U->getOperand(0));
3528 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3529 // lead to pointer expressions which cannot safely be expanded to GEPs,
3530 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3531 // simplifying integer expressions.
3533 case Instruction::GetElementPtr:
3534 return createNodeForGEP(cast<GEPOperator>(U));
3536 case Instruction::PHI:
3537 return createNodeForPHI(cast<PHINode>(U));
3539 case Instruction::Select:
3540 // This could be a smax or umax that was lowered earlier.
3541 // Try to recover it.
3542 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3543 Value *LHS = ICI->getOperand(0);
3544 Value *RHS = ICI->getOperand(1);
3545 switch (ICI->getPredicate()) {
3546 case ICmpInst::ICMP_SLT:
3547 case ICmpInst::ICMP_SLE:
3548 std::swap(LHS, RHS);
3550 case ICmpInst::ICMP_SGT:
3551 case ICmpInst::ICMP_SGE:
3552 // a >s b ? a+x : b+x -> smax(a, b)+x
3553 // a >s b ? b+x : a+x -> smin(a, b)+x
3554 if (LHS->getType() == U->getType()) {
3555 const SCEV *LS = getSCEV(LHS);
3556 const SCEV *RS = getSCEV(RHS);
3557 const SCEV *LA = getSCEV(U->getOperand(1));
3558 const SCEV *RA = getSCEV(U->getOperand(2));
3559 const SCEV *LDiff = getMinusSCEV(LA, LS);
3560 const SCEV *RDiff = getMinusSCEV(RA, RS);
3562 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3563 LDiff = getMinusSCEV(LA, RS);
3564 RDiff = getMinusSCEV(RA, LS);
3566 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3569 case ICmpInst::ICMP_ULT:
3570 case ICmpInst::ICMP_ULE:
3571 std::swap(LHS, RHS);
3573 case ICmpInst::ICMP_UGT:
3574 case ICmpInst::ICMP_UGE:
3575 // a >u b ? a+x : b+x -> umax(a, b)+x
3576 // a >u b ? b+x : a+x -> umin(a, b)+x
3577 if (LHS->getType() == U->getType()) {
3578 const SCEV *LS = getSCEV(LHS);
3579 const SCEV *RS = getSCEV(RHS);
3580 const SCEV *LA = getSCEV(U->getOperand(1));
3581 const SCEV *RA = getSCEV(U->getOperand(2));
3582 const SCEV *LDiff = getMinusSCEV(LA, LS);
3583 const SCEV *RDiff = getMinusSCEV(RA, RS);
3585 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3586 LDiff = getMinusSCEV(LA, RS);
3587 RDiff = getMinusSCEV(RA, LS);
3589 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3592 case ICmpInst::ICMP_NE:
3593 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3594 if (LHS->getType() == U->getType() &&
3595 isa<ConstantInt>(RHS) &&
3596 cast<ConstantInt>(RHS)->isZero()) {
3597 const SCEV *One = getConstant(LHS->getType(), 1);
3598 const SCEV *LS = getSCEV(LHS);
3599 const SCEV *LA = getSCEV(U->getOperand(1));
3600 const SCEV *RA = getSCEV(U->getOperand(2));
3601 const SCEV *LDiff = getMinusSCEV(LA, LS);
3602 const SCEV *RDiff = getMinusSCEV(RA, One);
3604 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3607 case ICmpInst::ICMP_EQ:
3608 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3609 if (LHS->getType() == U->getType() &&
3610 isa<ConstantInt>(RHS) &&
3611 cast<ConstantInt>(RHS)->isZero()) {
3612 const SCEV *One = getConstant(LHS->getType(), 1);
3613 const SCEV *LS = getSCEV(LHS);
3614 const SCEV *LA = getSCEV(U->getOperand(1));
3615 const SCEV *RA = getSCEV(U->getOperand(2));
3616 const SCEV *LDiff = getMinusSCEV(LA, One);
3617 const SCEV *RDiff = getMinusSCEV(RA, LS);
3619 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3627 default: // We cannot analyze this expression.
3631 return getUnknown(V);
3636 //===----------------------------------------------------------------------===//
3637 // Iteration Count Computation Code
3640 /// getBackedgeTakenCount - If the specified loop has a predictable
3641 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3642 /// object. The backedge-taken count is the number of times the loop header
3643 /// will be branched to from within the loop. This is one less than the
3644 /// trip count of the loop, since it doesn't count the first iteration,
3645 /// when the header is branched to from outside the loop.
3647 /// Note that it is not valid to call this method on a loop without a
3648 /// loop-invariant backedge-taken count (see
3649 /// hasLoopInvariantBackedgeTakenCount).
3651 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3652 return getBackedgeTakenInfo(L).Exact;
3655 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3656 /// return the least SCEV value that is known never to be less than the
3657 /// actual backedge taken count.
3658 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3659 return getBackedgeTakenInfo(L).Max;
3662 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3663 /// onto the given Worklist.
3665 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3666 BasicBlock *Header = L->getHeader();
3668 // Push all Loop-header PHIs onto the Worklist stack.
3669 for (BasicBlock::iterator I = Header->begin();
3670 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3671 Worklist.push_back(PN);
3674 const ScalarEvolution::BackedgeTakenInfo &
3675 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3676 // Initially insert a CouldNotCompute for this loop. If the insertion
3677 // succeeds, proceed to actually compute a backedge-taken count and
3678 // update the value. The temporary CouldNotCompute value tells SCEV
3679 // code elsewhere that it shouldn't attempt to request a new
3680 // backedge-taken count, which could result in infinite recursion.
3681 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3682 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3684 return Pair.first->second;
3686 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3687 if (BECount.Exact != getCouldNotCompute()) {
3688 assert(isLoopInvariant(BECount.Exact, L) &&
3689 isLoopInvariant(BECount.Max, L) &&
3690 "Computed backedge-taken count isn't loop invariant for loop!");
3691 ++NumTripCountsComputed;
3693 // Update the value in the map.
3694 Pair.first->second = BECount;
3696 if (BECount.Max != getCouldNotCompute())
3697 // Update the value in the map.
3698 Pair.first->second = BECount;
3699 if (isa<PHINode>(L->getHeader()->begin()))
3700 // Only count loops that have phi nodes as not being computable.
3701 ++NumTripCountsNotComputed;
3704 // Now that we know more about the trip count for this loop, forget any
3705 // existing SCEV values for PHI nodes in this loop since they are only
3706 // conservative estimates made without the benefit of trip count
3707 // information. This is similar to the code in forgetLoop, except that
3708 // it handles SCEVUnknown PHI nodes specially.
3709 if (BECount.hasAnyInfo()) {
3710 SmallVector<Instruction *, 16> Worklist;
3711 PushLoopPHIs(L, Worklist);
3713 SmallPtrSet<Instruction *, 8> Visited;
3714 while (!Worklist.empty()) {
3715 Instruction *I = Worklist.pop_back_val();
3716 if (!Visited.insert(I)) continue;
3718 ValueExprMapType::iterator It =
3719 ValueExprMap.find(static_cast<Value *>(I));
3720 if (It != ValueExprMap.end()) {
3721 const SCEV *Old = It->second;
3723 // SCEVUnknown for a PHI either means that it has an unrecognized
3724 // structure, or it's a PHI that's in the progress of being computed
3725 // by createNodeForPHI. In the former case, additional loop trip
3726 // count information isn't going to change anything. In the later
3727 // case, createNodeForPHI will perform the necessary updates on its
3728 // own when it gets to that point.
3729 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3730 forgetMemoizedResults(Old);
3731 ValueExprMap.erase(It);
3733 if (PHINode *PN = dyn_cast<PHINode>(I))
3734 ConstantEvolutionLoopExitValue.erase(PN);
3737 PushDefUseChildren(I, Worklist);
3740 return Pair.first->second;
3743 /// forgetLoop - This method should be called by the client when it has
3744 /// changed a loop in a way that may effect ScalarEvolution's ability to
3745 /// compute a trip count, or if the loop is deleted.
3746 void ScalarEvolution::forgetLoop(const Loop *L) {
3747 // Drop any stored trip count value.
3748 BackedgeTakenCounts.erase(L);
3750 // Drop information about expressions based on loop-header PHIs.
3751 SmallVector<Instruction *, 16> Worklist;
3752 PushLoopPHIs(L, Worklist);
3754 SmallPtrSet<Instruction *, 8> Visited;
3755 while (!Worklist.empty()) {
3756 Instruction *I = Worklist.pop_back_val();
3757 if (!Visited.insert(I)) continue;
3759 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3760 if (It != ValueExprMap.end()) {
3761 forgetMemoizedResults(It->second);
3762 ValueExprMap.erase(It);
3763 if (PHINode *PN = dyn_cast<PHINode>(I))
3764 ConstantEvolutionLoopExitValue.erase(PN);
3767 PushDefUseChildren(I, Worklist);
3770 // Forget all contained loops too, to avoid dangling entries in the
3771 // ValuesAtScopes map.
3772 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3776 /// forgetValue - This method should be called by the client when it has
3777 /// changed a value in a way that may effect its value, or which may
3778 /// disconnect it from a def-use chain linking it to a loop.
3779 void ScalarEvolution::forgetValue(Value *V) {
3780 Instruction *I = dyn_cast<Instruction>(V);
3783 // Drop information about expressions based on loop-header PHIs.
3784 SmallVector<Instruction *, 16> Worklist;
3785 Worklist.push_back(I);
3787 SmallPtrSet<Instruction *, 8> Visited;
3788 while (!Worklist.empty()) {
3789 I = Worklist.pop_back_val();
3790 if (!Visited.insert(I)) continue;
3792 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3793 if (It != ValueExprMap.end()) {
3794 forgetMemoizedResults(It->second);
3795 ValueExprMap.erase(It);
3796 if (PHINode *PN = dyn_cast<PHINode>(I))
3797 ConstantEvolutionLoopExitValue.erase(PN);
3800 PushDefUseChildren(I, Worklist);
3804 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3805 /// of the specified loop will execute.
3806 ScalarEvolution::BackedgeTakenInfo
3807 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3808 SmallVector<BasicBlock *, 8> ExitingBlocks;
3809 L->getExitingBlocks(ExitingBlocks);
3811 // Examine all exits and pick the most conservative values.
3812 const SCEV *BECount = getCouldNotCompute();
3813 const SCEV *MaxBECount = getCouldNotCompute();
3814 bool CouldNotComputeBECount = false;
3815 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3816 BackedgeTakenInfo NewBTI =
3817 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3819 if (NewBTI.Exact == getCouldNotCompute()) {
3820 // We couldn't compute an exact value for this exit, so
3821 // we won't be able to compute an exact value for the loop.
3822 CouldNotComputeBECount = true;
3823 BECount = getCouldNotCompute();
3824 } else if (!CouldNotComputeBECount) {
3825 if (BECount == getCouldNotCompute())
3826 BECount = NewBTI.Exact;
3828 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3830 if (MaxBECount == getCouldNotCompute())
3831 MaxBECount = NewBTI.Max;
3832 else if (NewBTI.Max != getCouldNotCompute())
3833 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3836 return BackedgeTakenInfo(BECount, MaxBECount);
3839 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3840 /// of the specified loop will execute if it exits via the specified block.
3841 ScalarEvolution::BackedgeTakenInfo
3842 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3843 BasicBlock *ExitingBlock) {
3845 // Okay, we've chosen an exiting block. See what condition causes us to
3846 // exit at this block.
3848 // FIXME: we should be able to handle switch instructions (with a single exit)
3849 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3850 if (ExitBr == 0) return getCouldNotCompute();
3851 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3853 // At this point, we know we have a conditional branch that determines whether
3854 // the loop is exited. However, we don't know if the branch is executed each
3855 // time through the loop. If not, then the execution count of the branch will
3856 // not be equal to the trip count of the loop.
3858 // Currently we check for this by checking to see if the Exit branch goes to
3859 // the loop header. If so, we know it will always execute the same number of
3860 // times as the loop. We also handle the case where the exit block *is* the
3861 // loop header. This is common for un-rotated loops.
3863 // If both of those tests fail, walk up the unique predecessor chain to the
3864 // header, stopping if there is an edge that doesn't exit the loop. If the
3865 // header is reached, the execution count of the branch will be equal to the
3866 // trip count of the loop.
3868 // More extensive analysis could be done to handle more cases here.
3870 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3871 ExitBr->getSuccessor(1) != L->getHeader() &&
3872 ExitBr->getParent() != L->getHeader()) {
3873 // The simple checks failed, try climbing the unique predecessor chain
3874 // up to the header.
3876 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3877 BasicBlock *Pred = BB->getUniquePredecessor();
3879 return getCouldNotCompute();
3880 TerminatorInst *PredTerm = Pred->getTerminator();
3881 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3882 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3885 // If the predecessor has a successor that isn't BB and isn't
3886 // outside the loop, assume the worst.
3887 if (L->contains(PredSucc))
3888 return getCouldNotCompute();
3890 if (Pred == L->getHeader()) {
3897 return getCouldNotCompute();
3900 // Proceed to the next level to examine the exit condition expression.
3901 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3902 ExitBr->getSuccessor(0),
3903 ExitBr->getSuccessor(1));
3906 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3907 /// backedge of the specified loop will execute if its exit condition
3908 /// were a conditional branch of ExitCond, TBB, and FBB.
3909 ScalarEvolution::BackedgeTakenInfo
3910 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3914 // Check if the controlling expression for this loop is an And or Or.
3915 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3916 if (BO->getOpcode() == Instruction::And) {
3917 // Recurse on the operands of the and.
3918 BackedgeTakenInfo BTI0 =
3919 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3920 BackedgeTakenInfo BTI1 =
3921 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3922 const SCEV *BECount = getCouldNotCompute();
3923 const SCEV *MaxBECount = getCouldNotCompute();
3924 if (L->contains(TBB)) {
3925 // Both conditions must be true for the loop to continue executing.
3926 // Choose the less conservative count.
3927 if (BTI0.Exact == getCouldNotCompute() ||
3928 BTI1.Exact == getCouldNotCompute())
3929 BECount = getCouldNotCompute();
3931 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3932 if (BTI0.Max == getCouldNotCompute())
3933 MaxBECount = BTI1.Max;
3934 else if (BTI1.Max == getCouldNotCompute())
3935 MaxBECount = BTI0.Max;
3937 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3939 // Both conditions must be true at the same time for the loop to exit.
3940 // For now, be conservative.
3941 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3942 if (BTI0.Max == BTI1.Max)
3943 MaxBECount = BTI0.Max;
3944 if (BTI0.Exact == BTI1.Exact)
3945 BECount = BTI0.Exact;
3948 return BackedgeTakenInfo(BECount, MaxBECount);
3950 if (BO->getOpcode() == Instruction::Or) {
3951 // Recurse on the operands of the or.
3952 BackedgeTakenInfo BTI0 =
3953 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3954 BackedgeTakenInfo BTI1 =
3955 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3956 const SCEV *BECount = getCouldNotCompute();
3957 const SCEV *MaxBECount = getCouldNotCompute();
3958 if (L->contains(FBB)) {
3959 // Both conditions must be false for the loop to continue executing.
3960 // Choose the less conservative count.
3961 if (BTI0.Exact == getCouldNotCompute() ||
3962 BTI1.Exact == getCouldNotCompute())
3963 BECount = getCouldNotCompute();
3965 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3966 if (BTI0.Max == getCouldNotCompute())
3967 MaxBECount = BTI1.Max;
3968 else if (BTI1.Max == getCouldNotCompute())
3969 MaxBECount = BTI0.Max;
3971 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3973 // Both conditions must be false at the same time for the loop to exit.
3974 // For now, be conservative.
3975 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3976 if (BTI0.Max == BTI1.Max)
3977 MaxBECount = BTI0.Max;
3978 if (BTI0.Exact == BTI1.Exact)
3979 BECount = BTI0.Exact;
3982 return BackedgeTakenInfo(BECount, MaxBECount);
3986 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3987 // Proceed to the next level to examine the icmp.
3988 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3989 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3991 // Check for a constant condition. These are normally stripped out by
3992 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3993 // preserve the CFG and is temporarily leaving constant conditions
3995 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3996 if (L->contains(FBB) == !CI->getZExtValue())
3997 // The backedge is always taken.
3998 return getCouldNotCompute();
4000 // The backedge is never taken.
4001 return getConstant(CI->getType(), 0);
4004 // If it's not an integer or pointer comparison then compute it the hard way.
4005 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4008 static const SCEVAddRecExpr *
4009 isSimpleUnwrappingAddRec(const SCEV *S, const Loop *L) {
4010 const SCEVAddRecExpr *SA = dyn_cast<SCEVAddRecExpr>(S);
4012 // The SCEV must be an addrec of this loop.
4013 if (!SA || SA->getLoop() != L || !SA->isAffine())
4016 // The SCEV must be known to not wrap in some way to be interesting.
4017 if (!SA->hasNoUnsignedWrap() && !SA->hasNoSignedWrap())
4020 // The stride must be a constant so that we know if it is striding up or down.
4021 if (!isa<SCEVConstant>(SA->getOperand(1)))
4026 /// getMinusSCEVForExitTest - When considering an exit test for a loop with a
4027 /// "x != y" exit test, we turn this into a computation that evaluates x-y != 0,
4028 /// and this function returns the expression to use for x-y. We know and take
4029 /// advantage of the fact that this subtraction is only being used in a
4030 /// comparison by zero context.
4032 static const SCEV *getMinusSCEVForExitTest(const SCEV *LHS, const SCEV *RHS,
4033 const Loop *L, ScalarEvolution &SE) {
4034 // If either LHS or RHS is an AddRec SCEV (of this loop) that is known to not
4035 // wrap (either NSW or NUW), then we know that the value will either become
4036 // the other one (and thus the loop terminates), that the loop will terminate
4037 // through some other exit condition first, or that the loop has undefined
4038 // behavior. This information is useful when the addrec has a stride that is
4039 // != 1 or -1, because it means we can't "miss" the exit value.
4041 // In any of these three cases, it is safe to turn the exit condition into a
4042 // "counting down" AddRec (to zero) by subtracting the two inputs as normal,
4043 // but since we know that the "end cannot be missed" we can force the
4044 // resulting AddRec to be a NUW addrec. Since it is counting down, this means
4045 // that the AddRec *cannot* pass zero.
4047 // See if LHS and RHS are addrec's we can handle.
4048 const SCEVAddRecExpr *LHSA = isSimpleUnwrappingAddRec(LHS, L);
4049 const SCEVAddRecExpr *RHSA = isSimpleUnwrappingAddRec(RHS, L);
4051 // If neither addrec is interesting, just return a minus.
4052 if (RHSA == 0 && LHSA == 0)
4053 return SE.getMinusSCEV(LHS, RHS);
4055 // If only one of LHS and RHS are an AddRec of this loop, make sure it is LHS.
4056 if (RHSA && LHSA == 0) {
4057 // Safe because a-b === b-a for comparisons against zero.
4058 std::swap(LHS, RHS);
4059 std::swap(LHSA, RHSA);
4062 // Handle the case when only one is advancing in a non-overflowing way.
4064 // If RHS is loop varying, then we can't predict when LHS will cross it.
4065 if (!SE.isLoopInvariant(RHS, L))
4066 return SE.getMinusSCEV(LHS, RHS);
4068 // If LHS has a positive stride, then we compute RHS-LHS, because the loop
4069 // is counting up until it crosses RHS (which must be larger than LHS). If
4070 // it is negative, we compute LHS-RHS because we're counting down to RHS.
4071 const ConstantInt *Stride =
4072 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4073 if (Stride->getValue().isNegative())
4074 std::swap(LHS, RHS);
4076 return SE.getMinusSCEV(RHS, LHS, true /*HasNUW*/);
4079 // If both LHS and RHS are interesting, we have something like:
4081 const ConstantInt *LHSStride =
4082 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4083 const ConstantInt *RHSStride =
4084 cast<SCEVConstant>(RHSA->getOperand(1))->getValue();
4086 // If the strides are equal, then this is just a (complex) loop invariant
4087 // comparison of a and b.
4088 if (LHSStride == RHSStride)
4089 return SE.getMinusSCEV(LHSA->getStart(), RHSA->getStart());
4091 // If the signs of the strides differ, then the negative stride is counting
4092 // down to the positive stride.
4093 if (LHSStride->getValue().isNegative() != RHSStride->getValue().isNegative()){
4094 if (RHSStride->getValue().isNegative())
4095 std::swap(LHS, RHS);
4097 // If LHS's stride is smaller than RHS's stride, then "b" must be less than
4098 // "a" and "b" is RHS is counting up (catching up) to LHS. This is true
4099 // whether the strides are positive or negative.
4100 if (RHSStride->getValue().slt(LHSStride->getValue()))
4101 std::swap(LHS, RHS);
4104 return SE.getMinusSCEV(LHS, RHS, true /*HasNUW*/);
4107 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
4108 /// backedge of the specified loop will execute if its exit condition
4109 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4110 ScalarEvolution::BackedgeTakenInfo
4111 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
4116 // If the condition was exit on true, convert the condition to exit on false
4117 ICmpInst::Predicate Cond;
4118 if (!L->contains(FBB))
4119 Cond = ExitCond->getPredicate();
4121 Cond = ExitCond->getInversePredicate();
4123 // Handle common loops like: for (X = "string"; *X; ++X)
4124 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4125 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
4126 BackedgeTakenInfo ItCnt =
4127 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
4128 if (ItCnt.hasAnyInfo())
4132 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4133 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4135 // Try to evaluate any dependencies out of the loop.
4136 LHS = getSCEVAtScope(LHS, L);
4137 RHS = getSCEVAtScope(RHS, L);
4139 // At this point, we would like to compute how many iterations of the
4140 // loop the predicate will return true for these inputs.
4141 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4142 // If there is a loop-invariant, force it into the RHS.
4143 std::swap(LHS, RHS);
4144 Cond = ICmpInst::getSwappedPredicate(Cond);
4147 // Simplify the operands before analyzing them.
4148 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4150 // If we have a comparison of a chrec against a constant, try to use value
4151 // ranges to answer this query.
4152 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4153 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4154 if (AddRec->getLoop() == L) {
4155 // Form the constant range.
4156 ConstantRange CompRange(
4157 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4159 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4160 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4164 case ICmpInst::ICMP_NE: { // while (X != Y)
4165 // Convert to: while (X-Y != 0)
4166 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEVForExitTest(LHS, RHS, L,
4168 if (BTI.hasAnyInfo()) return BTI;
4171 case ICmpInst::ICMP_EQ: { // while (X == Y)
4172 // Convert to: while (X-Y == 0)
4173 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4174 if (BTI.hasAnyInfo()) return BTI;
4177 case ICmpInst::ICMP_SLT: {
4178 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4179 if (BTI.hasAnyInfo()) return BTI;
4182 case ICmpInst::ICMP_SGT: {
4183 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4184 getNotSCEV(RHS), L, true);
4185 if (BTI.hasAnyInfo()) return BTI;
4188 case ICmpInst::ICMP_ULT: {
4189 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4190 if (BTI.hasAnyInfo()) return BTI;
4193 case ICmpInst::ICMP_UGT: {
4194 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4195 getNotSCEV(RHS), L, false);
4196 if (BTI.hasAnyInfo()) return BTI;
4201 dbgs() << "ComputeBackedgeTakenCount ";
4202 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4203 dbgs() << "[unsigned] ";
4204 dbgs() << *LHS << " "
4205 << Instruction::getOpcodeName(Instruction::ICmp)
4206 << " " << *RHS << "\n";
4211 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4214 static ConstantInt *
4215 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4216 ScalarEvolution &SE) {
4217 const SCEV *InVal = SE.getConstant(C);
4218 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4219 assert(isa<SCEVConstant>(Val) &&
4220 "Evaluation of SCEV at constant didn't fold correctly?");
4221 return cast<SCEVConstant>(Val)->getValue();
4224 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4225 /// and a GEP expression (missing the pointer index) indexing into it, return
4226 /// the addressed element of the initializer or null if the index expression is
4229 GetAddressedElementFromGlobal(GlobalVariable *GV,
4230 const std::vector<ConstantInt*> &Indices) {
4231 Constant *Init = GV->getInitializer();
4232 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4233 uint64_t Idx = Indices[i]->getZExtValue();
4234 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4235 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4236 Init = cast<Constant>(CS->getOperand(Idx));
4237 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4238 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4239 Init = cast<Constant>(CA->getOperand(Idx));
4240 } else if (isa<ConstantAggregateZero>(Init)) {
4241 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4242 assert(Idx < STy->getNumElements() && "Bad struct index!");
4243 Init = Constant::getNullValue(STy->getElementType(Idx));
4244 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4245 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4246 Init = Constant::getNullValue(ATy->getElementType());
4248 llvm_unreachable("Unknown constant aggregate type!");
4252 return 0; // Unknown initializer type
4258 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4259 /// 'icmp op load X, cst', try to see if we can compute the backedge
4260 /// execution count.
4261 ScalarEvolution::BackedgeTakenInfo
4262 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4266 ICmpInst::Predicate predicate) {
4267 if (LI->isVolatile()) return getCouldNotCompute();
4269 // Check to see if the loaded pointer is a getelementptr of a global.
4270 // TODO: Use SCEV instead of manually grubbing with GEPs.
4271 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4272 if (!GEP) return getCouldNotCompute();
4274 // Make sure that it is really a constant global we are gepping, with an
4275 // initializer, and make sure the first IDX is really 0.
4276 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4277 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4278 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4279 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4280 return getCouldNotCompute();
4282 // Okay, we allow one non-constant index into the GEP instruction.
4284 std::vector<ConstantInt*> Indexes;
4285 unsigned VarIdxNum = 0;
4286 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4287 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4288 Indexes.push_back(CI);
4289 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4290 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4291 VarIdx = GEP->getOperand(i);
4293 Indexes.push_back(0);
4296 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4297 // Check to see if X is a loop variant variable value now.
4298 const SCEV *Idx = getSCEV(VarIdx);
4299 Idx = getSCEVAtScope(Idx, L);
4301 // We can only recognize very limited forms of loop index expressions, in
4302 // particular, only affine AddRec's like {C1,+,C2}.
4303 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4304 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4305 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4306 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4307 return getCouldNotCompute();
4309 unsigned MaxSteps = MaxBruteForceIterations;
4310 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4311 ConstantInt *ItCst = ConstantInt::get(
4312 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4313 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4315 // Form the GEP offset.
4316 Indexes[VarIdxNum] = Val;
4318 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4319 if (Result == 0) break; // Cannot compute!
4321 // Evaluate the condition for this iteration.
4322 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4323 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4324 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4326 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4327 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4330 ++NumArrayLenItCounts;
4331 return getConstant(ItCst); // Found terminating iteration!
4334 return getCouldNotCompute();
4338 /// CanConstantFold - Return true if we can constant fold an instruction of the
4339 /// specified type, assuming that all operands were constants.
4340 static bool CanConstantFold(const Instruction *I) {
4341 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4342 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4345 if (const CallInst *CI = dyn_cast<CallInst>(I))
4346 if (const Function *F = CI->getCalledFunction())
4347 return canConstantFoldCallTo(F);
4351 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4352 /// in the loop that V is derived from. We allow arbitrary operations along the
4353 /// way, but the operands of an operation must either be constants or a value
4354 /// derived from a constant PHI. If this expression does not fit with these
4355 /// constraints, return null.
4356 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4357 // If this is not an instruction, or if this is an instruction outside of the
4358 // loop, it can't be derived from a loop PHI.
4359 Instruction *I = dyn_cast<Instruction>(V);
4360 if (I == 0 || !L->contains(I)) return 0;
4362 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4363 if (L->getHeader() == I->getParent())
4366 // We don't currently keep track of the control flow needed to evaluate
4367 // PHIs, so we cannot handle PHIs inside of loops.
4371 // If we won't be able to constant fold this expression even if the operands
4372 // are constants, return early.
4373 if (!CanConstantFold(I)) return 0;
4375 // Otherwise, we can evaluate this instruction if all of its operands are
4376 // constant or derived from a PHI node themselves.
4378 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4379 if (!isa<Constant>(I->getOperand(Op))) {
4380 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4381 if (P == 0) return 0; // Not evolving from PHI
4385 return 0; // Evolving from multiple different PHIs.
4388 // This is a expression evolving from a constant PHI!
4392 /// EvaluateExpression - Given an expression that passes the
4393 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4394 /// in the loop has the value PHIVal. If we can't fold this expression for some
4395 /// reason, return null.
4396 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4397 const TargetData *TD) {
4398 if (isa<PHINode>(V)) return PHIVal;
4399 if (Constant *C = dyn_cast<Constant>(V)) return C;
4400 Instruction *I = cast<Instruction>(V);
4402 std::vector<Constant*> Operands(I->getNumOperands());
4404 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4405 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4406 if (Operands[i] == 0) return 0;
4409 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4410 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4412 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4413 &Operands[0], Operands.size(), TD);
4416 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4417 /// in the header of its containing loop, we know the loop executes a
4418 /// constant number of times, and the PHI node is just a recurrence
4419 /// involving constants, fold it.
4421 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4424 std::map<PHINode*, Constant*>::const_iterator I =
4425 ConstantEvolutionLoopExitValue.find(PN);
4426 if (I != ConstantEvolutionLoopExitValue.end())
4429 if (BEs.ugt(MaxBruteForceIterations))
4430 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4432 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4434 // Since the loop is canonicalized, the PHI node must have two entries. One
4435 // entry must be a constant (coming in from outside of the loop), and the
4436 // second must be derived from the same PHI.
4437 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4438 Constant *StartCST =
4439 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4441 return RetVal = 0; // Must be a constant.
4443 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4444 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4445 !isa<Constant>(BEValue))
4446 return RetVal = 0; // Not derived from same PHI.
4448 // Execute the loop symbolically to determine the exit value.
4449 if (BEs.getActiveBits() >= 32)
4450 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4452 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4453 unsigned IterationNum = 0;
4454 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4455 if (IterationNum == NumIterations)
4456 return RetVal = PHIVal; // Got exit value!
4458 // Compute the value of the PHI node for the next iteration.
4459 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4460 if (NextPHI == PHIVal)
4461 return RetVal = NextPHI; // Stopped evolving!
4463 return 0; // Couldn't evaluate!
4468 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4469 /// constant number of times (the condition evolves only from constants),
4470 /// try to evaluate a few iterations of the loop until we get the exit
4471 /// condition gets a value of ExitWhen (true or false). If we cannot
4472 /// evaluate the trip count of the loop, return getCouldNotCompute().
4474 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4477 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4478 if (PN == 0) return getCouldNotCompute();
4480 // If the loop is canonicalized, the PHI will have exactly two entries.
4481 // That's the only form we support here.
4482 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4484 // One entry must be a constant (coming in from outside of the loop), and the
4485 // second must be derived from the same PHI.
4486 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4487 Constant *StartCST =
4488 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4489 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4491 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4492 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4493 !isa<Constant>(BEValue))
4494 return getCouldNotCompute(); // Not derived from same PHI.
4496 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4497 // the loop symbolically to determine when the condition gets a value of
4499 unsigned IterationNum = 0;
4500 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4501 for (Constant *PHIVal = StartCST;
4502 IterationNum != MaxIterations; ++IterationNum) {
4503 ConstantInt *CondVal =
4504 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4506 // Couldn't symbolically evaluate.
4507 if (!CondVal) return getCouldNotCompute();
4509 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4510 ++NumBruteForceTripCountsComputed;
4511 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4514 // Compute the value of the PHI node for the next iteration.
4515 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4516 if (NextPHI == 0 || NextPHI == PHIVal)
4517 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4521 // Too many iterations were needed to evaluate.
4522 return getCouldNotCompute();
4525 /// getSCEVAtScope - Return a SCEV expression for the specified value
4526 /// at the specified scope in the program. The L value specifies a loop
4527 /// nest to evaluate the expression at, where null is the top-level or a
4528 /// specified loop is immediately inside of the loop.
4530 /// This method can be used to compute the exit value for a variable defined
4531 /// in a loop by querying what the value will hold in the parent loop.
4533 /// In the case that a relevant loop exit value cannot be computed, the
4534 /// original value V is returned.
4535 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4536 // Check to see if we've folded this expression at this loop before.
4537 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4538 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4539 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4541 return Pair.first->second ? Pair.first->second : V;
4543 // Otherwise compute it.
4544 const SCEV *C = computeSCEVAtScope(V, L);
4545 ValuesAtScopes[V][L] = C;
4549 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4550 if (isa<SCEVConstant>(V)) return V;
4552 // If this instruction is evolved from a constant-evolving PHI, compute the
4553 // exit value from the loop without using SCEVs.
4554 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4555 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4556 const Loop *LI = (*this->LI)[I->getParent()];
4557 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4558 if (PHINode *PN = dyn_cast<PHINode>(I))
4559 if (PN->getParent() == LI->getHeader()) {
4560 // Okay, there is no closed form solution for the PHI node. Check
4561 // to see if the loop that contains it has a known backedge-taken
4562 // count. If so, we may be able to force computation of the exit
4564 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4565 if (const SCEVConstant *BTCC =
4566 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4567 // Okay, we know how many times the containing loop executes. If
4568 // this is a constant evolving PHI node, get the final value at
4569 // the specified iteration number.
4570 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4571 BTCC->getValue()->getValue(),
4573 if (RV) return getSCEV(RV);
4577 // Okay, this is an expression that we cannot symbolically evaluate
4578 // into a SCEV. Check to see if it's possible to symbolically evaluate
4579 // the arguments into constants, and if so, try to constant propagate the
4580 // result. This is particularly useful for computing loop exit values.
4581 if (CanConstantFold(I)) {
4582 SmallVector<Constant *, 4> Operands;
4583 bool MadeImprovement = false;
4584 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4585 Value *Op = I->getOperand(i);
4586 if (Constant *C = dyn_cast<Constant>(Op)) {
4587 Operands.push_back(C);
4591 // If any of the operands is non-constant and if they are
4592 // non-integer and non-pointer, don't even try to analyze them
4593 // with scev techniques.
4594 if (!isSCEVable(Op->getType()))
4597 const SCEV *OrigV = getSCEV(Op);
4598 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4599 MadeImprovement |= OrigV != OpV;
4602 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4604 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4605 C = dyn_cast<Constant>(SU->getValue());
4607 if (C->getType() != Op->getType())
4608 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4612 Operands.push_back(C);
4615 // Check to see if getSCEVAtScope actually made an improvement.
4616 if (MadeImprovement) {
4618 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4619 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4620 Operands[0], Operands[1], TD);
4622 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4623 &Operands[0], Operands.size(), TD);
4630 // This is some other type of SCEVUnknown, just return it.
4634 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4635 // Avoid performing the look-up in the common case where the specified
4636 // expression has no loop-variant portions.
4637 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4638 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4639 if (OpAtScope != Comm->getOperand(i)) {
4640 // Okay, at least one of these operands is loop variant but might be
4641 // foldable. Build a new instance of the folded commutative expression.
4642 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4643 Comm->op_begin()+i);
4644 NewOps.push_back(OpAtScope);
4646 for (++i; i != e; ++i) {
4647 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4648 NewOps.push_back(OpAtScope);
4650 if (isa<SCEVAddExpr>(Comm))
4651 return getAddExpr(NewOps);
4652 if (isa<SCEVMulExpr>(Comm))
4653 return getMulExpr(NewOps);
4654 if (isa<SCEVSMaxExpr>(Comm))
4655 return getSMaxExpr(NewOps);
4656 if (isa<SCEVUMaxExpr>(Comm))
4657 return getUMaxExpr(NewOps);
4658 llvm_unreachable("Unknown commutative SCEV type!");
4661 // If we got here, all operands are loop invariant.
4665 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4666 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4667 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4668 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4669 return Div; // must be loop invariant
4670 return getUDivExpr(LHS, RHS);
4673 // If this is a loop recurrence for a loop that does not contain L, then we
4674 // are dealing with the final value computed by the loop.
4675 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4676 // First, attempt to evaluate each operand.
4677 // Avoid performing the look-up in the common case where the specified
4678 // expression has no loop-variant portions.
4679 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4680 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4681 if (OpAtScope == AddRec->getOperand(i))
4684 // Okay, at least one of these operands is loop variant but might be
4685 // foldable. Build a new instance of the folded commutative expression.
4686 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4687 AddRec->op_begin()+i);
4688 NewOps.push_back(OpAtScope);
4689 for (++i; i != e; ++i)
4690 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4692 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4696 // If the scope is outside the addrec's loop, evaluate it by using the
4697 // loop exit value of the addrec.
4698 if (!AddRec->getLoop()->contains(L)) {
4699 // To evaluate this recurrence, we need to know how many times the AddRec
4700 // loop iterates. Compute this now.
4701 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4702 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4704 // Then, evaluate the AddRec.
4705 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4711 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4712 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4713 if (Op == Cast->getOperand())
4714 return Cast; // must be loop invariant
4715 return getZeroExtendExpr(Op, Cast->getType());
4718 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4719 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4720 if (Op == Cast->getOperand())
4721 return Cast; // must be loop invariant
4722 return getSignExtendExpr(Op, Cast->getType());
4725 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4726 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4727 if (Op == Cast->getOperand())
4728 return Cast; // must be loop invariant
4729 return getTruncateExpr(Op, Cast->getType());
4732 llvm_unreachable("Unknown SCEV type!");
4736 /// getSCEVAtScope - This is a convenience function which does
4737 /// getSCEVAtScope(getSCEV(V), L).
4738 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4739 return getSCEVAtScope(getSCEV(V), L);
4742 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4743 /// following equation:
4745 /// A * X = B (mod N)
4747 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4748 /// A and B isn't important.
4750 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4751 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4752 ScalarEvolution &SE) {
4753 uint32_t BW = A.getBitWidth();
4754 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4755 assert(A != 0 && "A must be non-zero.");
4759 // The gcd of A and N may have only one prime factor: 2. The number of
4760 // trailing zeros in A is its multiplicity
4761 uint32_t Mult2 = A.countTrailingZeros();
4764 // 2. Check if B is divisible by D.
4766 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4767 // is not less than multiplicity of this prime factor for D.
4768 if (B.countTrailingZeros() < Mult2)
4769 return SE.getCouldNotCompute();
4771 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4774 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4775 // bit width during computations.
4776 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4777 APInt Mod(BW + 1, 0);
4778 Mod.setBit(BW - Mult2); // Mod = N / D
4779 APInt I = AD.multiplicativeInverse(Mod);
4781 // 4. Compute the minimum unsigned root of the equation:
4782 // I * (B / D) mod (N / D)
4783 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4785 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4787 return SE.getConstant(Result.trunc(BW));
4790 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4791 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4792 /// might be the same) or two SCEVCouldNotCompute objects.
4794 static std::pair<const SCEV *,const SCEV *>
4795 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4796 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4797 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4798 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4799 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4801 // We currently can only solve this if the coefficients are constants.
4802 if (!LC || !MC || !NC) {
4803 const SCEV *CNC = SE.getCouldNotCompute();
4804 return std::make_pair(CNC, CNC);
4807 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4808 const APInt &L = LC->getValue()->getValue();
4809 const APInt &M = MC->getValue()->getValue();
4810 const APInt &N = NC->getValue()->getValue();
4811 APInt Two(BitWidth, 2);
4812 APInt Four(BitWidth, 4);
4815 using namespace APIntOps;
4817 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4818 // The B coefficient is M-N/2
4822 // The A coefficient is N/2
4823 APInt A(N.sdiv(Two));
4825 // Compute the B^2-4ac term.
4828 SqrtTerm -= Four * (A * C);
4830 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4831 // integer value or else APInt::sqrt() will assert.
4832 APInt SqrtVal(SqrtTerm.sqrt());
4834 // Compute the two solutions for the quadratic formula.
4835 // The divisions must be performed as signed divisions.
4837 APInt TwoA( A << 1 );
4838 if (TwoA.isMinValue()) {
4839 const SCEV *CNC = SE.getCouldNotCompute();
4840 return std::make_pair(CNC, CNC);
4843 LLVMContext &Context = SE.getContext();
4845 ConstantInt *Solution1 =
4846 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4847 ConstantInt *Solution2 =
4848 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4850 return std::make_pair(SE.getConstant(Solution1),
4851 SE.getConstant(Solution2));
4852 } // end APIntOps namespace
4855 /// HowFarToZero - Return the number of times a backedge comparing the specified
4856 /// value to zero will execute. If not computable, return CouldNotCompute.
4857 ScalarEvolution::BackedgeTakenInfo
4858 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4859 // If the value is a constant
4860 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4861 // If the value is already zero, the branch will execute zero times.
4862 if (C->getValue()->isZero()) return C;
4863 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4866 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4867 if (!AddRec || AddRec->getLoop() != L)
4868 return getCouldNotCompute();
4870 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4871 // the quadratic equation to solve it.
4872 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4873 std::pair<const SCEV *,const SCEV *> Roots =
4874 SolveQuadraticEquation(AddRec, *this);
4875 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4876 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4879 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4880 << " sol#2: " << *R2 << "\n";
4882 // Pick the smallest positive root value.
4883 if (ConstantInt *CB =
4884 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
4887 if (CB->getZExtValue() == false)
4888 std::swap(R1, R2); // R1 is the minimum root now.
4890 // We can only use this value if the chrec ends up with an exact zero
4891 // value at this index. When solving for "X*X != 5", for example, we
4892 // should not accept a root of 2.
4893 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4895 return R1; // We found a quadratic root!
4898 return getCouldNotCompute();
4901 // Otherwise we can only handle this if it is affine.
4902 if (!AddRec->isAffine())
4903 return getCouldNotCompute();
4905 // If this is an affine expression, the execution count of this branch is
4906 // the minimum unsigned root of the following equation:
4908 // Start + Step*N = 0 (mod 2^BW)
4912 // Step*N = -Start (mod 2^BW)
4914 // where BW is the common bit width of Start and Step.
4916 // Get the initial value for the loop.
4917 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
4918 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
4920 // If the AddRec is NUW, then (in an unsigned sense) it cannot be counting up
4921 // to wrap to 0, it must be counting down to equal 0. Also, while counting
4922 // down, it cannot "miss" 0 (which would cause it to wrap), regardless of what
4923 // the stride is. As such, NUW addrec's will always become zero in
4924 // "start / -stride" steps, and we know that the division is exact.
4925 if (AddRec->hasNoUnsignedWrap())
4926 // FIXME: We really want an "isexact" bit for udiv.
4927 return getUDivExpr(Start, getNegativeSCEV(Step));
4929 // For now we handle only constant steps.
4930 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
4932 return getCouldNotCompute();
4934 // First, handle unitary steps.
4935 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4936 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4938 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4939 return Start; // N = Start (as unsigned)
4941 // Then, try to solve the above equation provided that Start is constant.
4942 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4943 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4944 -StartC->getValue()->getValue(),
4946 return getCouldNotCompute();
4949 /// HowFarToNonZero - Return the number of times a backedge checking the
4950 /// specified value for nonzero will execute. If not computable, return
4952 ScalarEvolution::BackedgeTakenInfo
4953 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4954 // Loops that look like: while (X == 0) are very strange indeed. We don't
4955 // handle them yet except for the trivial case. This could be expanded in the
4956 // future as needed.
4958 // If the value is a constant, check to see if it is known to be non-zero
4959 // already. If so, the backedge will execute zero times.
4960 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4961 if (!C->getValue()->isNullValue())
4962 return getConstant(C->getType(), 0);
4963 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4966 // We could implement others, but I really doubt anyone writes loops like
4967 // this, and if they did, they would already be constant folded.
4968 return getCouldNotCompute();
4971 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4972 /// (which may not be an immediate predecessor) which has exactly one
4973 /// successor from which BB is reachable, or null if no such block is
4976 std::pair<BasicBlock *, BasicBlock *>
4977 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4978 // If the block has a unique predecessor, then there is no path from the
4979 // predecessor to the block that does not go through the direct edge
4980 // from the predecessor to the block.
4981 if (BasicBlock *Pred = BB->getSinglePredecessor())
4982 return std::make_pair(Pred, BB);
4984 // A loop's header is defined to be a block that dominates the loop.
4985 // If the header has a unique predecessor outside the loop, it must be
4986 // a block that has exactly one successor that can reach the loop.
4987 if (Loop *L = LI->getLoopFor(BB))
4988 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4990 return std::pair<BasicBlock *, BasicBlock *>();
4993 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4994 /// testing whether two expressions are equal, however for the purposes of
4995 /// looking for a condition guarding a loop, it can be useful to be a little
4996 /// more general, since a front-end may have replicated the controlling
4999 static bool HasSameValue(const SCEV *A, const SCEV *B) {
5000 // Quick check to see if they are the same SCEV.
5001 if (A == B) return true;
5003 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5004 // two different instructions with the same value. Check for this case.
5005 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5006 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5007 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5008 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
5009 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
5012 // Otherwise assume they may have a different value.
5016 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5017 /// predicate Pred. Return true iff any changes were made.
5019 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5020 const SCEV *&LHS, const SCEV *&RHS) {
5021 bool Changed = false;
5023 // Canonicalize a constant to the right side.
5024 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5025 // Check for both operands constant.
5026 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5027 if (ConstantExpr::getICmp(Pred,
5029 RHSC->getValue())->isNullValue())
5030 goto trivially_false;
5032 goto trivially_true;
5034 // Otherwise swap the operands to put the constant on the right.
5035 std::swap(LHS, RHS);
5036 Pred = ICmpInst::getSwappedPredicate(Pred);
5040 // If we're comparing an addrec with a value which is loop-invariant in the
5041 // addrec's loop, put the addrec on the left. Also make a dominance check,
5042 // as both operands could be addrecs loop-invariant in each other's loop.
5043 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5044 const Loop *L = AR->getLoop();
5045 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
5046 std::swap(LHS, RHS);
5047 Pred = ICmpInst::getSwappedPredicate(Pred);
5052 // If there's a constant operand, canonicalize comparisons with boundary
5053 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5054 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5055 const APInt &RA = RC->getValue()->getValue();
5057 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5058 case ICmpInst::ICMP_EQ:
5059 case ICmpInst::ICMP_NE:
5061 case ICmpInst::ICMP_UGE:
5062 if ((RA - 1).isMinValue()) {
5063 Pred = ICmpInst::ICMP_NE;
5064 RHS = getConstant(RA - 1);
5068 if (RA.isMaxValue()) {
5069 Pred = ICmpInst::ICMP_EQ;
5073 if (RA.isMinValue()) goto trivially_true;
5075 Pred = ICmpInst::ICMP_UGT;
5076 RHS = getConstant(RA - 1);
5079 case ICmpInst::ICMP_ULE:
5080 if ((RA + 1).isMaxValue()) {
5081 Pred = ICmpInst::ICMP_NE;
5082 RHS = getConstant(RA + 1);
5086 if (RA.isMinValue()) {
5087 Pred = ICmpInst::ICMP_EQ;
5091 if (RA.isMaxValue()) goto trivially_true;
5093 Pred = ICmpInst::ICMP_ULT;
5094 RHS = getConstant(RA + 1);
5097 case ICmpInst::ICMP_SGE:
5098 if ((RA - 1).isMinSignedValue()) {
5099 Pred = ICmpInst::ICMP_NE;
5100 RHS = getConstant(RA - 1);
5104 if (RA.isMaxSignedValue()) {
5105 Pred = ICmpInst::ICMP_EQ;
5109 if (RA.isMinSignedValue()) goto trivially_true;
5111 Pred = ICmpInst::ICMP_SGT;
5112 RHS = getConstant(RA - 1);
5115 case ICmpInst::ICMP_SLE:
5116 if ((RA + 1).isMaxSignedValue()) {
5117 Pred = ICmpInst::ICMP_NE;
5118 RHS = getConstant(RA + 1);
5122 if (RA.isMinSignedValue()) {
5123 Pred = ICmpInst::ICMP_EQ;
5127 if (RA.isMaxSignedValue()) goto trivially_true;
5129 Pred = ICmpInst::ICMP_SLT;
5130 RHS = getConstant(RA + 1);
5133 case ICmpInst::ICMP_UGT:
5134 if (RA.isMinValue()) {
5135 Pred = ICmpInst::ICMP_NE;
5139 if ((RA + 1).isMaxValue()) {
5140 Pred = ICmpInst::ICMP_EQ;
5141 RHS = getConstant(RA + 1);
5145 if (RA.isMaxValue()) goto trivially_false;
5147 case ICmpInst::ICMP_ULT:
5148 if (RA.isMaxValue()) {
5149 Pred = ICmpInst::ICMP_NE;
5153 if ((RA - 1).isMinValue()) {
5154 Pred = ICmpInst::ICMP_EQ;
5155 RHS = getConstant(RA - 1);
5159 if (RA.isMinValue()) goto trivially_false;
5161 case ICmpInst::ICMP_SGT:
5162 if (RA.isMinSignedValue()) {
5163 Pred = ICmpInst::ICMP_NE;
5167 if ((RA + 1).isMaxSignedValue()) {
5168 Pred = ICmpInst::ICMP_EQ;
5169 RHS = getConstant(RA + 1);
5173 if (RA.isMaxSignedValue()) goto trivially_false;
5175 case ICmpInst::ICMP_SLT:
5176 if (RA.isMaxSignedValue()) {
5177 Pred = ICmpInst::ICMP_NE;
5181 if ((RA - 1).isMinSignedValue()) {
5182 Pred = ICmpInst::ICMP_EQ;
5183 RHS = getConstant(RA - 1);
5187 if (RA.isMinSignedValue()) goto trivially_false;
5192 // Check for obvious equality.
5193 if (HasSameValue(LHS, RHS)) {
5194 if (ICmpInst::isTrueWhenEqual(Pred))
5195 goto trivially_true;
5196 if (ICmpInst::isFalseWhenEqual(Pred))
5197 goto trivially_false;
5200 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5201 // adding or subtracting 1 from one of the operands.
5203 case ICmpInst::ICMP_SLE:
5204 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5205 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5206 /*HasNUW=*/false, /*HasNSW=*/true);
5207 Pred = ICmpInst::ICMP_SLT;
5209 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5210 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5211 /*HasNUW=*/false, /*HasNSW=*/true);
5212 Pred = ICmpInst::ICMP_SLT;
5216 case ICmpInst::ICMP_SGE:
5217 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5218 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5219 /*HasNUW=*/false, /*HasNSW=*/true);
5220 Pred = ICmpInst::ICMP_SGT;
5222 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5223 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5224 /*HasNUW=*/false, /*HasNSW=*/true);
5225 Pred = ICmpInst::ICMP_SGT;
5229 case ICmpInst::ICMP_ULE:
5230 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5231 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5232 /*HasNUW=*/true, /*HasNSW=*/false);
5233 Pred = ICmpInst::ICMP_ULT;
5235 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5236 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5237 /*HasNUW=*/true, /*HasNSW=*/false);
5238 Pred = ICmpInst::ICMP_ULT;
5242 case ICmpInst::ICMP_UGE:
5243 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5244 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5245 /*HasNUW=*/true, /*HasNSW=*/false);
5246 Pred = ICmpInst::ICMP_UGT;
5248 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5249 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5250 /*HasNUW=*/true, /*HasNSW=*/false);
5251 Pred = ICmpInst::ICMP_UGT;
5259 // TODO: More simplifications are possible here.
5265 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5266 Pred = ICmpInst::ICMP_EQ;
5271 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5272 Pred = ICmpInst::ICMP_NE;
5276 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5277 return getSignedRange(S).getSignedMax().isNegative();
5280 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5281 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5284 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5285 return !getSignedRange(S).getSignedMin().isNegative();
5288 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5289 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5292 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5293 return isKnownNegative(S) || isKnownPositive(S);
5296 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5297 const SCEV *LHS, const SCEV *RHS) {
5298 // Canonicalize the inputs first.
5299 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5301 // If LHS or RHS is an addrec, check to see if the condition is true in
5302 // every iteration of the loop.
5303 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5304 if (isLoopEntryGuardedByCond(
5305 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5306 isLoopBackedgeGuardedByCond(
5307 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5309 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5310 if (isLoopEntryGuardedByCond(
5311 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5312 isLoopBackedgeGuardedByCond(
5313 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5316 // Otherwise see what can be done with known constant ranges.
5317 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5321 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5322 const SCEV *LHS, const SCEV *RHS) {
5323 if (HasSameValue(LHS, RHS))
5324 return ICmpInst::isTrueWhenEqual(Pred);
5326 // This code is split out from isKnownPredicate because it is called from
5327 // within isLoopEntryGuardedByCond.
5330 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5332 case ICmpInst::ICMP_SGT:
5333 Pred = ICmpInst::ICMP_SLT;
5334 std::swap(LHS, RHS);
5335 case ICmpInst::ICMP_SLT: {
5336 ConstantRange LHSRange = getSignedRange(LHS);
5337 ConstantRange RHSRange = getSignedRange(RHS);
5338 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5340 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5344 case ICmpInst::ICMP_SGE:
5345 Pred = ICmpInst::ICMP_SLE;
5346 std::swap(LHS, RHS);
5347 case ICmpInst::ICMP_SLE: {
5348 ConstantRange LHSRange = getSignedRange(LHS);
5349 ConstantRange RHSRange = getSignedRange(RHS);
5350 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5352 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5356 case ICmpInst::ICMP_UGT:
5357 Pred = ICmpInst::ICMP_ULT;
5358 std::swap(LHS, RHS);
5359 case ICmpInst::ICMP_ULT: {
5360 ConstantRange LHSRange = getUnsignedRange(LHS);
5361 ConstantRange RHSRange = getUnsignedRange(RHS);
5362 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5364 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5368 case ICmpInst::ICMP_UGE:
5369 Pred = ICmpInst::ICMP_ULE;
5370 std::swap(LHS, RHS);
5371 case ICmpInst::ICMP_ULE: {
5372 ConstantRange LHSRange = getUnsignedRange(LHS);
5373 ConstantRange RHSRange = getUnsignedRange(RHS);
5374 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5376 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5380 case ICmpInst::ICMP_NE: {
5381 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5383 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5386 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5387 if (isKnownNonZero(Diff))
5391 case ICmpInst::ICMP_EQ:
5392 // The check at the top of the function catches the case where
5393 // the values are known to be equal.
5399 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5400 /// protected by a conditional between LHS and RHS. This is used to
5401 /// to eliminate casts.
5403 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5404 ICmpInst::Predicate Pred,
5405 const SCEV *LHS, const SCEV *RHS) {
5406 // Interpret a null as meaning no loop, where there is obviously no guard
5407 // (interprocedural conditions notwithstanding).
5408 if (!L) return true;
5410 BasicBlock *Latch = L->getLoopLatch();
5414 BranchInst *LoopContinuePredicate =
5415 dyn_cast<BranchInst>(Latch->getTerminator());
5416 if (!LoopContinuePredicate ||
5417 LoopContinuePredicate->isUnconditional())
5420 return isImpliedCond(Pred, LHS, RHS,
5421 LoopContinuePredicate->getCondition(),
5422 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5425 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5426 /// by a conditional between LHS and RHS. This is used to help avoid max
5427 /// expressions in loop trip counts, and to eliminate casts.
5429 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5430 ICmpInst::Predicate Pred,
5431 const SCEV *LHS, const SCEV *RHS) {
5432 // Interpret a null as meaning no loop, where there is obviously no guard
5433 // (interprocedural conditions notwithstanding).
5434 if (!L) return false;
5436 // Starting at the loop predecessor, climb up the predecessor chain, as long
5437 // as there are predecessors that can be found that have unique successors
5438 // leading to the original header.
5439 for (std::pair<BasicBlock *, BasicBlock *>
5440 Pair(L->getLoopPredecessor(), L->getHeader());
5442 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5444 BranchInst *LoopEntryPredicate =
5445 dyn_cast<BranchInst>(Pair.first->getTerminator());
5446 if (!LoopEntryPredicate ||
5447 LoopEntryPredicate->isUnconditional())
5450 if (isImpliedCond(Pred, LHS, RHS,
5451 LoopEntryPredicate->getCondition(),
5452 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5459 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5460 /// and RHS is true whenever the given Cond value evaluates to true.
5461 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5462 const SCEV *LHS, const SCEV *RHS,
5463 Value *FoundCondValue,
5465 // Recursively handle And and Or conditions.
5466 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5467 if (BO->getOpcode() == Instruction::And) {
5469 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5470 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5471 } else if (BO->getOpcode() == Instruction::Or) {
5473 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5474 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5478 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5479 if (!ICI) return false;
5481 // Bail if the ICmp's operands' types are wider than the needed type
5482 // before attempting to call getSCEV on them. This avoids infinite
5483 // recursion, since the analysis of widening casts can require loop
5484 // exit condition information for overflow checking, which would
5486 if (getTypeSizeInBits(LHS->getType()) <
5487 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5490 // Now that we found a conditional branch that dominates the loop, check to
5491 // see if it is the comparison we are looking for.
5492 ICmpInst::Predicate FoundPred;
5494 FoundPred = ICI->getInversePredicate();
5496 FoundPred = ICI->getPredicate();
5498 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5499 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5501 // Balance the types. The case where FoundLHS' type is wider than
5502 // LHS' type is checked for above.
5503 if (getTypeSizeInBits(LHS->getType()) >
5504 getTypeSizeInBits(FoundLHS->getType())) {
5505 if (CmpInst::isSigned(Pred)) {
5506 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5507 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5509 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5510 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5514 // Canonicalize the query to match the way instcombine will have
5515 // canonicalized the comparison.
5516 if (SimplifyICmpOperands(Pred, LHS, RHS))
5518 return CmpInst::isTrueWhenEqual(Pred);
5519 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5520 if (FoundLHS == FoundRHS)
5521 return CmpInst::isFalseWhenEqual(Pred);
5523 // Check to see if we can make the LHS or RHS match.
5524 if (LHS == FoundRHS || RHS == FoundLHS) {
5525 if (isa<SCEVConstant>(RHS)) {
5526 std::swap(FoundLHS, FoundRHS);
5527 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5529 std::swap(LHS, RHS);
5530 Pred = ICmpInst::getSwappedPredicate(Pred);
5534 // Check whether the found predicate is the same as the desired predicate.
5535 if (FoundPred == Pred)
5536 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5538 // Check whether swapping the found predicate makes it the same as the
5539 // desired predicate.
5540 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5541 if (isa<SCEVConstant>(RHS))
5542 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5544 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5545 RHS, LHS, FoundLHS, FoundRHS);
5548 // Check whether the actual condition is beyond sufficient.
5549 if (FoundPred == ICmpInst::ICMP_EQ)
5550 if (ICmpInst::isTrueWhenEqual(Pred))
5551 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5553 if (Pred == ICmpInst::ICMP_NE)
5554 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5555 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5558 // Otherwise assume the worst.
5562 /// isImpliedCondOperands - Test whether the condition described by Pred,
5563 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5564 /// and FoundRHS is true.
5565 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5566 const SCEV *LHS, const SCEV *RHS,
5567 const SCEV *FoundLHS,
5568 const SCEV *FoundRHS) {
5569 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5570 FoundLHS, FoundRHS) ||
5571 // ~x < ~y --> x > y
5572 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5573 getNotSCEV(FoundRHS),
5574 getNotSCEV(FoundLHS));
5577 /// isImpliedCondOperandsHelper - Test whether the condition described by
5578 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5579 /// FoundLHS, and FoundRHS is true.
5581 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5582 const SCEV *LHS, const SCEV *RHS,
5583 const SCEV *FoundLHS,
5584 const SCEV *FoundRHS) {
5586 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5587 case ICmpInst::ICMP_EQ:
5588 case ICmpInst::ICMP_NE:
5589 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5592 case ICmpInst::ICMP_SLT:
5593 case ICmpInst::ICMP_SLE:
5594 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5595 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5598 case ICmpInst::ICMP_SGT:
5599 case ICmpInst::ICMP_SGE:
5600 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5601 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5604 case ICmpInst::ICMP_ULT:
5605 case ICmpInst::ICMP_ULE:
5606 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5607 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5610 case ICmpInst::ICMP_UGT:
5611 case ICmpInst::ICMP_UGE:
5612 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5613 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5621 /// getBECount - Subtract the end and start values and divide by the step,
5622 /// rounding up, to get the number of times the backedge is executed. Return
5623 /// CouldNotCompute if an intermediate computation overflows.
5624 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5628 assert(!isKnownNegative(Step) &&
5629 "This code doesn't handle negative strides yet!");
5631 const Type *Ty = Start->getType();
5632 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5633 const SCEV *Diff = getMinusSCEV(End, Start);
5634 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5636 // Add an adjustment to the difference between End and Start so that
5637 // the division will effectively round up.
5638 const SCEV *Add = getAddExpr(Diff, RoundUp);
5641 // Check Add for unsigned overflow.
5642 // TODO: More sophisticated things could be done here.
5643 const Type *WideTy = IntegerType::get(getContext(),
5644 getTypeSizeInBits(Ty) + 1);
5645 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5646 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5647 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5648 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5649 return getCouldNotCompute();
5652 return getUDivExpr(Add, Step);
5655 /// HowManyLessThans - Return the number of times a backedge containing the
5656 /// specified less-than comparison will execute. If not computable, return
5657 /// CouldNotCompute.
5658 ScalarEvolution::BackedgeTakenInfo
5659 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5660 const Loop *L, bool isSigned) {
5661 // Only handle: "ADDREC < LoopInvariant".
5662 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
5664 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5665 if (!AddRec || AddRec->getLoop() != L)
5666 return getCouldNotCompute();
5668 // Check to see if we have a flag which makes analysis easy.
5669 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5670 AddRec->hasNoUnsignedWrap();
5672 if (AddRec->isAffine()) {
5673 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5674 const SCEV *Step = AddRec->getStepRecurrence(*this);
5677 return getCouldNotCompute();
5678 if (Step->isOne()) {
5679 // With unit stride, the iteration never steps past the limit value.
5680 } else if (isKnownPositive(Step)) {
5681 // Test whether a positive iteration can step past the limit
5682 // value and past the maximum value for its type in a single step.
5683 // Note that it's not sufficient to check NoWrap here, because even
5684 // though the value after a wrap is undefined, it's not undefined
5685 // behavior, so if wrap does occur, the loop could either terminate or
5686 // loop infinitely, but in either case, the loop is guaranteed to
5687 // iterate at least until the iteration where the wrapping occurs.
5688 const SCEV *One = getConstant(Step->getType(), 1);
5690 APInt Max = APInt::getSignedMaxValue(BitWidth);
5691 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5692 .slt(getSignedRange(RHS).getSignedMax()))
5693 return getCouldNotCompute();
5695 APInt Max = APInt::getMaxValue(BitWidth);
5696 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5697 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5698 return getCouldNotCompute();
5701 // TODO: Handle negative strides here and below.
5702 return getCouldNotCompute();
5704 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5705 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5706 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5707 // treat m-n as signed nor unsigned due to overflow possibility.
5709 // First, we get the value of the LHS in the first iteration: n
5710 const SCEV *Start = AddRec->getOperand(0);
5712 // Determine the minimum constant start value.
5713 const SCEV *MinStart = getConstant(isSigned ?
5714 getSignedRange(Start).getSignedMin() :
5715 getUnsignedRange(Start).getUnsignedMin());
5717 // If we know that the condition is true in order to enter the loop,
5718 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5719 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5720 // the division must round up.
5721 const SCEV *End = RHS;
5722 if (!isLoopEntryGuardedByCond(L,
5723 isSigned ? ICmpInst::ICMP_SLT :
5725 getMinusSCEV(Start, Step), RHS))
5726 End = isSigned ? getSMaxExpr(RHS, Start)
5727 : getUMaxExpr(RHS, Start);
5729 // Determine the maximum constant end value.
5730 const SCEV *MaxEnd = getConstant(isSigned ?
5731 getSignedRange(End).getSignedMax() :
5732 getUnsignedRange(End).getUnsignedMax());
5734 // If MaxEnd is within a step of the maximum integer value in its type,
5735 // adjust it down to the minimum value which would produce the same effect.
5736 // This allows the subsequent ceiling division of (N+(step-1))/step to
5737 // compute the correct value.
5738 const SCEV *StepMinusOne = getMinusSCEV(Step,
5739 getConstant(Step->getType(), 1));
5742 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5745 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5748 // Finally, we subtract these two values and divide, rounding up, to get
5749 // the number of times the backedge is executed.
5750 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5752 // The maximum backedge count is similar, except using the minimum start
5753 // value and the maximum end value.
5754 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5756 return BackedgeTakenInfo(BECount, MaxBECount);
5759 return getCouldNotCompute();
5762 /// getNumIterationsInRange - Return the number of iterations of this loop that
5763 /// produce values in the specified constant range. Another way of looking at
5764 /// this is that it returns the first iteration number where the value is not in
5765 /// the condition, thus computing the exit count. If the iteration count can't
5766 /// be computed, an instance of SCEVCouldNotCompute is returned.
5767 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5768 ScalarEvolution &SE) const {
5769 if (Range.isFullSet()) // Infinite loop.
5770 return SE.getCouldNotCompute();
5772 // If the start is a non-zero constant, shift the range to simplify things.
5773 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5774 if (!SC->getValue()->isZero()) {
5775 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5776 Operands[0] = SE.getConstant(SC->getType(), 0);
5777 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5778 if (const SCEVAddRecExpr *ShiftedAddRec =
5779 dyn_cast<SCEVAddRecExpr>(Shifted))
5780 return ShiftedAddRec->getNumIterationsInRange(
5781 Range.subtract(SC->getValue()->getValue()), SE);
5782 // This is strange and shouldn't happen.
5783 return SE.getCouldNotCompute();
5786 // The only time we can solve this is when we have all constant indices.
5787 // Otherwise, we cannot determine the overflow conditions.
5788 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5789 if (!isa<SCEVConstant>(getOperand(i)))
5790 return SE.getCouldNotCompute();
5793 // Okay at this point we know that all elements of the chrec are constants and
5794 // that the start element is zero.
5796 // First check to see if the range contains zero. If not, the first
5798 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5799 if (!Range.contains(APInt(BitWidth, 0)))
5800 return SE.getConstant(getType(), 0);
5803 // If this is an affine expression then we have this situation:
5804 // Solve {0,+,A} in Range === Ax in Range
5806 // We know that zero is in the range. If A is positive then we know that
5807 // the upper value of the range must be the first possible exit value.
5808 // If A is negative then the lower of the range is the last possible loop
5809 // value. Also note that we already checked for a full range.
5810 APInt One(BitWidth,1);
5811 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5812 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5814 // The exit value should be (End+A)/A.
5815 APInt ExitVal = (End + A).udiv(A);
5816 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5818 // Evaluate at the exit value. If we really did fall out of the valid
5819 // range, then we computed our trip count, otherwise wrap around or other
5820 // things must have happened.
5821 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5822 if (Range.contains(Val->getValue()))
5823 return SE.getCouldNotCompute(); // Something strange happened
5825 // Ensure that the previous value is in the range. This is a sanity check.
5826 assert(Range.contains(
5827 EvaluateConstantChrecAtConstant(this,
5828 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5829 "Linear scev computation is off in a bad way!");
5830 return SE.getConstant(ExitValue);
5831 } else if (isQuadratic()) {
5832 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5833 // quadratic equation to solve it. To do this, we must frame our problem in
5834 // terms of figuring out when zero is crossed, instead of when
5835 // Range.getUpper() is crossed.
5836 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5837 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5838 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5840 // Next, solve the constructed addrec
5841 std::pair<const SCEV *,const SCEV *> Roots =
5842 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5843 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5844 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5846 // Pick the smallest positive root value.
5847 if (ConstantInt *CB =
5848 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5849 R1->getValue(), R2->getValue()))) {
5850 if (CB->getZExtValue() == false)
5851 std::swap(R1, R2); // R1 is the minimum root now.
5853 // Make sure the root is not off by one. The returned iteration should
5854 // not be in the range, but the previous one should be. When solving
5855 // for "X*X < 5", for example, we should not return a root of 2.
5856 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5859 if (Range.contains(R1Val->getValue())) {
5860 // The next iteration must be out of the range...
5861 ConstantInt *NextVal =
5862 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5864 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5865 if (!Range.contains(R1Val->getValue()))
5866 return SE.getConstant(NextVal);
5867 return SE.getCouldNotCompute(); // Something strange happened
5870 // If R1 was not in the range, then it is a good return value. Make
5871 // sure that R1-1 WAS in the range though, just in case.
5872 ConstantInt *NextVal =
5873 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5874 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5875 if (Range.contains(R1Val->getValue()))
5877 return SE.getCouldNotCompute(); // Something strange happened
5882 return SE.getCouldNotCompute();
5887 //===----------------------------------------------------------------------===//
5888 // SCEVCallbackVH Class Implementation
5889 //===----------------------------------------------------------------------===//
5891 void ScalarEvolution::SCEVCallbackVH::deleted() {
5892 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5893 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5894 SE->ConstantEvolutionLoopExitValue.erase(PN);
5895 SE->ValueExprMap.erase(getValPtr());
5896 // this now dangles!
5899 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5900 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5902 // Forget all the expressions associated with users of the old value,
5903 // so that future queries will recompute the expressions using the new
5905 Value *Old = getValPtr();
5906 SmallVector<User *, 16> Worklist;
5907 SmallPtrSet<User *, 8> Visited;
5908 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5910 Worklist.push_back(*UI);
5911 while (!Worklist.empty()) {
5912 User *U = Worklist.pop_back_val();
5913 // Deleting the Old value will cause this to dangle. Postpone
5914 // that until everything else is done.
5917 if (!Visited.insert(U))
5919 if (PHINode *PN = dyn_cast<PHINode>(U))
5920 SE->ConstantEvolutionLoopExitValue.erase(PN);
5921 SE->ValueExprMap.erase(U);
5922 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5924 Worklist.push_back(*UI);
5926 // Delete the Old value.
5927 if (PHINode *PN = dyn_cast<PHINode>(Old))
5928 SE->ConstantEvolutionLoopExitValue.erase(PN);
5929 SE->ValueExprMap.erase(Old);
5930 // this now dangles!
5933 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5934 : CallbackVH(V), SE(se) {}
5936 //===----------------------------------------------------------------------===//
5937 // ScalarEvolution Class Implementation
5938 //===----------------------------------------------------------------------===//
5940 ScalarEvolution::ScalarEvolution()
5941 : FunctionPass(ID), FirstUnknown(0) {
5942 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
5945 bool ScalarEvolution::runOnFunction(Function &F) {
5947 LI = &getAnalysis<LoopInfo>();
5948 TD = getAnalysisIfAvailable<TargetData>();
5949 DT = &getAnalysis<DominatorTree>();
5953 void ScalarEvolution::releaseMemory() {
5954 // Iterate through all the SCEVUnknown instances and call their
5955 // destructors, so that they release their references to their values.
5956 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5960 ValueExprMap.clear();
5961 BackedgeTakenCounts.clear();
5962 ConstantEvolutionLoopExitValue.clear();
5963 ValuesAtScopes.clear();
5964 LoopDispositions.clear();
5965 BlockDispositions.clear();
5966 UnsignedRanges.clear();
5967 SignedRanges.clear();
5968 UniqueSCEVs.clear();
5969 SCEVAllocator.Reset();
5972 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5973 AU.setPreservesAll();
5974 AU.addRequiredTransitive<LoopInfo>();
5975 AU.addRequiredTransitive<DominatorTree>();
5978 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5979 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5982 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5984 // Print all inner loops first
5985 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5986 PrintLoopInfo(OS, SE, *I);
5989 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5992 SmallVector<BasicBlock *, 8> ExitBlocks;
5993 L->getExitBlocks(ExitBlocks);
5994 if (ExitBlocks.size() != 1)
5995 OS << "<multiple exits> ";
5997 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5998 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
6000 OS << "Unpredictable backedge-taken count. ";
6005 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6008 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6009 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6011 OS << "Unpredictable max backedge-taken count. ";
6017 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
6018 // ScalarEvolution's implementation of the print method is to print
6019 // out SCEV values of all instructions that are interesting. Doing
6020 // this potentially causes it to create new SCEV objects though,
6021 // which technically conflicts with the const qualifier. This isn't
6022 // observable from outside the class though, so casting away the
6023 // const isn't dangerous.
6024 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6026 OS << "Classifying expressions for: ";
6027 WriteAsOperand(OS, F, /*PrintType=*/false);
6029 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
6030 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
6033 const SCEV *SV = SE.getSCEV(&*I);
6036 const Loop *L = LI->getLoopFor((*I).getParent());
6038 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
6045 OS << "\t\t" "Exits: ";
6046 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
6047 if (!SE.isLoopInvariant(ExitValue, L)) {
6048 OS << "<<Unknown>>";
6057 OS << "Determining loop execution counts for: ";
6058 WriteAsOperand(OS, F, /*PrintType=*/false);
6060 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6061 PrintLoopInfo(OS, &SE, *I);
6064 ScalarEvolution::LoopDisposition
6065 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6066 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6067 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6068 Values.insert(std::make_pair(L, LoopVariant));
6070 return Pair.first->second;
6072 LoopDisposition D = computeLoopDisposition(S, L);
6073 return LoopDispositions[S][L] = D;
6076 ScalarEvolution::LoopDisposition
6077 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
6078 switch (S->getSCEVType()) {
6080 return LoopInvariant;
6084 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
6085 case scAddRecExpr: {
6086 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6088 // If L is the addrec's loop, it's computable.
6089 if (AR->getLoop() == L)
6090 return LoopComputable;
6092 // Add recurrences are never invariant in the function-body (null loop).
6096 // This recurrence is variant w.r.t. L if L contains AR's loop.
6097 if (L->contains(AR->getLoop()))
6100 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6101 if (AR->getLoop()->contains(L))
6102 return LoopInvariant;
6104 // This recurrence is variant w.r.t. L if any of its operands
6106 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6108 if (!isLoopInvariant(*I, L))
6111 // Otherwise it's loop-invariant.
6112 return LoopInvariant;
6118 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6119 bool HasVarying = false;
6120 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6122 LoopDisposition D = getLoopDisposition(*I, L);
6123 if (D == LoopVariant)
6125 if (D == LoopComputable)
6128 return HasVarying ? LoopComputable : LoopInvariant;
6131 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6132 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6133 if (LD == LoopVariant)
6135 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6136 if (RD == LoopVariant)
6138 return (LD == LoopInvariant && RD == LoopInvariant) ?
6139 LoopInvariant : LoopComputable;
6142 // All non-instruction values are loop invariant. All instructions are loop
6143 // invariant if they are not contained in the specified loop.
6144 // Instructions are never considered invariant in the function body
6145 // (null loop) because they are defined within the "loop".
6146 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6147 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6148 return LoopInvariant;
6149 case scCouldNotCompute:
6150 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6154 llvm_unreachable("Unknown SCEV kind!");
6158 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6159 return getLoopDisposition(S, L) == LoopInvariant;
6162 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6163 return getLoopDisposition(S, L) == LoopComputable;
6166 ScalarEvolution::BlockDisposition
6167 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6168 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6169 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6170 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6172 return Pair.first->second;
6174 BlockDisposition D = computeBlockDisposition(S, BB);
6175 return BlockDispositions[S][BB] = D;
6178 ScalarEvolution::BlockDisposition
6179 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6180 switch (S->getSCEVType()) {
6182 return ProperlyDominatesBlock;
6186 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
6187 case scAddRecExpr: {
6188 // This uses a "dominates" query instead of "properly dominates" query
6189 // to test for proper dominance too, because the instruction which
6190 // produces the addrec's value is a PHI, and a PHI effectively properly
6191 // dominates its entire containing block.
6192 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6193 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6194 return DoesNotDominateBlock;
6196 // FALL THROUGH into SCEVNAryExpr handling.
6201 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6203 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6205 BlockDisposition D = getBlockDisposition(*I, BB);
6206 if (D == DoesNotDominateBlock)
6207 return DoesNotDominateBlock;
6208 if (D == DominatesBlock)
6211 return Proper ? ProperlyDominatesBlock : DominatesBlock;
6214 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6215 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6216 BlockDisposition LD = getBlockDisposition(LHS, BB);
6217 if (LD == DoesNotDominateBlock)
6218 return DoesNotDominateBlock;
6219 BlockDisposition RD = getBlockDisposition(RHS, BB);
6220 if (RD == DoesNotDominateBlock)
6221 return DoesNotDominateBlock;
6222 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6223 ProperlyDominatesBlock : DominatesBlock;
6226 if (Instruction *I =
6227 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6228 if (I->getParent() == BB)
6229 return DominatesBlock;
6230 if (DT->properlyDominates(I->getParent(), BB))
6231 return ProperlyDominatesBlock;
6232 return DoesNotDominateBlock;
6234 return ProperlyDominatesBlock;
6235 case scCouldNotCompute:
6236 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6237 return DoesNotDominateBlock;
6240 llvm_unreachable("Unknown SCEV kind!");
6241 return DoesNotDominateBlock;
6244 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6245 return getBlockDisposition(S, BB) >= DominatesBlock;
6248 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6249 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
6252 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6253 switch (S->getSCEVType()) {
6258 case scSignExtend: {
6259 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6260 const SCEV *CastOp = Cast->getOperand();
6261 return Op == CastOp || hasOperand(CastOp, Op);
6268 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6269 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6271 const SCEV *NAryOp = *I;
6272 if (NAryOp == Op || hasOperand(NAryOp, Op))
6278 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6279 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6280 return LHS == Op || hasOperand(LHS, Op) ||
6281 RHS == Op || hasOperand(RHS, Op);
6285 case scCouldNotCompute:
6286 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6290 llvm_unreachable("Unknown SCEV kind!");
6294 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6295 ValuesAtScopes.erase(S);
6296 LoopDispositions.erase(S);
6297 BlockDispositions.erase(S);
6298 UnsignedRanges.erase(S);
6299 SignedRanges.erase(S);