1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
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 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/Analysis/AssumptionTracker.h"
66 #include "llvm/Analysis/ConstantFolding.h"
67 #include "llvm/Analysis/InstructionSimplify.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
70 #include "llvm/Analysis/ValueTracking.h"
71 #include "llvm/IR/ConstantRange.h"
72 #include "llvm/IR/Constants.h"
73 #include "llvm/IR/DataLayout.h"
74 #include "llvm/IR/DerivedTypes.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/GetElementPtrTypeIterator.h"
77 #include "llvm/IR/GlobalAlias.h"
78 #include "llvm/IR/GlobalVariable.h"
79 #include "llvm/IR/InstIterator.h"
80 #include "llvm/IR/Instructions.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Operator.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetLibraryInfo.h"
92 #define DEBUG_TYPE "scalar-evolution"
94 STATISTIC(NumArrayLenItCounts,
95 "Number of trip counts computed with array length");
96 STATISTIC(NumTripCountsComputed,
97 "Number of loops with predictable loop counts");
98 STATISTIC(NumTripCountsNotComputed,
99 "Number of loops without predictable loop counts");
100 STATISTIC(NumBruteForceTripCountsComputed,
101 "Number of loops with trip counts computed by force");
103 static cl::opt<unsigned>
104 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
105 cl::desc("Maximum number of iterations SCEV will "
106 "symbolically execute a constant "
110 // FIXME: Enable this with XDEBUG when the test suite is clean.
112 VerifySCEV("verify-scev",
113 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
115 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
116 "Scalar Evolution Analysis", false, true)
117 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
118 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
119 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
120 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
121 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
122 "Scalar Evolution Analysis", false, true)
123 char ScalarEvolution::ID = 0;
125 //===----------------------------------------------------------------------===//
126 // SCEV class definitions
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
130 // Implementation of the SCEV class.
133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
134 void SCEV::dump() const {
140 void SCEV::print(raw_ostream &OS) const {
141 switch (static_cast<SCEVTypes>(getSCEVType())) {
143 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
146 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
147 const SCEV *Op = Trunc->getOperand();
148 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
149 << *Trunc->getType() << ")";
153 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
154 const SCEV *Op = ZExt->getOperand();
155 OS << "(zext " << *Op->getType() << " " << *Op << " to "
156 << *ZExt->getType() << ")";
160 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
161 const SCEV *Op = SExt->getOperand();
162 OS << "(sext " << *Op->getType() << " " << *Op << " to "
163 << *SExt->getType() << ")";
167 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
168 OS << "{" << *AR->getOperand(0);
169 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
170 OS << ",+," << *AR->getOperand(i);
172 if (AR->getNoWrapFlags(FlagNUW))
174 if (AR->getNoWrapFlags(FlagNSW))
176 if (AR->getNoWrapFlags(FlagNW) &&
177 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
179 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
187 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
188 const char *OpStr = nullptr;
189 switch (NAry->getSCEVType()) {
190 case scAddExpr: OpStr = " + "; break;
191 case scMulExpr: OpStr = " * "; break;
192 case scUMaxExpr: OpStr = " umax "; break;
193 case scSMaxExpr: OpStr = " smax "; break;
196 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
199 if (std::next(I) != E)
203 switch (NAry->getSCEVType()) {
206 if (NAry->getNoWrapFlags(FlagNUW))
208 if (NAry->getNoWrapFlags(FlagNSW))
214 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
215 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
219 const SCEVUnknown *U = cast<SCEVUnknown>(this);
221 if (U->isSizeOf(AllocTy)) {
222 OS << "sizeof(" << *AllocTy << ")";
225 if (U->isAlignOf(AllocTy)) {
226 OS << "alignof(" << *AllocTy << ")";
232 if (U->isOffsetOf(CTy, FieldNo)) {
233 OS << "offsetof(" << *CTy << ", ";
234 FieldNo->printAsOperand(OS, false);
239 // Otherwise just print it normally.
240 U->getValue()->printAsOperand(OS, false);
243 case scCouldNotCompute:
244 OS << "***COULDNOTCOMPUTE***";
247 llvm_unreachable("Unknown SCEV kind!");
250 Type *SCEV::getType() const {
251 switch (static_cast<SCEVTypes>(getSCEVType())) {
253 return cast<SCEVConstant>(this)->getType();
257 return cast<SCEVCastExpr>(this)->getType();
262 return cast<SCEVNAryExpr>(this)->getType();
264 return cast<SCEVAddExpr>(this)->getType();
266 return cast<SCEVUDivExpr>(this)->getType();
268 return cast<SCEVUnknown>(this)->getType();
269 case scCouldNotCompute:
270 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
272 llvm_unreachable("Unknown SCEV kind!");
275 bool SCEV::isZero() const {
276 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
277 return SC->getValue()->isZero();
281 bool SCEV::isOne() const {
282 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
283 return SC->getValue()->isOne();
287 bool SCEV::isAllOnesValue() const {
288 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
289 return SC->getValue()->isAllOnesValue();
293 /// isNonConstantNegative - Return true if the specified scev is negated, but
295 bool SCEV::isNonConstantNegative() const {
296 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
297 if (!Mul) return false;
299 // If there is a constant factor, it will be first.
300 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
301 if (!SC) return false;
303 // Return true if the value is negative, this matches things like (-42 * V).
304 return SC->getValue()->getValue().isNegative();
307 SCEVCouldNotCompute::SCEVCouldNotCompute() :
308 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
310 bool SCEVCouldNotCompute::classof(const SCEV *S) {
311 return S->getSCEVType() == scCouldNotCompute;
314 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
316 ID.AddInteger(scConstant);
319 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
320 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
321 UniqueSCEVs.InsertNode(S, IP);
325 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
326 return getConstant(ConstantInt::get(getContext(), Val));
330 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
331 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
332 return getConstant(ConstantInt::get(ITy, V, isSigned));
335 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
336 unsigned SCEVTy, const SCEV *op, Type *ty)
337 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
339 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
340 const SCEV *op, Type *ty)
341 : SCEVCastExpr(ID, scTruncate, op, ty) {
342 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
343 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
344 "Cannot truncate non-integer value!");
347 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
348 const SCEV *op, Type *ty)
349 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
350 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
351 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
352 "Cannot zero extend non-integer value!");
355 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
356 const SCEV *op, Type *ty)
357 : SCEVCastExpr(ID, scSignExtend, op, ty) {
358 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
359 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
360 "Cannot sign extend non-integer value!");
363 void SCEVUnknown::deleted() {
364 // Clear this SCEVUnknown from various maps.
365 SE->forgetMemoizedResults(this);
367 // Remove this SCEVUnknown from the uniquing map.
368 SE->UniqueSCEVs.RemoveNode(this);
370 // Release the value.
374 void SCEVUnknown::allUsesReplacedWith(Value *New) {
375 // Clear this SCEVUnknown from various maps.
376 SE->forgetMemoizedResults(this);
378 // Remove this SCEVUnknown from the uniquing map.
379 SE->UniqueSCEVs.RemoveNode(this);
381 // Update this SCEVUnknown to point to the new value. This is needed
382 // because there may still be outstanding SCEVs which still point to
387 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
388 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
389 if (VCE->getOpcode() == Instruction::PtrToInt)
390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
391 if (CE->getOpcode() == Instruction::GetElementPtr &&
392 CE->getOperand(0)->isNullValue() &&
393 CE->getNumOperands() == 2)
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
396 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
404 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
405 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
406 if (VCE->getOpcode() == Instruction::PtrToInt)
407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
408 if (CE->getOpcode() == Instruction::GetElementPtr &&
409 CE->getOperand(0)->isNullValue()) {
411 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
412 if (StructType *STy = dyn_cast<StructType>(Ty))
413 if (!STy->isPacked() &&
414 CE->getNumOperands() == 3 &&
415 CE->getOperand(1)->isNullValue()) {
416 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
418 STy->getNumElements() == 2 &&
419 STy->getElementType(0)->isIntegerTy(1)) {
420 AllocTy = STy->getElementType(1);
429 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
430 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
431 if (VCE->getOpcode() == Instruction::PtrToInt)
432 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
433 if (CE->getOpcode() == Instruction::GetElementPtr &&
434 CE->getNumOperands() == 3 &&
435 CE->getOperand(0)->isNullValue() &&
436 CE->getOperand(1)->isNullValue()) {
438 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
439 // Ignore vector types here so that ScalarEvolutionExpander doesn't
440 // emit getelementptrs that index into vectors.
441 if (Ty->isStructTy() || Ty->isArrayTy()) {
443 FieldNo = CE->getOperand(2);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
456 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
457 /// than the complexity of the RHS. This comparator is used to canonicalize
459 class SCEVComplexityCompare {
460 const LoopInfo *const LI;
462 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
464 // Return true or false if LHS is less than, or at least RHS, respectively.
465 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
466 return compare(LHS, RHS) < 0;
469 // Return negative, zero, or positive, if LHS is less than, equal to, or
470 // greater than RHS, respectively. A three-way result allows recursive
471 // comparisons to be more efficient.
472 int compare(const SCEV *LHS, const SCEV *RHS) const {
473 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
477 // Primarily, sort the SCEVs by their getSCEVType().
478 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
480 return (int)LType - (int)RType;
482 // Aside from the getSCEVType() ordering, the particular ordering
483 // isn't very important except that it's beneficial to be consistent,
484 // so that (a + b) and (b + a) don't end up as different expressions.
485 switch (static_cast<SCEVTypes>(LType)) {
487 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
488 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
490 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
491 // not as complete as it could be.
492 const Value *LV = LU->getValue(), *RV = RU->getValue();
494 // Order pointer values after integer values. This helps SCEVExpander
496 bool LIsPointer = LV->getType()->isPointerTy(),
497 RIsPointer = RV->getType()->isPointerTy();
498 if (LIsPointer != RIsPointer)
499 return (int)LIsPointer - (int)RIsPointer;
501 // Compare getValueID values.
502 unsigned LID = LV->getValueID(),
503 RID = RV->getValueID();
505 return (int)LID - (int)RID;
507 // Sort arguments by their position.
508 if (const Argument *LA = dyn_cast<Argument>(LV)) {
509 const Argument *RA = cast<Argument>(RV);
510 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
511 return (int)LArgNo - (int)RArgNo;
514 // For instructions, compare their loop depth, and their operand
515 // count. This is pretty loose.
516 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
517 const Instruction *RInst = cast<Instruction>(RV);
519 // Compare loop depths.
520 const BasicBlock *LParent = LInst->getParent(),
521 *RParent = RInst->getParent();
522 if (LParent != RParent) {
523 unsigned LDepth = LI->getLoopDepth(LParent),
524 RDepth = LI->getLoopDepth(RParent);
525 if (LDepth != RDepth)
526 return (int)LDepth - (int)RDepth;
529 // Compare the number of operands.
530 unsigned LNumOps = LInst->getNumOperands(),
531 RNumOps = RInst->getNumOperands();
532 return (int)LNumOps - (int)RNumOps;
539 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
540 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
542 // Compare constant values.
543 const APInt &LA = LC->getValue()->getValue();
544 const APInt &RA = RC->getValue()->getValue();
545 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
546 if (LBitWidth != RBitWidth)
547 return (int)LBitWidth - (int)RBitWidth;
548 return LA.ult(RA) ? -1 : 1;
552 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
553 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
555 // Compare addrec loop depths.
556 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
557 if (LLoop != RLoop) {
558 unsigned LDepth = LLoop->getLoopDepth(),
559 RDepth = RLoop->getLoopDepth();
560 if (LDepth != RDepth)
561 return (int)LDepth - (int)RDepth;
564 // Addrec complexity grows with operand count.
565 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
566 if (LNumOps != RNumOps)
567 return (int)LNumOps - (int)RNumOps;
569 // Lexicographically compare.
570 for (unsigned i = 0; i != LNumOps; ++i) {
571 long X = compare(LA->getOperand(i), RA->getOperand(i));
583 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
584 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
586 // Lexicographically compare n-ary expressions.
587 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
588 if (LNumOps != RNumOps)
589 return (int)LNumOps - (int)RNumOps;
591 for (unsigned i = 0; i != LNumOps; ++i) {
594 long X = compare(LC->getOperand(i), RC->getOperand(i));
598 return (int)LNumOps - (int)RNumOps;
602 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
603 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
605 // Lexicographically compare udiv expressions.
606 long X = compare(LC->getLHS(), RC->getLHS());
609 return compare(LC->getRHS(), RC->getRHS());
615 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
616 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
618 // Compare cast expressions by operand.
619 return compare(LC->getOperand(), RC->getOperand());
622 case scCouldNotCompute:
623 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
625 llvm_unreachable("Unknown SCEV kind!");
630 /// GroupByComplexity - Given a list of SCEV objects, order them by their
631 /// complexity, and group objects of the same complexity together by value.
632 /// When this routine is finished, we know that any duplicates in the vector are
633 /// consecutive and that complexity is monotonically increasing.
635 /// Note that we go take special precautions to ensure that we get deterministic
636 /// results from this routine. In other words, we don't want the results of
637 /// this to depend on where the addresses of various SCEV objects happened to
640 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
642 if (Ops.size() < 2) return; // Noop
643 if (Ops.size() == 2) {
644 // This is the common case, which also happens to be trivially simple.
646 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
647 if (SCEVComplexityCompare(LI)(RHS, LHS))
652 // Do the rough sort by complexity.
653 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
655 // Now that we are sorted by complexity, group elements of the same
656 // complexity. Note that this is, at worst, N^2, but the vector is likely to
657 // be extremely short in practice. Note that we take this approach because we
658 // do not want to depend on the addresses of the objects we are grouping.
659 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
660 const SCEV *S = Ops[i];
661 unsigned Complexity = S->getSCEVType();
663 // If there are any objects of the same complexity and same value as this
665 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
666 if (Ops[j] == S) { // Found a duplicate.
667 // Move it to immediately after i'th element.
668 std::swap(Ops[i+1], Ops[j]);
669 ++i; // no need to rescan it.
670 if (i == e-2) return; // Done!
678 //===----------------------------------------------------------------------===//
679 // Simple SCEV method implementations
680 //===----------------------------------------------------------------------===//
682 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
684 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
687 // Handle the simplest case efficiently.
689 return SE.getTruncateOrZeroExtend(It, ResultTy);
691 // We are using the following formula for BC(It, K):
693 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
695 // Suppose, W is the bitwidth of the return value. We must be prepared for
696 // overflow. Hence, we must assure that the result of our computation is
697 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
698 // safe in modular arithmetic.
700 // However, this code doesn't use exactly that formula; the formula it uses
701 // is something like the following, where T is the number of factors of 2 in
702 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
705 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
707 // This formula is trivially equivalent to the previous formula. However,
708 // this formula can be implemented much more efficiently. The trick is that
709 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
710 // arithmetic. To do exact division in modular arithmetic, all we have
711 // to do is multiply by the inverse. Therefore, this step can be done at
714 // The next issue is how to safely do the division by 2^T. The way this
715 // is done is by doing the multiplication step at a width of at least W + T
716 // bits. This way, the bottom W+T bits of the product are accurate. Then,
717 // when we perform the division by 2^T (which is equivalent to a right shift
718 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
719 // truncated out after the division by 2^T.
721 // In comparison to just directly using the first formula, this technique
722 // is much more efficient; using the first formula requires W * K bits,
723 // but this formula less than W + K bits. Also, the first formula requires
724 // a division step, whereas this formula only requires multiplies and shifts.
726 // It doesn't matter whether the subtraction step is done in the calculation
727 // width or the input iteration count's width; if the subtraction overflows,
728 // the result must be zero anyway. We prefer here to do it in the width of
729 // the induction variable because it helps a lot for certain cases; CodeGen
730 // isn't smart enough to ignore the overflow, which leads to much less
731 // efficient code if the width of the subtraction is wider than the native
734 // (It's possible to not widen at all by pulling out factors of 2 before
735 // the multiplication; for example, K=2 can be calculated as
736 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
737 // extra arithmetic, so it's not an obvious win, and it gets
738 // much more complicated for K > 3.)
740 // Protection from insane SCEVs; this bound is conservative,
741 // but it probably doesn't matter.
743 return SE.getCouldNotCompute();
745 unsigned W = SE.getTypeSizeInBits(ResultTy);
747 // Calculate K! / 2^T and T; we divide out the factors of two before
748 // multiplying for calculating K! / 2^T to avoid overflow.
749 // Other overflow doesn't matter because we only care about the bottom
750 // W bits of the result.
751 APInt OddFactorial(W, 1);
753 for (unsigned i = 3; i <= K; ++i) {
755 unsigned TwoFactors = Mult.countTrailingZeros();
757 Mult = Mult.lshr(TwoFactors);
758 OddFactorial *= Mult;
761 // We need at least W + T bits for the multiplication step
762 unsigned CalculationBits = W + T;
764 // Calculate 2^T, at width T+W.
765 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
767 // Calculate the multiplicative inverse of K! / 2^T;
768 // this multiplication factor will perform the exact division by
770 APInt Mod = APInt::getSignedMinValue(W+1);
771 APInt MultiplyFactor = OddFactorial.zext(W+1);
772 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
773 MultiplyFactor = MultiplyFactor.trunc(W);
775 // Calculate the product, at width T+W
776 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
778 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
779 for (unsigned i = 1; i != K; ++i) {
780 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
781 Dividend = SE.getMulExpr(Dividend,
782 SE.getTruncateOrZeroExtend(S, CalculationTy));
786 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
788 // Truncate the result, and divide by K! / 2^T.
790 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
791 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
794 /// evaluateAtIteration - Return the value of this chain of recurrences at
795 /// the specified iteration number. We can evaluate this recurrence by
796 /// multiplying each element in the chain by the binomial coefficient
797 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
799 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
801 /// where BC(It, k) stands for binomial coefficient.
803 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
804 ScalarEvolution &SE) const {
805 const SCEV *Result = getStart();
806 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
807 // The computation is correct in the face of overflow provided that the
808 // multiplication is performed _after_ the evaluation of the binomial
810 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
811 if (isa<SCEVCouldNotCompute>(Coeff))
814 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
819 //===----------------------------------------------------------------------===//
820 // SCEV Expression folder implementations
821 //===----------------------------------------------------------------------===//
823 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
825 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
826 "This is not a truncating conversion!");
827 assert(isSCEVable(Ty) &&
828 "This is not a conversion to a SCEVable type!");
829 Ty = getEffectiveSCEVType(Ty);
832 ID.AddInteger(scTruncate);
836 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
838 // Fold if the operand is constant.
839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
841 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
843 // trunc(trunc(x)) --> trunc(x)
844 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
845 return getTruncateExpr(ST->getOperand(), Ty);
847 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
848 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
849 return getTruncateOrSignExtend(SS->getOperand(), Ty);
851 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
852 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
853 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
855 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
856 // eliminate all the truncates.
857 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
858 SmallVector<const SCEV *, 4> Operands;
859 bool hasTrunc = false;
860 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
861 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
862 hasTrunc = isa<SCEVTruncateExpr>(S);
863 Operands.push_back(S);
866 return getAddExpr(Operands);
867 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
870 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
871 // eliminate all the truncates.
872 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
873 SmallVector<const SCEV *, 4> Operands;
874 bool hasTrunc = false;
875 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
876 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
877 hasTrunc = isa<SCEVTruncateExpr>(S);
878 Operands.push_back(S);
881 return getMulExpr(Operands);
882 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
885 // If the input value is a chrec scev, truncate the chrec's operands.
886 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
887 SmallVector<const SCEV *, 4> Operands;
888 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
889 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
890 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
893 // The cast wasn't folded; create an explicit cast node. We can reuse
894 // the existing insert position since if we get here, we won't have
895 // made any changes which would invalidate it.
896 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
898 UniqueSCEVs.InsertNode(S, IP);
902 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
904 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
905 "This is not an extending conversion!");
906 assert(isSCEVable(Ty) &&
907 "This is not a conversion to a SCEVable type!");
908 Ty = getEffectiveSCEVType(Ty);
910 // Fold if the operand is constant.
911 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
913 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
915 // zext(zext(x)) --> zext(x)
916 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
917 return getZeroExtendExpr(SZ->getOperand(), Ty);
919 // Before doing any expensive analysis, check to see if we've already
920 // computed a SCEV for this Op and Ty.
922 ID.AddInteger(scZeroExtend);
926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
928 // zext(trunc(x)) --> zext(x) or x or trunc(x)
929 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
930 // It's possible the bits taken off by the truncate were all zero bits. If
931 // so, we should be able to simplify this further.
932 const SCEV *X = ST->getOperand();
933 ConstantRange CR = getUnsignedRange(X);
934 unsigned TruncBits = getTypeSizeInBits(ST->getType());
935 unsigned NewBits = getTypeSizeInBits(Ty);
936 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
937 CR.zextOrTrunc(NewBits)))
938 return getTruncateOrZeroExtend(X, Ty);
941 // If the input value is a chrec scev, and we can prove that the value
942 // did not overflow the old, smaller, value, we can zero extend all of the
943 // operands (often constants). This allows analysis of something like
944 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
945 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
946 if (AR->isAffine()) {
947 const SCEV *Start = AR->getStart();
948 const SCEV *Step = AR->getStepRecurrence(*this);
949 unsigned BitWidth = getTypeSizeInBits(AR->getType());
950 const Loop *L = AR->getLoop();
952 // If we have special knowledge that this addrec won't overflow,
953 // we don't need to do any further analysis.
954 if (AR->getNoWrapFlags(SCEV::FlagNUW))
955 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
956 getZeroExtendExpr(Step, Ty),
957 L, AR->getNoWrapFlags());
959 // Check whether the backedge-taken count is SCEVCouldNotCompute.
960 // Note that this serves two purposes: It filters out loops that are
961 // simply not analyzable, and it covers the case where this code is
962 // being called from within backedge-taken count analysis, such that
963 // attempting to ask for the backedge-taken count would likely result
964 // in infinite recursion. In the later case, the analysis code will
965 // cope with a conservative value, and it will take care to purge
966 // that value once it has finished.
967 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
968 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
969 // Manually compute the final value for AR, checking for
972 // Check whether the backedge-taken count can be losslessly casted to
973 // the addrec's type. The count is always unsigned.
974 const SCEV *CastedMaxBECount =
975 getTruncateOrZeroExtend(MaxBECount, Start->getType());
976 const SCEV *RecastedMaxBECount =
977 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
978 if (MaxBECount == RecastedMaxBECount) {
979 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
980 // Check whether Start+Step*MaxBECount has no unsigned overflow.
981 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
982 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
983 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
984 const SCEV *WideMaxBECount =
985 getZeroExtendExpr(CastedMaxBECount, WideTy);
986 const SCEV *OperandExtendedAdd =
987 getAddExpr(WideStart,
988 getMulExpr(WideMaxBECount,
989 getZeroExtendExpr(Step, WideTy)));
990 if (ZAdd == OperandExtendedAdd) {
991 // Cache knowledge of AR NUW, which is propagated to this AddRec.
992 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
993 // Return the expression with the addrec on the outside.
994 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
995 getZeroExtendExpr(Step, Ty),
996 L, AR->getNoWrapFlags());
998 // Similar to above, only this time treat the step value as signed.
999 // This covers loops that count down.
1000 OperandExtendedAdd =
1001 getAddExpr(WideStart,
1002 getMulExpr(WideMaxBECount,
1003 getSignExtendExpr(Step, WideTy)));
1004 if (ZAdd == OperandExtendedAdd) {
1005 // Cache knowledge of AR NW, which is propagated to this AddRec.
1006 // Negative step causes unsigned wrap, but it still can't self-wrap.
1007 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1008 // Return the expression with the addrec on the outside.
1009 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1010 getSignExtendExpr(Step, Ty),
1011 L, AR->getNoWrapFlags());
1015 // If the backedge is guarded by a comparison with the pre-inc value
1016 // the addrec is safe. Also, if the entry is guarded by a comparison
1017 // with the start value and the backedge is guarded by a comparison
1018 // with the post-inc value, the addrec is safe.
1019 if (isKnownPositive(Step)) {
1020 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1021 getUnsignedRange(Step).getUnsignedMax());
1022 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1023 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1024 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1025 AR->getPostIncExpr(*this), N))) {
1026 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1027 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1028 // Return the expression with the addrec on the outside.
1029 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1030 getZeroExtendExpr(Step, Ty),
1031 L, AR->getNoWrapFlags());
1033 } else if (isKnownNegative(Step)) {
1034 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1035 getSignedRange(Step).getSignedMin());
1036 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1037 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1038 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1039 AR->getPostIncExpr(*this), N))) {
1040 // Cache knowledge of AR NW, which is propagated to this AddRec.
1041 // Negative step causes unsigned wrap, but it still can't self-wrap.
1042 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1043 // Return the expression with the addrec on the outside.
1044 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1045 getSignExtendExpr(Step, Ty),
1046 L, AR->getNoWrapFlags());
1052 // The cast wasn't folded; create an explicit cast node.
1053 // Recompute the insert position, as it may have been invalidated.
1054 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1055 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1057 UniqueSCEVs.InsertNode(S, IP);
1061 // Get the limit of a recurrence such that incrementing by Step cannot cause
1062 // signed overflow as long as the value of the recurrence within the loop does
1063 // not exceed this limit before incrementing.
1064 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1065 ICmpInst::Predicate *Pred,
1066 ScalarEvolution *SE) {
1067 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1068 if (SE->isKnownPositive(Step)) {
1069 *Pred = ICmpInst::ICMP_SLT;
1070 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1071 SE->getSignedRange(Step).getSignedMax());
1073 if (SE->isKnownNegative(Step)) {
1074 *Pred = ICmpInst::ICMP_SGT;
1075 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1076 SE->getSignedRange(Step).getSignedMin());
1081 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
1082 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
1083 // or postincrement sibling. This allows normalizing a sign extended AddRec as
1084 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1085 // result, the expression "Step + sext(PreIncAR)" is congruent with
1086 // "sext(PostIncAR)"
1087 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
1089 ScalarEvolution *SE) {
1090 const Loop *L = AR->getLoop();
1091 const SCEV *Start = AR->getStart();
1092 const SCEV *Step = AR->getStepRecurrence(*SE);
1094 // Check for a simple looking step prior to loop entry.
1095 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1099 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1100 // subtraction is expensive. For this purpose, perform a quick and dirty
1101 // difference, by checking for Step in the operand list.
1102 SmallVector<const SCEV *, 4> DiffOps;
1103 for (const SCEV *Op : SA->operands())
1105 DiffOps.push_back(Op);
1107 if (DiffOps.size() == SA->getNumOperands())
1110 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1111 // same three conditions that getSignExtendedExpr checks.
1113 // 1. NSW flags on the step increment.
1114 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1115 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1116 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1118 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
1121 // 2. Direct overflow check on the step operation's expression.
1122 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1123 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1124 const SCEV *OperandExtendedStart =
1125 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1126 SE->getSignExtendExpr(Step, WideTy));
1127 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1128 // Cache knowledge of PreAR NSW.
1130 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1131 // FIXME: this optimization needs a unit test
1132 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1136 // 3. Loop precondition.
1137 ICmpInst::Predicate Pred;
1138 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1140 if (OverflowLimit &&
1141 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1147 // Get the normalized sign-extended expression for this AddRec's Start.
1148 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
1150 ScalarEvolution *SE) {
1151 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1153 return SE->getSignExtendExpr(AR->getStart(), Ty);
1155 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1156 SE->getSignExtendExpr(PreStart, Ty));
1159 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1161 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1162 "This is not an extending conversion!");
1163 assert(isSCEVable(Ty) &&
1164 "This is not a conversion to a SCEVable type!");
1165 Ty = getEffectiveSCEVType(Ty);
1167 // Fold if the operand is constant.
1168 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1170 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1172 // sext(sext(x)) --> sext(x)
1173 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1174 return getSignExtendExpr(SS->getOperand(), Ty);
1176 // sext(zext(x)) --> zext(x)
1177 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1178 return getZeroExtendExpr(SZ->getOperand(), Ty);
1180 // Before doing any expensive analysis, check to see if we've already
1181 // computed a SCEV for this Op and Ty.
1182 FoldingSetNodeID ID;
1183 ID.AddInteger(scSignExtend);
1187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1189 // If the input value is provably positive, build a zext instead.
1190 if (isKnownNonNegative(Op))
1191 return getZeroExtendExpr(Op, Ty);
1193 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1194 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1195 // It's possible the bits taken off by the truncate were all sign bits. If
1196 // so, we should be able to simplify this further.
1197 const SCEV *X = ST->getOperand();
1198 ConstantRange CR = getSignedRange(X);
1199 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1200 unsigned NewBits = getTypeSizeInBits(Ty);
1201 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1202 CR.sextOrTrunc(NewBits)))
1203 return getTruncateOrSignExtend(X, Ty);
1206 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1207 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1208 if (SA->getNumOperands() == 2) {
1209 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1210 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1212 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1213 const APInt &C1 = SC1->getValue()->getValue();
1214 const APInt &C2 = SC2->getValue()->getValue();
1215 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1216 C2.ugt(C1) && C2.isPowerOf2())
1217 return getAddExpr(getSignExtendExpr(SC1, Ty),
1218 getSignExtendExpr(SMul, Ty));
1223 // If the input value is a chrec scev, and we can prove that the value
1224 // did not overflow the old, smaller, value, we can sign extend all of the
1225 // operands (often constants). This allows analysis of something like
1226 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1227 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1228 if (AR->isAffine()) {
1229 const SCEV *Start = AR->getStart();
1230 const SCEV *Step = AR->getStepRecurrence(*this);
1231 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1232 const Loop *L = AR->getLoop();
1234 // If we have special knowledge that this addrec won't overflow,
1235 // we don't need to do any further analysis.
1236 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1237 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1238 getSignExtendExpr(Step, Ty),
1241 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1242 // Note that this serves two purposes: It filters out loops that are
1243 // simply not analyzable, and it covers the case where this code is
1244 // being called from within backedge-taken count analysis, such that
1245 // attempting to ask for the backedge-taken count would likely result
1246 // in infinite recursion. In the later case, the analysis code will
1247 // cope with a conservative value, and it will take care to purge
1248 // that value once it has finished.
1249 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1250 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1251 // Manually compute the final value for AR, checking for
1254 // Check whether the backedge-taken count can be losslessly casted to
1255 // the addrec's type. The count is always unsigned.
1256 const SCEV *CastedMaxBECount =
1257 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1258 const SCEV *RecastedMaxBECount =
1259 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1260 if (MaxBECount == RecastedMaxBECount) {
1261 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1262 // Check whether Start+Step*MaxBECount has no signed overflow.
1263 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1264 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1265 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1266 const SCEV *WideMaxBECount =
1267 getZeroExtendExpr(CastedMaxBECount, WideTy);
1268 const SCEV *OperandExtendedAdd =
1269 getAddExpr(WideStart,
1270 getMulExpr(WideMaxBECount,
1271 getSignExtendExpr(Step, WideTy)));
1272 if (SAdd == OperandExtendedAdd) {
1273 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1274 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1275 // Return the expression with the addrec on the outside.
1276 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1277 getSignExtendExpr(Step, Ty),
1278 L, AR->getNoWrapFlags());
1280 // Similar to above, only this time treat the step value as unsigned.
1281 // This covers loops that count up with an unsigned step.
1282 OperandExtendedAdd =
1283 getAddExpr(WideStart,
1284 getMulExpr(WideMaxBECount,
1285 getZeroExtendExpr(Step, WideTy)));
1286 if (SAdd == OperandExtendedAdd) {
1287 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1288 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1289 // Return the expression with the addrec on the outside.
1290 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1291 getZeroExtendExpr(Step, Ty),
1292 L, AR->getNoWrapFlags());
1296 // If the backedge is guarded by a comparison with the pre-inc value
1297 // the addrec is safe. Also, if the entry is guarded by a comparison
1298 // with the start value and the backedge is guarded by a comparison
1299 // with the post-inc value, the addrec is safe.
1300 ICmpInst::Predicate Pred;
1301 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1302 if (OverflowLimit &&
1303 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1304 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1305 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1307 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1308 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1309 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1310 getSignExtendExpr(Step, Ty),
1311 L, AR->getNoWrapFlags());
1314 // If Start and Step are constants, check if we can apply this
1316 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1317 auto SC1 = dyn_cast<SCEVConstant>(Start);
1318 auto SC2 = dyn_cast<SCEVConstant>(Step);
1320 const APInt &C1 = SC1->getValue()->getValue();
1321 const APInt &C2 = SC2->getValue()->getValue();
1322 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1324 Start = getSignExtendExpr(Start, Ty);
1325 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1326 L, AR->getNoWrapFlags());
1327 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1332 // The cast wasn't folded; create an explicit cast node.
1333 // Recompute the insert position, as it may have been invalidated.
1334 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1335 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1337 UniqueSCEVs.InsertNode(S, IP);
1341 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1342 /// unspecified bits out to the given type.
1344 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1346 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1347 "This is not an extending conversion!");
1348 assert(isSCEVable(Ty) &&
1349 "This is not a conversion to a SCEVable type!");
1350 Ty = getEffectiveSCEVType(Ty);
1352 // Sign-extend negative constants.
1353 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1354 if (SC->getValue()->getValue().isNegative())
1355 return getSignExtendExpr(Op, Ty);
1357 // Peel off a truncate cast.
1358 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1359 const SCEV *NewOp = T->getOperand();
1360 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1361 return getAnyExtendExpr(NewOp, Ty);
1362 return getTruncateOrNoop(NewOp, Ty);
1365 // Next try a zext cast. If the cast is folded, use it.
1366 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1367 if (!isa<SCEVZeroExtendExpr>(ZExt))
1370 // Next try a sext cast. If the cast is folded, use it.
1371 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1372 if (!isa<SCEVSignExtendExpr>(SExt))
1375 // Force the cast to be folded into the operands of an addrec.
1376 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1377 SmallVector<const SCEV *, 4> Ops;
1378 for (const SCEV *Op : AR->operands())
1379 Ops.push_back(getAnyExtendExpr(Op, Ty));
1380 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1383 // If the expression is obviously signed, use the sext cast value.
1384 if (isa<SCEVSMaxExpr>(Op))
1387 // Absent any other information, use the zext cast value.
1391 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1392 /// a list of operands to be added under the given scale, update the given
1393 /// map. This is a helper function for getAddRecExpr. As an example of
1394 /// what it does, given a sequence of operands that would form an add
1395 /// expression like this:
1397 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1399 /// where A and B are constants, update the map with these values:
1401 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1403 /// and add 13 + A*B*29 to AccumulatedConstant.
1404 /// This will allow getAddRecExpr to produce this:
1406 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1408 /// This form often exposes folding opportunities that are hidden in
1409 /// the original operand list.
1411 /// Return true iff it appears that any interesting folding opportunities
1412 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1413 /// the common case where no interesting opportunities are present, and
1414 /// is also used as a check to avoid infinite recursion.
1417 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1418 SmallVectorImpl<const SCEV *> &NewOps,
1419 APInt &AccumulatedConstant,
1420 const SCEV *const *Ops, size_t NumOperands,
1422 ScalarEvolution &SE) {
1423 bool Interesting = false;
1425 // Iterate over the add operands. They are sorted, with constants first.
1427 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1429 // Pull a buried constant out to the outside.
1430 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1432 AccumulatedConstant += Scale * C->getValue()->getValue();
1435 // Next comes everything else. We're especially interested in multiplies
1436 // here, but they're in the middle, so just visit the rest with one loop.
1437 for (; i != NumOperands; ++i) {
1438 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1439 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1441 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1442 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1443 // A multiplication of a constant with another add; recurse.
1444 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1446 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1447 Add->op_begin(), Add->getNumOperands(),
1450 // A multiplication of a constant with some other value. Update
1452 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1453 const SCEV *Key = SE.getMulExpr(MulOps);
1454 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1455 M.insert(std::make_pair(Key, NewScale));
1457 NewOps.push_back(Pair.first->first);
1459 Pair.first->second += NewScale;
1460 // The map already had an entry for this value, which may indicate
1461 // a folding opportunity.
1466 // An ordinary operand. Update the map.
1467 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1468 M.insert(std::make_pair(Ops[i], Scale));
1470 NewOps.push_back(Pair.first->first);
1472 Pair.first->second += Scale;
1473 // The map already had an entry for this value, which may indicate
1474 // a folding opportunity.
1484 struct APIntCompare {
1485 bool operator()(const APInt &LHS, const APInt &RHS) const {
1486 return LHS.ult(RHS);
1491 /// getAddExpr - Get a canonical add expression, or something simpler if
1493 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1494 SCEV::NoWrapFlags Flags) {
1495 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1496 "only nuw or nsw allowed");
1497 assert(!Ops.empty() && "Cannot get empty add!");
1498 if (Ops.size() == 1) return Ops[0];
1500 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1501 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1502 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1503 "SCEVAddExpr operand types don't match!");
1506 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1508 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1509 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1510 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1512 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1513 E = Ops.end(); I != E; ++I)
1514 if (!isKnownNonNegative(*I)) {
1518 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1521 // Sort by complexity, this groups all similar expression types together.
1522 GroupByComplexity(Ops, LI);
1524 // If there are any constants, fold them together.
1526 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1528 assert(Idx < Ops.size());
1529 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1530 // We found two constants, fold them together!
1531 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1532 RHSC->getValue()->getValue());
1533 if (Ops.size() == 2) return Ops[0];
1534 Ops.erase(Ops.begin()+1); // Erase the folded element
1535 LHSC = cast<SCEVConstant>(Ops[0]);
1538 // If we are left with a constant zero being added, strip it off.
1539 if (LHSC->getValue()->isZero()) {
1540 Ops.erase(Ops.begin());
1544 if (Ops.size() == 1) return Ops[0];
1547 // Okay, check to see if the same value occurs in the operand list more than
1548 // once. If so, merge them together into an multiply expression. Since we
1549 // sorted the list, these values are required to be adjacent.
1550 Type *Ty = Ops[0]->getType();
1551 bool FoundMatch = false;
1552 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1553 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1554 // Scan ahead to count how many equal operands there are.
1556 while (i+Count != e && Ops[i+Count] == Ops[i])
1558 // Merge the values into a multiply.
1559 const SCEV *Scale = getConstant(Ty, Count);
1560 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1561 if (Ops.size() == Count)
1564 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1565 --i; e -= Count - 1;
1569 return getAddExpr(Ops, Flags);
1571 // Check for truncates. If all the operands are truncated from the same
1572 // type, see if factoring out the truncate would permit the result to be
1573 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1574 // if the contents of the resulting outer trunc fold to something simple.
1575 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1576 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1577 Type *DstType = Trunc->getType();
1578 Type *SrcType = Trunc->getOperand()->getType();
1579 SmallVector<const SCEV *, 8> LargeOps;
1581 // Check all the operands to see if they can be represented in the
1582 // source type of the truncate.
1583 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1584 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1585 if (T->getOperand()->getType() != SrcType) {
1589 LargeOps.push_back(T->getOperand());
1590 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1591 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1592 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1593 SmallVector<const SCEV *, 8> LargeMulOps;
1594 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1595 if (const SCEVTruncateExpr *T =
1596 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1597 if (T->getOperand()->getType() != SrcType) {
1601 LargeMulOps.push_back(T->getOperand());
1602 } else if (const SCEVConstant *C =
1603 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1604 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1611 LargeOps.push_back(getMulExpr(LargeMulOps));
1618 // Evaluate the expression in the larger type.
1619 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1620 // If it folds to something simple, use it. Otherwise, don't.
1621 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1622 return getTruncateExpr(Fold, DstType);
1626 // Skip past any other cast SCEVs.
1627 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1630 // If there are add operands they would be next.
1631 if (Idx < Ops.size()) {
1632 bool DeletedAdd = false;
1633 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1634 // If we have an add, expand the add operands onto the end of the operands
1636 Ops.erase(Ops.begin()+Idx);
1637 Ops.append(Add->op_begin(), Add->op_end());
1641 // If we deleted at least one add, we added operands to the end of the list,
1642 // and they are not necessarily sorted. Recurse to resort and resimplify
1643 // any operands we just acquired.
1645 return getAddExpr(Ops);
1648 // Skip over the add expression until we get to a multiply.
1649 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1652 // Check to see if there are any folding opportunities present with
1653 // operands multiplied by constant values.
1654 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1655 uint64_t BitWidth = getTypeSizeInBits(Ty);
1656 DenseMap<const SCEV *, APInt> M;
1657 SmallVector<const SCEV *, 8> NewOps;
1658 APInt AccumulatedConstant(BitWidth, 0);
1659 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1660 Ops.data(), Ops.size(),
1661 APInt(BitWidth, 1), *this)) {
1662 // Some interesting folding opportunity is present, so its worthwhile to
1663 // re-generate the operands list. Group the operands by constant scale,
1664 // to avoid multiplying by the same constant scale multiple times.
1665 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1666 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
1667 E = NewOps.end(); I != E; ++I)
1668 MulOpLists[M.find(*I)->second].push_back(*I);
1669 // Re-generate the operands list.
1671 if (AccumulatedConstant != 0)
1672 Ops.push_back(getConstant(AccumulatedConstant));
1673 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1674 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1676 Ops.push_back(getMulExpr(getConstant(I->first),
1677 getAddExpr(I->second)));
1679 return getConstant(Ty, 0);
1680 if (Ops.size() == 1)
1682 return getAddExpr(Ops);
1686 // If we are adding something to a multiply expression, make sure the
1687 // something is not already an operand of the multiply. If so, merge it into
1689 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1690 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1691 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1692 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1693 if (isa<SCEVConstant>(MulOpSCEV))
1695 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1696 if (MulOpSCEV == Ops[AddOp]) {
1697 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1698 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1699 if (Mul->getNumOperands() != 2) {
1700 // If the multiply has more than two operands, we must get the
1702 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1703 Mul->op_begin()+MulOp);
1704 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1705 InnerMul = getMulExpr(MulOps);
1707 const SCEV *One = getConstant(Ty, 1);
1708 const SCEV *AddOne = getAddExpr(One, InnerMul);
1709 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1710 if (Ops.size() == 2) return OuterMul;
1712 Ops.erase(Ops.begin()+AddOp);
1713 Ops.erase(Ops.begin()+Idx-1);
1715 Ops.erase(Ops.begin()+Idx);
1716 Ops.erase(Ops.begin()+AddOp-1);
1718 Ops.push_back(OuterMul);
1719 return getAddExpr(Ops);
1722 // Check this multiply against other multiplies being added together.
1723 for (unsigned OtherMulIdx = Idx+1;
1724 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1726 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1727 // If MulOp occurs in OtherMul, we can fold the two multiplies
1729 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1730 OMulOp != e; ++OMulOp)
1731 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1732 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1733 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1734 if (Mul->getNumOperands() != 2) {
1735 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1736 Mul->op_begin()+MulOp);
1737 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1738 InnerMul1 = getMulExpr(MulOps);
1740 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1741 if (OtherMul->getNumOperands() != 2) {
1742 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1743 OtherMul->op_begin()+OMulOp);
1744 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1745 InnerMul2 = getMulExpr(MulOps);
1747 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1748 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1749 if (Ops.size() == 2) return OuterMul;
1750 Ops.erase(Ops.begin()+Idx);
1751 Ops.erase(Ops.begin()+OtherMulIdx-1);
1752 Ops.push_back(OuterMul);
1753 return getAddExpr(Ops);
1759 // If there are any add recurrences in the operands list, see if any other
1760 // added values are loop invariant. If so, we can fold them into the
1762 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1765 // Scan over all recurrences, trying to fold loop invariants into them.
1766 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1767 // Scan all of the other operands to this add and add them to the vector if
1768 // they are loop invariant w.r.t. the recurrence.
1769 SmallVector<const SCEV *, 8> LIOps;
1770 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1771 const Loop *AddRecLoop = AddRec->getLoop();
1772 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1773 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1774 LIOps.push_back(Ops[i]);
1775 Ops.erase(Ops.begin()+i);
1779 // If we found some loop invariants, fold them into the recurrence.
1780 if (!LIOps.empty()) {
1781 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1782 LIOps.push_back(AddRec->getStart());
1784 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1786 AddRecOps[0] = getAddExpr(LIOps);
1788 // Build the new addrec. Propagate the NUW and NSW flags if both the
1789 // outer add and the inner addrec are guaranteed to have no overflow.
1790 // Always propagate NW.
1791 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
1792 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
1794 // If all of the other operands were loop invariant, we are done.
1795 if (Ops.size() == 1) return NewRec;
1797 // Otherwise, add the folded AddRec by the non-invariant parts.
1798 for (unsigned i = 0;; ++i)
1799 if (Ops[i] == AddRec) {
1803 return getAddExpr(Ops);
1806 // Okay, if there weren't any loop invariants to be folded, check to see if
1807 // there are multiple AddRec's with the same loop induction variable being
1808 // added together. If so, we can fold them.
1809 for (unsigned OtherIdx = Idx+1;
1810 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1812 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1813 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1814 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1816 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1818 if (const SCEVAddRecExpr *OtherAddRec =
1819 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1820 if (OtherAddRec->getLoop() == AddRecLoop) {
1821 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1823 if (i >= AddRecOps.size()) {
1824 AddRecOps.append(OtherAddRec->op_begin()+i,
1825 OtherAddRec->op_end());
1828 AddRecOps[i] = getAddExpr(AddRecOps[i],
1829 OtherAddRec->getOperand(i));
1831 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1833 // Step size has changed, so we cannot guarantee no self-wraparound.
1834 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
1835 return getAddExpr(Ops);
1838 // Otherwise couldn't fold anything into this recurrence. Move onto the
1842 // Okay, it looks like we really DO need an add expr. Check to see if we
1843 // already have one, otherwise create a new one.
1844 FoldingSetNodeID ID;
1845 ID.AddInteger(scAddExpr);
1846 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1847 ID.AddPointer(Ops[i]);
1850 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1852 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1853 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1854 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1856 UniqueSCEVs.InsertNode(S, IP);
1858 S->setNoWrapFlags(Flags);
1862 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
1864 if (j > 1 && k / j != i) Overflow = true;
1868 /// Compute the result of "n choose k", the binomial coefficient. If an
1869 /// intermediate computation overflows, Overflow will be set and the return will
1870 /// be garbage. Overflow is not cleared on absence of overflow.
1871 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
1872 // We use the multiplicative formula:
1873 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
1874 // At each iteration, we take the n-th term of the numeral and divide by the
1875 // (k-n)th term of the denominator. This division will always produce an
1876 // integral result, and helps reduce the chance of overflow in the
1877 // intermediate computations. However, we can still overflow even when the
1878 // final result would fit.
1880 if (n == 0 || n == k) return 1;
1881 if (k > n) return 0;
1887 for (uint64_t i = 1; i <= k; ++i) {
1888 r = umul_ov(r, n-(i-1), Overflow);
1894 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1896 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1897 SCEV::NoWrapFlags Flags) {
1898 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1899 "only nuw or nsw allowed");
1900 assert(!Ops.empty() && "Cannot get empty mul!");
1901 if (Ops.size() == 1) return Ops[0];
1903 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1904 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1905 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1906 "SCEVMulExpr operand types don't match!");
1909 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1911 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1912 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1913 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1915 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1916 E = Ops.end(); I != E; ++I)
1917 if (!isKnownNonNegative(*I)) {
1921 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1924 // Sort by complexity, this groups all similar expression types together.
1925 GroupByComplexity(Ops, LI);
1927 // If there are any constants, fold them together.
1929 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1931 // C1*(C2+V) -> C1*C2 + C1*V
1932 if (Ops.size() == 2)
1933 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1934 if (Add->getNumOperands() == 2 &&
1935 isa<SCEVConstant>(Add->getOperand(0)))
1936 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1937 getMulExpr(LHSC, Add->getOperand(1)));
1940 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1941 // We found two constants, fold them together!
1942 ConstantInt *Fold = ConstantInt::get(getContext(),
1943 LHSC->getValue()->getValue() *
1944 RHSC->getValue()->getValue());
1945 Ops[0] = getConstant(Fold);
1946 Ops.erase(Ops.begin()+1); // Erase the folded element
1947 if (Ops.size() == 1) return Ops[0];
1948 LHSC = cast<SCEVConstant>(Ops[0]);
1951 // If we are left with a constant one being multiplied, strip it off.
1952 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1953 Ops.erase(Ops.begin());
1955 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1956 // If we have a multiply of zero, it will always be zero.
1958 } else if (Ops[0]->isAllOnesValue()) {
1959 // If we have a mul by -1 of an add, try distributing the -1 among the
1961 if (Ops.size() == 2) {
1962 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1963 SmallVector<const SCEV *, 4> NewOps;
1964 bool AnyFolded = false;
1965 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1966 E = Add->op_end(); I != E; ++I) {
1967 const SCEV *Mul = getMulExpr(Ops[0], *I);
1968 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1969 NewOps.push_back(Mul);
1972 return getAddExpr(NewOps);
1974 else if (const SCEVAddRecExpr *
1975 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1976 // Negation preserves a recurrence's no self-wrap property.
1977 SmallVector<const SCEV *, 4> Operands;
1978 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1979 E = AddRec->op_end(); I != E; ++I) {
1980 Operands.push_back(getMulExpr(Ops[0], *I));
1982 return getAddRecExpr(Operands, AddRec->getLoop(),
1983 AddRec->getNoWrapFlags(SCEV::FlagNW));
1988 if (Ops.size() == 1)
1992 // Skip over the add expression until we get to a multiply.
1993 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1996 // If there are mul operands inline them all into this expression.
1997 if (Idx < Ops.size()) {
1998 bool DeletedMul = false;
1999 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2000 // If we have an mul, expand the mul operands onto the end of the operands
2002 Ops.erase(Ops.begin()+Idx);
2003 Ops.append(Mul->op_begin(), Mul->op_end());
2007 // If we deleted at least one mul, we added operands to the end of the list,
2008 // and they are not necessarily sorted. Recurse to resort and resimplify
2009 // any operands we just acquired.
2011 return getMulExpr(Ops);
2014 // If there are any add recurrences in the operands list, see if any other
2015 // added values are loop invariant. If so, we can fold them into the
2017 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2020 // Scan over all recurrences, trying to fold loop invariants into them.
2021 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2022 // Scan all of the other operands to this mul and add them to the vector if
2023 // they are loop invariant w.r.t. the recurrence.
2024 SmallVector<const SCEV *, 8> LIOps;
2025 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2026 const Loop *AddRecLoop = AddRec->getLoop();
2027 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2028 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2029 LIOps.push_back(Ops[i]);
2030 Ops.erase(Ops.begin()+i);
2034 // If we found some loop invariants, fold them into the recurrence.
2035 if (!LIOps.empty()) {
2036 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2037 SmallVector<const SCEV *, 4> NewOps;
2038 NewOps.reserve(AddRec->getNumOperands());
2039 const SCEV *Scale = getMulExpr(LIOps);
2040 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2041 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2043 // Build the new addrec. Propagate the NUW and NSW flags if both the
2044 // outer mul and the inner addrec are guaranteed to have no overflow.
2046 // No self-wrap cannot be guaranteed after changing the step size, but
2047 // will be inferred if either NUW or NSW is true.
2048 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2049 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2051 // If all of the other operands were loop invariant, we are done.
2052 if (Ops.size() == 1) return NewRec;
2054 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2055 for (unsigned i = 0;; ++i)
2056 if (Ops[i] == AddRec) {
2060 return getMulExpr(Ops);
2063 // Okay, if there weren't any loop invariants to be folded, check to see if
2064 // there are multiple AddRec's with the same loop induction variable being
2065 // multiplied together. If so, we can fold them.
2067 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2068 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2069 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2070 // ]]],+,...up to x=2n}.
2071 // Note that the arguments to choose() are always integers with values
2072 // known at compile time, never SCEV objects.
2074 // The implementation avoids pointless extra computations when the two
2075 // addrec's are of different length (mathematically, it's equivalent to
2076 // an infinite stream of zeros on the right).
2077 bool OpsModified = false;
2078 for (unsigned OtherIdx = Idx+1;
2079 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2081 const SCEVAddRecExpr *OtherAddRec =
2082 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2083 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2086 bool Overflow = false;
2087 Type *Ty = AddRec->getType();
2088 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2089 SmallVector<const SCEV*, 7> AddRecOps;
2090 for (int x = 0, xe = AddRec->getNumOperands() +
2091 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2092 const SCEV *Term = getConstant(Ty, 0);
2093 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2094 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2095 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2096 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2097 z < ze && !Overflow; ++z) {
2098 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2100 if (LargerThan64Bits)
2101 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2103 Coeff = Coeff1*Coeff2;
2104 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2105 const SCEV *Term1 = AddRec->getOperand(y-z);
2106 const SCEV *Term2 = OtherAddRec->getOperand(z);
2107 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2110 AddRecOps.push_back(Term);
2113 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2115 if (Ops.size() == 2) return NewAddRec;
2116 Ops[Idx] = NewAddRec;
2117 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2119 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2125 return getMulExpr(Ops);
2127 // Otherwise couldn't fold anything into this recurrence. Move onto the
2131 // Okay, it looks like we really DO need an mul expr. Check to see if we
2132 // already have one, otherwise create a new one.
2133 FoldingSetNodeID ID;
2134 ID.AddInteger(scMulExpr);
2135 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2136 ID.AddPointer(Ops[i]);
2139 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2141 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2142 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2143 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2145 UniqueSCEVs.InsertNode(S, IP);
2147 S->setNoWrapFlags(Flags);
2151 /// getUDivExpr - Get a canonical unsigned division expression, or something
2152 /// simpler if possible.
2153 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2155 assert(getEffectiveSCEVType(LHS->getType()) ==
2156 getEffectiveSCEVType(RHS->getType()) &&
2157 "SCEVUDivExpr operand types don't match!");
2159 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2160 if (RHSC->getValue()->equalsInt(1))
2161 return LHS; // X udiv 1 --> x
2162 // If the denominator is zero, the result of the udiv is undefined. Don't
2163 // try to analyze it, because the resolution chosen here may differ from
2164 // the resolution chosen in other parts of the compiler.
2165 if (!RHSC->getValue()->isZero()) {
2166 // Determine if the division can be folded into the operands of
2168 // TODO: Generalize this to non-constants by using known-bits information.
2169 Type *Ty = LHS->getType();
2170 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2171 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2172 // For non-power-of-two values, effectively round the value up to the
2173 // nearest power of two.
2174 if (!RHSC->getValue()->getValue().isPowerOf2())
2176 IntegerType *ExtTy =
2177 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2178 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2179 if (const SCEVConstant *Step =
2180 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2181 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2182 const APInt &StepInt = Step->getValue()->getValue();
2183 const APInt &DivInt = RHSC->getValue()->getValue();
2184 if (!StepInt.urem(DivInt) &&
2185 getZeroExtendExpr(AR, ExtTy) ==
2186 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2187 getZeroExtendExpr(Step, ExtTy),
2188 AR->getLoop(), SCEV::FlagAnyWrap)) {
2189 SmallVector<const SCEV *, 4> Operands;
2190 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2191 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2192 return getAddRecExpr(Operands, AR->getLoop(),
2195 /// Get a canonical UDivExpr for a recurrence.
2196 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2197 // We can currently only fold X%N if X is constant.
2198 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2199 if (StartC && !DivInt.urem(StepInt) &&
2200 getZeroExtendExpr(AR, ExtTy) ==
2201 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2202 getZeroExtendExpr(Step, ExtTy),
2203 AR->getLoop(), SCEV::FlagAnyWrap)) {
2204 const APInt &StartInt = StartC->getValue()->getValue();
2205 const APInt &StartRem = StartInt.urem(StepInt);
2207 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2208 AR->getLoop(), SCEV::FlagNW);
2211 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2212 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2213 SmallVector<const SCEV *, 4> Operands;
2214 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2215 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2216 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2217 // Find an operand that's safely divisible.
2218 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2219 const SCEV *Op = M->getOperand(i);
2220 const SCEV *Div = getUDivExpr(Op, RHSC);
2221 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2222 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2225 return getMulExpr(Operands);
2229 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2230 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2231 SmallVector<const SCEV *, 4> Operands;
2232 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2233 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2234 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2236 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2237 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2238 if (isa<SCEVUDivExpr>(Op) ||
2239 getMulExpr(Op, RHS) != A->getOperand(i))
2241 Operands.push_back(Op);
2243 if (Operands.size() == A->getNumOperands())
2244 return getAddExpr(Operands);
2248 // Fold if both operands are constant.
2249 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2250 Constant *LHSCV = LHSC->getValue();
2251 Constant *RHSCV = RHSC->getValue();
2252 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2258 FoldingSetNodeID ID;
2259 ID.AddInteger(scUDivExpr);
2263 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2264 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2266 UniqueSCEVs.InsertNode(S, IP);
2270 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2271 APInt A = C1->getValue()->getValue().abs();
2272 APInt B = C2->getValue()->getValue().abs();
2273 uint32_t ABW = A.getBitWidth();
2274 uint32_t BBW = B.getBitWidth();
2281 return APIntOps::GreatestCommonDivisor(A, B);
2284 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2285 /// something simpler if possible. There is no representation for an exact udiv
2286 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2287 /// We can't do this when it's not exact because the udiv may be clearing bits.
2288 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2290 // TODO: we could try to find factors in all sorts of things, but for now we
2291 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2292 // end of this file for inspiration.
2294 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2296 return getUDivExpr(LHS, RHS);
2298 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2299 // If the mulexpr multiplies by a constant, then that constant must be the
2300 // first element of the mulexpr.
2301 if (const SCEVConstant *LHSCst =
2302 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2303 if (LHSCst == RHSCst) {
2304 SmallVector<const SCEV *, 2> Operands;
2305 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2306 return getMulExpr(Operands);
2309 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2310 // that there's a factor provided by one of the other terms. We need to
2312 APInt Factor = gcd(LHSCst, RHSCst);
2313 if (!Factor.isIntN(1)) {
2314 LHSCst = cast<SCEVConstant>(
2315 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2316 RHSCst = cast<SCEVConstant>(
2317 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2318 SmallVector<const SCEV *, 2> Operands;
2319 Operands.push_back(LHSCst);
2320 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2321 LHS = getMulExpr(Operands);
2323 Mul = dyn_cast<SCEVMulExpr>(LHS);
2325 return getUDivExactExpr(LHS, RHS);
2330 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2331 if (Mul->getOperand(i) == RHS) {
2332 SmallVector<const SCEV *, 2> Operands;
2333 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2334 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2335 return getMulExpr(Operands);
2339 return getUDivExpr(LHS, RHS);
2342 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2343 /// Simplify the expression as much as possible.
2344 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2346 SCEV::NoWrapFlags Flags) {
2347 SmallVector<const SCEV *, 4> Operands;
2348 Operands.push_back(Start);
2349 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2350 if (StepChrec->getLoop() == L) {
2351 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2352 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2355 Operands.push_back(Step);
2356 return getAddRecExpr(Operands, L, Flags);
2359 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2360 /// Simplify the expression as much as possible.
2362 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2363 const Loop *L, SCEV::NoWrapFlags Flags) {
2364 if (Operands.size() == 1) return Operands[0];
2366 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2367 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2368 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2369 "SCEVAddRecExpr operand types don't match!");
2370 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2371 assert(isLoopInvariant(Operands[i], L) &&
2372 "SCEVAddRecExpr operand is not loop-invariant!");
2375 if (Operands.back()->isZero()) {
2376 Operands.pop_back();
2377 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2380 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2381 // use that information to infer NUW and NSW flags. However, computing a
2382 // BE count requires calling getAddRecExpr, so we may not yet have a
2383 // meaningful BE count at this point (and if we don't, we'd be stuck
2384 // with a SCEVCouldNotCompute as the cached BE count).
2386 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2388 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2389 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2390 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2392 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2393 E = Operands.end(); I != E; ++I)
2394 if (!isKnownNonNegative(*I)) {
2398 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2401 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2402 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2403 const Loop *NestedLoop = NestedAR->getLoop();
2404 if (L->contains(NestedLoop) ?
2405 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2406 (!NestedLoop->contains(L) &&
2407 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2408 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2409 NestedAR->op_end());
2410 Operands[0] = NestedAR->getStart();
2411 // AddRecs require their operands be loop-invariant with respect to their
2412 // loops. Don't perform this transformation if it would break this
2414 bool AllInvariant = true;
2415 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2416 if (!isLoopInvariant(Operands[i], L)) {
2417 AllInvariant = false;
2421 // Create a recurrence for the outer loop with the same step size.
2423 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2424 // inner recurrence has the same property.
2425 SCEV::NoWrapFlags OuterFlags =
2426 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2428 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2429 AllInvariant = true;
2430 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2431 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2432 AllInvariant = false;
2436 // Ok, both add recurrences are valid after the transformation.
2438 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2439 // the outer recurrence has the same property.
2440 SCEV::NoWrapFlags InnerFlags =
2441 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2442 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2445 // Reset Operands to its original state.
2446 Operands[0] = NestedAR;
2450 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2451 // already have one, otherwise create a new one.
2452 FoldingSetNodeID ID;
2453 ID.AddInteger(scAddRecExpr);
2454 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2455 ID.AddPointer(Operands[i]);
2459 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2461 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2462 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2463 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2464 O, Operands.size(), L);
2465 UniqueSCEVs.InsertNode(S, IP);
2467 S->setNoWrapFlags(Flags);
2471 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2473 SmallVector<const SCEV *, 2> Ops;
2476 return getSMaxExpr(Ops);
2480 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2481 assert(!Ops.empty() && "Cannot get empty smax!");
2482 if (Ops.size() == 1) return Ops[0];
2484 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2485 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2486 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2487 "SCEVSMaxExpr operand types don't match!");
2490 // Sort by complexity, this groups all similar expression types together.
2491 GroupByComplexity(Ops, LI);
2493 // If there are any constants, fold them together.
2495 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2497 assert(Idx < Ops.size());
2498 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2499 // We found two constants, fold them together!
2500 ConstantInt *Fold = ConstantInt::get(getContext(),
2501 APIntOps::smax(LHSC->getValue()->getValue(),
2502 RHSC->getValue()->getValue()));
2503 Ops[0] = getConstant(Fold);
2504 Ops.erase(Ops.begin()+1); // Erase the folded element
2505 if (Ops.size() == 1) return Ops[0];
2506 LHSC = cast<SCEVConstant>(Ops[0]);
2509 // If we are left with a constant minimum-int, strip it off.
2510 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2511 Ops.erase(Ops.begin());
2513 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2514 // If we have an smax with a constant maximum-int, it will always be
2519 if (Ops.size() == 1) return Ops[0];
2522 // Find the first SMax
2523 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2526 // Check to see if one of the operands is an SMax. If so, expand its operands
2527 // onto our operand list, and recurse to simplify.
2528 if (Idx < Ops.size()) {
2529 bool DeletedSMax = false;
2530 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2531 Ops.erase(Ops.begin()+Idx);
2532 Ops.append(SMax->op_begin(), SMax->op_end());
2537 return getSMaxExpr(Ops);
2540 // Okay, check to see if the same value occurs in the operand list twice. If
2541 // so, delete one. Since we sorted the list, these values are required to
2543 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2544 // X smax Y smax Y --> X smax Y
2545 // X smax Y --> X, if X is always greater than Y
2546 if (Ops[i] == Ops[i+1] ||
2547 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2548 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2550 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2551 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2555 if (Ops.size() == 1) return Ops[0];
2557 assert(!Ops.empty() && "Reduced smax down to nothing!");
2559 // Okay, it looks like we really DO need an smax expr. Check to see if we
2560 // already have one, otherwise create a new one.
2561 FoldingSetNodeID ID;
2562 ID.AddInteger(scSMaxExpr);
2563 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2564 ID.AddPointer(Ops[i]);
2566 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2567 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2568 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2569 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2571 UniqueSCEVs.InsertNode(S, IP);
2575 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2577 SmallVector<const SCEV *, 2> Ops;
2580 return getUMaxExpr(Ops);
2584 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2585 assert(!Ops.empty() && "Cannot get empty umax!");
2586 if (Ops.size() == 1) return Ops[0];
2588 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2589 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2590 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2591 "SCEVUMaxExpr operand types don't match!");
2594 // Sort by complexity, this groups all similar expression types together.
2595 GroupByComplexity(Ops, LI);
2597 // If there are any constants, fold them together.
2599 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2601 assert(Idx < Ops.size());
2602 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2603 // We found two constants, fold them together!
2604 ConstantInt *Fold = ConstantInt::get(getContext(),
2605 APIntOps::umax(LHSC->getValue()->getValue(),
2606 RHSC->getValue()->getValue()));
2607 Ops[0] = getConstant(Fold);
2608 Ops.erase(Ops.begin()+1); // Erase the folded element
2609 if (Ops.size() == 1) return Ops[0];
2610 LHSC = cast<SCEVConstant>(Ops[0]);
2613 // If we are left with a constant minimum-int, strip it off.
2614 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2615 Ops.erase(Ops.begin());
2617 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2618 // If we have an umax with a constant maximum-int, it will always be
2623 if (Ops.size() == 1) return Ops[0];
2626 // Find the first UMax
2627 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2630 // Check to see if one of the operands is a UMax. If so, expand its operands
2631 // onto our operand list, and recurse to simplify.
2632 if (Idx < Ops.size()) {
2633 bool DeletedUMax = false;
2634 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2635 Ops.erase(Ops.begin()+Idx);
2636 Ops.append(UMax->op_begin(), UMax->op_end());
2641 return getUMaxExpr(Ops);
2644 // Okay, check to see if the same value occurs in the operand list twice. If
2645 // so, delete one. Since we sorted the list, these values are required to
2647 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2648 // X umax Y umax Y --> X umax Y
2649 // X umax Y --> X, if X is always greater than Y
2650 if (Ops[i] == Ops[i+1] ||
2651 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2652 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2654 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2655 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2659 if (Ops.size() == 1) return Ops[0];
2661 assert(!Ops.empty() && "Reduced umax down to nothing!");
2663 // Okay, it looks like we really DO need a umax expr. Check to see if we
2664 // already have one, otherwise create a new one.
2665 FoldingSetNodeID ID;
2666 ID.AddInteger(scUMaxExpr);
2667 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2668 ID.AddPointer(Ops[i]);
2670 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2671 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2672 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2673 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2675 UniqueSCEVs.InsertNode(S, IP);
2679 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2681 // ~smax(~x, ~y) == smin(x, y).
2682 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2685 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2687 // ~umax(~x, ~y) == umin(x, y)
2688 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2691 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
2692 // If we have DataLayout, we can bypass creating a target-independent
2693 // constant expression and then folding it back into a ConstantInt.
2694 // This is just a compile-time optimization.
2696 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
2698 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2699 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2700 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
2702 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2703 assert(Ty == IntTy && "Effective SCEV type doesn't match");
2704 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2707 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
2710 // If we have DataLayout, we can bypass creating a target-independent
2711 // constant expression and then folding it back into a ConstantInt.
2712 // This is just a compile-time optimization.
2714 return getConstant(IntTy,
2715 DL->getStructLayout(STy)->getElementOffset(FieldNo));
2718 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2719 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2720 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
2723 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2724 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2727 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2728 // Don't attempt to do anything other than create a SCEVUnknown object
2729 // here. createSCEV only calls getUnknown after checking for all other
2730 // interesting possibilities, and any other code that calls getUnknown
2731 // is doing so in order to hide a value from SCEV canonicalization.
2733 FoldingSetNodeID ID;
2734 ID.AddInteger(scUnknown);
2737 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2738 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2739 "Stale SCEVUnknown in uniquing map!");
2742 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2744 FirstUnknown = cast<SCEVUnknown>(S);
2745 UniqueSCEVs.InsertNode(S, IP);
2749 //===----------------------------------------------------------------------===//
2750 // Basic SCEV Analysis and PHI Idiom Recognition Code
2753 /// isSCEVable - Test if values of the given type are analyzable within
2754 /// the SCEV framework. This primarily includes integer types, and it
2755 /// can optionally include pointer types if the ScalarEvolution class
2756 /// has access to target-specific information.
2757 bool ScalarEvolution::isSCEVable(Type *Ty) const {
2758 // Integers and pointers are always SCEVable.
2759 return Ty->isIntegerTy() || Ty->isPointerTy();
2762 /// getTypeSizeInBits - Return the size in bits of the specified type,
2763 /// for which isSCEVable must return true.
2764 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
2765 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2767 // If we have a DataLayout, use it!
2769 return DL->getTypeSizeInBits(Ty);
2771 // Integer types have fixed sizes.
2772 if (Ty->isIntegerTy())
2773 return Ty->getPrimitiveSizeInBits();
2775 // The only other support type is pointer. Without DataLayout, conservatively
2776 // assume pointers are 64-bit.
2777 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2781 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2782 /// the given type and which represents how SCEV will treat the given
2783 /// type, for which isSCEVable must return true. For pointer types,
2784 /// this is the pointer-sized integer type.
2785 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
2786 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2788 if (Ty->isIntegerTy()) {
2792 // The only other support type is pointer.
2793 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2796 return DL->getIntPtrType(Ty);
2798 // Without DataLayout, conservatively assume pointers are 64-bit.
2799 return Type::getInt64Ty(getContext());
2802 const SCEV *ScalarEvolution::getCouldNotCompute() {
2803 return &CouldNotCompute;
2807 // Helper class working with SCEVTraversal to figure out if a SCEV contains
2808 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
2809 // is set iff if find such SCEVUnknown.
2811 struct FindInvalidSCEVUnknown {
2813 FindInvalidSCEVUnknown() { FindOne = false; }
2814 bool follow(const SCEV *S) {
2815 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2819 if (!cast<SCEVUnknown>(S)->getValue())
2826 bool isDone() const { return FindOne; }
2830 bool ScalarEvolution::checkValidity(const SCEV *S) const {
2831 FindInvalidSCEVUnknown F;
2832 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
2838 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2839 /// expression and create a new one.
2840 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2841 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2843 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
2844 if (I != ValueExprMap.end()) {
2845 const SCEV *S = I->second;
2846 if (checkValidity(S))
2849 ValueExprMap.erase(I);
2851 const SCEV *S = createSCEV(V);
2853 // The process of creating a SCEV for V may have caused other SCEVs
2854 // to have been created, so it's necessary to insert the new entry
2855 // from scratch, rather than trying to remember the insert position
2857 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2861 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2863 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2864 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2866 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2868 Type *Ty = V->getType();
2869 Ty = getEffectiveSCEVType(Ty);
2870 return getMulExpr(V,
2871 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2874 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2875 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2876 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2878 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2880 Type *Ty = V->getType();
2881 Ty = getEffectiveSCEVType(Ty);
2882 const SCEV *AllOnes =
2883 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2884 return getMinusSCEV(AllOnes, V);
2887 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2888 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
2889 SCEV::NoWrapFlags Flags) {
2890 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
2892 // Fast path: X - X --> 0.
2894 return getConstant(LHS->getType(), 0);
2897 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
2900 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2901 /// input value to the specified type. If the type must be extended, it is zero
2904 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
2905 Type *SrcTy = V->getType();
2906 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2907 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2908 "Cannot truncate or zero extend with non-integer arguments!");
2909 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2910 return V; // No conversion
2911 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2912 return getTruncateExpr(V, Ty);
2913 return getZeroExtendExpr(V, Ty);
2916 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2917 /// input value to the specified type. If the type must be extended, it is sign
2920 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2922 Type *SrcTy = V->getType();
2923 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2924 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2925 "Cannot truncate or zero extend with non-integer arguments!");
2926 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2927 return V; // No conversion
2928 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2929 return getTruncateExpr(V, Ty);
2930 return getSignExtendExpr(V, Ty);
2933 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2934 /// input value to the specified type. If the type must be extended, it is zero
2935 /// extended. The conversion must not be narrowing.
2937 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
2938 Type *SrcTy = V->getType();
2939 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2940 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2941 "Cannot noop or zero extend with non-integer arguments!");
2942 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2943 "getNoopOrZeroExtend cannot truncate!");
2944 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2945 return V; // No conversion
2946 return getZeroExtendExpr(V, Ty);
2949 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2950 /// input value to the specified type. If the type must be extended, it is sign
2951 /// extended. The conversion must not be narrowing.
2953 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
2954 Type *SrcTy = V->getType();
2955 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2956 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2957 "Cannot noop or sign extend with non-integer arguments!");
2958 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2959 "getNoopOrSignExtend cannot truncate!");
2960 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2961 return V; // No conversion
2962 return getSignExtendExpr(V, Ty);
2965 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2966 /// the input value to the specified type. If the type must be extended,
2967 /// it is extended with unspecified bits. The conversion must not be
2970 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
2971 Type *SrcTy = V->getType();
2972 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2973 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2974 "Cannot noop or any extend with non-integer arguments!");
2975 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2976 "getNoopOrAnyExtend cannot truncate!");
2977 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2978 return V; // No conversion
2979 return getAnyExtendExpr(V, Ty);
2982 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2983 /// input value to the specified type. The conversion must not be widening.
2985 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
2986 Type *SrcTy = V->getType();
2987 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2988 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2989 "Cannot truncate or noop with non-integer arguments!");
2990 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2991 "getTruncateOrNoop cannot extend!");
2992 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2993 return V; // No conversion
2994 return getTruncateExpr(V, Ty);
2997 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2998 /// the types using zero-extension, and then perform a umax operation
3000 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3002 const SCEV *PromotedLHS = LHS;
3003 const SCEV *PromotedRHS = RHS;
3005 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3006 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3008 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3010 return getUMaxExpr(PromotedLHS, PromotedRHS);
3013 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3014 /// the types using zero-extension, and then perform a umin operation
3016 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3018 const SCEV *PromotedLHS = LHS;
3019 const SCEV *PromotedRHS = RHS;
3021 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3022 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3024 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3026 return getUMinExpr(PromotedLHS, PromotedRHS);
3029 /// getPointerBase - Transitively follow the chain of pointer-type operands
3030 /// until reaching a SCEV that does not have a single pointer operand. This
3031 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3032 /// but corner cases do exist.
3033 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3034 // A pointer operand may evaluate to a nonpointer expression, such as null.
3035 if (!V->getType()->isPointerTy())
3038 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3039 return getPointerBase(Cast->getOperand());
3041 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3042 const SCEV *PtrOp = nullptr;
3043 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3045 if ((*I)->getType()->isPointerTy()) {
3046 // Cannot find the base of an expression with multiple pointer operands.
3054 return getPointerBase(PtrOp);
3059 /// PushDefUseChildren - Push users of the given Instruction
3060 /// onto the given Worklist.
3062 PushDefUseChildren(Instruction *I,
3063 SmallVectorImpl<Instruction *> &Worklist) {
3064 // Push the def-use children onto the Worklist stack.
3065 for (User *U : I->users())
3066 Worklist.push_back(cast<Instruction>(U));
3069 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3070 /// instructions that depend on the given instruction and removes them from
3071 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3074 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3075 SmallVector<Instruction *, 16> Worklist;
3076 PushDefUseChildren(PN, Worklist);
3078 SmallPtrSet<Instruction *, 8> Visited;
3080 while (!Worklist.empty()) {
3081 Instruction *I = Worklist.pop_back_val();
3082 if (!Visited.insert(I)) continue;
3084 ValueExprMapType::iterator It =
3085 ValueExprMap.find_as(static_cast<Value *>(I));
3086 if (It != ValueExprMap.end()) {
3087 const SCEV *Old = It->second;
3089 // Short-circuit the def-use traversal if the symbolic name
3090 // ceases to appear in expressions.
3091 if (Old != SymName && !hasOperand(Old, SymName))
3094 // SCEVUnknown for a PHI either means that it has an unrecognized
3095 // structure, it's a PHI that's in the progress of being computed
3096 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3097 // additional loop trip count information isn't going to change anything.
3098 // In the second case, createNodeForPHI will perform the necessary
3099 // updates on its own when it gets to that point. In the third, we do
3100 // want to forget the SCEVUnknown.
3101 if (!isa<PHINode>(I) ||
3102 !isa<SCEVUnknown>(Old) ||
3103 (I != PN && Old == SymName)) {
3104 forgetMemoizedResults(Old);
3105 ValueExprMap.erase(It);
3109 PushDefUseChildren(I, Worklist);
3113 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3114 /// a loop header, making it a potential recurrence, or it doesn't.
3116 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3117 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3118 if (L->getHeader() == PN->getParent()) {
3119 // The loop may have multiple entrances or multiple exits; we can analyze
3120 // this phi as an addrec if it has a unique entry value and a unique
3122 Value *BEValueV = nullptr, *StartValueV = nullptr;
3123 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3124 Value *V = PN->getIncomingValue(i);
3125 if (L->contains(PN->getIncomingBlock(i))) {
3128 } else if (BEValueV != V) {
3132 } else if (!StartValueV) {
3134 } else if (StartValueV != V) {
3135 StartValueV = nullptr;
3139 if (BEValueV && StartValueV) {
3140 // While we are analyzing this PHI node, handle its value symbolically.
3141 const SCEV *SymbolicName = getUnknown(PN);
3142 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3143 "PHI node already processed?");
3144 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3146 // Using this symbolic name for the PHI, analyze the value coming around
3148 const SCEV *BEValue = getSCEV(BEValueV);
3150 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3151 // has a special value for the first iteration of the loop.
3153 // If the value coming around the backedge is an add with the symbolic
3154 // value we just inserted, then we found a simple induction variable!
3155 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3156 // If there is a single occurrence of the symbolic value, replace it
3157 // with a recurrence.
3158 unsigned FoundIndex = Add->getNumOperands();
3159 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3160 if (Add->getOperand(i) == SymbolicName)
3161 if (FoundIndex == e) {
3166 if (FoundIndex != Add->getNumOperands()) {
3167 // Create an add with everything but the specified operand.
3168 SmallVector<const SCEV *, 8> Ops;
3169 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3170 if (i != FoundIndex)
3171 Ops.push_back(Add->getOperand(i));
3172 const SCEV *Accum = getAddExpr(Ops);
3174 // This is not a valid addrec if the step amount is varying each
3175 // loop iteration, but is not itself an addrec in this loop.
3176 if (isLoopInvariant(Accum, L) ||
3177 (isa<SCEVAddRecExpr>(Accum) &&
3178 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3179 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3181 // If the increment doesn't overflow, then neither the addrec nor
3182 // the post-increment will overflow.
3183 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3184 if (OBO->hasNoUnsignedWrap())
3185 Flags = setFlags(Flags, SCEV::FlagNUW);
3186 if (OBO->hasNoSignedWrap())
3187 Flags = setFlags(Flags, SCEV::FlagNSW);
3188 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3189 // If the increment is an inbounds GEP, then we know the address
3190 // space cannot be wrapped around. We cannot make any guarantee
3191 // about signed or unsigned overflow because pointers are
3192 // unsigned but we may have a negative index from the base
3193 // pointer. We can guarantee that no unsigned wrap occurs if the
3194 // indices form a positive value.
3195 if (GEP->isInBounds()) {
3196 Flags = setFlags(Flags, SCEV::FlagNW);
3198 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3199 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3200 Flags = setFlags(Flags, SCEV::FlagNUW);
3202 } else if (const SubOperator *OBO =
3203 dyn_cast<SubOperator>(BEValueV)) {
3204 if (OBO->hasNoUnsignedWrap())
3205 Flags = setFlags(Flags, SCEV::FlagNUW);
3206 if (OBO->hasNoSignedWrap())
3207 Flags = setFlags(Flags, SCEV::FlagNSW);
3210 const SCEV *StartVal = getSCEV(StartValueV);
3211 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3213 // Since the no-wrap flags are on the increment, they apply to the
3214 // post-incremented value as well.
3215 if (isLoopInvariant(Accum, L))
3216 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
3219 // Okay, for the entire analysis of this edge we assumed the PHI
3220 // to be symbolic. We now need to go back and purge all of the
3221 // entries for the scalars that use the symbolic expression.
3222 ForgetSymbolicName(PN, SymbolicName);
3223 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3227 } else if (const SCEVAddRecExpr *AddRec =
3228 dyn_cast<SCEVAddRecExpr>(BEValue)) {
3229 // Otherwise, this could be a loop like this:
3230 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3231 // In this case, j = {1,+,1} and BEValue is j.
3232 // Because the other in-value of i (0) fits the evolution of BEValue
3233 // i really is an addrec evolution.
3234 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3235 const SCEV *StartVal = getSCEV(StartValueV);
3237 // If StartVal = j.start - j.stride, we can use StartVal as the
3238 // initial step of the addrec evolution.
3239 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3240 AddRec->getOperand(1))) {
3241 // FIXME: For constant StartVal, we should be able to infer
3243 const SCEV *PHISCEV =
3244 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3247 // Okay, for the entire analysis of this edge we assumed the PHI
3248 // to be symbolic. We now need to go back and purge all of the
3249 // entries for the scalars that use the symbolic expression.
3250 ForgetSymbolicName(PN, SymbolicName);
3251 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3259 // If the PHI has a single incoming value, follow that value, unless the
3260 // PHI's incoming blocks are in a different loop, in which case doing so
3261 // risks breaking LCSSA form. Instcombine would normally zap these, but
3262 // it doesn't have DominatorTree information, so it may miss cases.
3263 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AT))
3264 if (LI->replacementPreservesLCSSAForm(PN, V))
3267 // If it's not a loop phi, we can't handle it yet.
3268 return getUnknown(PN);
3271 /// createNodeForGEP - Expand GEP instructions into add and multiply
3272 /// operations. This allows them to be analyzed by regular SCEV code.
3274 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3275 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3276 Value *Base = GEP->getOperand(0);
3277 // Don't attempt to analyze GEPs over unsized objects.
3278 if (!Base->getType()->getPointerElementType()->isSized())
3279 return getUnknown(GEP);
3281 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3282 // Add expression, because the Instruction may be guarded by control flow
3283 // and the no-overflow bits may not be valid for the expression in any
3285 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3287 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3288 gep_type_iterator GTI = gep_type_begin(GEP);
3289 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
3293 // Compute the (potentially symbolic) offset in bytes for this index.
3294 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3295 // For a struct, add the member offset.
3296 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3297 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3299 // Add the field offset to the running total offset.
3300 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3302 // For an array, add the element offset, explicitly scaled.
3303 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
3304 const SCEV *IndexS = getSCEV(Index);
3305 // Getelementptr indices are signed.
3306 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3308 // Multiply the index by the element size to compute the element offset.
3309 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
3311 // Add the element offset to the running total offset.
3312 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3316 // Get the SCEV for the GEP base.
3317 const SCEV *BaseS = getSCEV(Base);
3319 // Add the total offset from all the GEP indices to the base.
3320 return getAddExpr(BaseS, TotalOffset, Wrap);
3323 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3324 /// guaranteed to end in (at every loop iteration). It is, at the same time,
3325 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3326 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
3328 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3329 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3330 return C->getValue()->getValue().countTrailingZeros();
3332 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3333 return std::min(GetMinTrailingZeros(T->getOperand()),
3334 (uint32_t)getTypeSizeInBits(T->getType()));
3336 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3337 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3338 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3339 getTypeSizeInBits(E->getType()) : OpRes;
3342 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3343 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3344 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3345 getTypeSizeInBits(E->getType()) : OpRes;
3348 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3349 // The result is the min of all operands results.
3350 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3351 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3352 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3356 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3357 // The result is the sum of all operands results.
3358 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3359 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3360 for (unsigned i = 1, e = M->getNumOperands();
3361 SumOpRes != BitWidth && i != e; ++i)
3362 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3367 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3368 // The result is the min of all operands results.
3369 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3370 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3371 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3375 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3376 // The result is the min of all operands results.
3377 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3378 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3379 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3383 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3384 // The result is the min of all operands results.
3385 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3386 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3387 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3391 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3392 // For a SCEVUnknown, ask ValueTracking.
3393 unsigned BitWidth = getTypeSizeInBits(U->getType());
3394 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3395 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3396 return Zeros.countTrailingOnes();
3403 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3406 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3407 // See if we've computed this range already.
3408 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3409 if (I != UnsignedRanges.end())
3412 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3413 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3415 unsigned BitWidth = getTypeSizeInBits(S->getType());
3416 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3418 // If the value has known zeros, the maximum unsigned value will have those
3419 // known zeros as well.
3420 uint32_t TZ = GetMinTrailingZeros(S);
3422 ConservativeResult =
3423 ConstantRange(APInt::getMinValue(BitWidth),
3424 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3426 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3427 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3428 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3429 X = X.add(getUnsignedRange(Add->getOperand(i)));
3430 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3433 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3434 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3435 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3436 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3437 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3440 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3441 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3442 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3443 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3444 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3447 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3448 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3449 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3450 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3451 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3454 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3455 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3456 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3457 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3460 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3461 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3462 return setUnsignedRange(ZExt,
3463 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3466 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3467 ConstantRange X = getUnsignedRange(SExt->getOperand());
3468 return setUnsignedRange(SExt,
3469 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3472 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3473 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3474 return setUnsignedRange(Trunc,
3475 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3478 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3479 // If there's no unsigned wrap, the value will never be less than its
3481 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3482 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3483 if (!C->getValue()->isZero())
3484 ConservativeResult =
3485 ConservativeResult.intersectWith(
3486 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3488 // TODO: non-affine addrec
3489 if (AddRec->isAffine()) {
3490 Type *Ty = AddRec->getType();
3491 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3492 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3493 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3494 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3496 const SCEV *Start = AddRec->getStart();
3497 const SCEV *Step = AddRec->getStepRecurrence(*this);
3499 ConstantRange StartRange = getUnsignedRange(Start);
3500 ConstantRange StepRange = getSignedRange(Step);
3501 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3502 ConstantRange EndRange =
3503 StartRange.add(MaxBECountRange.multiply(StepRange));
3505 // Check for overflow. This must be done with ConstantRange arithmetic
3506 // because we could be called from within the ScalarEvolution overflow
3508 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3509 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3510 ConstantRange ExtMaxBECountRange =
3511 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3512 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3513 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3515 return setUnsignedRange(AddRec, ConservativeResult);
3517 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3518 EndRange.getUnsignedMin());
3519 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3520 EndRange.getUnsignedMax());
3521 if (Min.isMinValue() && Max.isMaxValue())
3522 return setUnsignedRange(AddRec, ConservativeResult);
3523 return setUnsignedRange(AddRec,
3524 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3528 return setUnsignedRange(AddRec, ConservativeResult);
3531 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3532 // For a SCEVUnknown, ask ValueTracking.
3533 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3534 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3535 if (Ones == ~Zeros + 1)
3536 return setUnsignedRange(U, ConservativeResult);
3537 return setUnsignedRange(U,
3538 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3541 return setUnsignedRange(S, ConservativeResult);
3544 /// getSignedRange - Determine the signed range for a particular SCEV.
3547 ScalarEvolution::getSignedRange(const SCEV *S) {
3548 // See if we've computed this range already.
3549 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3550 if (I != SignedRanges.end())
3553 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3554 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3556 unsigned BitWidth = getTypeSizeInBits(S->getType());
3557 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3559 // If the value has known zeros, the maximum signed value will have those
3560 // known zeros as well.
3561 uint32_t TZ = GetMinTrailingZeros(S);
3563 ConservativeResult =
3564 ConstantRange(APInt::getSignedMinValue(BitWidth),
3565 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3567 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3568 ConstantRange X = getSignedRange(Add->getOperand(0));
3569 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3570 X = X.add(getSignedRange(Add->getOperand(i)));
3571 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3574 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3575 ConstantRange X = getSignedRange(Mul->getOperand(0));
3576 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3577 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3578 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3581 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3582 ConstantRange X = getSignedRange(SMax->getOperand(0));
3583 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3584 X = X.smax(getSignedRange(SMax->getOperand(i)));
3585 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3588 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3589 ConstantRange X = getSignedRange(UMax->getOperand(0));
3590 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3591 X = X.umax(getSignedRange(UMax->getOperand(i)));
3592 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3595 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3596 ConstantRange X = getSignedRange(UDiv->getLHS());
3597 ConstantRange Y = getSignedRange(UDiv->getRHS());
3598 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3601 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3602 ConstantRange X = getSignedRange(ZExt->getOperand());
3603 return setSignedRange(ZExt,
3604 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3607 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3608 ConstantRange X = getSignedRange(SExt->getOperand());
3609 return setSignedRange(SExt,
3610 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3613 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3614 ConstantRange X = getSignedRange(Trunc->getOperand());
3615 return setSignedRange(Trunc,
3616 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3619 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3620 // If there's no signed wrap, and all the operands have the same sign or
3621 // zero, the value won't ever change sign.
3622 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3623 bool AllNonNeg = true;
3624 bool AllNonPos = true;
3625 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3626 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3627 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3630 ConservativeResult = ConservativeResult.intersectWith(
3631 ConstantRange(APInt(BitWidth, 0),
3632 APInt::getSignedMinValue(BitWidth)));
3634 ConservativeResult = ConservativeResult.intersectWith(
3635 ConstantRange(APInt::getSignedMinValue(BitWidth),
3636 APInt(BitWidth, 1)));
3639 // TODO: non-affine addrec
3640 if (AddRec->isAffine()) {
3641 Type *Ty = AddRec->getType();
3642 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3643 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3644 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3645 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3647 const SCEV *Start = AddRec->getStart();
3648 const SCEV *Step = AddRec->getStepRecurrence(*this);
3650 ConstantRange StartRange = getSignedRange(Start);
3651 ConstantRange StepRange = getSignedRange(Step);
3652 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3653 ConstantRange EndRange =
3654 StartRange.add(MaxBECountRange.multiply(StepRange));
3656 // Check for overflow. This must be done with ConstantRange arithmetic
3657 // because we could be called from within the ScalarEvolution overflow
3659 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3660 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3661 ConstantRange ExtMaxBECountRange =
3662 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3663 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3664 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3666 return setSignedRange(AddRec, ConservativeResult);
3668 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3669 EndRange.getSignedMin());
3670 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3671 EndRange.getSignedMax());
3672 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3673 return setSignedRange(AddRec, ConservativeResult);
3674 return setSignedRange(AddRec,
3675 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3679 return setSignedRange(AddRec, ConservativeResult);
3682 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3683 // For a SCEVUnknown, ask ValueTracking.
3684 if (!U->getValue()->getType()->isIntegerTy() && !DL)
3685 return setSignedRange(U, ConservativeResult);
3686 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AT, nullptr, DT);
3688 return setSignedRange(U, ConservativeResult);
3689 return setSignedRange(U, ConservativeResult.intersectWith(
3690 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3691 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3694 return setSignedRange(S, ConservativeResult);
3697 /// createSCEV - We know that there is no SCEV for the specified value.
3698 /// Analyze the expression.
3700 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3701 if (!isSCEVable(V->getType()))
3702 return getUnknown(V);
3704 unsigned Opcode = Instruction::UserOp1;
3705 if (Instruction *I = dyn_cast<Instruction>(V)) {
3706 Opcode = I->getOpcode();
3708 // Don't attempt to analyze instructions in blocks that aren't
3709 // reachable. Such instructions don't matter, and they aren't required
3710 // to obey basic rules for definitions dominating uses which this
3711 // analysis depends on.
3712 if (!DT->isReachableFromEntry(I->getParent()))
3713 return getUnknown(V);
3714 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3715 Opcode = CE->getOpcode();
3716 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3717 return getConstant(CI);
3718 else if (isa<ConstantPointerNull>(V))
3719 return getConstant(V->getType(), 0);
3720 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3721 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3723 return getUnknown(V);
3725 Operator *U = cast<Operator>(V);
3727 case Instruction::Add: {
3728 // The simple thing to do would be to just call getSCEV on both operands
3729 // and call getAddExpr with the result. However if we're looking at a
3730 // bunch of things all added together, this can be quite inefficient,
3731 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3732 // Instead, gather up all the operands and make a single getAddExpr call.
3733 // LLVM IR canonical form means we need only traverse the left operands.
3735 // Don't apply this instruction's NSW or NUW flags to the new
3736 // expression. The instruction may be guarded by control flow that the
3737 // no-wrap behavior depends on. Non-control-equivalent instructions can be
3738 // mapped to the same SCEV expression, and it would be incorrect to transfer
3739 // NSW/NUW semantics to those operations.
3740 SmallVector<const SCEV *, 4> AddOps;
3741 AddOps.push_back(getSCEV(U->getOperand(1)));
3742 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3743 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3744 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3746 U = cast<Operator>(Op);
3747 const SCEV *Op1 = getSCEV(U->getOperand(1));
3748 if (Opcode == Instruction::Sub)
3749 AddOps.push_back(getNegativeSCEV(Op1));
3751 AddOps.push_back(Op1);
3753 AddOps.push_back(getSCEV(U->getOperand(0)));
3754 return getAddExpr(AddOps);
3756 case Instruction::Mul: {
3757 // Don't transfer NSW/NUW for the same reason as AddExpr.
3758 SmallVector<const SCEV *, 4> MulOps;
3759 MulOps.push_back(getSCEV(U->getOperand(1)));
3760 for (Value *Op = U->getOperand(0);
3761 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3762 Op = U->getOperand(0)) {
3763 U = cast<Operator>(Op);
3764 MulOps.push_back(getSCEV(U->getOperand(1)));
3766 MulOps.push_back(getSCEV(U->getOperand(0)));
3767 return getMulExpr(MulOps);
3769 case Instruction::UDiv:
3770 return getUDivExpr(getSCEV(U->getOperand(0)),
3771 getSCEV(U->getOperand(1)));
3772 case Instruction::Sub:
3773 return getMinusSCEV(getSCEV(U->getOperand(0)),
3774 getSCEV(U->getOperand(1)));
3775 case Instruction::And:
3776 // For an expression like x&255 that merely masks off the high bits,
3777 // use zext(trunc(x)) as the SCEV expression.
3778 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3779 if (CI->isNullValue())
3780 return getSCEV(U->getOperand(1));
3781 if (CI->isAllOnesValue())
3782 return getSCEV(U->getOperand(0));
3783 const APInt &A = CI->getValue();
3785 // Instcombine's ShrinkDemandedConstant may strip bits out of
3786 // constants, obscuring what would otherwise be a low-bits mask.
3787 // Use computeKnownBits to compute what ShrinkDemandedConstant
3788 // knew about to reconstruct a low-bits mask value.
3789 unsigned LZ = A.countLeadingZeros();
3790 unsigned TZ = A.countTrailingZeros();
3791 unsigned BitWidth = A.getBitWidth();
3792 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3793 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL,
3794 0, AT, nullptr, DT);
3796 APInt EffectiveMask =
3797 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
3798 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
3799 const SCEV *MulCount = getConstant(
3800 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
3804 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
3805 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
3812 case Instruction::Or:
3813 // If the RHS of the Or is a constant, we may have something like:
3814 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3815 // optimizations will transparently handle this case.
3817 // In order for this transformation to be safe, the LHS must be of the
3818 // form X*(2^n) and the Or constant must be less than 2^n.
3819 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3820 const SCEV *LHS = getSCEV(U->getOperand(0));
3821 const APInt &CIVal = CI->getValue();
3822 if (GetMinTrailingZeros(LHS) >=
3823 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3824 // Build a plain add SCEV.
3825 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3826 // If the LHS of the add was an addrec and it has no-wrap flags,
3827 // transfer the no-wrap flags, since an or won't introduce a wrap.
3828 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3829 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3830 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3831 OldAR->getNoWrapFlags());
3837 case Instruction::Xor:
3838 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3839 // If the RHS of the xor is a signbit, then this is just an add.
3840 // Instcombine turns add of signbit into xor as a strength reduction step.
3841 if (CI->getValue().isSignBit())
3842 return getAddExpr(getSCEV(U->getOperand(0)),
3843 getSCEV(U->getOperand(1)));
3845 // If the RHS of xor is -1, then this is a not operation.
3846 if (CI->isAllOnesValue())
3847 return getNotSCEV(getSCEV(U->getOperand(0)));
3849 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3850 // This is a variant of the check for xor with -1, and it handles
3851 // the case where instcombine has trimmed non-demanded bits out
3852 // of an xor with -1.
3853 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3854 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3855 if (BO->getOpcode() == Instruction::And &&
3856 LCI->getValue() == CI->getValue())
3857 if (const SCEVZeroExtendExpr *Z =
3858 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3859 Type *UTy = U->getType();
3860 const SCEV *Z0 = Z->getOperand();
3861 Type *Z0Ty = Z0->getType();
3862 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3864 // If C is a low-bits mask, the zero extend is serving to
3865 // mask off the high bits. Complement the operand and
3866 // re-apply the zext.
3867 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3868 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3870 // If C is a single bit, it may be in the sign-bit position
3871 // before the zero-extend. In this case, represent the xor
3872 // using an add, which is equivalent, and re-apply the zext.
3873 APInt Trunc = CI->getValue().trunc(Z0TySize);
3874 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3876 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3882 case Instruction::Shl:
3883 // Turn shift left of a constant amount into a multiply.
3884 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3885 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3887 // If the shift count is not less than the bitwidth, the result of
3888 // the shift is undefined. Don't try to analyze it, because the
3889 // resolution chosen here may differ from the resolution chosen in
3890 // other parts of the compiler.
3891 if (SA->getValue().uge(BitWidth))
3894 Constant *X = ConstantInt::get(getContext(),
3895 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3896 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3900 case Instruction::LShr:
3901 // Turn logical shift right of a constant into a unsigned divide.
3902 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3903 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3905 // If the shift count is not less than the bitwidth, the result of
3906 // the shift is undefined. Don't try to analyze it, because the
3907 // resolution chosen here may differ from the resolution chosen in
3908 // other parts of the compiler.
3909 if (SA->getValue().uge(BitWidth))
3912 Constant *X = ConstantInt::get(getContext(),
3913 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3914 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3918 case Instruction::AShr:
3919 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3920 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3921 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3922 if (L->getOpcode() == Instruction::Shl &&
3923 L->getOperand(1) == U->getOperand(1)) {
3924 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3926 // If the shift count is not less than the bitwidth, the result of
3927 // the shift is undefined. Don't try to analyze it, because the
3928 // resolution chosen here may differ from the resolution chosen in
3929 // other parts of the compiler.
3930 if (CI->getValue().uge(BitWidth))
3933 uint64_t Amt = BitWidth - CI->getZExtValue();
3934 if (Amt == BitWidth)
3935 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3937 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3938 IntegerType::get(getContext(),
3944 case Instruction::Trunc:
3945 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3947 case Instruction::ZExt:
3948 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3950 case Instruction::SExt:
3951 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3953 case Instruction::BitCast:
3954 // BitCasts are no-op casts so we just eliminate the cast.
3955 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3956 return getSCEV(U->getOperand(0));
3959 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3960 // lead to pointer expressions which cannot safely be expanded to GEPs,
3961 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3962 // simplifying integer expressions.
3964 case Instruction::GetElementPtr:
3965 return createNodeForGEP(cast<GEPOperator>(U));
3967 case Instruction::PHI:
3968 return createNodeForPHI(cast<PHINode>(U));
3970 case Instruction::Select:
3971 // This could be a smax or umax that was lowered earlier.
3972 // Try to recover it.
3973 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3974 Value *LHS = ICI->getOperand(0);
3975 Value *RHS = ICI->getOperand(1);
3976 switch (ICI->getPredicate()) {
3977 case ICmpInst::ICMP_SLT:
3978 case ICmpInst::ICMP_SLE:
3979 std::swap(LHS, RHS);
3981 case ICmpInst::ICMP_SGT:
3982 case ICmpInst::ICMP_SGE:
3983 // a >s b ? a+x : b+x -> smax(a, b)+x
3984 // a >s b ? b+x : a+x -> smin(a, b)+x
3985 if (LHS->getType() == U->getType()) {
3986 const SCEV *LS = getSCEV(LHS);
3987 const SCEV *RS = getSCEV(RHS);
3988 const SCEV *LA = getSCEV(U->getOperand(1));
3989 const SCEV *RA = getSCEV(U->getOperand(2));
3990 const SCEV *LDiff = getMinusSCEV(LA, LS);
3991 const SCEV *RDiff = getMinusSCEV(RA, RS);
3993 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3994 LDiff = getMinusSCEV(LA, RS);
3995 RDiff = getMinusSCEV(RA, LS);
3997 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4000 case ICmpInst::ICMP_ULT:
4001 case ICmpInst::ICMP_ULE:
4002 std::swap(LHS, RHS);
4004 case ICmpInst::ICMP_UGT:
4005 case ICmpInst::ICMP_UGE:
4006 // a >u b ? a+x : b+x -> umax(a, b)+x
4007 // a >u b ? b+x : a+x -> umin(a, b)+x
4008 if (LHS->getType() == U->getType()) {
4009 const SCEV *LS = getSCEV(LHS);
4010 const SCEV *RS = getSCEV(RHS);
4011 const SCEV *LA = getSCEV(U->getOperand(1));
4012 const SCEV *RA = getSCEV(U->getOperand(2));
4013 const SCEV *LDiff = getMinusSCEV(LA, LS);
4014 const SCEV *RDiff = getMinusSCEV(RA, RS);
4016 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4017 LDiff = getMinusSCEV(LA, RS);
4018 RDiff = getMinusSCEV(RA, LS);
4020 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4023 case ICmpInst::ICMP_NE:
4024 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4025 if (LHS->getType() == U->getType() &&
4026 isa<ConstantInt>(RHS) &&
4027 cast<ConstantInt>(RHS)->isZero()) {
4028 const SCEV *One = getConstant(LHS->getType(), 1);
4029 const SCEV *LS = getSCEV(LHS);
4030 const SCEV *LA = getSCEV(U->getOperand(1));
4031 const SCEV *RA = getSCEV(U->getOperand(2));
4032 const SCEV *LDiff = getMinusSCEV(LA, LS);
4033 const SCEV *RDiff = getMinusSCEV(RA, One);
4035 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4038 case ICmpInst::ICMP_EQ:
4039 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4040 if (LHS->getType() == U->getType() &&
4041 isa<ConstantInt>(RHS) &&
4042 cast<ConstantInt>(RHS)->isZero()) {
4043 const SCEV *One = getConstant(LHS->getType(), 1);
4044 const SCEV *LS = getSCEV(LHS);
4045 const SCEV *LA = getSCEV(U->getOperand(1));
4046 const SCEV *RA = getSCEV(U->getOperand(2));
4047 const SCEV *LDiff = getMinusSCEV(LA, One);
4048 const SCEV *RDiff = getMinusSCEV(RA, LS);
4050 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4058 default: // We cannot analyze this expression.
4062 return getUnknown(V);
4067 //===----------------------------------------------------------------------===//
4068 // Iteration Count Computation Code
4071 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
4072 /// normal unsigned value. Returns 0 if the trip count is unknown or not
4073 /// constant. Will also return 0 if the maximum trip count is very large (>=
4076 /// This "trip count" assumes that control exits via ExitingBlock. More
4077 /// precisely, it is the number of times that control may reach ExitingBlock
4078 /// before taking the branch. For loops with multiple exits, it may not be the
4079 /// number times that the loop header executes because the loop may exit
4080 /// prematurely via another branch.
4082 /// FIXME: We conservatively call getBackedgeTakenCount(L) instead of
4083 /// getExitCount(L, ExitingBlock) to compute a safe trip count considering all
4084 /// loop exits. getExitCount() may return an exact count for this branch
4085 /// assuming no-signed-wrap. The number of well-defined iterations may actually
4086 /// be higher than this trip count if this exit test is skipped and the loop
4087 /// exits via a different branch. Ideally, getExitCount() would know whether it
4088 /// depends on a NSW assumption, and we would only fall back to a conservative
4089 /// trip count in that case.
4090 unsigned ScalarEvolution::
4091 getSmallConstantTripCount(Loop *L, BasicBlock * /*ExitingBlock*/) {
4092 const SCEVConstant *ExitCount =
4093 dyn_cast<SCEVConstant>(getBackedgeTakenCount(L));
4097 ConstantInt *ExitConst = ExitCount->getValue();
4099 // Guard against huge trip counts.
4100 if (ExitConst->getValue().getActiveBits() > 32)
4103 // In case of integer overflow, this returns 0, which is correct.
4104 return ((unsigned)ExitConst->getZExtValue()) + 1;
4107 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4108 /// trip count of this loop as a normal unsigned value, if possible. This
4109 /// means that the actual trip count is always a multiple of the returned
4110 /// value (don't forget the trip count could very well be zero as well!).
4112 /// Returns 1 if the trip count is unknown or not guaranteed to be the
4113 /// multiple of a constant (which is also the case if the trip count is simply
4114 /// constant, use getSmallConstantTripCount for that case), Will also return 1
4115 /// if the trip count is very large (>= 2^32).
4117 /// As explained in the comments for getSmallConstantTripCount, this assumes
4118 /// that control exits the loop via ExitingBlock.
4119 unsigned ScalarEvolution::
4120 getSmallConstantTripMultiple(Loop *L, BasicBlock * /*ExitingBlock*/) {
4121 const SCEV *ExitCount = getBackedgeTakenCount(L);
4122 if (ExitCount == getCouldNotCompute())
4125 // Get the trip count from the BE count by adding 1.
4126 const SCEV *TCMul = getAddExpr(ExitCount,
4127 getConstant(ExitCount->getType(), 1));
4128 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4129 // to factor simple cases.
4130 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4131 TCMul = Mul->getOperand(0);
4133 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4137 ConstantInt *Result = MulC->getValue();
4139 // Guard against huge trip counts (this requires checking
4140 // for zero to handle the case where the trip count == -1 and the
4142 if (!Result || Result->getValue().getActiveBits() > 32 ||
4143 Result->getValue().getActiveBits() == 0)
4146 return (unsigned)Result->getZExtValue();
4149 // getExitCount - Get the expression for the number of loop iterations for which
4150 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
4151 // SCEVCouldNotCompute.
4152 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4153 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
4156 /// getBackedgeTakenCount - If the specified loop has a predictable
4157 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4158 /// object. The backedge-taken count is the number of times the loop header
4159 /// will be branched to from within the loop. This is one less than the
4160 /// trip count of the loop, since it doesn't count the first iteration,
4161 /// when the header is branched to from outside the loop.
4163 /// Note that it is not valid to call this method on a loop without a
4164 /// loop-invariant backedge-taken count (see
4165 /// hasLoopInvariantBackedgeTakenCount).
4167 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
4168 return getBackedgeTakenInfo(L).getExact(this);
4171 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4172 /// return the least SCEV value that is known never to be less than the
4173 /// actual backedge taken count.
4174 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
4175 return getBackedgeTakenInfo(L).getMax(this);
4178 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
4179 /// onto the given Worklist.
4181 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4182 BasicBlock *Header = L->getHeader();
4184 // Push all Loop-header PHIs onto the Worklist stack.
4185 for (BasicBlock::iterator I = Header->begin();
4186 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4187 Worklist.push_back(PN);
4190 const ScalarEvolution::BackedgeTakenInfo &
4191 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
4192 // Initially insert an invalid entry for this loop. If the insertion
4193 // succeeds, proceed to actually compute a backedge-taken count and
4194 // update the value. The temporary CouldNotCompute value tells SCEV
4195 // code elsewhere that it shouldn't attempt to request a new
4196 // backedge-taken count, which could result in infinite recursion.
4197 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
4198 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
4200 return Pair.first->second;
4202 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4203 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4204 // must be cleared in this scope.
4205 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4207 if (Result.getExact(this) != getCouldNotCompute()) {
4208 assert(isLoopInvariant(Result.getExact(this), L) &&
4209 isLoopInvariant(Result.getMax(this), L) &&
4210 "Computed backedge-taken count isn't loop invariant for loop!");
4211 ++NumTripCountsComputed;
4213 else if (Result.getMax(this) == getCouldNotCompute() &&
4214 isa<PHINode>(L->getHeader()->begin())) {
4215 // Only count loops that have phi nodes as not being computable.
4216 ++NumTripCountsNotComputed;
4219 // Now that we know more about the trip count for this loop, forget any
4220 // existing SCEV values for PHI nodes in this loop since they are only
4221 // conservative estimates made without the benefit of trip count
4222 // information. This is similar to the code in forgetLoop, except that
4223 // it handles SCEVUnknown PHI nodes specially.
4224 if (Result.hasAnyInfo()) {
4225 SmallVector<Instruction *, 16> Worklist;
4226 PushLoopPHIs(L, Worklist);
4228 SmallPtrSet<Instruction *, 8> Visited;
4229 while (!Worklist.empty()) {
4230 Instruction *I = Worklist.pop_back_val();
4231 if (!Visited.insert(I)) continue;
4233 ValueExprMapType::iterator It =
4234 ValueExprMap.find_as(static_cast<Value *>(I));
4235 if (It != ValueExprMap.end()) {
4236 const SCEV *Old = It->second;
4238 // SCEVUnknown for a PHI either means that it has an unrecognized
4239 // structure, or it's a PHI that's in the progress of being computed
4240 // by createNodeForPHI. In the former case, additional loop trip
4241 // count information isn't going to change anything. In the later
4242 // case, createNodeForPHI will perform the necessary updates on its
4243 // own when it gets to that point.
4244 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4245 forgetMemoizedResults(Old);
4246 ValueExprMap.erase(It);
4248 if (PHINode *PN = dyn_cast<PHINode>(I))
4249 ConstantEvolutionLoopExitValue.erase(PN);
4252 PushDefUseChildren(I, Worklist);
4256 // Re-lookup the insert position, since the call to
4257 // ComputeBackedgeTakenCount above could result in a
4258 // recusive call to getBackedgeTakenInfo (on a different
4259 // loop), which would invalidate the iterator computed
4261 return BackedgeTakenCounts.find(L)->second = Result;
4264 /// forgetLoop - This method should be called by the client when it has
4265 /// changed a loop in a way that may effect ScalarEvolution's ability to
4266 /// compute a trip count, or if the loop is deleted.
4267 void ScalarEvolution::forgetLoop(const Loop *L) {
4268 // Drop any stored trip count value.
4269 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4270 BackedgeTakenCounts.find(L);
4271 if (BTCPos != BackedgeTakenCounts.end()) {
4272 BTCPos->second.clear();
4273 BackedgeTakenCounts.erase(BTCPos);
4276 // Drop information about expressions based on loop-header PHIs.
4277 SmallVector<Instruction *, 16> Worklist;
4278 PushLoopPHIs(L, Worklist);
4280 SmallPtrSet<Instruction *, 8> Visited;
4281 while (!Worklist.empty()) {
4282 Instruction *I = Worklist.pop_back_val();
4283 if (!Visited.insert(I)) continue;
4285 ValueExprMapType::iterator It =
4286 ValueExprMap.find_as(static_cast<Value *>(I));
4287 if (It != ValueExprMap.end()) {
4288 forgetMemoizedResults(It->second);
4289 ValueExprMap.erase(It);
4290 if (PHINode *PN = dyn_cast<PHINode>(I))
4291 ConstantEvolutionLoopExitValue.erase(PN);
4294 PushDefUseChildren(I, Worklist);
4297 // Forget all contained loops too, to avoid dangling entries in the
4298 // ValuesAtScopes map.
4299 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4303 /// forgetValue - This method should be called by the client when it has
4304 /// changed a value in a way that may effect its value, or which may
4305 /// disconnect it from a def-use chain linking it to a loop.
4306 void ScalarEvolution::forgetValue(Value *V) {
4307 Instruction *I = dyn_cast<Instruction>(V);
4310 // Drop information about expressions based on loop-header PHIs.
4311 SmallVector<Instruction *, 16> Worklist;
4312 Worklist.push_back(I);
4314 SmallPtrSet<Instruction *, 8> Visited;
4315 while (!Worklist.empty()) {
4316 I = Worklist.pop_back_val();
4317 if (!Visited.insert(I)) continue;
4319 ValueExprMapType::iterator It =
4320 ValueExprMap.find_as(static_cast<Value *>(I));
4321 if (It != ValueExprMap.end()) {
4322 forgetMemoizedResults(It->second);
4323 ValueExprMap.erase(It);
4324 if (PHINode *PN = dyn_cast<PHINode>(I))
4325 ConstantEvolutionLoopExitValue.erase(PN);
4328 PushDefUseChildren(I, Worklist);
4332 /// getExact - Get the exact loop backedge taken count considering all loop
4333 /// exits. A computable result can only be return for loops with a single exit.
4334 /// Returning the minimum taken count among all exits is incorrect because one
4335 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4336 /// the limit of each loop test is never skipped. This is a valid assumption as
4337 /// long as the loop exits via that test. For precise results, it is the
4338 /// caller's responsibility to specify the relevant loop exit using
4339 /// getExact(ExitingBlock, SE).
4341 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4342 // If any exits were not computable, the loop is not computable.
4343 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4345 // We need exactly one computable exit.
4346 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4347 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4349 const SCEV *BECount = nullptr;
4350 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4351 ENT != nullptr; ENT = ENT->getNextExit()) {
4353 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4356 BECount = ENT->ExactNotTaken;
4357 else if (BECount != ENT->ExactNotTaken)
4358 return SE->getCouldNotCompute();
4360 assert(BECount && "Invalid not taken count for loop exit");
4364 /// getExact - Get the exact not taken count for this loop exit.
4366 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4367 ScalarEvolution *SE) const {
4368 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4369 ENT != nullptr; ENT = ENT->getNextExit()) {
4371 if (ENT->ExitingBlock == ExitingBlock)
4372 return ENT->ExactNotTaken;
4374 return SE->getCouldNotCompute();
4377 /// getMax - Get the max backedge taken count for the loop.
4379 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4380 return Max ? Max : SE->getCouldNotCompute();
4383 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4384 ScalarEvolution *SE) const {
4385 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4388 if (!ExitNotTaken.ExitingBlock)
4391 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4392 ENT != nullptr; ENT = ENT->getNextExit()) {
4394 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4395 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4402 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4403 /// computable exit into a persistent ExitNotTakenInfo array.
4404 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4405 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4406 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4409 ExitNotTaken.setIncomplete();
4411 unsigned NumExits = ExitCounts.size();
4412 if (NumExits == 0) return;
4414 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4415 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4416 if (NumExits == 1) return;
4418 // Handle the rare case of multiple computable exits.
4419 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4421 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4422 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4423 PrevENT->setNextExit(ENT);
4424 ENT->ExitingBlock = ExitCounts[i].first;
4425 ENT->ExactNotTaken = ExitCounts[i].second;
4429 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4430 void ScalarEvolution::BackedgeTakenInfo::clear() {
4431 ExitNotTaken.ExitingBlock = nullptr;
4432 ExitNotTaken.ExactNotTaken = nullptr;
4433 delete[] ExitNotTaken.getNextExit();
4436 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4437 /// of the specified loop will execute.
4438 ScalarEvolution::BackedgeTakenInfo
4439 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4440 SmallVector<BasicBlock *, 8> ExitingBlocks;
4441 L->getExitingBlocks(ExitingBlocks);
4443 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4444 bool CouldComputeBECount = true;
4445 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
4446 const SCEV *MustExitMaxBECount = nullptr;
4447 const SCEV *MayExitMaxBECount = nullptr;
4449 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4450 // and compute maxBECount.
4451 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4452 BasicBlock *ExitBB = ExitingBlocks[i];
4453 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4455 // 1. For each exit that can be computed, add an entry to ExitCounts.
4456 // CouldComputeBECount is true only if all exits can be computed.
4457 if (EL.Exact == getCouldNotCompute())
4458 // We couldn't compute an exact value for this exit, so
4459 // we won't be able to compute an exact value for the loop.
4460 CouldComputeBECount = false;
4462 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
4464 // 2. Derive the loop's MaxBECount from each exit's max number of
4465 // non-exiting iterations. Partition the loop exits into two kinds:
4466 // LoopMustExits and LoopMayExits.
4468 // A LoopMustExit meets two requirements:
4470 // (a) Its ExitLimit.MustExit flag must be set which indicates that the exit
4471 // test condition cannot be skipped (the tested variable has unit stride or
4472 // the test is less-than or greater-than, rather than a strict inequality).
4474 // (b) It must dominate the loop latch, hence must be tested on every loop
4477 // If any computable LoopMustExit is found, then MaxBECount is the minimum
4478 // EL.Max of computable LoopMustExits. Otherwise, MaxBECount is
4479 // conservatively the maximum EL.Max, where CouldNotCompute is considered
4480 // greater than any computable EL.Max.
4481 if (EL.MustExit && EL.Max != getCouldNotCompute() && Latch &&
4482 DT->dominates(ExitBB, Latch)) {
4483 if (!MustExitMaxBECount)
4484 MustExitMaxBECount = EL.Max;
4486 MustExitMaxBECount =
4487 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
4489 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4490 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4491 MayExitMaxBECount = EL.Max;
4494 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4498 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4499 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
4500 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4503 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4504 /// loop will execute if it exits via the specified block.
4505 ScalarEvolution::ExitLimit
4506 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4508 // Okay, we've chosen an exiting block. See what condition causes us to
4509 // exit at this block and remember the exit block and whether all other targets
4510 // lead to the loop header.
4511 bool MustExecuteLoopHeader = true;
4512 BasicBlock *Exit = nullptr;
4513 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4515 if (!L->contains(*SI)) {
4516 if (Exit) // Multiple exit successors.
4517 return getCouldNotCompute();
4519 } else if (*SI != L->getHeader()) {
4520 MustExecuteLoopHeader = false;
4523 // At this point, we know we have a conditional branch that determines whether
4524 // the loop is exited. However, we don't know if the branch is executed each
4525 // time through the loop. If not, then the execution count of the branch will
4526 // not be equal to the trip count of the loop.
4528 // Currently we check for this by checking to see if the Exit branch goes to
4529 // the loop header. If so, we know it will always execute the same number of
4530 // times as the loop. We also handle the case where the exit block *is* the
4531 // loop header. This is common for un-rotated loops.
4533 // If both of those tests fail, walk up the unique predecessor chain to the
4534 // header, stopping if there is an edge that doesn't exit the loop. If the
4535 // header is reached, the execution count of the branch will be equal to the
4536 // trip count of the loop.
4538 // More extensive analysis could be done to handle more cases here.
4540 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
4541 // The simple checks failed, try climbing the unique predecessor chain
4542 // up to the header.
4544 for (BasicBlock *BB = ExitingBlock; BB; ) {
4545 BasicBlock *Pred = BB->getUniquePredecessor();
4547 return getCouldNotCompute();
4548 TerminatorInst *PredTerm = Pred->getTerminator();
4549 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4550 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4553 // If the predecessor has a successor that isn't BB and isn't
4554 // outside the loop, assume the worst.
4555 if (L->contains(PredSucc))
4556 return getCouldNotCompute();
4558 if (Pred == L->getHeader()) {
4565 return getCouldNotCompute();
4568 TerminatorInst *Term = ExitingBlock->getTerminator();
4569 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4570 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4571 // Proceed to the next level to examine the exit condition expression.
4572 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4573 BI->getSuccessor(1),
4574 /*IsSubExpr=*/false);
4577 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4578 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
4579 /*IsSubExpr=*/false);
4581 return getCouldNotCompute();
4584 /// ComputeExitLimitFromCond - Compute the number of times the
4585 /// backedge of the specified loop will execute if its exit condition
4586 /// were a conditional branch of ExitCond, TBB, and FBB.
4588 /// @param IsSubExpr is true if ExitCond does not directly control the exit
4589 /// branch. In this case, we cannot assume that the loop only exits when the
4590 /// condition is true and cannot infer that failing to meet the condition prior
4591 /// to integer wraparound results in undefined behavior.
4592 ScalarEvolution::ExitLimit
4593 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4598 // Check if the controlling expression for this loop is an And or Or.
4599 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4600 if (BO->getOpcode() == Instruction::And) {
4601 // Recurse on the operands of the and.
4602 bool EitherMayExit = L->contains(TBB);
4603 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
4604 IsSubExpr || EitherMayExit);
4605 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
4606 IsSubExpr || EitherMayExit);
4607 const SCEV *BECount = getCouldNotCompute();
4608 const SCEV *MaxBECount = getCouldNotCompute();
4609 bool MustExit = false;
4610 if (EitherMayExit) {
4611 // Both conditions must be true for the loop to continue executing.
4612 // Choose the less conservative count.
4613 if (EL0.Exact == getCouldNotCompute() ||
4614 EL1.Exact == getCouldNotCompute())
4615 BECount = getCouldNotCompute();
4617 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4618 if (EL0.Max == getCouldNotCompute())
4619 MaxBECount = EL1.Max;
4620 else if (EL1.Max == getCouldNotCompute())
4621 MaxBECount = EL0.Max;
4623 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4624 MustExit = EL0.MustExit || EL1.MustExit;
4626 // Both conditions must be true at the same time for the loop to exit.
4627 // For now, be conservative.
4628 assert(L->contains(FBB) && "Loop block has no successor in loop!");
4629 if (EL0.Max == EL1.Max)
4630 MaxBECount = EL0.Max;
4631 if (EL0.Exact == EL1.Exact)
4632 BECount = EL0.Exact;
4633 MustExit = EL0.MustExit && EL1.MustExit;
4636 return ExitLimit(BECount, MaxBECount, MustExit);
4638 if (BO->getOpcode() == Instruction::Or) {
4639 // Recurse on the operands of the or.
4640 bool EitherMayExit = L->contains(FBB);
4641 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
4642 IsSubExpr || EitherMayExit);
4643 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
4644 IsSubExpr || EitherMayExit);
4645 const SCEV *BECount = getCouldNotCompute();
4646 const SCEV *MaxBECount = getCouldNotCompute();
4647 bool MustExit = false;
4648 if (EitherMayExit) {
4649 // Both conditions must be false for the loop to continue executing.
4650 // Choose the less conservative count.
4651 if (EL0.Exact == getCouldNotCompute() ||
4652 EL1.Exact == getCouldNotCompute())
4653 BECount = getCouldNotCompute();
4655 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4656 if (EL0.Max == getCouldNotCompute())
4657 MaxBECount = EL1.Max;
4658 else if (EL1.Max == getCouldNotCompute())
4659 MaxBECount = EL0.Max;
4661 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4662 MustExit = EL0.MustExit || EL1.MustExit;
4664 // Both conditions must be false at the same time for the loop to exit.
4665 // For now, be conservative.
4666 assert(L->contains(TBB) && "Loop block has no successor in loop!");
4667 if (EL0.Max == EL1.Max)
4668 MaxBECount = EL0.Max;
4669 if (EL0.Exact == EL1.Exact)
4670 BECount = EL0.Exact;
4671 MustExit = EL0.MustExit && EL1.MustExit;
4674 return ExitLimit(BECount, MaxBECount, MustExit);
4678 // With an icmp, it may be feasible to compute an exact backedge-taken count.
4679 // Proceed to the next level to examine the icmp.
4680 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4681 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, IsSubExpr);
4683 // Check for a constant condition. These are normally stripped out by
4684 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4685 // preserve the CFG and is temporarily leaving constant conditions
4687 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4688 if (L->contains(FBB) == !CI->getZExtValue())
4689 // The backedge is always taken.
4690 return getCouldNotCompute();
4692 // The backedge is never taken.
4693 return getConstant(CI->getType(), 0);
4696 // If it's not an integer or pointer comparison then compute it the hard way.
4697 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4700 /// ComputeExitLimitFromICmp - Compute the number of times the
4701 /// backedge of the specified loop will execute if its exit condition
4702 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4703 ScalarEvolution::ExitLimit
4704 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4710 // If the condition was exit on true, convert the condition to exit on false
4711 ICmpInst::Predicate Cond;
4712 if (!L->contains(FBB))
4713 Cond = ExitCond->getPredicate();
4715 Cond = ExitCond->getInversePredicate();
4717 // Handle common loops like: for (X = "string"; *X; ++X)
4718 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4719 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
4721 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
4722 if (ItCnt.hasAnyInfo())
4726 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4727 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4729 // Try to evaluate any dependencies out of the loop.
4730 LHS = getSCEVAtScope(LHS, L);
4731 RHS = getSCEVAtScope(RHS, L);
4733 // At this point, we would like to compute how many iterations of the
4734 // loop the predicate will return true for these inputs.
4735 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4736 // If there is a loop-invariant, force it into the RHS.
4737 std::swap(LHS, RHS);
4738 Cond = ICmpInst::getSwappedPredicate(Cond);
4741 // Simplify the operands before analyzing them.
4742 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4744 // If we have a comparison of a chrec against a constant, try to use value
4745 // ranges to answer this query.
4746 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4747 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4748 if (AddRec->getLoop() == L) {
4749 // Form the constant range.
4750 ConstantRange CompRange(
4751 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4753 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4754 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4758 case ICmpInst::ICMP_NE: { // while (X != Y)
4759 // Convert to: while (X-Y != 0)
4760 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
4761 if (EL.hasAnyInfo()) return EL;
4764 case ICmpInst::ICMP_EQ: { // while (X == Y)
4765 // Convert to: while (X-Y == 0)
4766 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4767 if (EL.hasAnyInfo()) return EL;
4770 case ICmpInst::ICMP_SLT:
4771 case ICmpInst::ICMP_ULT: { // while (X < Y)
4772 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
4773 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, IsSubExpr);
4774 if (EL.hasAnyInfo()) return EL;
4777 case ICmpInst::ICMP_SGT:
4778 case ICmpInst::ICMP_UGT: { // while (X > Y)
4779 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
4780 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, IsSubExpr);
4781 if (EL.hasAnyInfo()) return EL;
4786 dbgs() << "ComputeBackedgeTakenCount ";
4787 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4788 dbgs() << "[unsigned] ";
4789 dbgs() << *LHS << " "
4790 << Instruction::getOpcodeName(Instruction::ICmp)
4791 << " " << *RHS << "\n";
4795 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4798 ScalarEvolution::ExitLimit
4799 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
4801 BasicBlock *ExitingBlock,
4803 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
4805 // Give up if the exit is the default dest of a switch.
4806 if (Switch->getDefaultDest() == ExitingBlock)
4807 return getCouldNotCompute();
4809 assert(L->contains(Switch->getDefaultDest()) &&
4810 "Default case must not exit the loop!");
4811 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
4812 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
4814 // while (X != Y) --> while (X-Y != 0)
4815 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
4816 if (EL.hasAnyInfo())
4819 return getCouldNotCompute();
4822 static ConstantInt *
4823 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4824 ScalarEvolution &SE) {
4825 const SCEV *InVal = SE.getConstant(C);
4826 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4827 assert(isa<SCEVConstant>(Val) &&
4828 "Evaluation of SCEV at constant didn't fold correctly?");
4829 return cast<SCEVConstant>(Val)->getValue();
4832 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
4833 /// 'icmp op load X, cst', try to see if we can compute the backedge
4834 /// execution count.
4835 ScalarEvolution::ExitLimit
4836 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
4840 ICmpInst::Predicate predicate) {
4842 if (LI->isVolatile()) return getCouldNotCompute();
4844 // Check to see if the loaded pointer is a getelementptr of a global.
4845 // TODO: Use SCEV instead of manually grubbing with GEPs.
4846 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4847 if (!GEP) return getCouldNotCompute();
4849 // Make sure that it is really a constant global we are gepping, with an
4850 // initializer, and make sure the first IDX is really 0.
4851 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4852 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4853 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4854 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4855 return getCouldNotCompute();
4857 // Okay, we allow one non-constant index into the GEP instruction.
4858 Value *VarIdx = nullptr;
4859 std::vector<Constant*> Indexes;
4860 unsigned VarIdxNum = 0;
4861 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4862 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4863 Indexes.push_back(CI);
4864 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4865 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4866 VarIdx = GEP->getOperand(i);
4868 Indexes.push_back(nullptr);
4871 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
4873 return getCouldNotCompute();
4875 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4876 // Check to see if X is a loop variant variable value now.
4877 const SCEV *Idx = getSCEV(VarIdx);
4878 Idx = getSCEVAtScope(Idx, L);
4880 // We can only recognize very limited forms of loop index expressions, in
4881 // particular, only affine AddRec's like {C1,+,C2}.
4882 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4883 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4884 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4885 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4886 return getCouldNotCompute();
4888 unsigned MaxSteps = MaxBruteForceIterations;
4889 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4890 ConstantInt *ItCst = ConstantInt::get(
4891 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4892 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4894 // Form the GEP offset.
4895 Indexes[VarIdxNum] = Val;
4897 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
4899 if (!Result) break; // Cannot compute!
4901 // Evaluate the condition for this iteration.
4902 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4903 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4904 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4906 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4907 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4910 ++NumArrayLenItCounts;
4911 return getConstant(ItCst); // Found terminating iteration!
4914 return getCouldNotCompute();
4918 /// CanConstantFold - Return true if we can constant fold an instruction of the
4919 /// specified type, assuming that all operands were constants.
4920 static bool CanConstantFold(const Instruction *I) {
4921 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4922 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4926 if (const CallInst *CI = dyn_cast<CallInst>(I))
4927 if (const Function *F = CI->getCalledFunction())
4928 return canConstantFoldCallTo(F);
4932 /// Determine whether this instruction can constant evolve within this loop
4933 /// assuming its operands can all constant evolve.
4934 static bool canConstantEvolve(Instruction *I, const Loop *L) {
4935 // An instruction outside of the loop can't be derived from a loop PHI.
4936 if (!L->contains(I)) return false;
4938 if (isa<PHINode>(I)) {
4939 if (L->getHeader() == I->getParent())
4942 // We don't currently keep track of the control flow needed to evaluate
4943 // PHIs, so we cannot handle PHIs inside of loops.
4947 // If we won't be able to constant fold this expression even if the operands
4948 // are constants, bail early.
4949 return CanConstantFold(I);
4952 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
4953 /// recursing through each instruction operand until reaching a loop header phi.
4955 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
4956 DenseMap<Instruction *, PHINode *> &PHIMap) {
4958 // Otherwise, we can evaluate this instruction if all of its operands are
4959 // constant or derived from a PHI node themselves.
4960 PHINode *PHI = nullptr;
4961 for (Instruction::op_iterator OpI = UseInst->op_begin(),
4962 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
4964 if (isa<Constant>(*OpI)) continue;
4966 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
4967 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
4969 PHINode *P = dyn_cast<PHINode>(OpInst);
4971 // If this operand is already visited, reuse the prior result.
4972 // We may have P != PHI if this is the deepest point at which the
4973 // inconsistent paths meet.
4974 P = PHIMap.lookup(OpInst);
4976 // Recurse and memoize the results, whether a phi is found or not.
4977 // This recursive call invalidates pointers into PHIMap.
4978 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
4982 return nullptr; // Not evolving from PHI
4983 if (PHI && PHI != P)
4984 return nullptr; // Evolving from multiple different PHIs.
4987 // This is a expression evolving from a constant PHI!
4991 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4992 /// in the loop that V is derived from. We allow arbitrary operations along the
4993 /// way, but the operands of an operation must either be constants or a value
4994 /// derived from a constant PHI. If this expression does not fit with these
4995 /// constraints, return null.
4996 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4997 Instruction *I = dyn_cast<Instruction>(V);
4998 if (!I || !canConstantEvolve(I, L)) return nullptr;
5000 if (PHINode *PN = dyn_cast<PHINode>(I)) {
5004 // Record non-constant instructions contained by the loop.
5005 DenseMap<Instruction *, PHINode *> PHIMap;
5006 return getConstantEvolvingPHIOperands(I, L, PHIMap);
5009 /// EvaluateExpression - Given an expression that passes the
5010 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5011 /// in the loop has the value PHIVal. If we can't fold this expression for some
5012 /// reason, return null.
5013 static Constant *EvaluateExpression(Value *V, const Loop *L,
5014 DenseMap<Instruction *, Constant *> &Vals,
5015 const DataLayout *DL,
5016 const TargetLibraryInfo *TLI) {
5017 // Convenient constant check, but redundant for recursive calls.
5018 if (Constant *C = dyn_cast<Constant>(V)) return C;
5019 Instruction *I = dyn_cast<Instruction>(V);
5020 if (!I) return nullptr;
5022 if (Constant *C = Vals.lookup(I)) return C;
5024 // An instruction inside the loop depends on a value outside the loop that we
5025 // weren't given a mapping for, or a value such as a call inside the loop.
5026 if (!canConstantEvolve(I, L)) return nullptr;
5028 // An unmapped PHI can be due to a branch or another loop inside this loop,
5029 // or due to this not being the initial iteration through a loop where we
5030 // couldn't compute the evolution of this particular PHI last time.
5031 if (isa<PHINode>(I)) return nullptr;
5033 std::vector<Constant*> Operands(I->getNumOperands());
5035 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5036 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5038 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
5039 if (!Operands[i]) return nullptr;
5042 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
5044 if (!C) return nullptr;
5048 if (CmpInst *CI = dyn_cast<CmpInst>(I))
5049 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
5050 Operands[1], DL, TLI);
5051 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5052 if (!LI->isVolatile())
5053 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
5055 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
5059 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5060 /// in the header of its containing loop, we know the loop executes a
5061 /// constant number of times, and the PHI node is just a recurrence
5062 /// involving constants, fold it.
5064 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
5067 DenseMap<PHINode*, Constant*>::const_iterator I =
5068 ConstantEvolutionLoopExitValue.find(PN);
5069 if (I != ConstantEvolutionLoopExitValue.end())
5072 if (BEs.ugt(MaxBruteForceIterations))
5073 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
5075 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5077 DenseMap<Instruction *, Constant *> CurrentIterVals;
5078 BasicBlock *Header = L->getHeader();
5079 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5081 // Since the loop is canonicalized, the PHI node must have two entries. One
5082 // entry must be a constant (coming in from outside of the loop), and the
5083 // second must be derived from the same PHI.
5084 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5085 PHINode *PHI = nullptr;
5086 for (BasicBlock::iterator I = Header->begin();
5087 (PHI = dyn_cast<PHINode>(I)); ++I) {
5088 Constant *StartCST =
5089 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5090 if (!StartCST) continue;
5091 CurrentIterVals[PHI] = StartCST;
5093 if (!CurrentIterVals.count(PN))
5094 return RetVal = nullptr;
5096 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
5098 // Execute the loop symbolically to determine the exit value.
5099 if (BEs.getActiveBits() >= 32)
5100 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
5102 unsigned NumIterations = BEs.getZExtValue(); // must be in range
5103 unsigned IterationNum = 0;
5104 for (; ; ++IterationNum) {
5105 if (IterationNum == NumIterations)
5106 return RetVal = CurrentIterVals[PN]; // Got exit value!
5108 // Compute the value of the PHIs for the next iteration.
5109 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
5110 DenseMap<Instruction *, Constant *> NextIterVals;
5111 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
5114 return nullptr; // Couldn't evaluate!
5115 NextIterVals[PN] = NextPHI;
5117 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5119 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5120 // cease to be able to evaluate one of them or if they stop evolving,
5121 // because that doesn't necessarily prevent us from computing PN.
5122 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
5123 for (DenseMap<Instruction *, Constant *>::const_iterator
5124 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5125 PHINode *PHI = dyn_cast<PHINode>(I->first);
5126 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
5127 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5129 // We use two distinct loops because EvaluateExpression may invalidate any
5130 // iterators into CurrentIterVals.
5131 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5132 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5133 PHINode *PHI = I->first;
5134 Constant *&NextPHI = NextIterVals[PHI];
5135 if (!NextPHI) { // Not already computed.
5136 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5137 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5139 if (NextPHI != I->second)
5140 StoppedEvolving = false;
5143 // If all entries in CurrentIterVals == NextIterVals then we can stop
5144 // iterating, the loop can't continue to change.
5145 if (StoppedEvolving)
5146 return RetVal = CurrentIterVals[PN];
5148 CurrentIterVals.swap(NextIterVals);
5152 /// ComputeExitCountExhaustively - If the loop is known to execute a
5153 /// constant number of times (the condition evolves only from constants),
5154 /// try to evaluate a few iterations of the loop until we get the exit
5155 /// condition gets a value of ExitWhen (true or false). If we cannot
5156 /// evaluate the trip count of the loop, return getCouldNotCompute().
5157 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5160 PHINode *PN = getConstantEvolvingPHI(Cond, L);
5161 if (!PN) return getCouldNotCompute();
5163 // If the loop is canonicalized, the PHI will have exactly two entries.
5164 // That's the only form we support here.
5165 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5167 DenseMap<Instruction *, Constant *> CurrentIterVals;
5168 BasicBlock *Header = L->getHeader();
5169 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5171 // One entry must be a constant (coming in from outside of the loop), and the
5172 // second must be derived from the same PHI.
5173 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5174 PHINode *PHI = nullptr;
5175 for (BasicBlock::iterator I = Header->begin();
5176 (PHI = dyn_cast<PHINode>(I)); ++I) {
5177 Constant *StartCST =
5178 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5179 if (!StartCST) continue;
5180 CurrentIterVals[PHI] = StartCST;
5182 if (!CurrentIterVals.count(PN))
5183 return getCouldNotCompute();
5185 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5186 // the loop symbolically to determine when the condition gets a value of
5189 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
5190 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
5191 ConstantInt *CondVal =
5192 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
5195 // Couldn't symbolically evaluate.
5196 if (!CondVal) return getCouldNotCompute();
5198 if (CondVal->getValue() == uint64_t(ExitWhen)) {
5199 ++NumBruteForceTripCountsComputed;
5200 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
5203 // Update all the PHI nodes for the next iteration.
5204 DenseMap<Instruction *, Constant *> NextIterVals;
5206 // Create a list of which PHIs we need to compute. We want to do this before
5207 // calling EvaluateExpression on them because that may invalidate iterators
5208 // into CurrentIterVals.
5209 SmallVector<PHINode *, 8> PHIsToCompute;
5210 for (DenseMap<Instruction *, Constant *>::const_iterator
5211 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5212 PHINode *PHI = dyn_cast<PHINode>(I->first);
5213 if (!PHI || PHI->getParent() != Header) continue;
5214 PHIsToCompute.push_back(PHI);
5216 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5217 E = PHIsToCompute.end(); I != E; ++I) {
5219 Constant *&NextPHI = NextIterVals[PHI];
5220 if (NextPHI) continue; // Already computed!
5222 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5223 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5225 CurrentIterVals.swap(NextIterVals);
5228 // Too many iterations were needed to evaluate.
5229 return getCouldNotCompute();
5232 /// getSCEVAtScope - Return a SCEV expression for the specified value
5233 /// at the specified scope in the program. The L value specifies a loop
5234 /// nest to evaluate the expression at, where null is the top-level or a
5235 /// specified loop is immediately inside of the loop.
5237 /// This method can be used to compute the exit value for a variable defined
5238 /// in a loop by querying what the value will hold in the parent loop.
5240 /// In the case that a relevant loop exit value cannot be computed, the
5241 /// original value V is returned.
5242 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
5243 // Check to see if we've folded this expression at this loop before.
5244 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5245 for (unsigned u = 0; u < Values.size(); u++) {
5246 if (Values[u].first == L)
5247 return Values[u].second ? Values[u].second : V;
5249 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
5250 // Otherwise compute it.
5251 const SCEV *C = computeSCEVAtScope(V, L);
5252 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5253 for (unsigned u = Values2.size(); u > 0; u--) {
5254 if (Values2[u - 1].first == L) {
5255 Values2[u - 1].second = C;
5262 /// This builds up a Constant using the ConstantExpr interface. That way, we
5263 /// will return Constants for objects which aren't represented by a
5264 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5265 /// Returns NULL if the SCEV isn't representable as a Constant.
5266 static Constant *BuildConstantFromSCEV(const SCEV *V) {
5267 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
5268 case scCouldNotCompute:
5272 return cast<SCEVConstant>(V)->getValue();
5274 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5275 case scSignExtend: {
5276 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5277 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5278 return ConstantExpr::getSExt(CastOp, SS->getType());
5281 case scZeroExtend: {
5282 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5283 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5284 return ConstantExpr::getZExt(CastOp, SZ->getType());
5288 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5289 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5290 return ConstantExpr::getTrunc(CastOp, ST->getType());
5294 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5295 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5296 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5297 unsigned AS = PTy->getAddressSpace();
5298 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5299 C = ConstantExpr::getBitCast(C, DestPtrTy);
5301 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5302 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5303 if (!C2) return nullptr;
5306 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5307 unsigned AS = C2->getType()->getPointerAddressSpace();
5309 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5310 // The offsets have been converted to bytes. We can add bytes to an
5311 // i8* by GEP with the byte count in the first index.
5312 C = ConstantExpr::getBitCast(C, DestPtrTy);
5315 // Don't bother trying to sum two pointers. We probably can't
5316 // statically compute a load that results from it anyway.
5317 if (C2->getType()->isPointerTy())
5320 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5321 if (PTy->getElementType()->isStructTy())
5322 C2 = ConstantExpr::getIntegerCast(
5323 C2, Type::getInt32Ty(C->getContext()), true);
5324 C = ConstantExpr::getGetElementPtr(C, C2);
5326 C = ConstantExpr::getAdd(C, C2);
5333 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5334 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5335 // Don't bother with pointers at all.
5336 if (C->getType()->isPointerTy()) return nullptr;
5337 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5338 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
5339 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
5340 C = ConstantExpr::getMul(C, C2);
5347 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5348 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5349 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5350 if (LHS->getType() == RHS->getType())
5351 return ConstantExpr::getUDiv(LHS, RHS);
5356 break; // TODO: smax, umax.
5361 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
5362 if (isa<SCEVConstant>(V)) return V;
5364 // If this instruction is evolved from a constant-evolving PHI, compute the
5365 // exit value from the loop without using SCEVs.
5366 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
5367 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
5368 const Loop *LI = (*this->LI)[I->getParent()];
5369 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5370 if (PHINode *PN = dyn_cast<PHINode>(I))
5371 if (PN->getParent() == LI->getHeader()) {
5372 // Okay, there is no closed form solution for the PHI node. Check
5373 // to see if the loop that contains it has a known backedge-taken
5374 // count. If so, we may be able to force computation of the exit
5376 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
5377 if (const SCEVConstant *BTCC =
5378 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
5379 // Okay, we know how many times the containing loop executes. If
5380 // this is a constant evolving PHI node, get the final value at
5381 // the specified iteration number.
5382 Constant *RV = getConstantEvolutionLoopExitValue(PN,
5383 BTCC->getValue()->getValue(),
5385 if (RV) return getSCEV(RV);
5389 // Okay, this is an expression that we cannot symbolically evaluate
5390 // into a SCEV. Check to see if it's possible to symbolically evaluate
5391 // the arguments into constants, and if so, try to constant propagate the
5392 // result. This is particularly useful for computing loop exit values.
5393 if (CanConstantFold(I)) {
5394 SmallVector<Constant *, 4> Operands;
5395 bool MadeImprovement = false;
5396 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5397 Value *Op = I->getOperand(i);
5398 if (Constant *C = dyn_cast<Constant>(Op)) {
5399 Operands.push_back(C);
5403 // If any of the operands is non-constant and if they are
5404 // non-integer and non-pointer, don't even try to analyze them
5405 // with scev techniques.
5406 if (!isSCEVable(Op->getType()))
5409 const SCEV *OrigV = getSCEV(Op);
5410 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5411 MadeImprovement |= OrigV != OpV;
5413 Constant *C = BuildConstantFromSCEV(OpV);
5415 if (C->getType() != Op->getType())
5416 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5420 Operands.push_back(C);
5423 // Check to see if getSCEVAtScope actually made an improvement.
5424 if (MadeImprovement) {
5425 Constant *C = nullptr;
5426 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5427 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
5428 Operands[0], Operands[1], DL,
5430 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5431 if (!LI->isVolatile())
5432 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
5434 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
5442 // This is some other type of SCEVUnknown, just return it.
5446 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
5447 // Avoid performing the look-up in the common case where the specified
5448 // expression has no loop-variant portions.
5449 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
5450 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5451 if (OpAtScope != Comm->getOperand(i)) {
5452 // Okay, at least one of these operands is loop variant but might be
5453 // foldable. Build a new instance of the folded commutative expression.
5454 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5455 Comm->op_begin()+i);
5456 NewOps.push_back(OpAtScope);
5458 for (++i; i != e; ++i) {
5459 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5460 NewOps.push_back(OpAtScope);
5462 if (isa<SCEVAddExpr>(Comm))
5463 return getAddExpr(NewOps);
5464 if (isa<SCEVMulExpr>(Comm))
5465 return getMulExpr(NewOps);
5466 if (isa<SCEVSMaxExpr>(Comm))
5467 return getSMaxExpr(NewOps);
5468 if (isa<SCEVUMaxExpr>(Comm))
5469 return getUMaxExpr(NewOps);
5470 llvm_unreachable("Unknown commutative SCEV type!");
5473 // If we got here, all operands are loop invariant.
5477 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
5478 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5479 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
5480 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5481 return Div; // must be loop invariant
5482 return getUDivExpr(LHS, RHS);
5485 // If this is a loop recurrence for a loop that does not contain L, then we
5486 // are dealing with the final value computed by the loop.
5487 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5488 // First, attempt to evaluate each operand.
5489 // Avoid performing the look-up in the common case where the specified
5490 // expression has no loop-variant portions.
5491 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5492 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5493 if (OpAtScope == AddRec->getOperand(i))
5496 // Okay, at least one of these operands is loop variant but might be
5497 // foldable. Build a new instance of the folded commutative expression.
5498 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5499 AddRec->op_begin()+i);
5500 NewOps.push_back(OpAtScope);
5501 for (++i; i != e; ++i)
5502 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5504 const SCEV *FoldedRec =
5505 getAddRecExpr(NewOps, AddRec->getLoop(),
5506 AddRec->getNoWrapFlags(SCEV::FlagNW));
5507 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
5508 // The addrec may be folded to a nonrecurrence, for example, if the
5509 // induction variable is multiplied by zero after constant folding. Go
5510 // ahead and return the folded value.
5516 // If the scope is outside the addrec's loop, evaluate it by using the
5517 // loop exit value of the addrec.
5518 if (!AddRec->getLoop()->contains(L)) {
5519 // To evaluate this recurrence, we need to know how many times the AddRec
5520 // loop iterates. Compute this now.
5521 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
5522 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
5524 // Then, evaluate the AddRec.
5525 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
5531 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
5532 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5533 if (Op == Cast->getOperand())
5534 return Cast; // must be loop invariant
5535 return getZeroExtendExpr(Op, Cast->getType());
5538 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
5539 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5540 if (Op == Cast->getOperand())
5541 return Cast; // must be loop invariant
5542 return getSignExtendExpr(Op, Cast->getType());
5545 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
5546 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5547 if (Op == Cast->getOperand())
5548 return Cast; // must be loop invariant
5549 return getTruncateExpr(Op, Cast->getType());
5552 llvm_unreachable("Unknown SCEV type!");
5555 /// getSCEVAtScope - This is a convenience function which does
5556 /// getSCEVAtScope(getSCEV(V), L).
5557 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
5558 return getSCEVAtScope(getSCEV(V), L);
5561 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5562 /// following equation:
5564 /// A * X = B (mod N)
5566 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5567 /// A and B isn't important.
5569 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
5570 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
5571 ScalarEvolution &SE) {
5572 uint32_t BW = A.getBitWidth();
5573 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5574 assert(A != 0 && "A must be non-zero.");
5578 // The gcd of A and N may have only one prime factor: 2. The number of
5579 // trailing zeros in A is its multiplicity
5580 uint32_t Mult2 = A.countTrailingZeros();
5583 // 2. Check if B is divisible by D.
5585 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5586 // is not less than multiplicity of this prime factor for D.
5587 if (B.countTrailingZeros() < Mult2)
5588 return SE.getCouldNotCompute();
5590 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5593 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5594 // bit width during computations.
5595 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5596 APInt Mod(BW + 1, 0);
5597 Mod.setBit(BW - Mult2); // Mod = N / D
5598 APInt I = AD.multiplicativeInverse(Mod);
5600 // 4. Compute the minimum unsigned root of the equation:
5601 // I * (B / D) mod (N / D)
5602 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5604 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5606 return SE.getConstant(Result.trunc(BW));
5609 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5610 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5611 /// might be the same) or two SCEVCouldNotCompute objects.
5613 static std::pair<const SCEV *,const SCEV *>
5614 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
5615 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
5616 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5617 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5618 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
5620 // We currently can only solve this if the coefficients are constants.
5621 if (!LC || !MC || !NC) {
5622 const SCEV *CNC = SE.getCouldNotCompute();
5623 return std::make_pair(CNC, CNC);
5626 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
5627 const APInt &L = LC->getValue()->getValue();
5628 const APInt &M = MC->getValue()->getValue();
5629 const APInt &N = NC->getValue()->getValue();
5630 APInt Two(BitWidth, 2);
5631 APInt Four(BitWidth, 4);
5634 using namespace APIntOps;
5636 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5637 // The B coefficient is M-N/2
5641 // The A coefficient is N/2
5642 APInt A(N.sdiv(Two));
5644 // Compute the B^2-4ac term.
5647 SqrtTerm -= Four * (A * C);
5649 if (SqrtTerm.isNegative()) {
5650 // The loop is provably infinite.
5651 const SCEV *CNC = SE.getCouldNotCompute();
5652 return std::make_pair(CNC, CNC);
5655 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5656 // integer value or else APInt::sqrt() will assert.
5657 APInt SqrtVal(SqrtTerm.sqrt());
5659 // Compute the two solutions for the quadratic formula.
5660 // The divisions must be performed as signed divisions.
5663 if (TwoA.isMinValue()) {
5664 const SCEV *CNC = SE.getCouldNotCompute();
5665 return std::make_pair(CNC, CNC);
5668 LLVMContext &Context = SE.getContext();
5670 ConstantInt *Solution1 =
5671 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
5672 ConstantInt *Solution2 =
5673 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
5675 return std::make_pair(SE.getConstant(Solution1),
5676 SE.getConstant(Solution2));
5677 } // end APIntOps namespace
5680 /// HowFarToZero - Return the number of times a backedge comparing the specified
5681 /// value to zero will execute. If not computable, return CouldNotCompute.
5683 /// This is only used for loops with a "x != y" exit test. The exit condition is
5684 /// now expressed as a single expression, V = x-y. So the exit test is
5685 /// effectively V != 0. We know and take advantage of the fact that this
5686 /// expression only being used in a comparison by zero context.
5687 ScalarEvolution::ExitLimit
5688 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr) {
5689 // If the value is a constant
5690 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5691 // If the value is already zero, the branch will execute zero times.
5692 if (C->getValue()->isZero()) return C;
5693 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5696 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
5697 if (!AddRec || AddRec->getLoop() != L)
5698 return getCouldNotCompute();
5700 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5701 // the quadratic equation to solve it.
5702 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5703 std::pair<const SCEV *,const SCEV *> Roots =
5704 SolveQuadraticEquation(AddRec, *this);
5705 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5706 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5709 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
5710 << " sol#2: " << *R2 << "\n";
5712 // Pick the smallest positive root value.
5713 if (ConstantInt *CB =
5714 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5717 if (CB->getZExtValue() == false)
5718 std::swap(R1, R2); // R1 is the minimum root now.
5720 // We can only use this value if the chrec ends up with an exact zero
5721 // value at this index. When solving for "X*X != 5", for example, we
5722 // should not accept a root of 2.
5723 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
5725 return R1; // We found a quadratic root!
5728 return getCouldNotCompute();
5731 // Otherwise we can only handle this if it is affine.
5732 if (!AddRec->isAffine())
5733 return getCouldNotCompute();
5735 // If this is an affine expression, the execution count of this branch is
5736 // the minimum unsigned root of the following equation:
5738 // Start + Step*N = 0 (mod 2^BW)
5742 // Step*N = -Start (mod 2^BW)
5744 // where BW is the common bit width of Start and Step.
5746 // Get the initial value for the loop.
5747 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5748 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5750 // For now we handle only constant steps.
5752 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5753 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5754 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5755 // We have not yet seen any such cases.
5756 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5757 if (!StepC || StepC->getValue()->equalsInt(0))
5758 return getCouldNotCompute();
5760 // For positive steps (counting up until unsigned overflow):
5761 // N = -Start/Step (as unsigned)
5762 // For negative steps (counting down to zero):
5764 // First compute the unsigned distance from zero in the direction of Step.
5765 bool CountDown = StepC->getValue()->getValue().isNegative();
5766 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
5768 // Handle unitary steps, which cannot wraparound.
5769 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5770 // N = Distance (as unsigned)
5771 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
5772 ConstantRange CR = getUnsignedRange(Start);
5773 const SCEV *MaxBECount;
5774 if (!CountDown && CR.getUnsignedMin().isMinValue())
5775 // When counting up, the worst starting value is 1, not 0.
5776 MaxBECount = CR.getUnsignedMax().isMinValue()
5777 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
5778 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
5780 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
5781 : -CR.getUnsignedMin());
5782 return ExitLimit(Distance, MaxBECount, /*MustExit=*/true);
5785 // If the recurrence is known not to wraparound, unsigned divide computes the
5786 // back edge count. (Ideally we would have an "isexact" bit for udiv). We know
5787 // that the value will either become zero (and thus the loop terminates), that
5788 // the loop will terminate through some other exit condition first, or that
5789 // the loop has undefined behavior. This means we can't "miss" the exit
5790 // value, even with nonunit stride, and exit later via the same branch. Note
5791 // that we can skip this exit if loop later exits via a different
5792 // branch. Hence MustExit=false.
5794 // This is only valid for expressions that directly compute the loop exit. It
5795 // is invalid for subexpressions in which the loop may exit through this
5796 // branch even if this subexpression is false. In that case, the trip count
5797 // computed by this udiv could be smaller than the number of well-defined
5799 if (!IsSubExpr && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
5801 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
5802 return ExitLimit(Exact, Exact, /*MustExit=*/false);
5805 // If Step is a power of two that evenly divides Start we know that the loop
5806 // will always terminate. Start may not be a constant so we just have the
5807 // number of trailing zeros available. This is safe even in presence of
5808 // overflow as the recurrence will overflow to exactly 0.
5809 const APInt &StepV = StepC->getValue()->getValue();
5810 if (StepV.isPowerOf2() &&
5811 GetMinTrailingZeros(getNegativeSCEV(Start)) >= StepV.countTrailingZeros())
5812 return getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
5814 // Then, try to solve the above equation provided that Start is constant.
5815 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5816 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5817 -StartC->getValue()->getValue(),
5819 return getCouldNotCompute();
5822 /// HowFarToNonZero - Return the number of times a backedge checking the
5823 /// specified value for nonzero will execute. If not computable, return
5825 ScalarEvolution::ExitLimit
5826 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
5827 // Loops that look like: while (X == 0) are very strange indeed. We don't
5828 // handle them yet except for the trivial case. This could be expanded in the
5829 // future as needed.
5831 // If the value is a constant, check to see if it is known to be non-zero
5832 // already. If so, the backedge will execute zero times.
5833 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5834 if (!C->getValue()->isNullValue())
5835 return getConstant(C->getType(), 0);
5836 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5839 // We could implement others, but I really doubt anyone writes loops like
5840 // this, and if they did, they would already be constant folded.
5841 return getCouldNotCompute();
5844 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5845 /// (which may not be an immediate predecessor) which has exactly one
5846 /// successor from which BB is reachable, or null if no such block is
5849 std::pair<BasicBlock *, BasicBlock *>
5850 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
5851 // If the block has a unique predecessor, then there is no path from the
5852 // predecessor to the block that does not go through the direct edge
5853 // from the predecessor to the block.
5854 if (BasicBlock *Pred = BB->getSinglePredecessor())
5855 return std::make_pair(Pred, BB);
5857 // A loop's header is defined to be a block that dominates the loop.
5858 // If the header has a unique predecessor outside the loop, it must be
5859 // a block that has exactly one successor that can reach the loop.
5860 if (Loop *L = LI->getLoopFor(BB))
5861 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
5863 return std::pair<BasicBlock *, BasicBlock *>();
5866 /// HasSameValue - SCEV structural equivalence is usually sufficient for
5867 /// testing whether two expressions are equal, however for the purposes of
5868 /// looking for a condition guarding a loop, it can be useful to be a little
5869 /// more general, since a front-end may have replicated the controlling
5872 static bool HasSameValue(const SCEV *A, const SCEV *B) {
5873 // Quick check to see if they are the same SCEV.
5874 if (A == B) return true;
5876 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5877 // two different instructions with the same value. Check for this case.
5878 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5879 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5880 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5881 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
5882 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
5885 // Otherwise assume they may have a different value.
5889 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5890 /// predicate Pred. Return true iff any changes were made.
5892 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5893 const SCEV *&LHS, const SCEV *&RHS,
5895 bool Changed = false;
5897 // If we hit the max recursion limit bail out.
5901 // Canonicalize a constant to the right side.
5902 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5903 // Check for both operands constant.
5904 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5905 if (ConstantExpr::getICmp(Pred,
5907 RHSC->getValue())->isNullValue())
5908 goto trivially_false;
5910 goto trivially_true;
5912 // Otherwise swap the operands to put the constant on the right.
5913 std::swap(LHS, RHS);
5914 Pred = ICmpInst::getSwappedPredicate(Pred);
5918 // If we're comparing an addrec with a value which is loop-invariant in the
5919 // addrec's loop, put the addrec on the left. Also make a dominance check,
5920 // as both operands could be addrecs loop-invariant in each other's loop.
5921 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5922 const Loop *L = AR->getLoop();
5923 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
5924 std::swap(LHS, RHS);
5925 Pred = ICmpInst::getSwappedPredicate(Pred);
5930 // If there's a constant operand, canonicalize comparisons with boundary
5931 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5932 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5933 const APInt &RA = RC->getValue()->getValue();
5935 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5936 case ICmpInst::ICMP_EQ:
5937 case ICmpInst::ICMP_NE:
5938 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
5940 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
5941 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
5942 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
5943 ME->getOperand(0)->isAllOnesValue()) {
5944 RHS = AE->getOperand(1);
5945 LHS = ME->getOperand(1);
5949 case ICmpInst::ICMP_UGE:
5950 if ((RA - 1).isMinValue()) {
5951 Pred = ICmpInst::ICMP_NE;
5952 RHS = getConstant(RA - 1);
5956 if (RA.isMaxValue()) {
5957 Pred = ICmpInst::ICMP_EQ;
5961 if (RA.isMinValue()) goto trivially_true;
5963 Pred = ICmpInst::ICMP_UGT;
5964 RHS = getConstant(RA - 1);
5967 case ICmpInst::ICMP_ULE:
5968 if ((RA + 1).isMaxValue()) {
5969 Pred = ICmpInst::ICMP_NE;
5970 RHS = getConstant(RA + 1);
5974 if (RA.isMinValue()) {
5975 Pred = ICmpInst::ICMP_EQ;
5979 if (RA.isMaxValue()) goto trivially_true;
5981 Pred = ICmpInst::ICMP_ULT;
5982 RHS = getConstant(RA + 1);
5985 case ICmpInst::ICMP_SGE:
5986 if ((RA - 1).isMinSignedValue()) {
5987 Pred = ICmpInst::ICMP_NE;
5988 RHS = getConstant(RA - 1);
5992 if (RA.isMaxSignedValue()) {
5993 Pred = ICmpInst::ICMP_EQ;
5997 if (RA.isMinSignedValue()) goto trivially_true;
5999 Pred = ICmpInst::ICMP_SGT;
6000 RHS = getConstant(RA - 1);
6003 case ICmpInst::ICMP_SLE:
6004 if ((RA + 1).isMaxSignedValue()) {
6005 Pred = ICmpInst::ICMP_NE;
6006 RHS = getConstant(RA + 1);
6010 if (RA.isMinSignedValue()) {
6011 Pred = ICmpInst::ICMP_EQ;
6015 if (RA.isMaxSignedValue()) goto trivially_true;
6017 Pred = ICmpInst::ICMP_SLT;
6018 RHS = getConstant(RA + 1);
6021 case ICmpInst::ICMP_UGT:
6022 if (RA.isMinValue()) {
6023 Pred = ICmpInst::ICMP_NE;
6027 if ((RA + 1).isMaxValue()) {
6028 Pred = ICmpInst::ICMP_EQ;
6029 RHS = getConstant(RA + 1);
6033 if (RA.isMaxValue()) goto trivially_false;
6035 case ICmpInst::ICMP_ULT:
6036 if (RA.isMaxValue()) {
6037 Pred = ICmpInst::ICMP_NE;
6041 if ((RA - 1).isMinValue()) {
6042 Pred = ICmpInst::ICMP_EQ;
6043 RHS = getConstant(RA - 1);
6047 if (RA.isMinValue()) goto trivially_false;
6049 case ICmpInst::ICMP_SGT:
6050 if (RA.isMinSignedValue()) {
6051 Pred = ICmpInst::ICMP_NE;
6055 if ((RA + 1).isMaxSignedValue()) {
6056 Pred = ICmpInst::ICMP_EQ;
6057 RHS = getConstant(RA + 1);
6061 if (RA.isMaxSignedValue()) goto trivially_false;
6063 case ICmpInst::ICMP_SLT:
6064 if (RA.isMaxSignedValue()) {
6065 Pred = ICmpInst::ICMP_NE;
6069 if ((RA - 1).isMinSignedValue()) {
6070 Pred = ICmpInst::ICMP_EQ;
6071 RHS = getConstant(RA - 1);
6075 if (RA.isMinSignedValue()) goto trivially_false;
6080 // Check for obvious equality.
6081 if (HasSameValue(LHS, RHS)) {
6082 if (ICmpInst::isTrueWhenEqual(Pred))
6083 goto trivially_true;
6084 if (ICmpInst::isFalseWhenEqual(Pred))
6085 goto trivially_false;
6088 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6089 // adding or subtracting 1 from one of the operands.
6091 case ICmpInst::ICMP_SLE:
6092 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6093 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6095 Pred = ICmpInst::ICMP_SLT;
6097 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
6098 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6100 Pred = ICmpInst::ICMP_SLT;
6104 case ICmpInst::ICMP_SGE:
6105 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
6106 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6108 Pred = ICmpInst::ICMP_SGT;
6110 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6111 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6113 Pred = ICmpInst::ICMP_SGT;
6117 case ICmpInst::ICMP_ULE:
6118 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
6119 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6121 Pred = ICmpInst::ICMP_ULT;
6123 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
6124 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6126 Pred = ICmpInst::ICMP_ULT;
6130 case ICmpInst::ICMP_UGE:
6131 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
6132 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6134 Pred = ICmpInst::ICMP_UGT;
6136 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
6137 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6139 Pred = ICmpInst::ICMP_UGT;
6147 // TODO: More simplifications are possible here.
6149 // Recursively simplify until we either hit a recursion limit or nothing
6152 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6158 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6159 Pred = ICmpInst::ICMP_EQ;
6164 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6165 Pred = ICmpInst::ICMP_NE;
6169 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6170 return getSignedRange(S).getSignedMax().isNegative();
6173 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6174 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6177 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6178 return !getSignedRange(S).getSignedMin().isNegative();
6181 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6182 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6185 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6186 return isKnownNegative(S) || isKnownPositive(S);
6189 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6190 const SCEV *LHS, const SCEV *RHS) {
6191 // Canonicalize the inputs first.
6192 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6194 // If LHS or RHS is an addrec, check to see if the condition is true in
6195 // every iteration of the loop.
6196 // If LHS and RHS are both addrec, both conditions must be true in
6197 // every iteration of the loop.
6198 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6199 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6200 bool LeftGuarded = false;
6201 bool RightGuarded = false;
6203 const Loop *L = LAR->getLoop();
6204 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6205 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6206 if (!RAR) return true;
6211 const Loop *L = RAR->getLoop();
6212 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6213 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6214 if (!LAR) return true;
6215 RightGuarded = true;
6218 if (LeftGuarded && RightGuarded)
6221 // Otherwise see what can be done with known constant ranges.
6222 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6226 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6227 const SCEV *LHS, const SCEV *RHS) {
6228 if (HasSameValue(LHS, RHS))
6229 return ICmpInst::isTrueWhenEqual(Pred);
6231 // This code is split out from isKnownPredicate because it is called from
6232 // within isLoopEntryGuardedByCond.
6235 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6236 case ICmpInst::ICMP_SGT:
6237 std::swap(LHS, RHS);
6238 case ICmpInst::ICMP_SLT: {
6239 ConstantRange LHSRange = getSignedRange(LHS);
6240 ConstantRange RHSRange = getSignedRange(RHS);
6241 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6243 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6247 case ICmpInst::ICMP_SGE:
6248 std::swap(LHS, RHS);
6249 case ICmpInst::ICMP_SLE: {
6250 ConstantRange LHSRange = getSignedRange(LHS);
6251 ConstantRange RHSRange = getSignedRange(RHS);
6252 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6254 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6258 case ICmpInst::ICMP_UGT:
6259 std::swap(LHS, RHS);
6260 case ICmpInst::ICMP_ULT: {
6261 ConstantRange LHSRange = getUnsignedRange(LHS);
6262 ConstantRange RHSRange = getUnsignedRange(RHS);
6263 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6265 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6269 case ICmpInst::ICMP_UGE:
6270 std::swap(LHS, RHS);
6271 case ICmpInst::ICMP_ULE: {
6272 ConstantRange LHSRange = getUnsignedRange(LHS);
6273 ConstantRange RHSRange = getUnsignedRange(RHS);
6274 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6276 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6280 case ICmpInst::ICMP_NE: {
6281 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6283 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6286 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6287 if (isKnownNonZero(Diff))
6291 case ICmpInst::ICMP_EQ:
6292 // The check at the top of the function catches the case where
6293 // the values are known to be equal.
6299 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6300 /// protected by a conditional between LHS and RHS. This is used to
6301 /// to eliminate casts.
6303 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6304 ICmpInst::Predicate Pred,
6305 const SCEV *LHS, const SCEV *RHS) {
6306 // Interpret a null as meaning no loop, where there is obviously no guard
6307 // (interprocedural conditions notwithstanding).
6308 if (!L) return true;
6310 BasicBlock *Latch = L->getLoopLatch();
6314 BranchInst *LoopContinuePredicate =
6315 dyn_cast<BranchInst>(Latch->getTerminator());
6316 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6317 isImpliedCond(Pred, LHS, RHS,
6318 LoopContinuePredicate->getCondition(),
6319 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6322 // Check conditions due to any @llvm.assume intrinsics.
6323 for (auto &CI : AT->assumptions(F)) {
6324 if (!DT->dominates(CI, Latch->getTerminator()))
6327 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6334 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
6335 /// by a conditional between LHS and RHS. This is used to help avoid max
6336 /// expressions in loop trip counts, and to eliminate casts.
6338 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6339 ICmpInst::Predicate Pred,
6340 const SCEV *LHS, const SCEV *RHS) {
6341 // Interpret a null as meaning no loop, where there is obviously no guard
6342 // (interprocedural conditions notwithstanding).
6343 if (!L) return false;
6345 // Starting at the loop predecessor, climb up the predecessor chain, as long
6346 // as there are predecessors that can be found that have unique successors
6347 // leading to the original header.
6348 for (std::pair<BasicBlock *, BasicBlock *>
6349 Pair(L->getLoopPredecessor(), L->getHeader());
6351 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
6353 BranchInst *LoopEntryPredicate =
6354 dyn_cast<BranchInst>(Pair.first->getTerminator());
6355 if (!LoopEntryPredicate ||
6356 LoopEntryPredicate->isUnconditional())
6359 if (isImpliedCond(Pred, LHS, RHS,
6360 LoopEntryPredicate->getCondition(),
6361 LoopEntryPredicate->getSuccessor(0) != Pair.second))
6365 // Check conditions due to any @llvm.assume intrinsics.
6366 for (auto &CI : AT->assumptions(F)) {
6367 if (!DT->dominates(CI, L->getHeader()))
6370 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6377 /// RAII wrapper to prevent recursive application of isImpliedCond.
6378 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6379 /// currently evaluating isImpliedCond.
6380 struct MarkPendingLoopPredicate {
6382 DenseSet<Value*> &LoopPreds;
6385 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6386 : Cond(C), LoopPreds(LP) {
6387 Pending = !LoopPreds.insert(Cond).second;
6389 ~MarkPendingLoopPredicate() {
6391 LoopPreds.erase(Cond);
6395 /// isImpliedCond - Test whether the condition described by Pred, LHS,
6396 /// and RHS is true whenever the given Cond value evaluates to true.
6397 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
6398 const SCEV *LHS, const SCEV *RHS,
6399 Value *FoundCondValue,
6401 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6405 // Recursively handle And and Or conditions.
6406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
6407 if (BO->getOpcode() == Instruction::And) {
6409 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6410 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6411 } else if (BO->getOpcode() == Instruction::Or) {
6413 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6414 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6418 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
6419 if (!ICI) return false;
6421 // Bail if the ICmp's operands' types are wider than the needed type
6422 // before attempting to call getSCEV on them. This avoids infinite
6423 // recursion, since the analysis of widening casts can require loop
6424 // exit condition information for overflow checking, which would
6426 if (getTypeSizeInBits(LHS->getType()) <
6427 getTypeSizeInBits(ICI->getOperand(0)->getType()))
6430 // Now that we found a conditional branch that dominates the loop or controls
6431 // the loop latch. Check to see if it is the comparison we are looking for.
6432 ICmpInst::Predicate FoundPred;
6434 FoundPred = ICI->getInversePredicate();
6436 FoundPred = ICI->getPredicate();
6438 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6439 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
6441 // Balance the types. The case where FoundLHS' type is wider than
6442 // LHS' type is checked for above.
6443 if (getTypeSizeInBits(LHS->getType()) >
6444 getTypeSizeInBits(FoundLHS->getType())) {
6445 if (CmpInst::isSigned(FoundPred)) {
6446 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6447 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6449 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6450 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6454 // Canonicalize the query to match the way instcombine will have
6455 // canonicalized the comparison.
6456 if (SimplifyICmpOperands(Pred, LHS, RHS))
6458 return CmpInst::isTrueWhenEqual(Pred);
6459 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6460 if (FoundLHS == FoundRHS)
6461 return CmpInst::isFalseWhenEqual(FoundPred);
6463 // Check to see if we can make the LHS or RHS match.
6464 if (LHS == FoundRHS || RHS == FoundLHS) {
6465 if (isa<SCEVConstant>(RHS)) {
6466 std::swap(FoundLHS, FoundRHS);
6467 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6469 std::swap(LHS, RHS);
6470 Pred = ICmpInst::getSwappedPredicate(Pred);
6474 // Check whether the found predicate is the same as the desired predicate.
6475 if (FoundPred == Pred)
6476 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6478 // Check whether swapping the found predicate makes it the same as the
6479 // desired predicate.
6480 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6481 if (isa<SCEVConstant>(RHS))
6482 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6484 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6485 RHS, LHS, FoundLHS, FoundRHS);
6488 // Check whether the actual condition is beyond sufficient.
6489 if (FoundPred == ICmpInst::ICMP_EQ)
6490 if (ICmpInst::isTrueWhenEqual(Pred))
6491 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6493 if (Pred == ICmpInst::ICMP_NE)
6494 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6495 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6498 // Otherwise assume the worst.
6502 /// isImpliedCondOperands - Test whether the condition described by Pred,
6503 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
6504 /// and FoundRHS is true.
6505 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6506 const SCEV *LHS, const SCEV *RHS,
6507 const SCEV *FoundLHS,
6508 const SCEV *FoundRHS) {
6509 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6510 FoundLHS, FoundRHS) ||
6511 // ~x < ~y --> x > y
6512 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6513 getNotSCEV(FoundRHS),
6514 getNotSCEV(FoundLHS));
6517 /// isImpliedCondOperandsHelper - Test whether the condition described by
6518 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
6519 /// FoundLHS, and FoundRHS is true.
6521 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6522 const SCEV *LHS, const SCEV *RHS,
6523 const SCEV *FoundLHS,
6524 const SCEV *FoundRHS) {
6526 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6527 case ICmpInst::ICMP_EQ:
6528 case ICmpInst::ICMP_NE:
6529 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6532 case ICmpInst::ICMP_SLT:
6533 case ICmpInst::ICMP_SLE:
6534 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6535 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
6538 case ICmpInst::ICMP_SGT:
6539 case ICmpInst::ICMP_SGE:
6540 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6541 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
6544 case ICmpInst::ICMP_ULT:
6545 case ICmpInst::ICMP_ULE:
6546 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6547 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
6550 case ICmpInst::ICMP_UGT:
6551 case ICmpInst::ICMP_UGE:
6552 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6553 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
6561 // Verify if an linear IV with positive stride can overflow when in a
6562 // less-than comparison, knowing the invariant term of the comparison, the
6563 // stride and the knowledge of NSW/NUW flags on the recurrence.
6564 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
6565 bool IsSigned, bool NoWrap) {
6566 if (NoWrap) return false;
6568 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6569 const SCEV *One = getConstant(Stride->getType(), 1);
6572 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
6573 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
6574 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6577 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
6578 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
6581 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
6582 APInt MaxValue = APInt::getMaxValue(BitWidth);
6583 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6586 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
6587 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
6590 // Verify if an linear IV with negative stride can overflow when in a
6591 // greater-than comparison, knowing the invariant term of the comparison,
6592 // the stride and the knowledge of NSW/NUW flags on the recurrence.
6593 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
6594 bool IsSigned, bool NoWrap) {
6595 if (NoWrap) return false;
6597 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6598 const SCEV *One = getConstant(Stride->getType(), 1);
6601 APInt MinRHS = getSignedRange(RHS).getSignedMin();
6602 APInt MinValue = APInt::getSignedMinValue(BitWidth);
6603 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6606 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
6607 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
6610 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
6611 APInt MinValue = APInt::getMinValue(BitWidth);
6612 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6615 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
6616 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
6619 // Compute the backedge taken count knowing the interval difference, the
6620 // stride and presence of the equality in the comparison.
6621 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
6623 const SCEV *One = getConstant(Step->getType(), 1);
6624 Delta = Equality ? getAddExpr(Delta, Step)
6625 : getAddExpr(Delta, getMinusSCEV(Step, One));
6626 return getUDivExpr(Delta, Step);
6629 /// HowManyLessThans - Return the number of times a backedge containing the
6630 /// specified less-than comparison will execute. If not computable, return
6631 /// CouldNotCompute.
6633 /// @param IsSubExpr is true when the LHS < RHS condition does not directly
6634 /// control the branch. In this case, we can only compute an iteration count for
6635 /// a subexpression that cannot overflow before evaluating true.
6636 ScalarEvolution::ExitLimit
6637 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
6638 const Loop *L, bool IsSigned,
6640 // We handle only IV < Invariant
6641 if (!isLoopInvariant(RHS, L))
6642 return getCouldNotCompute();
6644 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
6646 // Avoid weird loops
6647 if (!IV || IV->getLoop() != L || !IV->isAffine())
6648 return getCouldNotCompute();
6650 bool NoWrap = !IsSubExpr &&
6651 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
6653 const SCEV *Stride = IV->getStepRecurrence(*this);
6655 // Avoid negative or zero stride values
6656 if (!isKnownPositive(Stride))
6657 return getCouldNotCompute();
6659 // Avoid proven overflow cases: this will ensure that the backedge taken count
6660 // will not generate any unsigned overflow. Relaxed no-overflow conditions
6661 // exploit NoWrapFlags, allowing to optimize in presence of undefined
6662 // behaviors like the case of C language.
6663 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
6664 return getCouldNotCompute();
6666 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
6667 : ICmpInst::ICMP_ULT;
6668 const SCEV *Start = IV->getStart();
6669 const SCEV *End = RHS;
6670 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
6671 End = IsSigned ? getSMaxExpr(RHS, Start)
6672 : getUMaxExpr(RHS, Start);
6674 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
6676 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
6677 : getUnsignedRange(Start).getUnsignedMin();
6679 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
6680 : getUnsignedRange(Stride).getUnsignedMin();
6682 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
6683 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
6684 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
6686 // Although End can be a MAX expression we estimate MaxEnd considering only
6687 // the case End = RHS. This is safe because in the other case (End - Start)
6688 // is zero, leading to a zero maximum backedge taken count.
6690 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
6691 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
6693 const SCEV *MaxBECount;
6694 if (isa<SCEVConstant>(BECount))
6695 MaxBECount = BECount;
6697 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
6698 getConstant(MinStride), false);
6700 if (isa<SCEVCouldNotCompute>(MaxBECount))
6701 MaxBECount = BECount;
6703 return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
6706 ScalarEvolution::ExitLimit
6707 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
6708 const Loop *L, bool IsSigned,
6710 // We handle only IV > Invariant
6711 if (!isLoopInvariant(RHS, L))
6712 return getCouldNotCompute();
6714 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
6716 // Avoid weird loops
6717 if (!IV || IV->getLoop() != L || !IV->isAffine())
6718 return getCouldNotCompute();
6720 bool NoWrap = !IsSubExpr &&
6721 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
6723 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
6725 // Avoid negative or zero stride values
6726 if (!isKnownPositive(Stride))
6727 return getCouldNotCompute();
6729 // Avoid proven overflow cases: this will ensure that the backedge taken count
6730 // will not generate any unsigned overflow. Relaxed no-overflow conditions
6731 // exploit NoWrapFlags, allowing to optimize in presence of undefined
6732 // behaviors like the case of C language.
6733 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
6734 return getCouldNotCompute();
6736 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
6737 : ICmpInst::ICMP_UGT;
6739 const SCEV *Start = IV->getStart();
6740 const SCEV *End = RHS;
6741 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
6742 End = IsSigned ? getSMinExpr(RHS, Start)
6743 : getUMinExpr(RHS, Start);
6745 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
6747 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
6748 : getUnsignedRange(Start).getUnsignedMax();
6750 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
6751 : getUnsignedRange(Stride).getUnsignedMin();
6753 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
6754 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
6755 : APInt::getMinValue(BitWidth) + (MinStride - 1);
6757 // Although End can be a MIN expression we estimate MinEnd considering only
6758 // the case End = RHS. This is safe because in the other case (Start - End)
6759 // is zero, leading to a zero maximum backedge taken count.
6761 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
6762 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
6765 const SCEV *MaxBECount = getCouldNotCompute();
6766 if (isa<SCEVConstant>(BECount))
6767 MaxBECount = BECount;
6769 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
6770 getConstant(MinStride), false);
6772 if (isa<SCEVCouldNotCompute>(MaxBECount))
6773 MaxBECount = BECount;
6775 return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
6778 /// getNumIterationsInRange - Return the number of iterations of this loop that
6779 /// produce values in the specified constant range. Another way of looking at
6780 /// this is that it returns the first iteration number where the value is not in
6781 /// the condition, thus computing the exit count. If the iteration count can't
6782 /// be computed, an instance of SCEVCouldNotCompute is returned.
6783 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
6784 ScalarEvolution &SE) const {
6785 if (Range.isFullSet()) // Infinite loop.
6786 return SE.getCouldNotCompute();
6788 // If the start is a non-zero constant, shift the range to simplify things.
6789 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
6790 if (!SC->getValue()->isZero()) {
6791 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
6792 Operands[0] = SE.getConstant(SC->getType(), 0);
6793 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
6794 getNoWrapFlags(FlagNW));
6795 if (const SCEVAddRecExpr *ShiftedAddRec =
6796 dyn_cast<SCEVAddRecExpr>(Shifted))
6797 return ShiftedAddRec->getNumIterationsInRange(
6798 Range.subtract(SC->getValue()->getValue()), SE);
6799 // This is strange and shouldn't happen.
6800 return SE.getCouldNotCompute();
6803 // The only time we can solve this is when we have all constant indices.
6804 // Otherwise, we cannot determine the overflow conditions.
6805 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6806 if (!isa<SCEVConstant>(getOperand(i)))
6807 return SE.getCouldNotCompute();
6810 // Okay at this point we know that all elements of the chrec are constants and
6811 // that the start element is zero.
6813 // First check to see if the range contains zero. If not, the first
6815 unsigned BitWidth = SE.getTypeSizeInBits(getType());
6816 if (!Range.contains(APInt(BitWidth, 0)))
6817 return SE.getConstant(getType(), 0);
6820 // If this is an affine expression then we have this situation:
6821 // Solve {0,+,A} in Range === Ax in Range
6823 // We know that zero is in the range. If A is positive then we know that
6824 // the upper value of the range must be the first possible exit value.
6825 // If A is negative then the lower of the range is the last possible loop
6826 // value. Also note that we already checked for a full range.
6827 APInt One(BitWidth,1);
6828 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
6829 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
6831 // The exit value should be (End+A)/A.
6832 APInt ExitVal = (End + A).udiv(A);
6833 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
6835 // Evaluate at the exit value. If we really did fall out of the valid
6836 // range, then we computed our trip count, otherwise wrap around or other
6837 // things must have happened.
6838 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
6839 if (Range.contains(Val->getValue()))
6840 return SE.getCouldNotCompute(); // Something strange happened
6842 // Ensure that the previous value is in the range. This is a sanity check.
6843 assert(Range.contains(
6844 EvaluateConstantChrecAtConstant(this,
6845 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
6846 "Linear scev computation is off in a bad way!");
6847 return SE.getConstant(ExitValue);
6848 } else if (isQuadratic()) {
6849 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
6850 // quadratic equation to solve it. To do this, we must frame our problem in
6851 // terms of figuring out when zero is crossed, instead of when
6852 // Range.getUpper() is crossed.
6853 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
6854 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
6855 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
6856 // getNoWrapFlags(FlagNW)
6859 // Next, solve the constructed addrec
6860 std::pair<const SCEV *,const SCEV *> Roots =
6861 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
6862 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6863 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6865 // Pick the smallest positive root value.
6866 if (ConstantInt *CB =
6867 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
6868 R1->getValue(), R2->getValue()))) {
6869 if (CB->getZExtValue() == false)
6870 std::swap(R1, R2); // R1 is the minimum root now.
6872 // Make sure the root is not off by one. The returned iteration should
6873 // not be in the range, but the previous one should be. When solving
6874 // for "X*X < 5", for example, we should not return a root of 2.
6875 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
6878 if (Range.contains(R1Val->getValue())) {
6879 // The next iteration must be out of the range...
6880 ConstantInt *NextVal =
6881 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
6883 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6884 if (!Range.contains(R1Val->getValue()))
6885 return SE.getConstant(NextVal);
6886 return SE.getCouldNotCompute(); // Something strange happened
6889 // If R1 was not in the range, then it is a good return value. Make
6890 // sure that R1-1 WAS in the range though, just in case.
6891 ConstantInt *NextVal =
6892 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
6893 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6894 if (Range.contains(R1Val->getValue()))
6896 return SE.getCouldNotCompute(); // Something strange happened
6901 return SE.getCouldNotCompute();
6907 FindUndefs() : Found(false) {}
6909 bool follow(const SCEV *S) {
6910 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
6911 if (isa<UndefValue>(C->getValue()))
6913 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
6914 if (isa<UndefValue>(C->getValue()))
6918 // Keep looking if we haven't found it yet.
6921 bool isDone() const {
6922 // Stop recursion if we have found an undef.
6928 // Return true when S contains at least an undef value.
6930 containsUndefs(const SCEV *S) {
6932 SCEVTraversal<FindUndefs> ST(F);
6939 // Collect all steps of SCEV expressions.
6940 struct SCEVCollectStrides {
6941 ScalarEvolution &SE;
6942 SmallVectorImpl<const SCEV *> &Strides;
6944 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
6945 : SE(SE), Strides(S) {}
6947 bool follow(const SCEV *S) {
6948 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
6949 Strides.push_back(AR->getStepRecurrence(SE));
6952 bool isDone() const { return false; }
6955 // Collect all SCEVUnknown and SCEVMulExpr expressions.
6956 struct SCEVCollectTerms {
6957 SmallVectorImpl<const SCEV *> &Terms;
6959 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
6962 bool follow(const SCEV *S) {
6963 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
6964 if (!containsUndefs(S))
6967 // Stop recursion: once we collected a term, do not walk its operands.
6974 bool isDone() const { return false; }
6978 /// Find parametric terms in this SCEVAddRecExpr.
6979 void SCEVAddRecExpr::collectParametricTerms(
6980 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
6981 SmallVector<const SCEV *, 4> Strides;
6982 SCEVCollectStrides StrideCollector(SE, Strides);
6983 visitAll(this, StrideCollector);
6986 dbgs() << "Strides:\n";
6987 for (const SCEV *S : Strides)
6988 dbgs() << *S << "\n";
6991 for (const SCEV *S : Strides) {
6992 SCEVCollectTerms TermCollector(Terms);
6993 visitAll(S, TermCollector);
6997 dbgs() << "Terms:\n";
6998 for (const SCEV *T : Terms)
6999 dbgs() << *T << "\n";
7003 static const APInt srem(const SCEVConstant *C1, const SCEVConstant *C2) {
7004 APInt A = C1->getValue()->getValue();
7005 APInt B = C2->getValue()->getValue();
7006 uint32_t ABW = A.getBitWidth();
7007 uint32_t BBW = B.getBitWidth();
7014 return APIntOps::srem(A, B);
7017 static const APInt sdiv(const SCEVConstant *C1, const SCEVConstant *C2) {
7018 APInt A = C1->getValue()->getValue();
7019 APInt B = C2->getValue()->getValue();
7020 uint32_t ABW = A.getBitWidth();
7021 uint32_t BBW = B.getBitWidth();
7028 return APIntOps::sdiv(A, B);
7032 struct FindSCEVSize {
7034 FindSCEVSize() : Size(0) {}
7036 bool follow(const SCEV *S) {
7038 // Keep looking at all operands of S.
7041 bool isDone() const {
7047 // Returns the size of the SCEV S.
7048 static inline int sizeOfSCEV(const SCEV *S) {
7050 SCEVTraversal<FindSCEVSize> ST(F);
7057 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
7059 // Computes the Quotient and Remainder of the division of Numerator by
7061 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
7062 const SCEV *Denominator, const SCEV **Quotient,
7063 const SCEV **Remainder) {
7064 assert(Numerator && Denominator && "Uninitialized SCEV");
7066 SCEVDivision D(SE, Numerator, Denominator);
7068 // Check for the trivial case here to avoid having to check for it in the
7069 // rest of the code.
7070 if (Numerator == Denominator) {
7072 *Remainder = D.Zero;
7076 if (Numerator->isZero()) {
7078 *Remainder = D.Zero;
7082 // Split the Denominator when it is a product.
7083 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
7085 *Quotient = Numerator;
7086 for (const SCEV *Op : T->operands()) {
7087 divide(SE, *Quotient, Op, &Q, &R);
7090 // Bail out when the Numerator is not divisible by one of the terms of
7094 *Remainder = Numerator;
7098 *Remainder = D.Zero;
7103 *Quotient = D.Quotient;
7104 *Remainder = D.Remainder;
7107 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, const SCEV *Denominator)
7108 : SE(S), Denominator(Denominator) {
7109 Zero = SE.getConstant(Denominator->getType(), 0);
7110 One = SE.getConstant(Denominator->getType(), 1);
7112 // By default, we don't know how to divide Expr by Denominator.
7113 // Providing the default here simplifies the rest of the code.
7115 Remainder = Numerator;
7118 // Except in the trivial case described above, we do not know how to divide
7119 // Expr by Denominator for the following functions with empty implementation.
7120 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
7121 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
7122 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
7123 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
7124 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
7125 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
7126 void visitUnknown(const SCEVUnknown *Numerator) {}
7127 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
7129 void visitConstant(const SCEVConstant *Numerator) {
7130 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
7131 Quotient = SE.getConstant(sdiv(Numerator, D));
7132 Remainder = SE.getConstant(srem(Numerator, D));
7137 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
7138 const SCEV *StartQ, *StartR, *StepQ, *StepR;
7139 assert(Numerator->isAffine() && "Numerator should be affine");
7140 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
7141 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
7142 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
7143 Numerator->getNoWrapFlags());
7144 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
7145 Numerator->getNoWrapFlags());
7148 void visitAddExpr(const SCEVAddExpr *Numerator) {
7149 SmallVector<const SCEV *, 2> Qs, Rs;
7150 Type *Ty = Denominator->getType();
7152 for (const SCEV *Op : Numerator->operands()) {
7154 divide(SE, Op, Denominator, &Q, &R);
7156 // Bail out if types do not match.
7157 if (Ty != Q->getType() || Ty != R->getType()) {
7159 Remainder = Numerator;
7167 if (Qs.size() == 1) {
7173 Quotient = SE.getAddExpr(Qs);
7174 Remainder = SE.getAddExpr(Rs);
7177 void visitMulExpr(const SCEVMulExpr *Numerator) {
7178 SmallVector<const SCEV *, 2> Qs;
7179 Type *Ty = Denominator->getType();
7181 bool FoundDenominatorTerm = false;
7182 for (const SCEV *Op : Numerator->operands()) {
7183 // Bail out if types do not match.
7184 if (Ty != Op->getType()) {
7186 Remainder = Numerator;
7190 if (FoundDenominatorTerm) {
7195 // Check whether Denominator divides one of the product operands.
7197 divide(SE, Op, Denominator, &Q, &R);
7203 // Bail out if types do not match.
7204 if (Ty != Q->getType()) {
7206 Remainder = Numerator;
7210 FoundDenominatorTerm = true;
7214 if (FoundDenominatorTerm) {
7219 Quotient = SE.getMulExpr(Qs);
7223 if (!isa<SCEVUnknown>(Denominator)) {
7225 Remainder = Numerator;
7229 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
7230 ValueToValueMap RewriteMap;
7231 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
7232 cast<SCEVConstant>(Zero)->getValue();
7233 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
7235 if (Remainder->isZero()) {
7236 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
7237 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
7238 cast<SCEVConstant>(One)->getValue();
7240 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
7244 // Quotient is (Numerator - Remainder) divided by Denominator.
7246 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
7247 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
7248 // This SCEV does not seem to simplify: fail the division here.
7250 Remainder = Numerator;
7253 divide(SE, Diff, Denominator, &Q, &R);
7255 "(Numerator - Remainder) should evenly divide Denominator");
7260 ScalarEvolution &SE;
7261 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
7265 static bool findArrayDimensionsRec(ScalarEvolution &SE,
7266 SmallVectorImpl<const SCEV *> &Terms,
7267 SmallVectorImpl<const SCEV *> &Sizes) {
7268 int Last = Terms.size() - 1;
7269 const SCEV *Step = Terms[Last];
7271 // End of recursion.
7273 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
7274 SmallVector<const SCEV *, 2> Qs;
7275 for (const SCEV *Op : M->operands())
7276 if (!isa<SCEVConstant>(Op))
7279 Step = SE.getMulExpr(Qs);
7282 Sizes.push_back(Step);
7286 for (const SCEV *&Term : Terms) {
7287 // Normalize the terms before the next call to findArrayDimensionsRec.
7289 SCEVDivision::divide(SE, Term, Step, &Q, &R);
7291 // Bail out when GCD does not evenly divide one of the terms.
7298 // Remove all SCEVConstants.
7299 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7300 return isa<SCEVConstant>(E);
7304 if (Terms.size() > 0)
7305 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7308 Sizes.push_back(Step);
7313 struct FindParameter {
7314 bool FoundParameter;
7315 FindParameter() : FoundParameter(false) {}
7317 bool follow(const SCEV *S) {
7318 if (isa<SCEVUnknown>(S)) {
7319 FoundParameter = true;
7320 // Stop recursion: we found a parameter.
7326 bool isDone() const {
7327 // Stop recursion if we have found a parameter.
7328 return FoundParameter;
7333 // Returns true when S contains at least a SCEVUnknown parameter.
7335 containsParameters(const SCEV *S) {
7337 SCEVTraversal<FindParameter> ST(F);
7340 return F.FoundParameter;
7343 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7345 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7346 for (const SCEV *T : Terms)
7347 if (containsParameters(T))
7352 // Return the number of product terms in S.
7353 static inline int numberOfTerms(const SCEV *S) {
7354 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7355 return Expr->getNumOperands();
7359 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7360 if (isa<SCEVConstant>(T))
7363 if (isa<SCEVUnknown>(T))
7366 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7367 SmallVector<const SCEV *, 2> Factors;
7368 for (const SCEV *Op : M->operands())
7369 if (!isa<SCEVConstant>(Op))
7370 Factors.push_back(Op);
7372 return SE.getMulExpr(Factors);
7378 /// Return the size of an element read or written by Inst.
7379 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7381 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7382 Ty = Store->getValueOperand()->getType();
7383 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
7384 Ty = Load->getType();
7388 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7389 return getSizeOfExpr(ETy, Ty);
7392 /// Second step of delinearization: compute the array dimensions Sizes from the
7393 /// set of Terms extracted from the memory access function of this SCEVAddRec.
7394 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7395 SmallVectorImpl<const SCEV *> &Sizes,
7396 const SCEV *ElementSize) const {
7398 if (Terms.size() < 1 || !ElementSize)
7401 // Early return when Terms do not contain parameters: we do not delinearize
7402 // non parametric SCEVs.
7403 if (!containsParameters(Terms))
7407 dbgs() << "Terms:\n";
7408 for (const SCEV *T : Terms)
7409 dbgs() << *T << "\n";
7412 // Remove duplicates.
7413 std::sort(Terms.begin(), Terms.end());
7414 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7416 // Put larger terms first.
7417 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7418 return numberOfTerms(LHS) > numberOfTerms(RHS);
7421 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7423 // Divide all terms by the element size.
7424 for (const SCEV *&Term : Terms) {
7426 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
7430 SmallVector<const SCEV *, 4> NewTerms;
7432 // Remove constant factors.
7433 for (const SCEV *T : Terms)
7434 if (const SCEV *NewT = removeConstantFactors(SE, T))
7435 NewTerms.push_back(NewT);
7438 dbgs() << "Terms after sorting:\n";
7439 for (const SCEV *T : NewTerms)
7440 dbgs() << *T << "\n";
7443 if (NewTerms.empty() ||
7444 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
7449 // The last element to be pushed into Sizes is the size of an element.
7450 Sizes.push_back(ElementSize);
7453 dbgs() << "Sizes:\n";
7454 for (const SCEV *S : Sizes)
7455 dbgs() << *S << "\n";
7459 /// Third step of delinearization: compute the access functions for the
7460 /// Subscripts based on the dimensions in Sizes.
7461 void SCEVAddRecExpr::computeAccessFunctions(
7462 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7463 SmallVectorImpl<const SCEV *> &Sizes) const {
7465 // Early exit in case this SCEV is not an affine multivariate function.
7466 if (Sizes.empty() || !this->isAffine())
7469 const SCEV *Res = this;
7470 int Last = Sizes.size() - 1;
7471 for (int i = Last; i >= 0; i--) {
7473 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
7476 dbgs() << "Res: " << *Res << "\n";
7477 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7478 dbgs() << "Res divided by Sizes[i]:\n";
7479 dbgs() << "Quotient: " << *Q << "\n";
7480 dbgs() << "Remainder: " << *R << "\n";
7485 // Do not record the last subscript corresponding to the size of elements in
7489 // Bail out if the remainder is too complex.
7490 if (isa<SCEVAddRecExpr>(R)) {
7499 // Record the access function for the current subscript.
7500 Subscripts.push_back(R);
7503 // Also push in last position the remainder of the last division: it will be
7504 // the access function of the innermost dimension.
7505 Subscripts.push_back(Res);
7507 std::reverse(Subscripts.begin(), Subscripts.end());
7510 dbgs() << "Subscripts:\n";
7511 for (const SCEV *S : Subscripts)
7512 dbgs() << *S << "\n";
7516 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7517 /// sizes of an array access. Returns the remainder of the delinearization that
7518 /// is the offset start of the array. The SCEV->delinearize algorithm computes
7519 /// the multiples of SCEV coefficients: that is a pattern matching of sub
7520 /// expressions in the stride and base of a SCEV corresponding to the
7521 /// computation of a GCD (greatest common divisor) of base and stride. When
7522 /// SCEV->delinearize fails, it returns the SCEV unchanged.
7524 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
7526 /// void foo(long n, long m, long o, double A[n][m][o]) {
7528 /// for (long i = 0; i < n; i++)
7529 /// for (long j = 0; j < m; j++)
7530 /// for (long k = 0; k < o; k++)
7531 /// A[i][j][k] = 1.0;
7534 /// the delinearization input is the following AddRec SCEV:
7536 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7538 /// From this SCEV, we are able to say that the base offset of the access is %A
7539 /// because it appears as an offset that does not divide any of the strides in
7542 /// CHECK: Base offset: %A
7544 /// and then SCEV->delinearize determines the size of some of the dimensions of
7545 /// the array as these are the multiples by which the strides are happening:
7547 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7549 /// Note that the outermost dimension remains of UnknownSize because there are
7550 /// no strides that would help identifying the size of the last dimension: when
7551 /// the array has been statically allocated, one could compute the size of that
7552 /// dimension by dividing the overall size of the array by the size of the known
7553 /// dimensions: %m * %o * 8.
7555 /// Finally delinearize provides the access functions for the array reference
7556 /// that does correspond to A[i][j][k] of the above C testcase:
7558 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7560 /// The testcases are checking the output of a function pass:
7561 /// DelinearizationPass that walks through all loads and stores of a function
7562 /// asking for the SCEV of the memory access with respect to all enclosing
7563 /// loops, calling SCEV->delinearize on that and printing the results.
7565 void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7566 SmallVectorImpl<const SCEV *> &Subscripts,
7567 SmallVectorImpl<const SCEV *> &Sizes,
7568 const SCEV *ElementSize) const {
7569 // First step: collect parametric terms.
7570 SmallVector<const SCEV *, 4> Terms;
7571 collectParametricTerms(SE, Terms);
7576 // Second step: find subscript sizes.
7577 SE.findArrayDimensions(Terms, Sizes, ElementSize);
7582 // Third step: compute the access functions for each subscript.
7583 computeAccessFunctions(SE, Subscripts, Sizes);
7585 if (Subscripts.empty())
7589 dbgs() << "succeeded to delinearize " << *this << "\n";
7590 dbgs() << "ArrayDecl[UnknownSize]";
7591 for (const SCEV *S : Sizes)
7592 dbgs() << "[" << *S << "]";
7594 dbgs() << "\nArrayRef";
7595 for (const SCEV *S : Subscripts)
7596 dbgs() << "[" << *S << "]";
7601 //===----------------------------------------------------------------------===//
7602 // SCEVCallbackVH Class Implementation
7603 //===----------------------------------------------------------------------===//
7605 void ScalarEvolution::SCEVCallbackVH::deleted() {
7606 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7607 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7608 SE->ConstantEvolutionLoopExitValue.erase(PN);
7609 SE->ValueExprMap.erase(getValPtr());
7610 // this now dangles!
7613 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
7614 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7616 // Forget all the expressions associated with users of the old value,
7617 // so that future queries will recompute the expressions using the new
7619 Value *Old = getValPtr();
7620 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
7621 SmallPtrSet<User *, 8> Visited;
7622 while (!Worklist.empty()) {
7623 User *U = Worklist.pop_back_val();
7624 // Deleting the Old value will cause this to dangle. Postpone
7625 // that until everything else is done.
7628 if (!Visited.insert(U))
7630 if (PHINode *PN = dyn_cast<PHINode>(U))
7631 SE->ConstantEvolutionLoopExitValue.erase(PN);
7632 SE->ValueExprMap.erase(U);
7633 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
7635 // Delete the Old value.
7636 if (PHINode *PN = dyn_cast<PHINode>(Old))
7637 SE->ConstantEvolutionLoopExitValue.erase(PN);
7638 SE->ValueExprMap.erase(Old);
7639 // this now dangles!
7642 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
7643 : CallbackVH(V), SE(se) {}
7645 //===----------------------------------------------------------------------===//
7646 // ScalarEvolution Class Implementation
7647 //===----------------------------------------------------------------------===//
7649 ScalarEvolution::ScalarEvolution()
7650 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7651 BlockDispositions(64), FirstUnknown(nullptr) {
7652 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
7655 bool ScalarEvolution::runOnFunction(Function &F) {
7657 AT = &getAnalysis<AssumptionTracker>();
7658 LI = &getAnalysis<LoopInfo>();
7659 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
7660 DL = DLP ? &DLP->getDataLayout() : nullptr;
7661 TLI = &getAnalysis<TargetLibraryInfo>();
7662 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7666 void ScalarEvolution::releaseMemory() {
7667 // Iterate through all the SCEVUnknown instances and call their
7668 // destructors, so that they release their references to their values.
7669 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7671 FirstUnknown = nullptr;
7673 ValueExprMap.clear();
7675 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7676 // that a loop had multiple computable exits.
7677 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7678 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7683 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7685 BackedgeTakenCounts.clear();
7686 ConstantEvolutionLoopExitValue.clear();
7687 ValuesAtScopes.clear();
7688 LoopDispositions.clear();
7689 BlockDispositions.clear();
7690 UnsignedRanges.clear();
7691 SignedRanges.clear();
7692 UniqueSCEVs.clear();
7693 SCEVAllocator.Reset();
7696 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
7697 AU.setPreservesAll();
7698 AU.addRequired<AssumptionTracker>();
7699 AU.addRequiredTransitive<LoopInfo>();
7700 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
7701 AU.addRequired<TargetLibraryInfo>();
7704 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
7705 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
7708 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
7710 // Print all inner loops first
7711 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
7712 PrintLoopInfo(OS, SE, *I);
7715 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7718 SmallVector<BasicBlock *, 8> ExitBlocks;
7719 L->getExitBlocks(ExitBlocks);
7720 if (ExitBlocks.size() != 1)
7721 OS << "<multiple exits> ";
7723 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
7724 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
7726 OS << "Unpredictable backedge-taken count. ";
7731 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7734 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
7735 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
7737 OS << "Unpredictable max backedge-taken count. ";
7743 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
7744 // ScalarEvolution's implementation of the print method is to print
7745 // out SCEV values of all instructions that are interesting. Doing
7746 // this potentially causes it to create new SCEV objects though,
7747 // which technically conflicts with the const qualifier. This isn't
7748 // observable from outside the class though, so casting away the
7749 // const isn't dangerous.
7750 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7752 OS << "Classifying expressions for: ";
7753 F->printAsOperand(OS, /*PrintType=*/false);
7755 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
7756 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
7759 const SCEV *SV = SE.getSCEV(&*I);
7762 const Loop *L = LI->getLoopFor((*I).getParent());
7764 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
7771 OS << "\t\t" "Exits: ";
7772 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
7773 if (!SE.isLoopInvariant(ExitValue, L)) {
7774 OS << "<<Unknown>>";
7783 OS << "Determining loop execution counts for: ";
7784 F->printAsOperand(OS, /*PrintType=*/false);
7786 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
7787 PrintLoopInfo(OS, &SE, *I);
7790 ScalarEvolution::LoopDisposition
7791 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
7792 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values = LoopDispositions[S];
7793 for (unsigned u = 0; u < Values.size(); u++) {
7794 if (Values[u].first == L)
7795 return Values[u].second;
7797 Values.push_back(std::make_pair(L, LoopVariant));
7798 LoopDisposition D = computeLoopDisposition(S, L);
7799 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values2 = LoopDispositions[S];
7800 for (unsigned u = Values2.size(); u > 0; u--) {
7801 if (Values2[u - 1].first == L) {
7802 Values2[u - 1].second = D;
7809 ScalarEvolution::LoopDisposition
7810 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
7811 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
7813 return LoopInvariant;
7817 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
7818 case scAddRecExpr: {
7819 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7821 // If L is the addrec's loop, it's computable.
7822 if (AR->getLoop() == L)
7823 return LoopComputable;
7825 // Add recurrences are never invariant in the function-body (null loop).
7829 // This recurrence is variant w.r.t. L if L contains AR's loop.
7830 if (L->contains(AR->getLoop()))
7833 // This recurrence is invariant w.r.t. L if AR's loop contains L.
7834 if (AR->getLoop()->contains(L))
7835 return LoopInvariant;
7837 // This recurrence is variant w.r.t. L if any of its operands
7839 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
7841 if (!isLoopInvariant(*I, L))
7844 // Otherwise it's loop-invariant.
7845 return LoopInvariant;
7851 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
7852 bool HasVarying = false;
7853 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
7855 LoopDisposition D = getLoopDisposition(*I, L);
7856 if (D == LoopVariant)
7858 if (D == LoopComputable)
7861 return HasVarying ? LoopComputable : LoopInvariant;
7864 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
7865 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
7866 if (LD == LoopVariant)
7868 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
7869 if (RD == LoopVariant)
7871 return (LD == LoopInvariant && RD == LoopInvariant) ?
7872 LoopInvariant : LoopComputable;
7875 // All non-instruction values are loop invariant. All instructions are loop
7876 // invariant if they are not contained in the specified loop.
7877 // Instructions are never considered invariant in the function body
7878 // (null loop) because they are defined within the "loop".
7879 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
7880 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
7881 return LoopInvariant;
7882 case scCouldNotCompute:
7883 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7885 llvm_unreachable("Unknown SCEV kind!");
7888 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
7889 return getLoopDisposition(S, L) == LoopInvariant;
7892 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
7893 return getLoopDisposition(S, L) == LoopComputable;
7896 ScalarEvolution::BlockDisposition
7897 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
7898 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values = BlockDispositions[S];
7899 for (unsigned u = 0; u < Values.size(); u++) {
7900 if (Values[u].first == BB)
7901 return Values[u].second;
7903 Values.push_back(std::make_pair(BB, DoesNotDominateBlock));
7904 BlockDisposition D = computeBlockDisposition(S, BB);
7905 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values2 = BlockDispositions[S];
7906 for (unsigned u = Values2.size(); u > 0; u--) {
7907 if (Values2[u - 1].first == BB) {
7908 Values2[u - 1].second = D;
7915 ScalarEvolution::BlockDisposition
7916 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
7917 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
7919 return ProperlyDominatesBlock;
7923 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
7924 case scAddRecExpr: {
7925 // This uses a "dominates" query instead of "properly dominates" query
7926 // to test for proper dominance too, because the instruction which
7927 // produces the addrec's value is a PHI, and a PHI effectively properly
7928 // dominates its entire containing block.
7929 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7930 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
7931 return DoesNotDominateBlock;
7933 // FALL THROUGH into SCEVNAryExpr handling.
7938 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
7940 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
7942 BlockDisposition D = getBlockDisposition(*I, BB);
7943 if (D == DoesNotDominateBlock)
7944 return DoesNotDominateBlock;
7945 if (D == DominatesBlock)
7948 return Proper ? ProperlyDominatesBlock : DominatesBlock;
7951 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
7952 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
7953 BlockDisposition LD = getBlockDisposition(LHS, BB);
7954 if (LD == DoesNotDominateBlock)
7955 return DoesNotDominateBlock;
7956 BlockDisposition RD = getBlockDisposition(RHS, BB);
7957 if (RD == DoesNotDominateBlock)
7958 return DoesNotDominateBlock;
7959 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
7960 ProperlyDominatesBlock : DominatesBlock;
7963 if (Instruction *I =
7964 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
7965 if (I->getParent() == BB)
7966 return DominatesBlock;
7967 if (DT->properlyDominates(I->getParent(), BB))
7968 return ProperlyDominatesBlock;
7969 return DoesNotDominateBlock;
7971 return ProperlyDominatesBlock;
7972 case scCouldNotCompute:
7973 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7975 llvm_unreachable("Unknown SCEV kind!");
7978 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
7979 return getBlockDisposition(S, BB) >= DominatesBlock;
7982 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
7983 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
7987 // Search for a SCEV expression node within an expression tree.
7988 // Implements SCEVTraversal::Visitor.
7993 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
7995 bool follow(const SCEV *S) {
7996 IsFound |= (S == Node);
7999 bool isDone() const { return IsFound; }
8003 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
8004 SCEVSearch Search(Op);
8005 visitAll(S, Search);
8006 return Search.IsFound;
8009 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8010 ValuesAtScopes.erase(S);
8011 LoopDispositions.erase(S);
8012 BlockDispositions.erase(S);
8013 UnsignedRanges.erase(S);
8014 SignedRanges.erase(S);
8016 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8017 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8018 BackedgeTakenInfo &BEInfo = I->second;
8019 if (BEInfo.hasOperand(S, this)) {
8021 BackedgeTakenCounts.erase(I++);
8028 typedef DenseMap<const Loop *, std::string> VerifyMap;
8030 /// replaceSubString - Replaces all occurrences of From in Str with To.
8031 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8033 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8034 Str.replace(Pos, From.size(), To.data(), To.size());
8039 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8041 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8042 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8043 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8045 std::string &S = Map[L];
8047 raw_string_ostream OS(S);
8048 SE.getBackedgeTakenCount(L)->print(OS);
8050 // false and 0 are semantically equivalent. This can happen in dead loops.
8051 replaceSubString(OS.str(), "false", "0");
8052 // Remove wrap flags, their use in SCEV is highly fragile.
8053 // FIXME: Remove this when SCEV gets smarter about them.
8054 replaceSubString(OS.str(), "<nw>", "");
8055 replaceSubString(OS.str(), "<nsw>", "");
8056 replaceSubString(OS.str(), "<nuw>", "");
8061 void ScalarEvolution::verifyAnalysis() const {
8065 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8067 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8068 // FIXME: It would be much better to store actual values instead of strings,
8069 // but SCEV pointers will change if we drop the caches.
8070 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8071 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8072 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8074 // Gather stringified backedge taken counts for all loops without using
8077 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8078 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8080 // Now compare whether they're the same with and without caches. This allows
8081 // verifying that no pass changed the cache.
8082 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8083 "New loops suddenly appeared!");
8085 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8086 OldE = BackedgeDumpsOld.end(),
8087 NewI = BackedgeDumpsNew.begin();
8088 OldI != OldE; ++OldI, ++NewI) {
8089 assert(OldI->first == NewI->first && "Loop order changed!");
8091 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8093 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
8094 // means that a pass is buggy or SCEV has to learn a new pattern but is
8095 // usually not harmful.
8096 if (OldI->second != NewI->second &&
8097 OldI->second.find("undef") == std::string::npos &&
8098 NewI->second.find("undef") == std::string::npos &&
8099 OldI->second != "***COULDNOTCOMPUTE***" &&
8100 NewI->second != "***COULDNOTCOMPUTE***") {
8101 dbgs() << "SCEVValidator: SCEV for loop '"
8102 << OldI->first->getHeader()->getName()
8103 << "' changed from '" << OldI->second
8104 << "' to '" << NewI->second << "'!\n";
8109 // TODO: Verify more things.