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/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Analysis/AssumptionTracker.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/InstructionSimplify.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
71 #include "llvm/Analysis/ValueTracking.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DerivedTypes.h"
76 #include "llvm/IR/Dominators.h"
77 #include "llvm/IR/GetElementPtrTypeIterator.h"
78 #include "llvm/IR/GlobalAlias.h"
79 #include "llvm/IR/GlobalVariable.h"
80 #include "llvm/IR/InstIterator.h"
81 #include "llvm/IR/Instructions.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/ErrorHandling.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetLibraryInfo.h"
94 #define DEBUG_TYPE "scalar-evolution"
96 STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98 STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100 STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102 STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
105 static cl::opt<unsigned>
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant "
112 // FIXME: Enable this with XDEBUG when the test suite is clean.
114 VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
117 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
119 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
120 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
122 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
123 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
124 "Scalar Evolution Analysis", false, true)
125 char ScalarEvolution::ID = 0;
127 //===----------------------------------------------------------------------===//
128 // SCEV class definitions
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
132 // Implementation of the SCEV class.
135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
136 void SCEV::dump() const {
142 void SCEV::print(raw_ostream &OS) const {
143 switch (static_cast<SCEVTypes>(getSCEVType())) {
145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
174 if (AR->getNoWrapFlags(FlagNUW))
176 if (AR->getNoWrapFlags(FlagNSW))
178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
190 const char *OpStr = nullptr;
191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
201 if (std::next(I) != E)
205 switch (NAry->getSCEVType()) {
208 if (NAry->getNoWrapFlags(FlagNUW))
210 if (NAry->getNoWrapFlags(FlagNSW))
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
236 FieldNo->printAsOperand(OS, false);
241 // Otherwise just print it normally.
242 U->getValue()->printAsOperand(OS, false);
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
249 llvm_unreachable("Unknown SCEV kind!");
252 Type *SCEV::getType() const {
253 switch (static_cast<SCEVTypes>(getSCEVType())) {
255 return cast<SCEVConstant>(this)->getType();
259 return cast<SCEVCastExpr>(this)->getType();
264 return cast<SCEVNAryExpr>(this)->getType();
266 return cast<SCEVAddExpr>(this)->getType();
268 return cast<SCEVUDivExpr>(this)->getType();
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
274 llvm_unreachable("Unknown SCEV kind!");
277 bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
283 bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
289 bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
295 /// isNonConstantNegative - Return true if the specified scev is negated, but
297 bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
309 SCEVCouldNotCompute::SCEVCouldNotCompute() :
310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
312 bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
316 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
318 ID.AddInteger(scConstant);
321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
323 UniqueSCEVs.InsertNode(S, IP);
327 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
328 return getConstant(ConstantInt::get(getContext(), Val));
332 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
334 return getConstant(ConstantInt::get(ITy, V, isSigned));
337 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
338 unsigned SCEVTy, const SCEV *op, Type *ty)
339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
341 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
342 const SCEV *op, Type *ty)
343 : SCEVCastExpr(ID, scTruncate, op, ty) {
344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
346 "Cannot truncate non-integer value!");
349 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
350 const SCEV *op, Type *ty)
351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
354 "Cannot zero extend non-integer value!");
357 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
358 const SCEV *op, Type *ty)
359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
362 "Cannot sign extend non-integer value!");
365 void SCEVUnknown::deleted() {
366 // Clear this SCEVUnknown from various maps.
367 SE->forgetMemoizedResults(this);
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
372 // Release the value.
376 void SCEVUnknown::allUsesReplacedWith(Value *New) {
377 // Clear this SCEVUnknown from various maps.
378 SE->forgetMemoizedResults(this);
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
389 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
406 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
414 if (StructType *STy = dyn_cast<StructType>(Ty))
415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
420 STy->getNumElements() == 2 &&
421 STy->getElementType(0)->isIntegerTy(1)) {
422 AllocTy = STy->getElementType(1);
431 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
443 if (Ty->isStructTy() || Ty->isArrayTy()) {
445 FieldNo = CE->getOperand(2);
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
461 class SCEVComplexityCompare {
462 const LoopInfo *const LI;
464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
466 // Return true or false if LHS is less than, or at least RHS, respectively.
467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
468 return compare(LHS, RHS) < 0;
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
479 // Primarily, sort the SCEVs by their getSCEVType().
480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
482 return (int)LType - (int)RType;
484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
487 switch (static_cast<SCEVTypes>(LType)) {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
494 const Value *LV = LU->getValue(), *RV = RU->getValue();
496 // Order pointer values after integer values. This helps SCEVExpander
498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
500 if (LIsPointer != RIsPointer)
501 return (int)LIsPointer - (int)RIsPointer;
503 // Compare getValueID values.
504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
507 return (int)LID - (int)RID;
509 // Sort arguments by their position.
510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
521 // Compare loop depths.
522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
528 return (int)LDepth - (int)RDepth;
531 // Compare the number of operands.
532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
534 return (int)LNumOps - (int)RNumOps;
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
544 // Compare constant values.
545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
548 if (LBitWidth != RBitWidth)
549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
557 // Compare addrec loop depths.
558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
563 return (int)LDepth - (int)RDepth;
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
588 // Lexicographically compare n-ary expressions.
589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
593 for (unsigned i = 0; i != LNumOps; ++i) {
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
600 return (int)LNumOps - (int)RNumOps;
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
611 return compare(LC->getRHS(), RC->getRHS());
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
627 llvm_unreachable("Unknown SCEV kind!");
632 /// GroupByComplexity - Given a list of SCEV objects, order them by their
633 /// complexity, and group objects of the same complexity together by value.
634 /// When this routine is finished, we know that any duplicates in the vector are
635 /// consecutive and that complexity is monotonically increasing.
637 /// Note that we go take special precautions to ensure that we get deterministic
638 /// results from this routine. In other words, we don't want the results of
639 /// this to depend on where the addresses of various SCEV objects happened to
642 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
665 // If there are any objects of the same complexity and same value as this
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
678 static const APInt srem(const SCEVConstant *C1, const SCEVConstant *C2) {
679 APInt A = C1->getValue()->getValue();
680 APInt B = C2->getValue()->getValue();
681 uint32_t ABW = A.getBitWidth();
682 uint32_t BBW = B.getBitWidth();
689 return APIntOps::srem(A, B);
692 static const APInt sdiv(const SCEVConstant *C1, const SCEVConstant *C2) {
693 APInt A = C1->getValue()->getValue();
694 APInt B = C2->getValue()->getValue();
695 uint32_t ABW = A.getBitWidth();
696 uint32_t BBW = B.getBitWidth();
703 return APIntOps::sdiv(A, B);
707 struct FindSCEVSize {
709 FindSCEVSize() : Size(0) {}
711 bool follow(const SCEV *S) {
713 // Keep looking at all operands of S.
716 bool isDone() const {
722 // Returns the size of the SCEV S.
723 static inline int sizeOfSCEV(const SCEV *S) {
725 SCEVTraversal<FindSCEVSize> ST(F);
732 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
734 // Computes the Quotient and Remainder of the division of Numerator by
736 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
737 const SCEV *Denominator, const SCEV **Quotient,
738 const SCEV **Remainder) {
739 assert(Numerator && Denominator && "Uninitialized SCEV");
741 SCEVDivision D(SE, Numerator, Denominator);
743 // Check for the trivial case here to avoid having to check for it in the
745 if (Numerator == Denominator) {
751 if (Numerator->isZero()) {
757 // Split the Denominator when it is a product.
758 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
760 *Quotient = Numerator;
761 for (const SCEV *Op : T->operands()) {
762 divide(SE, *Quotient, Op, &Q, &R);
765 // Bail out when the Numerator is not divisible by one of the terms of
769 *Remainder = Numerator;
778 *Quotient = D.Quotient;
779 *Remainder = D.Remainder;
782 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, const SCEV *Denominator)
783 : SE(S), Denominator(Denominator) {
784 Zero = SE.getConstant(Denominator->getType(), 0);
785 One = SE.getConstant(Denominator->getType(), 1);
787 // By default, we don't know how to divide Expr by Denominator.
788 // Providing the default here simplifies the rest of the code.
790 Remainder = Numerator;
793 // Except in the trivial case described above, we do not know how to divide
794 // Expr by Denominator for the following functions with empty implementation.
795 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
796 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
797 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
798 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
799 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
800 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
801 void visitUnknown(const SCEVUnknown *Numerator) {}
802 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
804 void visitConstant(const SCEVConstant *Numerator) {
805 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
806 Quotient = SE.getConstant(sdiv(Numerator, D));
807 Remainder = SE.getConstant(srem(Numerator, D));
812 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
813 const SCEV *StartQ, *StartR, *StepQ, *StepR;
814 assert(Numerator->isAffine() && "Numerator should be affine");
815 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
816 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
817 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
818 Numerator->getNoWrapFlags());
819 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
820 Numerator->getNoWrapFlags());
823 void visitAddExpr(const SCEVAddExpr *Numerator) {
824 SmallVector<const SCEV *, 2> Qs, Rs;
825 Type *Ty = Denominator->getType();
827 for (const SCEV *Op : Numerator->operands()) {
829 divide(SE, Op, Denominator, &Q, &R);
831 // Bail out if types do not match.
832 if (Ty != Q->getType() || Ty != R->getType()) {
834 Remainder = Numerator;
842 if (Qs.size() == 1) {
848 Quotient = SE.getAddExpr(Qs);
849 Remainder = SE.getAddExpr(Rs);
852 void visitMulExpr(const SCEVMulExpr *Numerator) {
853 SmallVector<const SCEV *, 2> Qs;
854 Type *Ty = Denominator->getType();
856 bool FoundDenominatorTerm = false;
857 for (const SCEV *Op : Numerator->operands()) {
858 // Bail out if types do not match.
859 if (Ty != Op->getType()) {
861 Remainder = Numerator;
865 if (FoundDenominatorTerm) {
870 // Check whether Denominator divides one of the product operands.
872 divide(SE, Op, Denominator, &Q, &R);
878 // Bail out if types do not match.
879 if (Ty != Q->getType()) {
881 Remainder = Numerator;
885 FoundDenominatorTerm = true;
889 if (FoundDenominatorTerm) {
894 Quotient = SE.getMulExpr(Qs);
898 if (!isa<SCEVUnknown>(Denominator)) {
900 Remainder = Numerator;
904 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
905 ValueToValueMap RewriteMap;
906 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
907 cast<SCEVConstant>(Zero)->getValue();
908 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
910 if (Remainder->isZero()) {
911 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
912 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
913 cast<SCEVConstant>(One)->getValue();
915 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
919 // Quotient is (Numerator - Remainder) divided by Denominator.
921 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
922 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
923 // This SCEV does not seem to simplify: fail the division here.
925 Remainder = Numerator;
928 divide(SE, Diff, Denominator, &Q, &R);
930 "(Numerator - Remainder) should evenly divide Denominator");
936 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
942 //===----------------------------------------------------------------------===//
943 // Simple SCEV method implementations
944 //===----------------------------------------------------------------------===//
946 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
948 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
951 // Handle the simplest case efficiently.
953 return SE.getTruncateOrZeroExtend(It, ResultTy);
955 // We are using the following formula for BC(It, K):
957 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
959 // Suppose, W is the bitwidth of the return value. We must be prepared for
960 // overflow. Hence, we must assure that the result of our computation is
961 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
962 // safe in modular arithmetic.
964 // However, this code doesn't use exactly that formula; the formula it uses
965 // is something like the following, where T is the number of factors of 2 in
966 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
969 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
971 // This formula is trivially equivalent to the previous formula. However,
972 // this formula can be implemented much more efficiently. The trick is that
973 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
974 // arithmetic. To do exact division in modular arithmetic, all we have
975 // to do is multiply by the inverse. Therefore, this step can be done at
978 // The next issue is how to safely do the division by 2^T. The way this
979 // is done is by doing the multiplication step at a width of at least W + T
980 // bits. This way, the bottom W+T bits of the product are accurate. Then,
981 // when we perform the division by 2^T (which is equivalent to a right shift
982 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
983 // truncated out after the division by 2^T.
985 // In comparison to just directly using the first formula, this technique
986 // is much more efficient; using the first formula requires W * K bits,
987 // but this formula less than W + K bits. Also, the first formula requires
988 // a division step, whereas this formula only requires multiplies and shifts.
990 // It doesn't matter whether the subtraction step is done in the calculation
991 // width or the input iteration count's width; if the subtraction overflows,
992 // the result must be zero anyway. We prefer here to do it in the width of
993 // the induction variable because it helps a lot for certain cases; CodeGen
994 // isn't smart enough to ignore the overflow, which leads to much less
995 // efficient code if the width of the subtraction is wider than the native
998 // (It's possible to not widen at all by pulling out factors of 2 before
999 // the multiplication; for example, K=2 can be calculated as
1000 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1001 // extra arithmetic, so it's not an obvious win, and it gets
1002 // much more complicated for K > 3.)
1004 // Protection from insane SCEVs; this bound is conservative,
1005 // but it probably doesn't matter.
1007 return SE.getCouldNotCompute();
1009 unsigned W = SE.getTypeSizeInBits(ResultTy);
1011 // Calculate K! / 2^T and T; we divide out the factors of two before
1012 // multiplying for calculating K! / 2^T to avoid overflow.
1013 // Other overflow doesn't matter because we only care about the bottom
1014 // W bits of the result.
1015 APInt OddFactorial(W, 1);
1017 for (unsigned i = 3; i <= K; ++i) {
1019 unsigned TwoFactors = Mult.countTrailingZeros();
1021 Mult = Mult.lshr(TwoFactors);
1022 OddFactorial *= Mult;
1025 // We need at least W + T bits for the multiplication step
1026 unsigned CalculationBits = W + T;
1028 // Calculate 2^T, at width T+W.
1029 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1031 // Calculate the multiplicative inverse of K! / 2^T;
1032 // this multiplication factor will perform the exact division by
1034 APInt Mod = APInt::getSignedMinValue(W+1);
1035 APInt MultiplyFactor = OddFactorial.zext(W+1);
1036 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1037 MultiplyFactor = MultiplyFactor.trunc(W);
1039 // Calculate the product, at width T+W
1040 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1042 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1043 for (unsigned i = 1; i != K; ++i) {
1044 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1045 Dividend = SE.getMulExpr(Dividend,
1046 SE.getTruncateOrZeroExtend(S, CalculationTy));
1050 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1052 // Truncate the result, and divide by K! / 2^T.
1054 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1055 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1058 /// evaluateAtIteration - Return the value of this chain of recurrences at
1059 /// the specified iteration number. We can evaluate this recurrence by
1060 /// multiplying each element in the chain by the binomial coefficient
1061 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1063 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1065 /// where BC(It, k) stands for binomial coefficient.
1067 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1068 ScalarEvolution &SE) const {
1069 const SCEV *Result = getStart();
1070 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1071 // The computation is correct in the face of overflow provided that the
1072 // multiplication is performed _after_ the evaluation of the binomial
1074 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1075 if (isa<SCEVCouldNotCompute>(Coeff))
1078 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1083 //===----------------------------------------------------------------------===//
1084 // SCEV Expression folder implementations
1085 //===----------------------------------------------------------------------===//
1087 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1089 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1090 "This is not a truncating conversion!");
1091 assert(isSCEVable(Ty) &&
1092 "This is not a conversion to a SCEVable type!");
1093 Ty = getEffectiveSCEVType(Ty);
1095 FoldingSetNodeID ID;
1096 ID.AddInteger(scTruncate);
1100 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1102 // Fold if the operand is constant.
1103 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1105 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1107 // trunc(trunc(x)) --> trunc(x)
1108 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1109 return getTruncateExpr(ST->getOperand(), Ty);
1111 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1112 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1113 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1115 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1116 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1117 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1119 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1120 // eliminate all the truncates.
1121 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1122 SmallVector<const SCEV *, 4> Operands;
1123 bool hasTrunc = false;
1124 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1125 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
1127 Operands.push_back(S);
1130 return getAddExpr(Operands);
1131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1134 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1135 // eliminate all the truncates.
1136 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1137 SmallVector<const SCEV *, 4> Operands;
1138 bool hasTrunc = false;
1139 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1140 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1141 hasTrunc = isa<SCEVTruncateExpr>(S);
1142 Operands.push_back(S);
1145 return getMulExpr(Operands);
1146 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1149 // If the input value is a chrec scev, truncate the chrec's operands.
1150 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1151 SmallVector<const SCEV *, 4> Operands;
1152 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1153 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
1154 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1157 // The cast wasn't folded; create an explicit cast node. We can reuse
1158 // the existing insert position since if we get here, we won't have
1159 // made any changes which would invalidate it.
1160 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1162 UniqueSCEVs.InsertNode(S, IP);
1166 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1168 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1169 "This is not an extending conversion!");
1170 assert(isSCEVable(Ty) &&
1171 "This is not a conversion to a SCEVable type!");
1172 Ty = getEffectiveSCEVType(Ty);
1174 // Fold if the operand is constant.
1175 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1177 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1179 // zext(zext(x)) --> zext(x)
1180 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1181 return getZeroExtendExpr(SZ->getOperand(), Ty);
1183 // Before doing any expensive analysis, check to see if we've already
1184 // computed a SCEV for this Op and Ty.
1185 FoldingSetNodeID ID;
1186 ID.AddInteger(scZeroExtend);
1190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1192 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1193 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1194 // It's possible the bits taken off by the truncate were all zero bits. If
1195 // so, we should be able to simplify this further.
1196 const SCEV *X = ST->getOperand();
1197 ConstantRange CR = getUnsignedRange(X);
1198 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1199 unsigned NewBits = getTypeSizeInBits(Ty);
1200 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1201 CR.zextOrTrunc(NewBits)))
1202 return getTruncateOrZeroExtend(X, Ty);
1205 // If the input value is a chrec scev, and we can prove that the value
1206 // did not overflow the old, smaller, value, we can zero extend all of the
1207 // operands (often constants). This allows analysis of something like
1208 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1209 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1210 if (AR->isAffine()) {
1211 const SCEV *Start = AR->getStart();
1212 const SCEV *Step = AR->getStepRecurrence(*this);
1213 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1214 const Loop *L = AR->getLoop();
1216 // If we have special knowledge that this addrec won't overflow,
1217 // we don't need to do any further analysis.
1218 if (AR->getNoWrapFlags(SCEV::FlagNUW))
1219 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1220 getZeroExtendExpr(Step, Ty),
1221 L, AR->getNoWrapFlags());
1223 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1224 // Note that this serves two purposes: It filters out loops that are
1225 // simply not analyzable, and it covers the case where this code is
1226 // being called from within backedge-taken count analysis, such that
1227 // attempting to ask for the backedge-taken count would likely result
1228 // in infinite recursion. In the later case, the analysis code will
1229 // cope with a conservative value, and it will take care to purge
1230 // that value once it has finished.
1231 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1232 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1233 // Manually compute the final value for AR, checking for
1236 // Check whether the backedge-taken count can be losslessly casted to
1237 // the addrec's type. The count is always unsigned.
1238 const SCEV *CastedMaxBECount =
1239 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1240 const SCEV *RecastedMaxBECount =
1241 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1242 if (MaxBECount == RecastedMaxBECount) {
1243 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1244 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1245 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1246 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1247 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1248 const SCEV *WideMaxBECount =
1249 getZeroExtendExpr(CastedMaxBECount, WideTy);
1250 const SCEV *OperandExtendedAdd =
1251 getAddExpr(WideStart,
1252 getMulExpr(WideMaxBECount,
1253 getZeroExtendExpr(Step, WideTy)));
1254 if (ZAdd == OperandExtendedAdd) {
1255 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1256 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1257 // Return the expression with the addrec on the outside.
1258 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1259 getZeroExtendExpr(Step, Ty),
1260 L, AR->getNoWrapFlags());
1262 // Similar to above, only this time treat the step value as signed.
1263 // This covers loops that count down.
1264 OperandExtendedAdd =
1265 getAddExpr(WideStart,
1266 getMulExpr(WideMaxBECount,
1267 getSignExtendExpr(Step, WideTy)));
1268 if (ZAdd == OperandExtendedAdd) {
1269 // Cache knowledge of AR NW, which is propagated to this AddRec.
1270 // Negative step causes unsigned wrap, but it still can't self-wrap.
1271 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1272 // Return the expression with the addrec on the outside.
1273 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1274 getSignExtendExpr(Step, Ty),
1275 L, AR->getNoWrapFlags());
1279 // If the backedge is guarded by a comparison with the pre-inc value
1280 // the addrec is safe. Also, if the entry is guarded by a comparison
1281 // with the start value and the backedge is guarded by a comparison
1282 // with the post-inc value, the addrec is safe.
1283 if (isKnownPositive(Step)) {
1284 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1285 getUnsignedRange(Step).getUnsignedMax());
1286 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1287 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1288 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1289 AR->getPostIncExpr(*this), N))) {
1290 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1291 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1292 // Return the expression with the addrec on the outside.
1293 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1294 getZeroExtendExpr(Step, Ty),
1295 L, AR->getNoWrapFlags());
1297 } else if (isKnownNegative(Step)) {
1298 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1299 getSignedRange(Step).getSignedMin());
1300 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1301 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1302 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1303 AR->getPostIncExpr(*this), N))) {
1304 // Cache knowledge of AR NW, which is propagated to this AddRec.
1305 // Negative step causes unsigned wrap, but it still can't self-wrap.
1306 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1307 // Return the expression with the addrec on the outside.
1308 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1309 getSignExtendExpr(Step, Ty),
1310 L, AR->getNoWrapFlags());
1316 // The cast wasn't folded; create an explicit cast node.
1317 // Recompute the insert position, as it may have been invalidated.
1318 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1319 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1321 UniqueSCEVs.InsertNode(S, IP);
1325 // Get the limit of a recurrence such that incrementing by Step cannot cause
1326 // signed overflow as long as the value of the recurrence within the loop does
1327 // not exceed this limit before incrementing.
1328 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1329 ICmpInst::Predicate *Pred,
1330 ScalarEvolution *SE) {
1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1332 if (SE->isKnownPositive(Step)) {
1333 *Pred = ICmpInst::ICMP_SLT;
1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1335 SE->getSignedRange(Step).getSignedMax());
1337 if (SE->isKnownNegative(Step)) {
1338 *Pred = ICmpInst::ICMP_SGT;
1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1340 SE->getSignedRange(Step).getSignedMin());
1345 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
1346 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
1347 // or postincrement sibling. This allows normalizing a sign extended AddRec as
1348 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1349 // result, the expression "Step + sext(PreIncAR)" is congruent with
1350 // "sext(PostIncAR)"
1351 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
1353 ScalarEvolution *SE) {
1354 const Loop *L = AR->getLoop();
1355 const SCEV *Start = AR->getStart();
1356 const SCEV *Step = AR->getStepRecurrence(*SE);
1358 // Check for a simple looking step prior to loop entry.
1359 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1363 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1364 // subtraction is expensive. For this purpose, perform a quick and dirty
1365 // difference, by checking for Step in the operand list.
1366 SmallVector<const SCEV *, 4> DiffOps;
1367 for (const SCEV *Op : SA->operands())
1369 DiffOps.push_back(Op);
1371 if (DiffOps.size() == SA->getNumOperands())
1374 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1375 // same three conditions that getSignExtendedExpr checks.
1377 // 1. NSW flags on the step increment.
1378 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1379 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1380 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1382 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
1385 // 2. Direct overflow check on the step operation's expression.
1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1388 const SCEV *OperandExtendedStart =
1389 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1390 SE->getSignExtendExpr(Step, WideTy));
1391 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1392 // Cache knowledge of PreAR NSW.
1394 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1395 // FIXME: this optimization needs a unit test
1396 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1400 // 3. Loop precondition.
1401 ICmpInst::Predicate Pred;
1402 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1404 if (OverflowLimit &&
1405 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1411 // Get the normalized sign-extended expression for this AddRec's Start.
1412 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
1414 ScalarEvolution *SE) {
1415 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1417 return SE->getSignExtendExpr(AR->getStart(), Ty);
1419 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1420 SE->getSignExtendExpr(PreStart, Ty));
1423 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1425 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1426 "This is not an extending conversion!");
1427 assert(isSCEVable(Ty) &&
1428 "This is not a conversion to a SCEVable type!");
1429 Ty = getEffectiveSCEVType(Ty);
1431 // Fold if the operand is constant.
1432 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1434 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1436 // sext(sext(x)) --> sext(x)
1437 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1438 return getSignExtendExpr(SS->getOperand(), Ty);
1440 // sext(zext(x)) --> zext(x)
1441 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1442 return getZeroExtendExpr(SZ->getOperand(), Ty);
1444 // Before doing any expensive analysis, check to see if we've already
1445 // computed a SCEV for this Op and Ty.
1446 FoldingSetNodeID ID;
1447 ID.AddInteger(scSignExtend);
1451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1453 // If the input value is provably positive, build a zext instead.
1454 if (isKnownNonNegative(Op))
1455 return getZeroExtendExpr(Op, Ty);
1457 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1458 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1459 // It's possible the bits taken off by the truncate were all sign bits. If
1460 // so, we should be able to simplify this further.
1461 const SCEV *X = ST->getOperand();
1462 ConstantRange CR = getSignedRange(X);
1463 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1464 unsigned NewBits = getTypeSizeInBits(Ty);
1465 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1466 CR.sextOrTrunc(NewBits)))
1467 return getTruncateOrSignExtend(X, Ty);
1470 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1471 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1472 if (SA->getNumOperands() == 2) {
1473 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1474 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1476 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1477 const APInt &C1 = SC1->getValue()->getValue();
1478 const APInt &C2 = SC2->getValue()->getValue();
1479 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1480 C2.ugt(C1) && C2.isPowerOf2())
1481 return getAddExpr(getSignExtendExpr(SC1, Ty),
1482 getSignExtendExpr(SMul, Ty));
1487 // If the input value is a chrec scev, and we can prove that the value
1488 // did not overflow the old, smaller, value, we can sign extend all of the
1489 // operands (often constants). This allows analysis of something like
1490 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1491 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1492 if (AR->isAffine()) {
1493 const SCEV *Start = AR->getStart();
1494 const SCEV *Step = AR->getStepRecurrence(*this);
1495 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1496 const Loop *L = AR->getLoop();
1498 // If we have special knowledge that this addrec won't overflow,
1499 // we don't need to do any further analysis.
1500 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1501 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1502 getSignExtendExpr(Step, Ty),
1505 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1506 // Note that this serves two purposes: It filters out loops that are
1507 // simply not analyzable, and it covers the case where this code is
1508 // being called from within backedge-taken count analysis, such that
1509 // attempting to ask for the backedge-taken count would likely result
1510 // in infinite recursion. In the later case, the analysis code will
1511 // cope with a conservative value, and it will take care to purge
1512 // that value once it has finished.
1513 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1514 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1515 // Manually compute the final value for AR, checking for
1518 // Check whether the backedge-taken count can be losslessly casted to
1519 // the addrec's type. The count is always unsigned.
1520 const SCEV *CastedMaxBECount =
1521 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1522 const SCEV *RecastedMaxBECount =
1523 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1524 if (MaxBECount == RecastedMaxBECount) {
1525 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1526 // Check whether Start+Step*MaxBECount has no signed overflow.
1527 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1528 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1529 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1530 const SCEV *WideMaxBECount =
1531 getZeroExtendExpr(CastedMaxBECount, WideTy);
1532 const SCEV *OperandExtendedAdd =
1533 getAddExpr(WideStart,
1534 getMulExpr(WideMaxBECount,
1535 getSignExtendExpr(Step, WideTy)));
1536 if (SAdd == OperandExtendedAdd) {
1537 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1538 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1539 // Return the expression with the addrec on the outside.
1540 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1541 getSignExtendExpr(Step, Ty),
1542 L, AR->getNoWrapFlags());
1544 // Similar to above, only this time treat the step value as unsigned.
1545 // This covers loops that count up with an unsigned step.
1546 OperandExtendedAdd =
1547 getAddExpr(WideStart,
1548 getMulExpr(WideMaxBECount,
1549 getZeroExtendExpr(Step, WideTy)));
1550 if (SAdd == OperandExtendedAdd) {
1551 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1552 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1553 // Return the expression with the addrec on the outside.
1554 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1555 getZeroExtendExpr(Step, Ty),
1556 L, AR->getNoWrapFlags());
1560 // If the backedge is guarded by a comparison with the pre-inc value
1561 // the addrec is safe. Also, if the entry is guarded by a comparison
1562 // with the start value and the backedge is guarded by a comparison
1563 // with the post-inc value, the addrec is safe.
1564 ICmpInst::Predicate Pred;
1565 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1566 if (OverflowLimit &&
1567 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1568 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1569 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1571 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1572 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1573 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1574 getSignExtendExpr(Step, Ty),
1575 L, AR->getNoWrapFlags());
1578 // If Start and Step are constants, check if we can apply this
1580 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1581 auto SC1 = dyn_cast<SCEVConstant>(Start);
1582 auto SC2 = dyn_cast<SCEVConstant>(Step);
1584 const APInt &C1 = SC1->getValue()->getValue();
1585 const APInt &C2 = SC2->getValue()->getValue();
1586 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1588 Start = getSignExtendExpr(Start, Ty);
1589 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1590 L, AR->getNoWrapFlags());
1591 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1596 // The cast wasn't folded; create an explicit cast node.
1597 // Recompute the insert position, as it may have been invalidated.
1598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1599 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1601 UniqueSCEVs.InsertNode(S, IP);
1605 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1606 /// unspecified bits out to the given type.
1608 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1610 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1611 "This is not an extending conversion!");
1612 assert(isSCEVable(Ty) &&
1613 "This is not a conversion to a SCEVable type!");
1614 Ty = getEffectiveSCEVType(Ty);
1616 // Sign-extend negative constants.
1617 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1618 if (SC->getValue()->getValue().isNegative())
1619 return getSignExtendExpr(Op, Ty);
1621 // Peel off a truncate cast.
1622 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1623 const SCEV *NewOp = T->getOperand();
1624 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1625 return getAnyExtendExpr(NewOp, Ty);
1626 return getTruncateOrNoop(NewOp, Ty);
1629 // Next try a zext cast. If the cast is folded, use it.
1630 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1631 if (!isa<SCEVZeroExtendExpr>(ZExt))
1634 // Next try a sext cast. If the cast is folded, use it.
1635 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1636 if (!isa<SCEVSignExtendExpr>(SExt))
1639 // Force the cast to be folded into the operands of an addrec.
1640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1641 SmallVector<const SCEV *, 4> Ops;
1642 for (const SCEV *Op : AR->operands())
1643 Ops.push_back(getAnyExtendExpr(Op, Ty));
1644 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1647 // If the expression is obviously signed, use the sext cast value.
1648 if (isa<SCEVSMaxExpr>(Op))
1651 // Absent any other information, use the zext cast value.
1655 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1656 /// a list of operands to be added under the given scale, update the given
1657 /// map. This is a helper function for getAddRecExpr. As an example of
1658 /// what it does, given a sequence of operands that would form an add
1659 /// expression like this:
1661 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1663 /// where A and B are constants, update the map with these values:
1665 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1667 /// and add 13 + A*B*29 to AccumulatedConstant.
1668 /// This will allow getAddRecExpr to produce this:
1670 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1672 /// This form often exposes folding opportunities that are hidden in
1673 /// the original operand list.
1675 /// Return true iff it appears that any interesting folding opportunities
1676 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1677 /// the common case where no interesting opportunities are present, and
1678 /// is also used as a check to avoid infinite recursion.
1681 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1682 SmallVectorImpl<const SCEV *> &NewOps,
1683 APInt &AccumulatedConstant,
1684 const SCEV *const *Ops, size_t NumOperands,
1686 ScalarEvolution &SE) {
1687 bool Interesting = false;
1689 // Iterate over the add operands. They are sorted, with constants first.
1691 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1693 // Pull a buried constant out to the outside.
1694 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1696 AccumulatedConstant += Scale * C->getValue()->getValue();
1699 // Next comes everything else. We're especially interested in multiplies
1700 // here, but they're in the middle, so just visit the rest with one loop.
1701 for (; i != NumOperands; ++i) {
1702 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1703 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1705 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1706 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1707 // A multiplication of a constant with another add; recurse.
1708 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1710 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1711 Add->op_begin(), Add->getNumOperands(),
1714 // A multiplication of a constant with some other value. Update
1716 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1717 const SCEV *Key = SE.getMulExpr(MulOps);
1718 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1719 M.insert(std::make_pair(Key, NewScale));
1721 NewOps.push_back(Pair.first->first);
1723 Pair.first->second += NewScale;
1724 // The map already had an entry for this value, which may indicate
1725 // a folding opportunity.
1730 // An ordinary operand. Update the map.
1731 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1732 M.insert(std::make_pair(Ops[i], Scale));
1734 NewOps.push_back(Pair.first->first);
1736 Pair.first->second += Scale;
1737 // The map already had an entry for this value, which may indicate
1738 // a folding opportunity.
1748 struct APIntCompare {
1749 bool operator()(const APInt &LHS, const APInt &RHS) const {
1750 return LHS.ult(RHS);
1755 /// getAddExpr - Get a canonical add expression, or something simpler if
1757 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1758 SCEV::NoWrapFlags Flags) {
1759 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1760 "only nuw or nsw allowed");
1761 assert(!Ops.empty() && "Cannot get empty add!");
1762 if (Ops.size() == 1) return Ops[0];
1764 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1765 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1766 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1767 "SCEVAddExpr operand types don't match!");
1770 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1772 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1773 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1774 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1776 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1777 E = Ops.end(); I != E; ++I)
1778 if (!isKnownNonNegative(*I)) {
1782 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1785 // Sort by complexity, this groups all similar expression types together.
1786 GroupByComplexity(Ops, LI);
1788 // If there are any constants, fold them together.
1790 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1792 assert(Idx < Ops.size());
1793 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1794 // We found two constants, fold them together!
1795 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1796 RHSC->getValue()->getValue());
1797 if (Ops.size() == 2) return Ops[0];
1798 Ops.erase(Ops.begin()+1); // Erase the folded element
1799 LHSC = cast<SCEVConstant>(Ops[0]);
1802 // If we are left with a constant zero being added, strip it off.
1803 if (LHSC->getValue()->isZero()) {
1804 Ops.erase(Ops.begin());
1808 if (Ops.size() == 1) return Ops[0];
1811 // Okay, check to see if the same value occurs in the operand list more than
1812 // once. If so, merge them together into an multiply expression. Since we
1813 // sorted the list, these values are required to be adjacent.
1814 Type *Ty = Ops[0]->getType();
1815 bool FoundMatch = false;
1816 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1817 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1818 // Scan ahead to count how many equal operands there are.
1820 while (i+Count != e && Ops[i+Count] == Ops[i])
1822 // Merge the values into a multiply.
1823 const SCEV *Scale = getConstant(Ty, Count);
1824 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1825 if (Ops.size() == Count)
1828 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1829 --i; e -= Count - 1;
1833 return getAddExpr(Ops, Flags);
1835 // Check for truncates. If all the operands are truncated from the same
1836 // type, see if factoring out the truncate would permit the result to be
1837 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1838 // if the contents of the resulting outer trunc fold to something simple.
1839 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1840 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1841 Type *DstType = Trunc->getType();
1842 Type *SrcType = Trunc->getOperand()->getType();
1843 SmallVector<const SCEV *, 8> LargeOps;
1845 // Check all the operands to see if they can be represented in the
1846 // source type of the truncate.
1847 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1848 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1849 if (T->getOperand()->getType() != SrcType) {
1853 LargeOps.push_back(T->getOperand());
1854 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1855 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1856 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1857 SmallVector<const SCEV *, 8> LargeMulOps;
1858 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1859 if (const SCEVTruncateExpr *T =
1860 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1861 if (T->getOperand()->getType() != SrcType) {
1865 LargeMulOps.push_back(T->getOperand());
1866 } else if (const SCEVConstant *C =
1867 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1868 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1875 LargeOps.push_back(getMulExpr(LargeMulOps));
1882 // Evaluate the expression in the larger type.
1883 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1884 // If it folds to something simple, use it. Otherwise, don't.
1885 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1886 return getTruncateExpr(Fold, DstType);
1890 // Skip past any other cast SCEVs.
1891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1894 // If there are add operands they would be next.
1895 if (Idx < Ops.size()) {
1896 bool DeletedAdd = false;
1897 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1898 // If we have an add, expand the add operands onto the end of the operands
1900 Ops.erase(Ops.begin()+Idx);
1901 Ops.append(Add->op_begin(), Add->op_end());
1905 // If we deleted at least one add, we added operands to the end of the list,
1906 // and they are not necessarily sorted. Recurse to resort and resimplify
1907 // any operands we just acquired.
1909 return getAddExpr(Ops);
1912 // Skip over the add expression until we get to a multiply.
1913 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1916 // Check to see if there are any folding opportunities present with
1917 // operands multiplied by constant values.
1918 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1919 uint64_t BitWidth = getTypeSizeInBits(Ty);
1920 DenseMap<const SCEV *, APInt> M;
1921 SmallVector<const SCEV *, 8> NewOps;
1922 APInt AccumulatedConstant(BitWidth, 0);
1923 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1924 Ops.data(), Ops.size(),
1925 APInt(BitWidth, 1), *this)) {
1926 // Some interesting folding opportunity is present, so its worthwhile to
1927 // re-generate the operands list. Group the operands by constant scale,
1928 // to avoid multiplying by the same constant scale multiple times.
1929 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1930 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
1931 E = NewOps.end(); I != E; ++I)
1932 MulOpLists[M.find(*I)->second].push_back(*I);
1933 // Re-generate the operands list.
1935 if (AccumulatedConstant != 0)
1936 Ops.push_back(getConstant(AccumulatedConstant));
1937 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1938 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1940 Ops.push_back(getMulExpr(getConstant(I->first),
1941 getAddExpr(I->second)));
1943 return getConstant(Ty, 0);
1944 if (Ops.size() == 1)
1946 return getAddExpr(Ops);
1950 // If we are adding something to a multiply expression, make sure the
1951 // something is not already an operand of the multiply. If so, merge it into
1953 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1954 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1955 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1956 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1957 if (isa<SCEVConstant>(MulOpSCEV))
1959 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1960 if (MulOpSCEV == Ops[AddOp]) {
1961 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1962 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1963 if (Mul->getNumOperands() != 2) {
1964 // If the multiply has more than two operands, we must get the
1966 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1967 Mul->op_begin()+MulOp);
1968 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1969 InnerMul = getMulExpr(MulOps);
1971 const SCEV *One = getConstant(Ty, 1);
1972 const SCEV *AddOne = getAddExpr(One, InnerMul);
1973 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1974 if (Ops.size() == 2) return OuterMul;
1976 Ops.erase(Ops.begin()+AddOp);
1977 Ops.erase(Ops.begin()+Idx-1);
1979 Ops.erase(Ops.begin()+Idx);
1980 Ops.erase(Ops.begin()+AddOp-1);
1982 Ops.push_back(OuterMul);
1983 return getAddExpr(Ops);
1986 // Check this multiply against other multiplies being added together.
1987 for (unsigned OtherMulIdx = Idx+1;
1988 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1990 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1991 // If MulOp occurs in OtherMul, we can fold the two multiplies
1993 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1994 OMulOp != e; ++OMulOp)
1995 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1996 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1997 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1998 if (Mul->getNumOperands() != 2) {
1999 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2000 Mul->op_begin()+MulOp);
2001 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2002 InnerMul1 = getMulExpr(MulOps);
2004 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2005 if (OtherMul->getNumOperands() != 2) {
2006 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2007 OtherMul->op_begin()+OMulOp);
2008 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2009 InnerMul2 = getMulExpr(MulOps);
2011 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2012 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2013 if (Ops.size() == 2) return OuterMul;
2014 Ops.erase(Ops.begin()+Idx);
2015 Ops.erase(Ops.begin()+OtherMulIdx-1);
2016 Ops.push_back(OuterMul);
2017 return getAddExpr(Ops);
2023 // If there are any add recurrences in the operands list, see if any other
2024 // added values are loop invariant. If so, we can fold them into the
2026 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2029 // Scan over all recurrences, trying to fold loop invariants into them.
2030 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2031 // Scan all of the other operands to this add and add them to the vector if
2032 // they are loop invariant w.r.t. the recurrence.
2033 SmallVector<const SCEV *, 8> LIOps;
2034 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2035 const Loop *AddRecLoop = AddRec->getLoop();
2036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2037 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2038 LIOps.push_back(Ops[i]);
2039 Ops.erase(Ops.begin()+i);
2043 // If we found some loop invariants, fold them into the recurrence.
2044 if (!LIOps.empty()) {
2045 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2046 LIOps.push_back(AddRec->getStart());
2048 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2050 AddRecOps[0] = getAddExpr(LIOps);
2052 // Build the new addrec. Propagate the NUW and NSW flags if both the
2053 // outer add and the inner addrec are guaranteed to have no overflow.
2054 // Always propagate NW.
2055 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2056 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2058 // If all of the other operands were loop invariant, we are done.
2059 if (Ops.size() == 1) return NewRec;
2061 // Otherwise, add the folded AddRec by the non-invariant parts.
2062 for (unsigned i = 0;; ++i)
2063 if (Ops[i] == AddRec) {
2067 return getAddExpr(Ops);
2070 // Okay, if there weren't any loop invariants to be folded, check to see if
2071 // there are multiple AddRec's with the same loop induction variable being
2072 // added together. If so, we can fold them.
2073 for (unsigned OtherIdx = Idx+1;
2074 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2076 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2077 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2078 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2080 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2082 if (const SCEVAddRecExpr *OtherAddRec =
2083 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2084 if (OtherAddRec->getLoop() == AddRecLoop) {
2085 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2087 if (i >= AddRecOps.size()) {
2088 AddRecOps.append(OtherAddRec->op_begin()+i,
2089 OtherAddRec->op_end());
2092 AddRecOps[i] = getAddExpr(AddRecOps[i],
2093 OtherAddRec->getOperand(i));
2095 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2097 // Step size has changed, so we cannot guarantee no self-wraparound.
2098 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2099 return getAddExpr(Ops);
2102 // Otherwise couldn't fold anything into this recurrence. Move onto the
2106 // Okay, it looks like we really DO need an add expr. Check to see if we
2107 // already have one, otherwise create a new one.
2108 FoldingSetNodeID ID;
2109 ID.AddInteger(scAddExpr);
2110 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2111 ID.AddPointer(Ops[i]);
2114 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2116 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2117 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2118 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2120 UniqueSCEVs.InsertNode(S, IP);
2122 S->setNoWrapFlags(Flags);
2126 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2128 if (j > 1 && k / j != i) Overflow = true;
2132 /// Compute the result of "n choose k", the binomial coefficient. If an
2133 /// intermediate computation overflows, Overflow will be set and the return will
2134 /// be garbage. Overflow is not cleared on absence of overflow.
2135 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2136 // We use the multiplicative formula:
2137 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2138 // At each iteration, we take the n-th term of the numeral and divide by the
2139 // (k-n)th term of the denominator. This division will always produce an
2140 // integral result, and helps reduce the chance of overflow in the
2141 // intermediate computations. However, we can still overflow even when the
2142 // final result would fit.
2144 if (n == 0 || n == k) return 1;
2145 if (k > n) return 0;
2151 for (uint64_t i = 1; i <= k; ++i) {
2152 r = umul_ov(r, n-(i-1), Overflow);
2158 /// getMulExpr - Get a canonical multiply expression, or something simpler if
2160 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2161 SCEV::NoWrapFlags Flags) {
2162 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2163 "only nuw or nsw allowed");
2164 assert(!Ops.empty() && "Cannot get empty mul!");
2165 if (Ops.size() == 1) return Ops[0];
2167 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2168 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2169 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2170 "SCEVMulExpr operand types don't match!");
2173 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2175 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2176 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2177 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2179 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
2180 E = Ops.end(); I != E; ++I)
2181 if (!isKnownNonNegative(*I)) {
2185 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2188 // Sort by complexity, this groups all similar expression types together.
2189 GroupByComplexity(Ops, LI);
2191 // If there are any constants, fold them together.
2193 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2195 // C1*(C2+V) -> C1*C2 + C1*V
2196 if (Ops.size() == 2)
2197 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2198 if (Add->getNumOperands() == 2 &&
2199 isa<SCEVConstant>(Add->getOperand(0)))
2200 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2201 getMulExpr(LHSC, Add->getOperand(1)));
2204 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2205 // We found two constants, fold them together!
2206 ConstantInt *Fold = ConstantInt::get(getContext(),
2207 LHSC->getValue()->getValue() *
2208 RHSC->getValue()->getValue());
2209 Ops[0] = getConstant(Fold);
2210 Ops.erase(Ops.begin()+1); // Erase the folded element
2211 if (Ops.size() == 1) return Ops[0];
2212 LHSC = cast<SCEVConstant>(Ops[0]);
2215 // If we are left with a constant one being multiplied, strip it off.
2216 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2217 Ops.erase(Ops.begin());
2219 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2220 // If we have a multiply of zero, it will always be zero.
2222 } else if (Ops[0]->isAllOnesValue()) {
2223 // If we have a mul by -1 of an add, try distributing the -1 among the
2225 if (Ops.size() == 2) {
2226 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2227 SmallVector<const SCEV *, 4> NewOps;
2228 bool AnyFolded = false;
2229 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2230 E = Add->op_end(); I != E; ++I) {
2231 const SCEV *Mul = getMulExpr(Ops[0], *I);
2232 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2233 NewOps.push_back(Mul);
2236 return getAddExpr(NewOps);
2238 else if (const SCEVAddRecExpr *
2239 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2240 // Negation preserves a recurrence's no self-wrap property.
2241 SmallVector<const SCEV *, 4> Operands;
2242 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2243 E = AddRec->op_end(); I != E; ++I) {
2244 Operands.push_back(getMulExpr(Ops[0], *I));
2246 return getAddRecExpr(Operands, AddRec->getLoop(),
2247 AddRec->getNoWrapFlags(SCEV::FlagNW));
2252 if (Ops.size() == 1)
2256 // Skip over the add expression until we get to a multiply.
2257 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2260 // If there are mul operands inline them all into this expression.
2261 if (Idx < Ops.size()) {
2262 bool DeletedMul = false;
2263 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2264 // If we have an mul, expand the mul operands onto the end of the operands
2266 Ops.erase(Ops.begin()+Idx);
2267 Ops.append(Mul->op_begin(), Mul->op_end());
2271 // If we deleted at least one mul, we added operands to the end of the list,
2272 // and they are not necessarily sorted. Recurse to resort and resimplify
2273 // any operands we just acquired.
2275 return getMulExpr(Ops);
2278 // If there are any add recurrences in the operands list, see if any other
2279 // added values are loop invariant. If so, we can fold them into the
2281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2284 // Scan over all recurrences, trying to fold loop invariants into them.
2285 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2286 // Scan all of the other operands to this mul and add them to the vector if
2287 // they are loop invariant w.r.t. the recurrence.
2288 SmallVector<const SCEV *, 8> LIOps;
2289 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2290 const Loop *AddRecLoop = AddRec->getLoop();
2291 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2292 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2293 LIOps.push_back(Ops[i]);
2294 Ops.erase(Ops.begin()+i);
2298 // If we found some loop invariants, fold them into the recurrence.
2299 if (!LIOps.empty()) {
2300 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2301 SmallVector<const SCEV *, 4> NewOps;
2302 NewOps.reserve(AddRec->getNumOperands());
2303 const SCEV *Scale = getMulExpr(LIOps);
2304 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2305 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2307 // Build the new addrec. Propagate the NUW and NSW flags if both the
2308 // outer mul and the inner addrec are guaranteed to have no overflow.
2310 // No self-wrap cannot be guaranteed after changing the step size, but
2311 // will be inferred if either NUW or NSW is true.
2312 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2313 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2315 // If all of the other operands were loop invariant, we are done.
2316 if (Ops.size() == 1) return NewRec;
2318 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2319 for (unsigned i = 0;; ++i)
2320 if (Ops[i] == AddRec) {
2324 return getMulExpr(Ops);
2327 // Okay, if there weren't any loop invariants to be folded, check to see if
2328 // there are multiple AddRec's with the same loop induction variable being
2329 // multiplied together. If so, we can fold them.
2331 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2332 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2333 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2334 // ]]],+,...up to x=2n}.
2335 // Note that the arguments to choose() are always integers with values
2336 // known at compile time, never SCEV objects.
2338 // The implementation avoids pointless extra computations when the two
2339 // addrec's are of different length (mathematically, it's equivalent to
2340 // an infinite stream of zeros on the right).
2341 bool OpsModified = false;
2342 for (unsigned OtherIdx = Idx+1;
2343 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2345 const SCEVAddRecExpr *OtherAddRec =
2346 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2347 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2350 bool Overflow = false;
2351 Type *Ty = AddRec->getType();
2352 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2353 SmallVector<const SCEV*, 7> AddRecOps;
2354 for (int x = 0, xe = AddRec->getNumOperands() +
2355 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2356 const SCEV *Term = getConstant(Ty, 0);
2357 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2358 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2359 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2360 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2361 z < ze && !Overflow; ++z) {
2362 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2364 if (LargerThan64Bits)
2365 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2367 Coeff = Coeff1*Coeff2;
2368 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2369 const SCEV *Term1 = AddRec->getOperand(y-z);
2370 const SCEV *Term2 = OtherAddRec->getOperand(z);
2371 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2374 AddRecOps.push_back(Term);
2377 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2379 if (Ops.size() == 2) return NewAddRec;
2380 Ops[Idx] = NewAddRec;
2381 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2383 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2389 return getMulExpr(Ops);
2391 // Otherwise couldn't fold anything into this recurrence. Move onto the
2395 // Okay, it looks like we really DO need an mul expr. Check to see if we
2396 // already have one, otherwise create a new one.
2397 FoldingSetNodeID ID;
2398 ID.AddInteger(scMulExpr);
2399 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2400 ID.AddPointer(Ops[i]);
2403 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2405 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2406 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2407 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2409 UniqueSCEVs.InsertNode(S, IP);
2411 S->setNoWrapFlags(Flags);
2415 /// getUDivExpr - Get a canonical unsigned division expression, or something
2416 /// simpler if possible.
2417 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2419 assert(getEffectiveSCEVType(LHS->getType()) ==
2420 getEffectiveSCEVType(RHS->getType()) &&
2421 "SCEVUDivExpr operand types don't match!");
2423 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2424 if (RHSC->getValue()->equalsInt(1))
2425 return LHS; // X udiv 1 --> x
2426 // If the denominator is zero, the result of the udiv is undefined. Don't
2427 // try to analyze it, because the resolution chosen here may differ from
2428 // the resolution chosen in other parts of the compiler.
2429 if (!RHSC->getValue()->isZero()) {
2430 // Determine if the division can be folded into the operands of
2432 // TODO: Generalize this to non-constants by using known-bits information.
2433 Type *Ty = LHS->getType();
2434 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2435 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2436 // For non-power-of-two values, effectively round the value up to the
2437 // nearest power of two.
2438 if (!RHSC->getValue()->getValue().isPowerOf2())
2440 IntegerType *ExtTy =
2441 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2442 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2443 if (const SCEVConstant *Step =
2444 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2445 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2446 const APInt &StepInt = Step->getValue()->getValue();
2447 const APInt &DivInt = RHSC->getValue()->getValue();
2448 if (!StepInt.urem(DivInt) &&
2449 getZeroExtendExpr(AR, ExtTy) ==
2450 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2451 getZeroExtendExpr(Step, ExtTy),
2452 AR->getLoop(), SCEV::FlagAnyWrap)) {
2453 SmallVector<const SCEV *, 4> Operands;
2454 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2455 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2456 return getAddRecExpr(Operands, AR->getLoop(),
2459 /// Get a canonical UDivExpr for a recurrence.
2460 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2461 // We can currently only fold X%N if X is constant.
2462 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2463 if (StartC && !DivInt.urem(StepInt) &&
2464 getZeroExtendExpr(AR, ExtTy) ==
2465 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2466 getZeroExtendExpr(Step, ExtTy),
2467 AR->getLoop(), SCEV::FlagAnyWrap)) {
2468 const APInt &StartInt = StartC->getValue()->getValue();
2469 const APInt &StartRem = StartInt.urem(StepInt);
2471 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2472 AR->getLoop(), SCEV::FlagNW);
2475 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2476 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2477 SmallVector<const SCEV *, 4> Operands;
2478 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2479 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2480 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2481 // Find an operand that's safely divisible.
2482 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2483 const SCEV *Op = M->getOperand(i);
2484 const SCEV *Div = getUDivExpr(Op, RHSC);
2485 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2486 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2489 return getMulExpr(Operands);
2493 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2494 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2495 SmallVector<const SCEV *, 4> Operands;
2496 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2497 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2498 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2500 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2501 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2502 if (isa<SCEVUDivExpr>(Op) ||
2503 getMulExpr(Op, RHS) != A->getOperand(i))
2505 Operands.push_back(Op);
2507 if (Operands.size() == A->getNumOperands())
2508 return getAddExpr(Operands);
2512 // Fold if both operands are constant.
2513 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2514 Constant *LHSCV = LHSC->getValue();
2515 Constant *RHSCV = RHSC->getValue();
2516 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2522 FoldingSetNodeID ID;
2523 ID.AddInteger(scUDivExpr);
2527 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2528 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2530 UniqueSCEVs.InsertNode(S, IP);
2534 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2535 APInt A = C1->getValue()->getValue().abs();
2536 APInt B = C2->getValue()->getValue().abs();
2537 uint32_t ABW = A.getBitWidth();
2538 uint32_t BBW = B.getBitWidth();
2545 return APIntOps::GreatestCommonDivisor(A, B);
2548 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2549 /// something simpler if possible. There is no representation for an exact udiv
2550 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2551 /// We can't do this when it's not exact because the udiv may be clearing bits.
2552 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2554 // TODO: we could try to find factors in all sorts of things, but for now we
2555 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2556 // end of this file for inspiration.
2558 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2560 return getUDivExpr(LHS, RHS);
2562 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2563 // If the mulexpr multiplies by a constant, then that constant must be the
2564 // first element of the mulexpr.
2565 if (const SCEVConstant *LHSCst =
2566 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2567 if (LHSCst == RHSCst) {
2568 SmallVector<const SCEV *, 2> Operands;
2569 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2570 return getMulExpr(Operands);
2573 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2574 // that there's a factor provided by one of the other terms. We need to
2576 APInt Factor = gcd(LHSCst, RHSCst);
2577 if (!Factor.isIntN(1)) {
2578 LHSCst = cast<SCEVConstant>(
2579 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2580 RHSCst = cast<SCEVConstant>(
2581 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2582 SmallVector<const SCEV *, 2> Operands;
2583 Operands.push_back(LHSCst);
2584 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2585 LHS = getMulExpr(Operands);
2587 Mul = dyn_cast<SCEVMulExpr>(LHS);
2589 return getUDivExactExpr(LHS, RHS);
2594 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2595 if (Mul->getOperand(i) == RHS) {
2596 SmallVector<const SCEV *, 2> Operands;
2597 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2598 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2599 return getMulExpr(Operands);
2603 return getUDivExpr(LHS, RHS);
2606 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2607 /// Simplify the expression as much as possible.
2608 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2610 SCEV::NoWrapFlags Flags) {
2611 SmallVector<const SCEV *, 4> Operands;
2612 Operands.push_back(Start);
2613 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2614 if (StepChrec->getLoop() == L) {
2615 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2616 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2619 Operands.push_back(Step);
2620 return getAddRecExpr(Operands, L, Flags);
2623 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2624 /// Simplify the expression as much as possible.
2626 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2627 const Loop *L, SCEV::NoWrapFlags Flags) {
2628 if (Operands.size() == 1) return Operands[0];
2630 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2631 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2632 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2633 "SCEVAddRecExpr operand types don't match!");
2634 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2635 assert(isLoopInvariant(Operands[i], L) &&
2636 "SCEVAddRecExpr operand is not loop-invariant!");
2639 if (Operands.back()->isZero()) {
2640 Operands.pop_back();
2641 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2644 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2645 // use that information to infer NUW and NSW flags. However, computing a
2646 // BE count requires calling getAddRecExpr, so we may not yet have a
2647 // meaningful BE count at this point (and if we don't, we'd be stuck
2648 // with a SCEVCouldNotCompute as the cached BE count).
2650 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2652 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2653 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2654 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2656 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2657 E = Operands.end(); I != E; ++I)
2658 if (!isKnownNonNegative(*I)) {
2662 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2665 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2666 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2667 const Loop *NestedLoop = NestedAR->getLoop();
2668 if (L->contains(NestedLoop) ?
2669 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2670 (!NestedLoop->contains(L) &&
2671 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2672 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2673 NestedAR->op_end());
2674 Operands[0] = NestedAR->getStart();
2675 // AddRecs require their operands be loop-invariant with respect to their
2676 // loops. Don't perform this transformation if it would break this
2678 bool AllInvariant = true;
2679 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2680 if (!isLoopInvariant(Operands[i], L)) {
2681 AllInvariant = false;
2685 // Create a recurrence for the outer loop with the same step size.
2687 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2688 // inner recurrence has the same property.
2689 SCEV::NoWrapFlags OuterFlags =
2690 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2692 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2693 AllInvariant = true;
2694 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2695 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2696 AllInvariant = false;
2700 // Ok, both add recurrences are valid after the transformation.
2702 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2703 // the outer recurrence has the same property.
2704 SCEV::NoWrapFlags InnerFlags =
2705 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2706 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2709 // Reset Operands to its original state.
2710 Operands[0] = NestedAR;
2714 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2715 // already have one, otherwise create a new one.
2716 FoldingSetNodeID ID;
2717 ID.AddInteger(scAddRecExpr);
2718 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2719 ID.AddPointer(Operands[i]);
2723 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2725 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2726 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2727 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2728 O, Operands.size(), L);
2729 UniqueSCEVs.InsertNode(S, IP);
2731 S->setNoWrapFlags(Flags);
2735 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2737 SmallVector<const SCEV *, 2> Ops;
2740 return getSMaxExpr(Ops);
2744 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2745 assert(!Ops.empty() && "Cannot get empty smax!");
2746 if (Ops.size() == 1) return Ops[0];
2748 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2749 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2750 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2751 "SCEVSMaxExpr operand types don't match!");
2754 // Sort by complexity, this groups all similar expression types together.
2755 GroupByComplexity(Ops, LI);
2757 // If there are any constants, fold them together.
2759 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2761 assert(Idx < Ops.size());
2762 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2763 // We found two constants, fold them together!
2764 ConstantInt *Fold = ConstantInt::get(getContext(),
2765 APIntOps::smax(LHSC->getValue()->getValue(),
2766 RHSC->getValue()->getValue()));
2767 Ops[0] = getConstant(Fold);
2768 Ops.erase(Ops.begin()+1); // Erase the folded element
2769 if (Ops.size() == 1) return Ops[0];
2770 LHSC = cast<SCEVConstant>(Ops[0]);
2773 // If we are left with a constant minimum-int, strip it off.
2774 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2775 Ops.erase(Ops.begin());
2777 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2778 // If we have an smax with a constant maximum-int, it will always be
2783 if (Ops.size() == 1) return Ops[0];
2786 // Find the first SMax
2787 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2790 // Check to see if one of the operands is an SMax. If so, expand its operands
2791 // onto our operand list, and recurse to simplify.
2792 if (Idx < Ops.size()) {
2793 bool DeletedSMax = false;
2794 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2795 Ops.erase(Ops.begin()+Idx);
2796 Ops.append(SMax->op_begin(), SMax->op_end());
2801 return getSMaxExpr(Ops);
2804 // Okay, check to see if the same value occurs in the operand list twice. If
2805 // so, delete one. Since we sorted the list, these values are required to
2807 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2808 // X smax Y smax Y --> X smax Y
2809 // X smax Y --> X, if X is always greater than Y
2810 if (Ops[i] == Ops[i+1] ||
2811 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2812 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2814 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2815 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2819 if (Ops.size() == 1) return Ops[0];
2821 assert(!Ops.empty() && "Reduced smax down to nothing!");
2823 // Okay, it looks like we really DO need an smax expr. Check to see if we
2824 // already have one, otherwise create a new one.
2825 FoldingSetNodeID ID;
2826 ID.AddInteger(scSMaxExpr);
2827 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828 ID.AddPointer(Ops[i]);
2830 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2831 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2832 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2833 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2835 UniqueSCEVs.InsertNode(S, IP);
2839 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2841 SmallVector<const SCEV *, 2> Ops;
2844 return getUMaxExpr(Ops);
2848 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2849 assert(!Ops.empty() && "Cannot get empty umax!");
2850 if (Ops.size() == 1) return Ops[0];
2852 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2853 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2854 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2855 "SCEVUMaxExpr operand types don't match!");
2858 // Sort by complexity, this groups all similar expression types together.
2859 GroupByComplexity(Ops, LI);
2861 // If there are any constants, fold them together.
2863 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2865 assert(Idx < Ops.size());
2866 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2867 // We found two constants, fold them together!
2868 ConstantInt *Fold = ConstantInt::get(getContext(),
2869 APIntOps::umax(LHSC->getValue()->getValue(),
2870 RHSC->getValue()->getValue()));
2871 Ops[0] = getConstant(Fold);
2872 Ops.erase(Ops.begin()+1); // Erase the folded element
2873 if (Ops.size() == 1) return Ops[0];
2874 LHSC = cast<SCEVConstant>(Ops[0]);
2877 // If we are left with a constant minimum-int, strip it off.
2878 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2879 Ops.erase(Ops.begin());
2881 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2882 // If we have an umax with a constant maximum-int, it will always be
2887 if (Ops.size() == 1) return Ops[0];
2890 // Find the first UMax
2891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2894 // Check to see if one of the operands is a UMax. If so, expand its operands
2895 // onto our operand list, and recurse to simplify.
2896 if (Idx < Ops.size()) {
2897 bool DeletedUMax = false;
2898 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2899 Ops.erase(Ops.begin()+Idx);
2900 Ops.append(UMax->op_begin(), UMax->op_end());
2905 return getUMaxExpr(Ops);
2908 // Okay, check to see if the same value occurs in the operand list twice. If
2909 // so, delete one. Since we sorted the list, these values are required to
2911 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2912 // X umax Y umax Y --> X umax Y
2913 // X umax Y --> X, if X is always greater than Y
2914 if (Ops[i] == Ops[i+1] ||
2915 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2916 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2918 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2919 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2923 if (Ops.size() == 1) return Ops[0];
2925 assert(!Ops.empty() && "Reduced umax down to nothing!");
2927 // Okay, it looks like we really DO need a umax expr. Check to see if we
2928 // already have one, otherwise create a new one.
2929 FoldingSetNodeID ID;
2930 ID.AddInteger(scUMaxExpr);
2931 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2932 ID.AddPointer(Ops[i]);
2934 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2935 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2936 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2937 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2939 UniqueSCEVs.InsertNode(S, IP);
2943 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2945 // ~smax(~x, ~y) == smin(x, y).
2946 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2949 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2951 // ~umax(~x, ~y) == umin(x, y)
2952 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2955 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
2956 // If we have DataLayout, we can bypass creating a target-independent
2957 // constant expression and then folding it back into a ConstantInt.
2958 // This is just a compile-time optimization.
2960 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
2962 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2964 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
2966 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2967 assert(Ty == IntTy && "Effective SCEV type doesn't match");
2968 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2971 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
2974 // If we have DataLayout, we can bypass creating a target-independent
2975 // constant expression and then folding it back into a ConstantInt.
2976 // This is just a compile-time optimization.
2978 return getConstant(IntTy,
2979 DL->getStructLayout(STy)->getElementOffset(FieldNo));
2982 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2983 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2984 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
2987 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2988 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2991 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2992 // Don't attempt to do anything other than create a SCEVUnknown object
2993 // here. createSCEV only calls getUnknown after checking for all other
2994 // interesting possibilities, and any other code that calls getUnknown
2995 // is doing so in order to hide a value from SCEV canonicalization.
2997 FoldingSetNodeID ID;
2998 ID.AddInteger(scUnknown);
3001 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3002 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3003 "Stale SCEVUnknown in uniquing map!");
3006 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3008 FirstUnknown = cast<SCEVUnknown>(S);
3009 UniqueSCEVs.InsertNode(S, IP);
3013 //===----------------------------------------------------------------------===//
3014 // Basic SCEV Analysis and PHI Idiom Recognition Code
3017 /// isSCEVable - Test if values of the given type are analyzable within
3018 /// the SCEV framework. This primarily includes integer types, and it
3019 /// can optionally include pointer types if the ScalarEvolution class
3020 /// has access to target-specific information.
3021 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3022 // Integers and pointers are always SCEVable.
3023 return Ty->isIntegerTy() || Ty->isPointerTy();
3026 /// getTypeSizeInBits - Return the size in bits of the specified type,
3027 /// for which isSCEVable must return true.
3028 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3029 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3031 // If we have a DataLayout, use it!
3033 return DL->getTypeSizeInBits(Ty);
3035 // Integer types have fixed sizes.
3036 if (Ty->isIntegerTy())
3037 return Ty->getPrimitiveSizeInBits();
3039 // The only other support type is pointer. Without DataLayout, conservatively
3040 // assume pointers are 64-bit.
3041 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
3045 /// getEffectiveSCEVType - Return a type with the same bitwidth as
3046 /// the given type and which represents how SCEV will treat the given
3047 /// type, for which isSCEVable must return true. For pointer types,
3048 /// this is the pointer-sized integer type.
3049 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3050 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3052 if (Ty->isIntegerTy()) {
3056 // The only other support type is pointer.
3057 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3060 return DL->getIntPtrType(Ty);
3062 // Without DataLayout, conservatively assume pointers are 64-bit.
3063 return Type::getInt64Ty(getContext());
3066 const SCEV *ScalarEvolution::getCouldNotCompute() {
3067 return &CouldNotCompute;
3071 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3072 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3073 // is set iff if find such SCEVUnknown.
3075 struct FindInvalidSCEVUnknown {
3077 FindInvalidSCEVUnknown() { FindOne = false; }
3078 bool follow(const SCEV *S) {
3079 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3083 if (!cast<SCEVUnknown>(S)->getValue())
3090 bool isDone() const { return FindOne; }
3094 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3095 FindInvalidSCEVUnknown F;
3096 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3102 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3103 /// expression and create a new one.
3104 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3105 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3107 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3108 if (I != ValueExprMap.end()) {
3109 const SCEV *S = I->second;
3110 if (checkValidity(S))
3113 ValueExprMap.erase(I);
3115 const SCEV *S = createSCEV(V);
3117 // The process of creating a SCEV for V may have caused other SCEVs
3118 // to have been created, so it's necessary to insert the new entry
3119 // from scratch, rather than trying to remember the insert position
3121 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3125 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3127 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
3128 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3130 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3132 Type *Ty = V->getType();
3133 Ty = getEffectiveSCEVType(Ty);
3134 return getMulExpr(V,
3135 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
3138 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3139 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3140 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3142 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3144 Type *Ty = V->getType();
3145 Ty = getEffectiveSCEVType(Ty);
3146 const SCEV *AllOnes =
3147 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3148 return getMinusSCEV(AllOnes, V);
3151 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
3152 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3153 SCEV::NoWrapFlags Flags) {
3154 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3156 // Fast path: X - X --> 0.
3158 return getConstant(LHS->getType(), 0);
3161 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
3164 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3165 /// input value to the specified type. If the type must be extended, it is zero
3168 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3169 Type *SrcTy = V->getType();
3170 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3171 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3172 "Cannot truncate or zero extend with non-integer arguments!");
3173 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3174 return V; // No conversion
3175 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3176 return getTruncateExpr(V, Ty);
3177 return getZeroExtendExpr(V, Ty);
3180 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3181 /// input value to the specified type. If the type must be extended, it is sign
3184 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3186 Type *SrcTy = V->getType();
3187 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3188 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3189 "Cannot truncate or zero extend with non-integer arguments!");
3190 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3191 return V; // No conversion
3192 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3193 return getTruncateExpr(V, Ty);
3194 return getSignExtendExpr(V, Ty);
3197 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3198 /// input value to the specified type. If the type must be extended, it is zero
3199 /// extended. The conversion must not be narrowing.
3201 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3202 Type *SrcTy = V->getType();
3203 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3204 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3205 "Cannot noop or zero extend with non-integer arguments!");
3206 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3207 "getNoopOrZeroExtend cannot truncate!");
3208 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3209 return V; // No conversion
3210 return getZeroExtendExpr(V, Ty);
3213 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3214 /// input value to the specified type. If the type must be extended, it is sign
3215 /// extended. The conversion must not be narrowing.
3217 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3218 Type *SrcTy = V->getType();
3219 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3220 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3221 "Cannot noop or sign extend with non-integer arguments!");
3222 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3223 "getNoopOrSignExtend cannot truncate!");
3224 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3225 return V; // No conversion
3226 return getSignExtendExpr(V, Ty);
3229 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3230 /// the input value to the specified type. If the type must be extended,
3231 /// it is extended with unspecified bits. The conversion must not be
3234 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3235 Type *SrcTy = V->getType();
3236 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3237 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3238 "Cannot noop or any extend with non-integer arguments!");
3239 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3240 "getNoopOrAnyExtend cannot truncate!");
3241 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3242 return V; // No conversion
3243 return getAnyExtendExpr(V, Ty);
3246 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3247 /// input value to the specified type. The conversion must not be widening.
3249 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3250 Type *SrcTy = V->getType();
3251 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3252 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3253 "Cannot truncate or noop with non-integer arguments!");
3254 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3255 "getTruncateOrNoop cannot extend!");
3256 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3257 return V; // No conversion
3258 return getTruncateExpr(V, Ty);
3261 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3262 /// the types using zero-extension, and then perform a umax operation
3264 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3266 const SCEV *PromotedLHS = LHS;
3267 const SCEV *PromotedRHS = RHS;
3269 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3270 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3272 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3274 return getUMaxExpr(PromotedLHS, PromotedRHS);
3277 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3278 /// the types using zero-extension, and then perform a umin operation
3280 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3282 const SCEV *PromotedLHS = LHS;
3283 const SCEV *PromotedRHS = RHS;
3285 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3286 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3288 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3290 return getUMinExpr(PromotedLHS, PromotedRHS);
3293 /// getPointerBase - Transitively follow the chain of pointer-type operands
3294 /// until reaching a SCEV that does not have a single pointer operand. This
3295 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3296 /// but corner cases do exist.
3297 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3298 // A pointer operand may evaluate to a nonpointer expression, such as null.
3299 if (!V->getType()->isPointerTy())
3302 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3303 return getPointerBase(Cast->getOperand());
3305 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3306 const SCEV *PtrOp = nullptr;
3307 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3309 if ((*I)->getType()->isPointerTy()) {
3310 // Cannot find the base of an expression with multiple pointer operands.
3318 return getPointerBase(PtrOp);
3323 /// PushDefUseChildren - Push users of the given Instruction
3324 /// onto the given Worklist.
3326 PushDefUseChildren(Instruction *I,
3327 SmallVectorImpl<Instruction *> &Worklist) {
3328 // Push the def-use children onto the Worklist stack.
3329 for (User *U : I->users())
3330 Worklist.push_back(cast<Instruction>(U));
3333 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3334 /// instructions that depend on the given instruction and removes them from
3335 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3338 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3339 SmallVector<Instruction *, 16> Worklist;
3340 PushDefUseChildren(PN, Worklist);
3342 SmallPtrSet<Instruction *, 8> Visited;
3344 while (!Worklist.empty()) {
3345 Instruction *I = Worklist.pop_back_val();
3346 if (!Visited.insert(I)) continue;
3348 ValueExprMapType::iterator It =
3349 ValueExprMap.find_as(static_cast<Value *>(I));
3350 if (It != ValueExprMap.end()) {
3351 const SCEV *Old = It->second;
3353 // Short-circuit the def-use traversal if the symbolic name
3354 // ceases to appear in expressions.
3355 if (Old != SymName && !hasOperand(Old, SymName))
3358 // SCEVUnknown for a PHI either means that it has an unrecognized
3359 // structure, it's a PHI that's in the progress of being computed
3360 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3361 // additional loop trip count information isn't going to change anything.
3362 // In the second case, createNodeForPHI will perform the necessary
3363 // updates on its own when it gets to that point. In the third, we do
3364 // want to forget the SCEVUnknown.
3365 if (!isa<PHINode>(I) ||
3366 !isa<SCEVUnknown>(Old) ||
3367 (I != PN && Old == SymName)) {
3368 forgetMemoizedResults(Old);
3369 ValueExprMap.erase(It);
3373 PushDefUseChildren(I, Worklist);
3377 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3378 /// a loop header, making it a potential recurrence, or it doesn't.
3380 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3381 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3382 if (L->getHeader() == PN->getParent()) {
3383 // The loop may have multiple entrances or multiple exits; we can analyze
3384 // this phi as an addrec if it has a unique entry value and a unique
3386 Value *BEValueV = nullptr, *StartValueV = nullptr;
3387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3388 Value *V = PN->getIncomingValue(i);
3389 if (L->contains(PN->getIncomingBlock(i))) {
3392 } else if (BEValueV != V) {
3396 } else if (!StartValueV) {
3398 } else if (StartValueV != V) {
3399 StartValueV = nullptr;
3403 if (BEValueV && StartValueV) {
3404 // While we are analyzing this PHI node, handle its value symbolically.
3405 const SCEV *SymbolicName = getUnknown(PN);
3406 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3407 "PHI node already processed?");
3408 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3410 // Using this symbolic name for the PHI, analyze the value coming around
3412 const SCEV *BEValue = getSCEV(BEValueV);
3414 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3415 // has a special value for the first iteration of the loop.
3417 // If the value coming around the backedge is an add with the symbolic
3418 // value we just inserted, then we found a simple induction variable!
3419 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3420 // If there is a single occurrence of the symbolic value, replace it
3421 // with a recurrence.
3422 unsigned FoundIndex = Add->getNumOperands();
3423 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3424 if (Add->getOperand(i) == SymbolicName)
3425 if (FoundIndex == e) {
3430 if (FoundIndex != Add->getNumOperands()) {
3431 // Create an add with everything but the specified operand.
3432 SmallVector<const SCEV *, 8> Ops;
3433 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3434 if (i != FoundIndex)
3435 Ops.push_back(Add->getOperand(i));
3436 const SCEV *Accum = getAddExpr(Ops);
3438 // This is not a valid addrec if the step amount is varying each
3439 // loop iteration, but is not itself an addrec in this loop.
3440 if (isLoopInvariant(Accum, L) ||
3441 (isa<SCEVAddRecExpr>(Accum) &&
3442 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3443 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3445 // If the increment doesn't overflow, then neither the addrec nor
3446 // the post-increment will overflow.
3447 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3448 if (OBO->hasNoUnsignedWrap())
3449 Flags = setFlags(Flags, SCEV::FlagNUW);
3450 if (OBO->hasNoSignedWrap())
3451 Flags = setFlags(Flags, SCEV::FlagNSW);
3452 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3453 // If the increment is an inbounds GEP, then we know the address
3454 // space cannot be wrapped around. We cannot make any guarantee
3455 // about signed or unsigned overflow because pointers are
3456 // unsigned but we may have a negative index from the base
3457 // pointer. We can guarantee that no unsigned wrap occurs if the
3458 // indices form a positive value.
3459 if (GEP->isInBounds()) {
3460 Flags = setFlags(Flags, SCEV::FlagNW);
3462 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3463 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3464 Flags = setFlags(Flags, SCEV::FlagNUW);
3466 } else if (const SubOperator *OBO =
3467 dyn_cast<SubOperator>(BEValueV)) {
3468 if (OBO->hasNoUnsignedWrap())
3469 Flags = setFlags(Flags, SCEV::FlagNUW);
3470 if (OBO->hasNoSignedWrap())
3471 Flags = setFlags(Flags, SCEV::FlagNSW);
3474 const SCEV *StartVal = getSCEV(StartValueV);
3475 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3477 // Since the no-wrap flags are on the increment, they apply to the
3478 // post-incremented value as well.
3479 if (isLoopInvariant(Accum, L))
3480 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
3483 // Okay, for the entire analysis of this edge we assumed the PHI
3484 // to be symbolic. We now need to go back and purge all of the
3485 // entries for the scalars that use the symbolic expression.
3486 ForgetSymbolicName(PN, SymbolicName);
3487 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3491 } else if (const SCEVAddRecExpr *AddRec =
3492 dyn_cast<SCEVAddRecExpr>(BEValue)) {
3493 // Otherwise, this could be a loop like this:
3494 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3495 // In this case, j = {1,+,1} and BEValue is j.
3496 // Because the other in-value of i (0) fits the evolution of BEValue
3497 // i really is an addrec evolution.
3498 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3499 const SCEV *StartVal = getSCEV(StartValueV);
3501 // If StartVal = j.start - j.stride, we can use StartVal as the
3502 // initial step of the addrec evolution.
3503 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3504 AddRec->getOperand(1))) {
3505 // FIXME: For constant StartVal, we should be able to infer
3507 const SCEV *PHISCEV =
3508 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3511 // Okay, for the entire analysis of this edge we assumed the PHI
3512 // to be symbolic. We now need to go back and purge all of the
3513 // entries for the scalars that use the symbolic expression.
3514 ForgetSymbolicName(PN, SymbolicName);
3515 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3523 // If the PHI has a single incoming value, follow that value, unless the
3524 // PHI's incoming blocks are in a different loop, in which case doing so
3525 // risks breaking LCSSA form. Instcombine would normally zap these, but
3526 // it doesn't have DominatorTree information, so it may miss cases.
3527 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AT))
3528 if (LI->replacementPreservesLCSSAForm(PN, V))
3531 // If it's not a loop phi, we can't handle it yet.
3532 return getUnknown(PN);
3535 /// createNodeForGEP - Expand GEP instructions into add and multiply
3536 /// operations. This allows them to be analyzed by regular SCEV code.
3538 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3539 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3540 Value *Base = GEP->getOperand(0);
3541 // Don't attempt to analyze GEPs over unsized objects.
3542 if (!Base->getType()->getPointerElementType()->isSized())
3543 return getUnknown(GEP);
3545 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3546 // Add expression, because the Instruction may be guarded by control flow
3547 // and the no-overflow bits may not be valid for the expression in any
3549 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3551 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3552 gep_type_iterator GTI = gep_type_begin(GEP);
3553 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
3557 // Compute the (potentially symbolic) offset in bytes for this index.
3558 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3559 // For a struct, add the member offset.
3560 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3561 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3563 // Add the field offset to the running total offset.
3564 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3566 // For an array, add the element offset, explicitly scaled.
3567 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
3568 const SCEV *IndexS = getSCEV(Index);
3569 // Getelementptr indices are signed.
3570 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3572 // Multiply the index by the element size to compute the element offset.
3573 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
3575 // Add the element offset to the running total offset.
3576 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3580 // Get the SCEV for the GEP base.
3581 const SCEV *BaseS = getSCEV(Base);
3583 // Add the total offset from all the GEP indices to the base.
3584 return getAddExpr(BaseS, TotalOffset, Wrap);
3587 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3588 /// guaranteed to end in (at every loop iteration). It is, at the same time,
3589 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3590 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
3592 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3593 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3594 return C->getValue()->getValue().countTrailingZeros();
3596 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3597 return std::min(GetMinTrailingZeros(T->getOperand()),
3598 (uint32_t)getTypeSizeInBits(T->getType()));
3600 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3601 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3602 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3603 getTypeSizeInBits(E->getType()) : OpRes;
3606 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3607 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3608 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3609 getTypeSizeInBits(E->getType()) : OpRes;
3612 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3613 // The result is the min of all operands results.
3614 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3615 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3616 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3620 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3621 // The result is the sum of all operands results.
3622 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3623 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3624 for (unsigned i = 1, e = M->getNumOperands();
3625 SumOpRes != BitWidth && i != e; ++i)
3626 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3631 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3632 // The result is the min of all operands results.
3633 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3634 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3635 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3639 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3640 // The result is the min of all operands results.
3641 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3642 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3643 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3647 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3648 // The result is the min of all operands results.
3649 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3650 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3651 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3655 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3656 // For a SCEVUnknown, ask ValueTracking.
3657 unsigned BitWidth = getTypeSizeInBits(U->getType());
3658 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3659 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3660 return Zeros.countTrailingOnes();
3667 /// GetRangeFromMetadata - Helper method to assign a range to V from
3668 /// metadata present in the IR.
3669 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3670 if (Instruction *I = dyn_cast<Instruction>(V)) {
3671 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
3672 ConstantRange TotalRange(
3673 cast<IntegerType>(I->getType())->getBitWidth(), false);
3675 unsigned NumRanges = MD->getNumOperands() / 2;
3676 assert(NumRanges >= 1);
3678 for (unsigned i = 0; i < NumRanges; ++i) {
3679 ConstantInt *Lower = cast<ConstantInt>(MD->getOperand(2*i + 0));
3680 ConstantInt *Upper = cast<ConstantInt>(MD->getOperand(2*i + 1));
3681 ConstantRange Range(Lower->getValue(), Upper->getValue());
3682 TotalRange = TotalRange.unionWith(Range);
3692 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3695 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3696 // See if we've computed this range already.
3697 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3698 if (I != UnsignedRanges.end())
3701 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3702 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3704 unsigned BitWidth = getTypeSizeInBits(S->getType());
3705 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3707 // If the value has known zeros, the maximum unsigned value will have those
3708 // known zeros as well.
3709 uint32_t TZ = GetMinTrailingZeros(S);
3711 ConservativeResult =
3712 ConstantRange(APInt::getMinValue(BitWidth),
3713 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3715 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3716 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3717 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3718 X = X.add(getUnsignedRange(Add->getOperand(i)));
3719 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3722 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3723 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3724 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3725 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3726 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3729 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3730 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3731 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3732 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3733 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3736 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3737 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3738 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3739 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3740 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3743 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3744 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3745 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3746 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3749 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3750 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3751 return setUnsignedRange(ZExt,
3752 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3755 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3756 ConstantRange X = getUnsignedRange(SExt->getOperand());
3757 return setUnsignedRange(SExt,
3758 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3761 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3762 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3763 return setUnsignedRange(Trunc,
3764 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3767 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3768 // If there's no unsigned wrap, the value will never be less than its
3770 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3771 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3772 if (!C->getValue()->isZero())
3773 ConservativeResult =
3774 ConservativeResult.intersectWith(
3775 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3777 // TODO: non-affine addrec
3778 if (AddRec->isAffine()) {
3779 Type *Ty = AddRec->getType();
3780 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3781 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3782 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3783 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3785 const SCEV *Start = AddRec->getStart();
3786 const SCEV *Step = AddRec->getStepRecurrence(*this);
3788 ConstantRange StartRange = getUnsignedRange(Start);
3789 ConstantRange StepRange = getSignedRange(Step);
3790 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3791 ConstantRange EndRange =
3792 StartRange.add(MaxBECountRange.multiply(StepRange));
3794 // Check for overflow. This must be done with ConstantRange arithmetic
3795 // because we could be called from within the ScalarEvolution overflow
3797 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3798 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3799 ConstantRange ExtMaxBECountRange =
3800 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3801 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3802 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3804 return setUnsignedRange(AddRec, ConservativeResult);
3806 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3807 EndRange.getUnsignedMin());
3808 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3809 EndRange.getUnsignedMax());
3810 if (Min.isMinValue() && Max.isMaxValue())
3811 return setUnsignedRange(AddRec, ConservativeResult);
3812 return setUnsignedRange(AddRec,
3813 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3817 return setUnsignedRange(AddRec, ConservativeResult);
3820 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3821 // Check if the IR explicitly contains !range metadata.
3822 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3823 if (MDRange.hasValue())
3824 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3826 // For a SCEVUnknown, ask ValueTracking.
3827 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3828 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3829 if (Ones == ~Zeros + 1)
3830 return setUnsignedRange(U, ConservativeResult);
3831 return setUnsignedRange(U,
3832 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3835 return setUnsignedRange(S, ConservativeResult);
3838 /// getSignedRange - Determine the signed range for a particular SCEV.
3841 ScalarEvolution::getSignedRange(const SCEV *S) {
3842 // See if we've computed this range already.
3843 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3844 if (I != SignedRanges.end())
3847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3848 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3850 unsigned BitWidth = getTypeSizeInBits(S->getType());
3851 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3853 // If the value has known zeros, the maximum signed value will have those
3854 // known zeros as well.
3855 uint32_t TZ = GetMinTrailingZeros(S);
3857 ConservativeResult =
3858 ConstantRange(APInt::getSignedMinValue(BitWidth),
3859 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3861 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3862 ConstantRange X = getSignedRange(Add->getOperand(0));
3863 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3864 X = X.add(getSignedRange(Add->getOperand(i)));
3865 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3868 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3869 ConstantRange X = getSignedRange(Mul->getOperand(0));
3870 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3871 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3872 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3875 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3876 ConstantRange X = getSignedRange(SMax->getOperand(0));
3877 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3878 X = X.smax(getSignedRange(SMax->getOperand(i)));
3879 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3882 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3883 ConstantRange X = getSignedRange(UMax->getOperand(0));
3884 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3885 X = X.umax(getSignedRange(UMax->getOperand(i)));
3886 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3889 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3890 ConstantRange X = getSignedRange(UDiv->getLHS());
3891 ConstantRange Y = getSignedRange(UDiv->getRHS());
3892 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3895 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3896 ConstantRange X = getSignedRange(ZExt->getOperand());
3897 return setSignedRange(ZExt,
3898 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3901 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3902 ConstantRange X = getSignedRange(SExt->getOperand());
3903 return setSignedRange(SExt,
3904 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3907 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3908 ConstantRange X = getSignedRange(Trunc->getOperand());
3909 return setSignedRange(Trunc,
3910 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3913 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3914 // If there's no signed wrap, and all the operands have the same sign or
3915 // zero, the value won't ever change sign.
3916 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3917 bool AllNonNeg = true;
3918 bool AllNonPos = true;
3919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3920 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3921 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3924 ConservativeResult = ConservativeResult.intersectWith(
3925 ConstantRange(APInt(BitWidth, 0),
3926 APInt::getSignedMinValue(BitWidth)));
3928 ConservativeResult = ConservativeResult.intersectWith(
3929 ConstantRange(APInt::getSignedMinValue(BitWidth),
3930 APInt(BitWidth, 1)));
3933 // TODO: non-affine addrec
3934 if (AddRec->isAffine()) {
3935 Type *Ty = AddRec->getType();
3936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3937 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3938 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3939 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3941 const SCEV *Start = AddRec->getStart();
3942 const SCEV *Step = AddRec->getStepRecurrence(*this);
3944 ConstantRange StartRange = getSignedRange(Start);
3945 ConstantRange StepRange = getSignedRange(Step);
3946 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3947 ConstantRange EndRange =
3948 StartRange.add(MaxBECountRange.multiply(StepRange));
3950 // Check for overflow. This must be done with ConstantRange arithmetic
3951 // because we could be called from within the ScalarEvolution overflow
3953 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3954 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3955 ConstantRange ExtMaxBECountRange =
3956 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3957 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3958 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3960 return setSignedRange(AddRec, ConservativeResult);
3962 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3963 EndRange.getSignedMin());
3964 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3965 EndRange.getSignedMax());
3966 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3967 return setSignedRange(AddRec, ConservativeResult);
3968 return setSignedRange(AddRec,
3969 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3973 return setSignedRange(AddRec, ConservativeResult);
3976 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3977 // Check if the IR explicitly contains !range metadata.
3978 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3979 if (MDRange.hasValue())
3980 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3982 // For a SCEVUnknown, ask ValueTracking.
3983 if (!U->getValue()->getType()->isIntegerTy() && !DL)
3984 return setSignedRange(U, ConservativeResult);
3985 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AT, nullptr, DT);
3987 return setSignedRange(U, ConservativeResult);
3988 return setSignedRange(U, ConservativeResult.intersectWith(
3989 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3990 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3993 return setSignedRange(S, ConservativeResult);
3996 /// createSCEV - We know that there is no SCEV for the specified value.
3997 /// Analyze the expression.
3999 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4000 if (!isSCEVable(V->getType()))
4001 return getUnknown(V);
4003 unsigned Opcode = Instruction::UserOp1;
4004 if (Instruction *I = dyn_cast<Instruction>(V)) {
4005 Opcode = I->getOpcode();
4007 // Don't attempt to analyze instructions in blocks that aren't
4008 // reachable. Such instructions don't matter, and they aren't required
4009 // to obey basic rules for definitions dominating uses which this
4010 // analysis depends on.
4011 if (!DT->isReachableFromEntry(I->getParent()))
4012 return getUnknown(V);
4013 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4014 Opcode = CE->getOpcode();
4015 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4016 return getConstant(CI);
4017 else if (isa<ConstantPointerNull>(V))
4018 return getConstant(V->getType(), 0);
4019 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4020 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
4022 return getUnknown(V);
4024 Operator *U = cast<Operator>(V);
4026 case Instruction::Add: {
4027 // The simple thing to do would be to just call getSCEV on both operands
4028 // and call getAddExpr with the result. However if we're looking at a
4029 // bunch of things all added together, this can be quite inefficient,
4030 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4031 // Instead, gather up all the operands and make a single getAddExpr call.
4032 // LLVM IR canonical form means we need only traverse the left operands.
4034 // Don't apply this instruction's NSW or NUW flags to the new
4035 // expression. The instruction may be guarded by control flow that the
4036 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4037 // mapped to the same SCEV expression, and it would be incorrect to transfer
4038 // NSW/NUW semantics to those operations.
4039 SmallVector<const SCEV *, 4> AddOps;
4040 AddOps.push_back(getSCEV(U->getOperand(1)));
4041 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4042 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4043 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4045 U = cast<Operator>(Op);
4046 const SCEV *Op1 = getSCEV(U->getOperand(1));
4047 if (Opcode == Instruction::Sub)
4048 AddOps.push_back(getNegativeSCEV(Op1));
4050 AddOps.push_back(Op1);
4052 AddOps.push_back(getSCEV(U->getOperand(0)));
4053 return getAddExpr(AddOps);
4055 case Instruction::Mul: {
4056 // Don't transfer NSW/NUW for the same reason as AddExpr.
4057 SmallVector<const SCEV *, 4> MulOps;
4058 MulOps.push_back(getSCEV(U->getOperand(1)));
4059 for (Value *Op = U->getOperand(0);
4060 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
4061 Op = U->getOperand(0)) {
4062 U = cast<Operator>(Op);
4063 MulOps.push_back(getSCEV(U->getOperand(1)));
4065 MulOps.push_back(getSCEV(U->getOperand(0)));
4066 return getMulExpr(MulOps);
4068 case Instruction::UDiv:
4069 return getUDivExpr(getSCEV(U->getOperand(0)),
4070 getSCEV(U->getOperand(1)));
4071 case Instruction::Sub:
4072 return getMinusSCEV(getSCEV(U->getOperand(0)),
4073 getSCEV(U->getOperand(1)));
4074 case Instruction::And:
4075 // For an expression like x&255 that merely masks off the high bits,
4076 // use zext(trunc(x)) as the SCEV expression.
4077 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4078 if (CI->isNullValue())
4079 return getSCEV(U->getOperand(1));
4080 if (CI->isAllOnesValue())
4081 return getSCEV(U->getOperand(0));
4082 const APInt &A = CI->getValue();
4084 // Instcombine's ShrinkDemandedConstant may strip bits out of
4085 // constants, obscuring what would otherwise be a low-bits mask.
4086 // Use computeKnownBits to compute what ShrinkDemandedConstant
4087 // knew about to reconstruct a low-bits mask value.
4088 unsigned LZ = A.countLeadingZeros();
4089 unsigned TZ = A.countTrailingZeros();
4090 unsigned BitWidth = A.getBitWidth();
4091 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4092 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL,
4093 0, AT, nullptr, DT);
4095 APInt EffectiveMask =
4096 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4097 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4098 const SCEV *MulCount = getConstant(
4099 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4103 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4104 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4111 case Instruction::Or:
4112 // If the RHS of the Or is a constant, we may have something like:
4113 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4114 // optimizations will transparently handle this case.
4116 // In order for this transformation to be safe, the LHS must be of the
4117 // form X*(2^n) and the Or constant must be less than 2^n.
4118 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4119 const SCEV *LHS = getSCEV(U->getOperand(0));
4120 const APInt &CIVal = CI->getValue();
4121 if (GetMinTrailingZeros(LHS) >=
4122 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4123 // Build a plain add SCEV.
4124 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4125 // If the LHS of the add was an addrec and it has no-wrap flags,
4126 // transfer the no-wrap flags, since an or won't introduce a wrap.
4127 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4128 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
4129 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4130 OldAR->getNoWrapFlags());
4136 case Instruction::Xor:
4137 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4138 // If the RHS of the xor is a signbit, then this is just an add.
4139 // Instcombine turns add of signbit into xor as a strength reduction step.
4140 if (CI->getValue().isSignBit())
4141 return getAddExpr(getSCEV(U->getOperand(0)),
4142 getSCEV(U->getOperand(1)));
4144 // If the RHS of xor is -1, then this is a not operation.
4145 if (CI->isAllOnesValue())
4146 return getNotSCEV(getSCEV(U->getOperand(0)));
4148 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4149 // This is a variant of the check for xor with -1, and it handles
4150 // the case where instcombine has trimmed non-demanded bits out
4151 // of an xor with -1.
4152 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4153 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4154 if (BO->getOpcode() == Instruction::And &&
4155 LCI->getValue() == CI->getValue())
4156 if (const SCEVZeroExtendExpr *Z =
4157 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
4158 Type *UTy = U->getType();
4159 const SCEV *Z0 = Z->getOperand();
4160 Type *Z0Ty = Z0->getType();
4161 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4163 // If C is a low-bits mask, the zero extend is serving to
4164 // mask off the high bits. Complement the operand and
4165 // re-apply the zext.
4166 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4167 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4169 // If C is a single bit, it may be in the sign-bit position
4170 // before the zero-extend. In this case, represent the xor
4171 // using an add, which is equivalent, and re-apply the zext.
4172 APInt Trunc = CI->getValue().trunc(Z0TySize);
4173 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
4175 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4181 case Instruction::Shl:
4182 // Turn shift left of a constant amount into a multiply.
4183 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4184 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4186 // If the shift count is not less than the bitwidth, the result of
4187 // the shift is undefined. Don't try to analyze it, because the
4188 // resolution chosen here may differ from the resolution chosen in
4189 // other parts of the compiler.
4190 if (SA->getValue().uge(BitWidth))
4193 Constant *X = ConstantInt::get(getContext(),
4194 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4195 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4199 case Instruction::LShr:
4200 // Turn logical shift right of a constant into a unsigned divide.
4201 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4202 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4204 // If the shift count is not less than the bitwidth, the result of
4205 // the shift is undefined. Don't try to analyze it, because the
4206 // resolution chosen here may differ from the resolution chosen in
4207 // other parts of the compiler.
4208 if (SA->getValue().uge(BitWidth))
4211 Constant *X = ConstantInt::get(getContext(),
4212 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4213 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4217 case Instruction::AShr:
4218 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4219 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
4220 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
4221 if (L->getOpcode() == Instruction::Shl &&
4222 L->getOperand(1) == U->getOperand(1)) {
4223 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4225 // If the shift count is not less than the bitwidth, the result of
4226 // the shift is undefined. Don't try to analyze it, because the
4227 // resolution chosen here may differ from the resolution chosen in
4228 // other parts of the compiler.
4229 if (CI->getValue().uge(BitWidth))
4232 uint64_t Amt = BitWidth - CI->getZExtValue();
4233 if (Amt == BitWidth)
4234 return getSCEV(L->getOperand(0)); // shift by zero --> noop
4236 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
4237 IntegerType::get(getContext(),
4243 case Instruction::Trunc:
4244 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
4246 case Instruction::ZExt:
4247 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4249 case Instruction::SExt:
4250 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4252 case Instruction::BitCast:
4253 // BitCasts are no-op casts so we just eliminate the cast.
4254 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
4255 return getSCEV(U->getOperand(0));
4258 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4259 // lead to pointer expressions which cannot safely be expanded to GEPs,
4260 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4261 // simplifying integer expressions.
4263 case Instruction::GetElementPtr:
4264 return createNodeForGEP(cast<GEPOperator>(U));
4266 case Instruction::PHI:
4267 return createNodeForPHI(cast<PHINode>(U));
4269 case Instruction::Select:
4270 // This could be a smax or umax that was lowered earlier.
4271 // Try to recover it.
4272 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4273 Value *LHS = ICI->getOperand(0);
4274 Value *RHS = ICI->getOperand(1);
4275 switch (ICI->getPredicate()) {
4276 case ICmpInst::ICMP_SLT:
4277 case ICmpInst::ICMP_SLE:
4278 std::swap(LHS, RHS);
4280 case ICmpInst::ICMP_SGT:
4281 case ICmpInst::ICMP_SGE:
4282 // a >s b ? a+x : b+x -> smax(a, b)+x
4283 // a >s b ? b+x : a+x -> smin(a, b)+x
4284 if (LHS->getType() == U->getType()) {
4285 const SCEV *LS = getSCEV(LHS);
4286 const SCEV *RS = getSCEV(RHS);
4287 const SCEV *LA = getSCEV(U->getOperand(1));
4288 const SCEV *RA = getSCEV(U->getOperand(2));
4289 const SCEV *LDiff = getMinusSCEV(LA, LS);
4290 const SCEV *RDiff = getMinusSCEV(RA, RS);
4292 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4293 LDiff = getMinusSCEV(LA, RS);
4294 RDiff = getMinusSCEV(RA, LS);
4296 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4299 case ICmpInst::ICMP_ULT:
4300 case ICmpInst::ICMP_ULE:
4301 std::swap(LHS, RHS);
4303 case ICmpInst::ICMP_UGT:
4304 case ICmpInst::ICMP_UGE:
4305 // a >u b ? a+x : b+x -> umax(a, b)+x
4306 // a >u b ? b+x : a+x -> umin(a, b)+x
4307 if (LHS->getType() == U->getType()) {
4308 const SCEV *LS = getSCEV(LHS);
4309 const SCEV *RS = getSCEV(RHS);
4310 const SCEV *LA = getSCEV(U->getOperand(1));
4311 const SCEV *RA = getSCEV(U->getOperand(2));
4312 const SCEV *LDiff = getMinusSCEV(LA, LS);
4313 const SCEV *RDiff = getMinusSCEV(RA, RS);
4315 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4316 LDiff = getMinusSCEV(LA, RS);
4317 RDiff = getMinusSCEV(RA, LS);
4319 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4322 case ICmpInst::ICMP_NE:
4323 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4324 if (LHS->getType() == U->getType() &&
4325 isa<ConstantInt>(RHS) &&
4326 cast<ConstantInt>(RHS)->isZero()) {
4327 const SCEV *One = getConstant(LHS->getType(), 1);
4328 const SCEV *LS = getSCEV(LHS);
4329 const SCEV *LA = getSCEV(U->getOperand(1));
4330 const SCEV *RA = getSCEV(U->getOperand(2));
4331 const SCEV *LDiff = getMinusSCEV(LA, LS);
4332 const SCEV *RDiff = getMinusSCEV(RA, One);
4334 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4337 case ICmpInst::ICMP_EQ:
4338 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4339 if (LHS->getType() == U->getType() &&
4340 isa<ConstantInt>(RHS) &&
4341 cast<ConstantInt>(RHS)->isZero()) {
4342 const SCEV *One = getConstant(LHS->getType(), 1);
4343 const SCEV *LS = getSCEV(LHS);
4344 const SCEV *LA = getSCEV(U->getOperand(1));
4345 const SCEV *RA = getSCEV(U->getOperand(2));
4346 const SCEV *LDiff = getMinusSCEV(LA, One);
4347 const SCEV *RDiff = getMinusSCEV(RA, LS);
4349 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4357 default: // We cannot analyze this expression.
4361 return getUnknown(V);
4366 //===----------------------------------------------------------------------===//
4367 // Iteration Count Computation Code
4370 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4371 if (BasicBlock *ExitingBB = L->getExitingBlock())
4372 return getSmallConstantTripCount(L, ExitingBB);
4374 // No trip count information for multiple exits.
4378 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
4379 /// normal unsigned value. Returns 0 if the trip count is unknown or not
4380 /// constant. Will also return 0 if the maximum trip count is very large (>=
4383 /// This "trip count" assumes that control exits via ExitingBlock. More
4384 /// precisely, it is the number of times that control may reach ExitingBlock
4385 /// before taking the branch. For loops with multiple exits, it may not be the
4386 /// number times that the loop header executes because the loop may exit
4387 /// prematurely via another branch.
4388 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4389 BasicBlock *ExitingBlock) {
4390 assert(ExitingBlock && "Must pass a non-null exiting block!");
4391 assert(L->isLoopExiting(ExitingBlock) &&
4392 "Exiting block must actually branch out of the loop!");
4393 const SCEVConstant *ExitCount =
4394 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
4398 ConstantInt *ExitConst = ExitCount->getValue();
4400 // Guard against huge trip counts.
4401 if (ExitConst->getValue().getActiveBits() > 32)
4404 // In case of integer overflow, this returns 0, which is correct.
4405 return ((unsigned)ExitConst->getZExtValue()) + 1;
4408 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4409 if (BasicBlock *ExitingBB = L->getExitingBlock())
4410 return getSmallConstantTripMultiple(L, ExitingBB);
4412 // No trip multiple information for multiple exits.
4416 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4417 /// trip count of this loop as a normal unsigned value, if possible. This
4418 /// means that the actual trip count is always a multiple of the returned
4419 /// value (don't forget the trip count could very well be zero as well!).
4421 /// Returns 1 if the trip count is unknown or not guaranteed to be the
4422 /// multiple of a constant (which is also the case if the trip count is simply
4423 /// constant, use getSmallConstantTripCount for that case), Will also return 1
4424 /// if the trip count is very large (>= 2^32).
4426 /// As explained in the comments for getSmallConstantTripCount, this assumes
4427 /// that control exits the loop via ExitingBlock.
4429 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4430 BasicBlock *ExitingBlock) {
4431 assert(ExitingBlock && "Must pass a non-null exiting block!");
4432 assert(L->isLoopExiting(ExitingBlock) &&
4433 "Exiting block must actually branch out of the loop!");
4434 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
4435 if (ExitCount == getCouldNotCompute())
4438 // Get the trip count from the BE count by adding 1.
4439 const SCEV *TCMul = getAddExpr(ExitCount,
4440 getConstant(ExitCount->getType(), 1));
4441 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4442 // to factor simple cases.
4443 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4444 TCMul = Mul->getOperand(0);
4446 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4450 ConstantInt *Result = MulC->getValue();
4452 // Guard against huge trip counts (this requires checking
4453 // for zero to handle the case where the trip count == -1 and the
4455 if (!Result || Result->getValue().getActiveBits() > 32 ||
4456 Result->getValue().getActiveBits() == 0)
4459 return (unsigned)Result->getZExtValue();
4462 // getExitCount - Get the expression for the number of loop iterations for which
4463 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
4464 // SCEVCouldNotCompute.
4465 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4466 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
4469 /// getBackedgeTakenCount - If the specified loop has a predictable
4470 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4471 /// object. The backedge-taken count is the number of times the loop header
4472 /// will be branched to from within the loop. This is one less than the
4473 /// trip count of the loop, since it doesn't count the first iteration,
4474 /// when the header is branched to from outside the loop.
4476 /// Note that it is not valid to call this method on a loop without a
4477 /// loop-invariant backedge-taken count (see
4478 /// hasLoopInvariantBackedgeTakenCount).
4480 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
4481 return getBackedgeTakenInfo(L).getExact(this);
4484 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4485 /// return the least SCEV value that is known never to be less than the
4486 /// actual backedge taken count.
4487 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
4488 return getBackedgeTakenInfo(L).getMax(this);
4491 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
4492 /// onto the given Worklist.
4494 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4495 BasicBlock *Header = L->getHeader();
4497 // Push all Loop-header PHIs onto the Worklist stack.
4498 for (BasicBlock::iterator I = Header->begin();
4499 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4500 Worklist.push_back(PN);
4503 const ScalarEvolution::BackedgeTakenInfo &
4504 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
4505 // Initially insert an invalid entry for this loop. If the insertion
4506 // succeeds, proceed to actually compute a backedge-taken count and
4507 // update the value. The temporary CouldNotCompute value tells SCEV
4508 // code elsewhere that it shouldn't attempt to request a new
4509 // backedge-taken count, which could result in infinite recursion.
4510 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
4511 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
4513 return Pair.first->second;
4515 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4516 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4517 // must be cleared in this scope.
4518 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4520 if (Result.getExact(this) != getCouldNotCompute()) {
4521 assert(isLoopInvariant(Result.getExact(this), L) &&
4522 isLoopInvariant(Result.getMax(this), L) &&
4523 "Computed backedge-taken count isn't loop invariant for loop!");
4524 ++NumTripCountsComputed;
4526 else if (Result.getMax(this) == getCouldNotCompute() &&
4527 isa<PHINode>(L->getHeader()->begin())) {
4528 // Only count loops that have phi nodes as not being computable.
4529 ++NumTripCountsNotComputed;
4532 // Now that we know more about the trip count for this loop, forget any
4533 // existing SCEV values for PHI nodes in this loop since they are only
4534 // conservative estimates made without the benefit of trip count
4535 // information. This is similar to the code in forgetLoop, except that
4536 // it handles SCEVUnknown PHI nodes specially.
4537 if (Result.hasAnyInfo()) {
4538 SmallVector<Instruction *, 16> Worklist;
4539 PushLoopPHIs(L, Worklist);
4541 SmallPtrSet<Instruction *, 8> Visited;
4542 while (!Worklist.empty()) {
4543 Instruction *I = Worklist.pop_back_val();
4544 if (!Visited.insert(I)) continue;
4546 ValueExprMapType::iterator It =
4547 ValueExprMap.find_as(static_cast<Value *>(I));
4548 if (It != ValueExprMap.end()) {
4549 const SCEV *Old = It->second;
4551 // SCEVUnknown for a PHI either means that it has an unrecognized
4552 // structure, or it's a PHI that's in the progress of being computed
4553 // by createNodeForPHI. In the former case, additional loop trip
4554 // count information isn't going to change anything. In the later
4555 // case, createNodeForPHI will perform the necessary updates on its
4556 // own when it gets to that point.
4557 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4558 forgetMemoizedResults(Old);
4559 ValueExprMap.erase(It);
4561 if (PHINode *PN = dyn_cast<PHINode>(I))
4562 ConstantEvolutionLoopExitValue.erase(PN);
4565 PushDefUseChildren(I, Worklist);
4569 // Re-lookup the insert position, since the call to
4570 // ComputeBackedgeTakenCount above could result in a
4571 // recusive call to getBackedgeTakenInfo (on a different
4572 // loop), which would invalidate the iterator computed
4574 return BackedgeTakenCounts.find(L)->second = Result;
4577 /// forgetLoop - This method should be called by the client when it has
4578 /// changed a loop in a way that may effect ScalarEvolution's ability to
4579 /// compute a trip count, or if the loop is deleted.
4580 void ScalarEvolution::forgetLoop(const Loop *L) {
4581 // Drop any stored trip count value.
4582 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4583 BackedgeTakenCounts.find(L);
4584 if (BTCPos != BackedgeTakenCounts.end()) {
4585 BTCPos->second.clear();
4586 BackedgeTakenCounts.erase(BTCPos);
4589 // Drop information about expressions based on loop-header PHIs.
4590 SmallVector<Instruction *, 16> Worklist;
4591 PushLoopPHIs(L, Worklist);
4593 SmallPtrSet<Instruction *, 8> Visited;
4594 while (!Worklist.empty()) {
4595 Instruction *I = Worklist.pop_back_val();
4596 if (!Visited.insert(I)) continue;
4598 ValueExprMapType::iterator It =
4599 ValueExprMap.find_as(static_cast<Value *>(I));
4600 if (It != ValueExprMap.end()) {
4601 forgetMemoizedResults(It->second);
4602 ValueExprMap.erase(It);
4603 if (PHINode *PN = dyn_cast<PHINode>(I))
4604 ConstantEvolutionLoopExitValue.erase(PN);
4607 PushDefUseChildren(I, Worklist);
4610 // Forget all contained loops too, to avoid dangling entries in the
4611 // ValuesAtScopes map.
4612 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4616 /// forgetValue - This method should be called by the client when it has
4617 /// changed a value in a way that may effect its value, or which may
4618 /// disconnect it from a def-use chain linking it to a loop.
4619 void ScalarEvolution::forgetValue(Value *V) {
4620 Instruction *I = dyn_cast<Instruction>(V);
4623 // Drop information about expressions based on loop-header PHIs.
4624 SmallVector<Instruction *, 16> Worklist;
4625 Worklist.push_back(I);
4627 SmallPtrSet<Instruction *, 8> Visited;
4628 while (!Worklist.empty()) {
4629 I = Worklist.pop_back_val();
4630 if (!Visited.insert(I)) continue;
4632 ValueExprMapType::iterator It =
4633 ValueExprMap.find_as(static_cast<Value *>(I));
4634 if (It != ValueExprMap.end()) {
4635 forgetMemoizedResults(It->second);
4636 ValueExprMap.erase(It);
4637 if (PHINode *PN = dyn_cast<PHINode>(I))
4638 ConstantEvolutionLoopExitValue.erase(PN);
4641 PushDefUseChildren(I, Worklist);
4645 /// getExact - Get the exact loop backedge taken count considering all loop
4646 /// exits. A computable result can only be return for loops with a single exit.
4647 /// Returning the minimum taken count among all exits is incorrect because one
4648 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4649 /// the limit of each loop test is never skipped. This is a valid assumption as
4650 /// long as the loop exits via that test. For precise results, it is the
4651 /// caller's responsibility to specify the relevant loop exit using
4652 /// getExact(ExitingBlock, SE).
4654 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4655 // If any exits were not computable, the loop is not computable.
4656 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4658 // We need exactly one computable exit.
4659 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4660 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4662 const SCEV *BECount = nullptr;
4663 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4664 ENT != nullptr; ENT = ENT->getNextExit()) {
4666 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4669 BECount = ENT->ExactNotTaken;
4670 else if (BECount != ENT->ExactNotTaken)
4671 return SE->getCouldNotCompute();
4673 assert(BECount && "Invalid not taken count for loop exit");
4677 /// getExact - Get the exact not taken count for this loop exit.
4679 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4680 ScalarEvolution *SE) const {
4681 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4682 ENT != nullptr; ENT = ENT->getNextExit()) {
4684 if (ENT->ExitingBlock == ExitingBlock)
4685 return ENT->ExactNotTaken;
4687 return SE->getCouldNotCompute();
4690 /// getMax - Get the max backedge taken count for the loop.
4692 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4693 return Max ? Max : SE->getCouldNotCompute();
4696 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4697 ScalarEvolution *SE) const {
4698 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4701 if (!ExitNotTaken.ExitingBlock)
4704 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4705 ENT != nullptr; ENT = ENT->getNextExit()) {
4707 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4708 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4715 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4716 /// computable exit into a persistent ExitNotTakenInfo array.
4717 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4718 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4719 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4722 ExitNotTaken.setIncomplete();
4724 unsigned NumExits = ExitCounts.size();
4725 if (NumExits == 0) return;
4727 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4728 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4729 if (NumExits == 1) return;
4731 // Handle the rare case of multiple computable exits.
4732 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4734 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4735 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4736 PrevENT->setNextExit(ENT);
4737 ENT->ExitingBlock = ExitCounts[i].first;
4738 ENT->ExactNotTaken = ExitCounts[i].second;
4742 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4743 void ScalarEvolution::BackedgeTakenInfo::clear() {
4744 ExitNotTaken.ExitingBlock = nullptr;
4745 ExitNotTaken.ExactNotTaken = nullptr;
4746 delete[] ExitNotTaken.getNextExit();
4749 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4750 /// of the specified loop will execute.
4751 ScalarEvolution::BackedgeTakenInfo
4752 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4753 SmallVector<BasicBlock *, 8> ExitingBlocks;
4754 L->getExitingBlocks(ExitingBlocks);
4756 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4757 bool CouldComputeBECount = true;
4758 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
4759 const SCEV *MustExitMaxBECount = nullptr;
4760 const SCEV *MayExitMaxBECount = nullptr;
4762 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4763 // and compute maxBECount.
4764 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4765 BasicBlock *ExitBB = ExitingBlocks[i];
4766 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4768 // 1. For each exit that can be computed, add an entry to ExitCounts.
4769 // CouldComputeBECount is true only if all exits can be computed.
4770 if (EL.Exact == getCouldNotCompute())
4771 // We couldn't compute an exact value for this exit, so
4772 // we won't be able to compute an exact value for the loop.
4773 CouldComputeBECount = false;
4775 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
4777 // 2. Derive the loop's MaxBECount from each exit's max number of
4778 // non-exiting iterations. Partition the loop exits into two kinds:
4779 // LoopMustExits and LoopMayExits.
4781 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4782 // is a LoopMayExit. If any computable LoopMustExit is found, then
4783 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4784 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4785 // considered greater than any computable EL.Max.
4786 if (EL.Max != getCouldNotCompute() && Latch &&
4787 DT->dominates(ExitBB, Latch)) {
4788 if (!MustExitMaxBECount)
4789 MustExitMaxBECount = EL.Max;
4791 MustExitMaxBECount =
4792 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
4794 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4795 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4796 MayExitMaxBECount = EL.Max;
4799 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4803 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4804 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
4805 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4808 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4809 /// loop will execute if it exits via the specified block.
4810 ScalarEvolution::ExitLimit
4811 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4813 // Okay, we've chosen an exiting block. See what condition causes us to
4814 // exit at this block and remember the exit block and whether all other targets
4815 // lead to the loop header.
4816 bool MustExecuteLoopHeader = true;
4817 BasicBlock *Exit = nullptr;
4818 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4820 if (!L->contains(*SI)) {
4821 if (Exit) // Multiple exit successors.
4822 return getCouldNotCompute();
4824 } else if (*SI != L->getHeader()) {
4825 MustExecuteLoopHeader = false;
4828 // At this point, we know we have a conditional branch that determines whether
4829 // the loop is exited. However, we don't know if the branch is executed each
4830 // time through the loop. If not, then the execution count of the branch will
4831 // not be equal to the trip count of the loop.
4833 // Currently we check for this by checking to see if the Exit branch goes to
4834 // the loop header. If so, we know it will always execute the same number of
4835 // times as the loop. We also handle the case where the exit block *is* the
4836 // loop header. This is common for un-rotated loops.
4838 // If both of those tests fail, walk up the unique predecessor chain to the
4839 // header, stopping if there is an edge that doesn't exit the loop. If the
4840 // header is reached, the execution count of the branch will be equal to the
4841 // trip count of the loop.
4843 // More extensive analysis could be done to handle more cases here.
4845 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
4846 // The simple checks failed, try climbing the unique predecessor chain
4847 // up to the header.
4849 for (BasicBlock *BB = ExitingBlock; BB; ) {
4850 BasicBlock *Pred = BB->getUniquePredecessor();
4852 return getCouldNotCompute();
4853 TerminatorInst *PredTerm = Pred->getTerminator();
4854 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4855 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4858 // If the predecessor has a successor that isn't BB and isn't
4859 // outside the loop, assume the worst.
4860 if (L->contains(PredSucc))
4861 return getCouldNotCompute();
4863 if (Pred == L->getHeader()) {
4870 return getCouldNotCompute();
4873 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
4874 TerminatorInst *Term = ExitingBlock->getTerminator();
4875 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4876 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4877 // Proceed to the next level to examine the exit condition expression.
4878 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4879 BI->getSuccessor(1),
4880 /*ControlsExit=*/IsOnlyExit);
4883 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4884 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
4885 /*ControlsExit=*/IsOnlyExit);
4887 return getCouldNotCompute();
4890 /// ComputeExitLimitFromCond - Compute the number of times the
4891 /// backedge of the specified loop will execute if its exit condition
4892 /// were a conditional branch of ExitCond, TBB, and FBB.
4894 /// @param ControlsExit is true if ExitCond directly controls the exit
4895 /// branch. In this case, we can assume that the loop exits only if the
4896 /// condition is true and can infer that failing to meet the condition prior to
4897 /// integer wraparound results in undefined behavior.
4898 ScalarEvolution::ExitLimit
4899 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4903 bool ControlsExit) {
4904 // Check if the controlling expression for this loop is an And or Or.
4905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4906 if (BO->getOpcode() == Instruction::And) {
4907 // Recurse on the operands of the and.
4908 bool EitherMayExit = L->contains(TBB);
4909 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
4910 ControlsExit && !EitherMayExit);
4911 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
4912 ControlsExit && !EitherMayExit);
4913 const SCEV *BECount = getCouldNotCompute();
4914 const SCEV *MaxBECount = getCouldNotCompute();
4915 if (EitherMayExit) {
4916 // Both conditions must be true for the loop to continue executing.
4917 // Choose the less conservative count.
4918 if (EL0.Exact == getCouldNotCompute() ||
4919 EL1.Exact == getCouldNotCompute())
4920 BECount = getCouldNotCompute();
4922 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4923 if (EL0.Max == getCouldNotCompute())
4924 MaxBECount = EL1.Max;
4925 else if (EL1.Max == getCouldNotCompute())
4926 MaxBECount = EL0.Max;
4928 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4930 // Both conditions must be true at the same time for the loop to exit.
4931 // For now, be conservative.
4932 assert(L->contains(FBB) && "Loop block has no successor in loop!");
4933 if (EL0.Max == EL1.Max)
4934 MaxBECount = EL0.Max;
4935 if (EL0.Exact == EL1.Exact)
4936 BECount = EL0.Exact;
4939 return ExitLimit(BECount, MaxBECount);
4941 if (BO->getOpcode() == Instruction::Or) {
4942 // Recurse on the operands of the or.
4943 bool EitherMayExit = L->contains(FBB);
4944 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
4945 ControlsExit && !EitherMayExit);
4946 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
4947 ControlsExit && !EitherMayExit);
4948 const SCEV *BECount = getCouldNotCompute();
4949 const SCEV *MaxBECount = getCouldNotCompute();
4950 if (EitherMayExit) {
4951 // Both conditions must be false for the loop to continue executing.
4952 // Choose the less conservative count.
4953 if (EL0.Exact == getCouldNotCompute() ||
4954 EL1.Exact == getCouldNotCompute())
4955 BECount = getCouldNotCompute();
4957 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4958 if (EL0.Max == getCouldNotCompute())
4959 MaxBECount = EL1.Max;
4960 else if (EL1.Max == getCouldNotCompute())
4961 MaxBECount = EL0.Max;
4963 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4965 // Both conditions must be false at the same time for the loop to exit.
4966 // For now, be conservative.
4967 assert(L->contains(TBB) && "Loop block has no successor in loop!");
4968 if (EL0.Max == EL1.Max)
4969 MaxBECount = EL0.Max;
4970 if (EL0.Exact == EL1.Exact)
4971 BECount = EL0.Exact;
4974 return ExitLimit(BECount, MaxBECount);
4978 // With an icmp, it may be feasible to compute an exact backedge-taken count.
4979 // Proceed to the next level to examine the icmp.
4980 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4981 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
4983 // Check for a constant condition. These are normally stripped out by
4984 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4985 // preserve the CFG and is temporarily leaving constant conditions
4987 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4988 if (L->contains(FBB) == !CI->getZExtValue())
4989 // The backedge is always taken.
4990 return getCouldNotCompute();
4992 // The backedge is never taken.
4993 return getConstant(CI->getType(), 0);
4996 // If it's not an integer or pointer comparison then compute it the hard way.
4997 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5000 /// ComputeExitLimitFromICmp - Compute the number of times the
5001 /// backedge of the specified loop will execute if its exit condition
5002 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
5003 ScalarEvolution::ExitLimit
5004 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
5008 bool ControlsExit) {
5010 // If the condition was exit on true, convert the condition to exit on false
5011 ICmpInst::Predicate Cond;
5012 if (!L->contains(FBB))
5013 Cond = ExitCond->getPredicate();
5015 Cond = ExitCond->getInversePredicate();
5017 // Handle common loops like: for (X = "string"; *X; ++X)
5018 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5019 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5021 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5022 if (ItCnt.hasAnyInfo())
5026 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5027 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5029 // Try to evaluate any dependencies out of the loop.
5030 LHS = getSCEVAtScope(LHS, L);
5031 RHS = getSCEVAtScope(RHS, L);
5033 // At this point, we would like to compute how many iterations of the
5034 // loop the predicate will return true for these inputs.
5035 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5036 // If there is a loop-invariant, force it into the RHS.
5037 std::swap(LHS, RHS);
5038 Cond = ICmpInst::getSwappedPredicate(Cond);
5041 // Simplify the operands before analyzing them.
5042 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5044 // If we have a comparison of a chrec against a constant, try to use value
5045 // ranges to answer this query.
5046 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5047 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5048 if (AddRec->getLoop() == L) {
5049 // Form the constant range.
5050 ConstantRange CompRange(
5051 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
5053 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
5054 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
5058 case ICmpInst::ICMP_NE: { // while (X != Y)
5059 // Convert to: while (X-Y != 0)
5060 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5061 if (EL.hasAnyInfo()) return EL;
5064 case ICmpInst::ICMP_EQ: { // while (X == Y)
5065 // Convert to: while (X-Y == 0)
5066 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5067 if (EL.hasAnyInfo()) return EL;
5070 case ICmpInst::ICMP_SLT:
5071 case ICmpInst::ICMP_ULT: { // while (X < Y)
5072 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
5073 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
5074 if (EL.hasAnyInfo()) return EL;
5077 case ICmpInst::ICMP_SGT:
5078 case ICmpInst::ICMP_UGT: { // while (X > Y)
5079 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
5080 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
5081 if (EL.hasAnyInfo()) return EL;
5086 dbgs() << "ComputeBackedgeTakenCount ";
5087 if (ExitCond->getOperand(0)->getType()->isUnsigned())
5088 dbgs() << "[unsigned] ";
5089 dbgs() << *LHS << " "
5090 << Instruction::getOpcodeName(Instruction::ICmp)
5091 << " " << *RHS << "\n";
5095 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5098 ScalarEvolution::ExitLimit
5099 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5101 BasicBlock *ExitingBlock,
5102 bool ControlsExit) {
5103 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5105 // Give up if the exit is the default dest of a switch.
5106 if (Switch->getDefaultDest() == ExitingBlock)
5107 return getCouldNotCompute();
5109 assert(L->contains(Switch->getDefaultDest()) &&
5110 "Default case must not exit the loop!");
5111 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5112 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5114 // while (X != Y) --> while (X-Y != 0)
5115 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5116 if (EL.hasAnyInfo())
5119 return getCouldNotCompute();
5122 static ConstantInt *
5123 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5124 ScalarEvolution &SE) {
5125 const SCEV *InVal = SE.getConstant(C);
5126 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
5127 assert(isa<SCEVConstant>(Val) &&
5128 "Evaluation of SCEV at constant didn't fold correctly?");
5129 return cast<SCEVConstant>(Val)->getValue();
5132 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
5133 /// 'icmp op load X, cst', try to see if we can compute the backedge
5134 /// execution count.
5135 ScalarEvolution::ExitLimit
5136 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5140 ICmpInst::Predicate predicate) {
5142 if (LI->isVolatile()) return getCouldNotCompute();
5144 // Check to see if the loaded pointer is a getelementptr of a global.
5145 // TODO: Use SCEV instead of manually grubbing with GEPs.
5146 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
5147 if (!GEP) return getCouldNotCompute();
5149 // Make sure that it is really a constant global we are gepping, with an
5150 // initializer, and make sure the first IDX is really 0.
5151 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
5152 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
5153 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5154 !cast<Constant>(GEP->getOperand(1))->isNullValue())
5155 return getCouldNotCompute();
5157 // Okay, we allow one non-constant index into the GEP instruction.
5158 Value *VarIdx = nullptr;
5159 std::vector<Constant*> Indexes;
5160 unsigned VarIdxNum = 0;
5161 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5162 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5163 Indexes.push_back(CI);
5164 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
5165 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
5166 VarIdx = GEP->getOperand(i);
5168 Indexes.push_back(nullptr);
5171 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5173 return getCouldNotCompute();
5175 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5176 // Check to see if X is a loop variant variable value now.
5177 const SCEV *Idx = getSCEV(VarIdx);
5178 Idx = getSCEVAtScope(Idx, L);
5180 // We can only recognize very limited forms of loop index expressions, in
5181 // particular, only affine AddRec's like {C1,+,C2}.
5182 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
5183 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
5184 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5185 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
5186 return getCouldNotCompute();
5188 unsigned MaxSteps = MaxBruteForceIterations;
5189 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
5190 ConstantInt *ItCst = ConstantInt::get(
5191 cast<IntegerType>(IdxExpr->getType()), IterationNum);
5192 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
5194 // Form the GEP offset.
5195 Indexes[VarIdxNum] = Val;
5197 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5199 if (!Result) break; // Cannot compute!
5201 // Evaluate the condition for this iteration.
5202 Result = ConstantExpr::getICmp(predicate, Result, RHS);
5203 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
5204 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
5206 dbgs() << "\n***\n*** Computed loop count " << *ItCst
5207 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5210 ++NumArrayLenItCounts;
5211 return getConstant(ItCst); // Found terminating iteration!
5214 return getCouldNotCompute();
5218 /// CanConstantFold - Return true if we can constant fold an instruction of the
5219 /// specified type, assuming that all operands were constants.
5220 static bool CanConstantFold(const Instruction *I) {
5221 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
5222 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5226 if (const CallInst *CI = dyn_cast<CallInst>(I))
5227 if (const Function *F = CI->getCalledFunction())
5228 return canConstantFoldCallTo(F);
5232 /// Determine whether this instruction can constant evolve within this loop
5233 /// assuming its operands can all constant evolve.
5234 static bool canConstantEvolve(Instruction *I, const Loop *L) {
5235 // An instruction outside of the loop can't be derived from a loop PHI.
5236 if (!L->contains(I)) return false;
5238 if (isa<PHINode>(I)) {
5239 if (L->getHeader() == I->getParent())
5242 // We don't currently keep track of the control flow needed to evaluate
5243 // PHIs, so we cannot handle PHIs inside of loops.
5247 // If we won't be able to constant fold this expression even if the operands
5248 // are constants, bail early.
5249 return CanConstantFold(I);
5252 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5253 /// recursing through each instruction operand until reaching a loop header phi.
5255 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
5256 DenseMap<Instruction *, PHINode *> &PHIMap) {
5258 // Otherwise, we can evaluate this instruction if all of its operands are
5259 // constant or derived from a PHI node themselves.
5260 PHINode *PHI = nullptr;
5261 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5262 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5264 if (isa<Constant>(*OpI)) continue;
5266 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
5267 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
5269 PHINode *P = dyn_cast<PHINode>(OpInst);
5271 // If this operand is already visited, reuse the prior result.
5272 // We may have P != PHI if this is the deepest point at which the
5273 // inconsistent paths meet.
5274 P = PHIMap.lookup(OpInst);
5276 // Recurse and memoize the results, whether a phi is found or not.
5277 // This recursive call invalidates pointers into PHIMap.
5278 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5282 return nullptr; // Not evolving from PHI
5283 if (PHI && PHI != P)
5284 return nullptr; // Evolving from multiple different PHIs.
5287 // This is a expression evolving from a constant PHI!
5291 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5292 /// in the loop that V is derived from. We allow arbitrary operations along the
5293 /// way, but the operands of an operation must either be constants or a value
5294 /// derived from a constant PHI. If this expression does not fit with these
5295 /// constraints, return null.
5296 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
5297 Instruction *I = dyn_cast<Instruction>(V);
5298 if (!I || !canConstantEvolve(I, L)) return nullptr;
5300 if (PHINode *PN = dyn_cast<PHINode>(I)) {
5304 // Record non-constant instructions contained by the loop.
5305 DenseMap<Instruction *, PHINode *> PHIMap;
5306 return getConstantEvolvingPHIOperands(I, L, PHIMap);
5309 /// EvaluateExpression - Given an expression that passes the
5310 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5311 /// in the loop has the value PHIVal. If we can't fold this expression for some
5312 /// reason, return null.
5313 static Constant *EvaluateExpression(Value *V, const Loop *L,
5314 DenseMap<Instruction *, Constant *> &Vals,
5315 const DataLayout *DL,
5316 const TargetLibraryInfo *TLI) {
5317 // Convenient constant check, but redundant for recursive calls.
5318 if (Constant *C = dyn_cast<Constant>(V)) return C;
5319 Instruction *I = dyn_cast<Instruction>(V);
5320 if (!I) return nullptr;
5322 if (Constant *C = Vals.lookup(I)) return C;
5324 // An instruction inside the loop depends on a value outside the loop that we
5325 // weren't given a mapping for, or a value such as a call inside the loop.
5326 if (!canConstantEvolve(I, L)) return nullptr;
5328 // An unmapped PHI can be due to a branch or another loop inside this loop,
5329 // or due to this not being the initial iteration through a loop where we
5330 // couldn't compute the evolution of this particular PHI last time.
5331 if (isa<PHINode>(I)) return nullptr;
5333 std::vector<Constant*> Operands(I->getNumOperands());
5335 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5336 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5338 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
5339 if (!Operands[i]) return nullptr;
5342 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
5344 if (!C) return nullptr;
5348 if (CmpInst *CI = dyn_cast<CmpInst>(I))
5349 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
5350 Operands[1], DL, TLI);
5351 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5352 if (!LI->isVolatile())
5353 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
5355 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
5359 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5360 /// in the header of its containing loop, we know the loop executes a
5361 /// constant number of times, and the PHI node is just a recurrence
5362 /// involving constants, fold it.
5364 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
5367 DenseMap<PHINode*, Constant*>::const_iterator I =
5368 ConstantEvolutionLoopExitValue.find(PN);
5369 if (I != ConstantEvolutionLoopExitValue.end())
5372 if (BEs.ugt(MaxBruteForceIterations))
5373 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
5375 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5377 DenseMap<Instruction *, Constant *> CurrentIterVals;
5378 BasicBlock *Header = L->getHeader();
5379 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5381 // Since the loop is canonicalized, the PHI node must have two entries. One
5382 // entry must be a constant (coming in from outside of the loop), and the
5383 // second must be derived from the same PHI.
5384 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5385 PHINode *PHI = nullptr;
5386 for (BasicBlock::iterator I = Header->begin();
5387 (PHI = dyn_cast<PHINode>(I)); ++I) {
5388 Constant *StartCST =
5389 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5390 if (!StartCST) continue;
5391 CurrentIterVals[PHI] = StartCST;
5393 if (!CurrentIterVals.count(PN))
5394 return RetVal = nullptr;
5396 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
5398 // Execute the loop symbolically to determine the exit value.
5399 if (BEs.getActiveBits() >= 32)
5400 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
5402 unsigned NumIterations = BEs.getZExtValue(); // must be in range
5403 unsigned IterationNum = 0;
5404 for (; ; ++IterationNum) {
5405 if (IterationNum == NumIterations)
5406 return RetVal = CurrentIterVals[PN]; // Got exit value!
5408 // Compute the value of the PHIs for the next iteration.
5409 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
5410 DenseMap<Instruction *, Constant *> NextIterVals;
5411 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
5414 return nullptr; // Couldn't evaluate!
5415 NextIterVals[PN] = NextPHI;
5417 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5419 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5420 // cease to be able to evaluate one of them or if they stop evolving,
5421 // because that doesn't necessarily prevent us from computing PN.
5422 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
5423 for (DenseMap<Instruction *, Constant *>::const_iterator
5424 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5425 PHINode *PHI = dyn_cast<PHINode>(I->first);
5426 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
5427 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5429 // We use two distinct loops because EvaluateExpression may invalidate any
5430 // iterators into CurrentIterVals.
5431 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5432 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5433 PHINode *PHI = I->first;
5434 Constant *&NextPHI = NextIterVals[PHI];
5435 if (!NextPHI) { // Not already computed.
5436 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5437 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5439 if (NextPHI != I->second)
5440 StoppedEvolving = false;
5443 // If all entries in CurrentIterVals == NextIterVals then we can stop
5444 // iterating, the loop can't continue to change.
5445 if (StoppedEvolving)
5446 return RetVal = CurrentIterVals[PN];
5448 CurrentIterVals.swap(NextIterVals);
5452 /// ComputeExitCountExhaustively - If the loop is known to execute a
5453 /// constant number of times (the condition evolves only from constants),
5454 /// try to evaluate a few iterations of the loop until we get the exit
5455 /// condition gets a value of ExitWhen (true or false). If we cannot
5456 /// evaluate the trip count of the loop, return getCouldNotCompute().
5457 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5460 PHINode *PN = getConstantEvolvingPHI(Cond, L);
5461 if (!PN) return getCouldNotCompute();
5463 // If the loop is canonicalized, the PHI will have exactly two entries.
5464 // That's the only form we support here.
5465 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5467 DenseMap<Instruction *, Constant *> CurrentIterVals;
5468 BasicBlock *Header = L->getHeader();
5469 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5471 // One entry must be a constant (coming in from outside of the loop), and the
5472 // second must be derived from the same PHI.
5473 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5474 PHINode *PHI = nullptr;
5475 for (BasicBlock::iterator I = Header->begin();
5476 (PHI = dyn_cast<PHINode>(I)); ++I) {
5477 Constant *StartCST =
5478 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5479 if (!StartCST) continue;
5480 CurrentIterVals[PHI] = StartCST;
5482 if (!CurrentIterVals.count(PN))
5483 return getCouldNotCompute();
5485 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5486 // the loop symbolically to determine when the condition gets a value of
5489 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
5490 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
5491 ConstantInt *CondVal =
5492 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
5495 // Couldn't symbolically evaluate.
5496 if (!CondVal) return getCouldNotCompute();
5498 if (CondVal->getValue() == uint64_t(ExitWhen)) {
5499 ++NumBruteForceTripCountsComputed;
5500 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
5503 // Update all the PHI nodes for the next iteration.
5504 DenseMap<Instruction *, Constant *> NextIterVals;
5506 // Create a list of which PHIs we need to compute. We want to do this before
5507 // calling EvaluateExpression on them because that may invalidate iterators
5508 // into CurrentIterVals.
5509 SmallVector<PHINode *, 8> PHIsToCompute;
5510 for (DenseMap<Instruction *, Constant *>::const_iterator
5511 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5512 PHINode *PHI = dyn_cast<PHINode>(I->first);
5513 if (!PHI || PHI->getParent() != Header) continue;
5514 PHIsToCompute.push_back(PHI);
5516 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5517 E = PHIsToCompute.end(); I != E; ++I) {
5519 Constant *&NextPHI = NextIterVals[PHI];
5520 if (NextPHI) continue; // Already computed!
5522 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5523 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5525 CurrentIterVals.swap(NextIterVals);
5528 // Too many iterations were needed to evaluate.
5529 return getCouldNotCompute();
5532 /// getSCEVAtScope - Return a SCEV expression for the specified value
5533 /// at the specified scope in the program. The L value specifies a loop
5534 /// nest to evaluate the expression at, where null is the top-level or a
5535 /// specified loop is immediately inside of the loop.
5537 /// This method can be used to compute the exit value for a variable defined
5538 /// in a loop by querying what the value will hold in the parent loop.
5540 /// In the case that a relevant loop exit value cannot be computed, the
5541 /// original value V is returned.
5542 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
5543 // Check to see if we've folded this expression at this loop before.
5544 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5545 for (unsigned u = 0; u < Values.size(); u++) {
5546 if (Values[u].first == L)
5547 return Values[u].second ? Values[u].second : V;
5549 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
5550 // Otherwise compute it.
5551 const SCEV *C = computeSCEVAtScope(V, L);
5552 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5553 for (unsigned u = Values2.size(); u > 0; u--) {
5554 if (Values2[u - 1].first == L) {
5555 Values2[u - 1].second = C;
5562 /// This builds up a Constant using the ConstantExpr interface. That way, we
5563 /// will return Constants for objects which aren't represented by a
5564 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5565 /// Returns NULL if the SCEV isn't representable as a Constant.
5566 static Constant *BuildConstantFromSCEV(const SCEV *V) {
5567 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
5568 case scCouldNotCompute:
5572 return cast<SCEVConstant>(V)->getValue();
5574 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5575 case scSignExtend: {
5576 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5577 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5578 return ConstantExpr::getSExt(CastOp, SS->getType());
5581 case scZeroExtend: {
5582 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5583 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5584 return ConstantExpr::getZExt(CastOp, SZ->getType());
5588 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5589 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5590 return ConstantExpr::getTrunc(CastOp, ST->getType());
5594 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5595 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5596 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5597 unsigned AS = PTy->getAddressSpace();
5598 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5599 C = ConstantExpr::getBitCast(C, DestPtrTy);
5601 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5602 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5603 if (!C2) return nullptr;
5606 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5607 unsigned AS = C2->getType()->getPointerAddressSpace();
5609 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5610 // The offsets have been converted to bytes. We can add bytes to an
5611 // i8* by GEP with the byte count in the first index.
5612 C = ConstantExpr::getBitCast(C, DestPtrTy);
5615 // Don't bother trying to sum two pointers. We probably can't
5616 // statically compute a load that results from it anyway.
5617 if (C2->getType()->isPointerTy())
5620 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5621 if (PTy->getElementType()->isStructTy())
5622 C2 = ConstantExpr::getIntegerCast(
5623 C2, Type::getInt32Ty(C->getContext()), true);
5624 C = ConstantExpr::getGetElementPtr(C, C2);
5626 C = ConstantExpr::getAdd(C, C2);
5633 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5634 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5635 // Don't bother with pointers at all.
5636 if (C->getType()->isPointerTy()) return nullptr;
5637 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5638 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
5639 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
5640 C = ConstantExpr::getMul(C, C2);
5647 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5648 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5649 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5650 if (LHS->getType() == RHS->getType())
5651 return ConstantExpr::getUDiv(LHS, RHS);
5656 break; // TODO: smax, umax.
5661 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
5662 if (isa<SCEVConstant>(V)) return V;
5664 // If this instruction is evolved from a constant-evolving PHI, compute the
5665 // exit value from the loop without using SCEVs.
5666 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
5667 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
5668 const Loop *LI = (*this->LI)[I->getParent()];
5669 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5670 if (PHINode *PN = dyn_cast<PHINode>(I))
5671 if (PN->getParent() == LI->getHeader()) {
5672 // Okay, there is no closed form solution for the PHI node. Check
5673 // to see if the loop that contains it has a known backedge-taken
5674 // count. If so, we may be able to force computation of the exit
5676 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
5677 if (const SCEVConstant *BTCC =
5678 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
5679 // Okay, we know how many times the containing loop executes. If
5680 // this is a constant evolving PHI node, get the final value at
5681 // the specified iteration number.
5682 Constant *RV = getConstantEvolutionLoopExitValue(PN,
5683 BTCC->getValue()->getValue(),
5685 if (RV) return getSCEV(RV);
5689 // Okay, this is an expression that we cannot symbolically evaluate
5690 // into a SCEV. Check to see if it's possible to symbolically evaluate
5691 // the arguments into constants, and if so, try to constant propagate the
5692 // result. This is particularly useful for computing loop exit values.
5693 if (CanConstantFold(I)) {
5694 SmallVector<Constant *, 4> Operands;
5695 bool MadeImprovement = false;
5696 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5697 Value *Op = I->getOperand(i);
5698 if (Constant *C = dyn_cast<Constant>(Op)) {
5699 Operands.push_back(C);
5703 // If any of the operands is non-constant and if they are
5704 // non-integer and non-pointer, don't even try to analyze them
5705 // with scev techniques.
5706 if (!isSCEVable(Op->getType()))
5709 const SCEV *OrigV = getSCEV(Op);
5710 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5711 MadeImprovement |= OrigV != OpV;
5713 Constant *C = BuildConstantFromSCEV(OpV);
5715 if (C->getType() != Op->getType())
5716 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5720 Operands.push_back(C);
5723 // Check to see if getSCEVAtScope actually made an improvement.
5724 if (MadeImprovement) {
5725 Constant *C = nullptr;
5726 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5727 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
5728 Operands[0], Operands[1], DL,
5730 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5731 if (!LI->isVolatile())
5732 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
5734 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
5742 // This is some other type of SCEVUnknown, just return it.
5746 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
5747 // Avoid performing the look-up in the common case where the specified
5748 // expression has no loop-variant portions.
5749 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
5750 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5751 if (OpAtScope != Comm->getOperand(i)) {
5752 // Okay, at least one of these operands is loop variant but might be
5753 // foldable. Build a new instance of the folded commutative expression.
5754 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5755 Comm->op_begin()+i);
5756 NewOps.push_back(OpAtScope);
5758 for (++i; i != e; ++i) {
5759 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5760 NewOps.push_back(OpAtScope);
5762 if (isa<SCEVAddExpr>(Comm))
5763 return getAddExpr(NewOps);
5764 if (isa<SCEVMulExpr>(Comm))
5765 return getMulExpr(NewOps);
5766 if (isa<SCEVSMaxExpr>(Comm))
5767 return getSMaxExpr(NewOps);
5768 if (isa<SCEVUMaxExpr>(Comm))
5769 return getUMaxExpr(NewOps);
5770 llvm_unreachable("Unknown commutative SCEV type!");
5773 // If we got here, all operands are loop invariant.
5777 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
5778 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5779 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
5780 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5781 return Div; // must be loop invariant
5782 return getUDivExpr(LHS, RHS);
5785 // If this is a loop recurrence for a loop that does not contain L, then we
5786 // are dealing with the final value computed by the loop.
5787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5788 // First, attempt to evaluate each operand.
5789 // Avoid performing the look-up in the common case where the specified
5790 // expression has no loop-variant portions.
5791 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5792 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5793 if (OpAtScope == AddRec->getOperand(i))
5796 // Okay, at least one of these operands is loop variant but might be
5797 // foldable. Build a new instance of the folded commutative expression.
5798 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5799 AddRec->op_begin()+i);
5800 NewOps.push_back(OpAtScope);
5801 for (++i; i != e; ++i)
5802 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5804 const SCEV *FoldedRec =
5805 getAddRecExpr(NewOps, AddRec->getLoop(),
5806 AddRec->getNoWrapFlags(SCEV::FlagNW));
5807 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
5808 // The addrec may be folded to a nonrecurrence, for example, if the
5809 // induction variable is multiplied by zero after constant folding. Go
5810 // ahead and return the folded value.
5816 // If the scope is outside the addrec's loop, evaluate it by using the
5817 // loop exit value of the addrec.
5818 if (!AddRec->getLoop()->contains(L)) {
5819 // To evaluate this recurrence, we need to know how many times the AddRec
5820 // loop iterates. Compute this now.
5821 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
5822 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
5824 // Then, evaluate the AddRec.
5825 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
5831 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
5832 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5833 if (Op == Cast->getOperand())
5834 return Cast; // must be loop invariant
5835 return getZeroExtendExpr(Op, Cast->getType());
5838 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
5839 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5840 if (Op == Cast->getOperand())
5841 return Cast; // must be loop invariant
5842 return getSignExtendExpr(Op, Cast->getType());
5845 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
5846 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5847 if (Op == Cast->getOperand())
5848 return Cast; // must be loop invariant
5849 return getTruncateExpr(Op, Cast->getType());
5852 llvm_unreachable("Unknown SCEV type!");
5855 /// getSCEVAtScope - This is a convenience function which does
5856 /// getSCEVAtScope(getSCEV(V), L).
5857 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
5858 return getSCEVAtScope(getSCEV(V), L);
5861 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5862 /// following equation:
5864 /// A * X = B (mod N)
5866 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5867 /// A and B isn't important.
5869 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
5870 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
5871 ScalarEvolution &SE) {
5872 uint32_t BW = A.getBitWidth();
5873 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5874 assert(A != 0 && "A must be non-zero.");
5878 // The gcd of A and N may have only one prime factor: 2. The number of
5879 // trailing zeros in A is its multiplicity
5880 uint32_t Mult2 = A.countTrailingZeros();
5883 // 2. Check if B is divisible by D.
5885 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5886 // is not less than multiplicity of this prime factor for D.
5887 if (B.countTrailingZeros() < Mult2)
5888 return SE.getCouldNotCompute();
5890 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5893 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5894 // bit width during computations.
5895 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5896 APInt Mod(BW + 1, 0);
5897 Mod.setBit(BW - Mult2); // Mod = N / D
5898 APInt I = AD.multiplicativeInverse(Mod);
5900 // 4. Compute the minimum unsigned root of the equation:
5901 // I * (B / D) mod (N / D)
5902 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5904 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5906 return SE.getConstant(Result.trunc(BW));
5909 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5910 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5911 /// might be the same) or two SCEVCouldNotCompute objects.
5913 static std::pair<const SCEV *,const SCEV *>
5914 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
5915 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
5916 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5917 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5918 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
5920 // We currently can only solve this if the coefficients are constants.
5921 if (!LC || !MC || !NC) {
5922 const SCEV *CNC = SE.getCouldNotCompute();
5923 return std::make_pair(CNC, CNC);
5926 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
5927 const APInt &L = LC->getValue()->getValue();
5928 const APInt &M = MC->getValue()->getValue();
5929 const APInt &N = NC->getValue()->getValue();
5930 APInt Two(BitWidth, 2);
5931 APInt Four(BitWidth, 4);
5934 using namespace APIntOps;
5936 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5937 // The B coefficient is M-N/2
5941 // The A coefficient is N/2
5942 APInt A(N.sdiv(Two));
5944 // Compute the B^2-4ac term.
5947 SqrtTerm -= Four * (A * C);
5949 if (SqrtTerm.isNegative()) {
5950 // The loop is provably infinite.
5951 const SCEV *CNC = SE.getCouldNotCompute();
5952 return std::make_pair(CNC, CNC);
5955 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5956 // integer value or else APInt::sqrt() will assert.
5957 APInt SqrtVal(SqrtTerm.sqrt());
5959 // Compute the two solutions for the quadratic formula.
5960 // The divisions must be performed as signed divisions.
5963 if (TwoA.isMinValue()) {
5964 const SCEV *CNC = SE.getCouldNotCompute();
5965 return std::make_pair(CNC, CNC);
5968 LLVMContext &Context = SE.getContext();
5970 ConstantInt *Solution1 =
5971 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
5972 ConstantInt *Solution2 =
5973 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
5975 return std::make_pair(SE.getConstant(Solution1),
5976 SE.getConstant(Solution2));
5977 } // end APIntOps namespace
5980 /// HowFarToZero - Return the number of times a backedge comparing the specified
5981 /// value to zero will execute. If not computable, return CouldNotCompute.
5983 /// This is only used for loops with a "x != y" exit test. The exit condition is
5984 /// now expressed as a single expression, V = x-y. So the exit test is
5985 /// effectively V != 0. We know and take advantage of the fact that this
5986 /// expression only being used in a comparison by zero context.
5987 ScalarEvolution::ExitLimit
5988 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
5989 // If the value is a constant
5990 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5991 // If the value is already zero, the branch will execute zero times.
5992 if (C->getValue()->isZero()) return C;
5993 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5996 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
5997 if (!AddRec || AddRec->getLoop() != L)
5998 return getCouldNotCompute();
6000 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6001 // the quadratic equation to solve it.
6002 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6003 std::pair<const SCEV *,const SCEV *> Roots =
6004 SolveQuadraticEquation(AddRec, *this);
6005 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6006 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6009 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
6010 << " sol#2: " << *R2 << "\n";
6012 // Pick the smallest positive root value.
6013 if (ConstantInt *CB =
6014 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6017 if (CB->getZExtValue() == false)
6018 std::swap(R1, R2); // R1 is the minimum root now.
6020 // We can only use this value if the chrec ends up with an exact zero
6021 // value at this index. When solving for "X*X != 5", for example, we
6022 // should not accept a root of 2.
6023 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
6025 return R1; // We found a quadratic root!
6028 return getCouldNotCompute();
6031 // Otherwise we can only handle this if it is affine.
6032 if (!AddRec->isAffine())
6033 return getCouldNotCompute();
6035 // If this is an affine expression, the execution count of this branch is
6036 // the minimum unsigned root of the following equation:
6038 // Start + Step*N = 0 (mod 2^BW)
6042 // Step*N = -Start (mod 2^BW)
6044 // where BW is the common bit width of Start and Step.
6046 // Get the initial value for the loop.
6047 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6048 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6050 // For now we handle only constant steps.
6052 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6053 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6054 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6055 // We have not yet seen any such cases.
6056 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
6057 if (!StepC || StepC->getValue()->equalsInt(0))
6058 return getCouldNotCompute();
6060 // For positive steps (counting up until unsigned overflow):
6061 // N = -Start/Step (as unsigned)
6062 // For negative steps (counting down to zero):
6064 // First compute the unsigned distance from zero in the direction of Step.
6065 bool CountDown = StepC->getValue()->getValue().isNegative();
6066 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
6068 // Handle unitary steps, which cannot wraparound.
6069 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6070 // N = Distance (as unsigned)
6071 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6072 ConstantRange CR = getUnsignedRange(Start);
6073 const SCEV *MaxBECount;
6074 if (!CountDown && CR.getUnsignedMin().isMinValue())
6075 // When counting up, the worst starting value is 1, not 0.
6076 MaxBECount = CR.getUnsignedMax().isMinValue()
6077 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6078 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6080 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6081 : -CR.getUnsignedMin());
6082 return ExitLimit(Distance, MaxBECount);
6085 // If the step exactly divides the distance then unsigned divide computes the
6088 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6089 SCEVDivision::divide(SE, Distance, Step, &Q, &R);
6092 getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6093 return ExitLimit(Exact, Exact);
6096 // If the condition controls loop exit (the loop exits only if the expression
6097 // is true) and the addition is no-wrap we can use unsigned divide to
6098 // compute the backedge count. In this case, the step may not divide the
6099 // distance, but we don't care because if the condition is "missed" the loop
6100 // will have undefined behavior due to wrapping.
6101 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6103 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6104 return ExitLimit(Exact, Exact);
6107 // Then, try to solve the above equation provided that Start is constant.
6108 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6109 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6110 -StartC->getValue()->getValue(),
6112 return getCouldNotCompute();
6115 /// HowFarToNonZero - Return the number of times a backedge checking the
6116 /// specified value for nonzero will execute. If not computable, return
6118 ScalarEvolution::ExitLimit
6119 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
6120 // Loops that look like: while (X == 0) are very strange indeed. We don't
6121 // handle them yet except for the trivial case. This could be expanded in the
6122 // future as needed.
6124 // If the value is a constant, check to see if it is known to be non-zero
6125 // already. If so, the backedge will execute zero times.
6126 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6127 if (!C->getValue()->isNullValue())
6128 return getConstant(C->getType(), 0);
6129 return getCouldNotCompute(); // Otherwise it will loop infinitely.
6132 // We could implement others, but I really doubt anyone writes loops like
6133 // this, and if they did, they would already be constant folded.
6134 return getCouldNotCompute();
6137 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6138 /// (which may not be an immediate predecessor) which has exactly one
6139 /// successor from which BB is reachable, or null if no such block is
6142 std::pair<BasicBlock *, BasicBlock *>
6143 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
6144 // If the block has a unique predecessor, then there is no path from the
6145 // predecessor to the block that does not go through the direct edge
6146 // from the predecessor to the block.
6147 if (BasicBlock *Pred = BB->getSinglePredecessor())
6148 return std::make_pair(Pred, BB);
6150 // A loop's header is defined to be a block that dominates the loop.
6151 // If the header has a unique predecessor outside the loop, it must be
6152 // a block that has exactly one successor that can reach the loop.
6153 if (Loop *L = LI->getLoopFor(BB))
6154 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
6156 return std::pair<BasicBlock *, BasicBlock *>();
6159 /// HasSameValue - SCEV structural equivalence is usually sufficient for
6160 /// testing whether two expressions are equal, however for the purposes of
6161 /// looking for a condition guarding a loop, it can be useful to be a little
6162 /// more general, since a front-end may have replicated the controlling
6165 static bool HasSameValue(const SCEV *A, const SCEV *B) {
6166 // Quick check to see if they are the same SCEV.
6167 if (A == B) return true;
6169 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6170 // two different instructions with the same value. Check for this case.
6171 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6172 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6173 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6174 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
6175 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
6178 // Otherwise assume they may have a different value.
6182 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
6183 /// predicate Pred. Return true iff any changes were made.
6185 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
6186 const SCEV *&LHS, const SCEV *&RHS,
6188 bool Changed = false;
6190 // If we hit the max recursion limit bail out.
6194 // Canonicalize a constant to the right side.
6195 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6196 // Check for both operands constant.
6197 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6198 if (ConstantExpr::getICmp(Pred,
6200 RHSC->getValue())->isNullValue())
6201 goto trivially_false;
6203 goto trivially_true;
6205 // Otherwise swap the operands to put the constant on the right.
6206 std::swap(LHS, RHS);
6207 Pred = ICmpInst::getSwappedPredicate(Pred);
6211 // If we're comparing an addrec with a value which is loop-invariant in the
6212 // addrec's loop, put the addrec on the left. Also make a dominance check,
6213 // as both operands could be addrecs loop-invariant in each other's loop.
6214 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6215 const Loop *L = AR->getLoop();
6216 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
6217 std::swap(LHS, RHS);
6218 Pred = ICmpInst::getSwappedPredicate(Pred);
6223 // If there's a constant operand, canonicalize comparisons with boundary
6224 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6225 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6226 const APInt &RA = RC->getValue()->getValue();
6228 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6229 case ICmpInst::ICMP_EQ:
6230 case ICmpInst::ICMP_NE:
6231 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6233 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6234 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
6235 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6236 ME->getOperand(0)->isAllOnesValue()) {
6237 RHS = AE->getOperand(1);
6238 LHS = ME->getOperand(1);
6242 case ICmpInst::ICMP_UGE:
6243 if ((RA - 1).isMinValue()) {
6244 Pred = ICmpInst::ICMP_NE;
6245 RHS = getConstant(RA - 1);
6249 if (RA.isMaxValue()) {
6250 Pred = ICmpInst::ICMP_EQ;
6254 if (RA.isMinValue()) goto trivially_true;
6256 Pred = ICmpInst::ICMP_UGT;
6257 RHS = getConstant(RA - 1);
6260 case ICmpInst::ICMP_ULE:
6261 if ((RA + 1).isMaxValue()) {
6262 Pred = ICmpInst::ICMP_NE;
6263 RHS = getConstant(RA + 1);
6267 if (RA.isMinValue()) {
6268 Pred = ICmpInst::ICMP_EQ;
6272 if (RA.isMaxValue()) goto trivially_true;
6274 Pred = ICmpInst::ICMP_ULT;
6275 RHS = getConstant(RA + 1);
6278 case ICmpInst::ICMP_SGE:
6279 if ((RA - 1).isMinSignedValue()) {
6280 Pred = ICmpInst::ICMP_NE;
6281 RHS = getConstant(RA - 1);
6285 if (RA.isMaxSignedValue()) {
6286 Pred = ICmpInst::ICMP_EQ;
6290 if (RA.isMinSignedValue()) goto trivially_true;
6292 Pred = ICmpInst::ICMP_SGT;
6293 RHS = getConstant(RA - 1);
6296 case ICmpInst::ICMP_SLE:
6297 if ((RA + 1).isMaxSignedValue()) {
6298 Pred = ICmpInst::ICMP_NE;
6299 RHS = getConstant(RA + 1);
6303 if (RA.isMinSignedValue()) {
6304 Pred = ICmpInst::ICMP_EQ;
6308 if (RA.isMaxSignedValue()) goto trivially_true;
6310 Pred = ICmpInst::ICMP_SLT;
6311 RHS = getConstant(RA + 1);
6314 case ICmpInst::ICMP_UGT:
6315 if (RA.isMinValue()) {
6316 Pred = ICmpInst::ICMP_NE;
6320 if ((RA + 1).isMaxValue()) {
6321 Pred = ICmpInst::ICMP_EQ;
6322 RHS = getConstant(RA + 1);
6326 if (RA.isMaxValue()) goto trivially_false;
6328 case ICmpInst::ICMP_ULT:
6329 if (RA.isMaxValue()) {
6330 Pred = ICmpInst::ICMP_NE;
6334 if ((RA - 1).isMinValue()) {
6335 Pred = ICmpInst::ICMP_EQ;
6336 RHS = getConstant(RA - 1);
6340 if (RA.isMinValue()) goto trivially_false;
6342 case ICmpInst::ICMP_SGT:
6343 if (RA.isMinSignedValue()) {
6344 Pred = ICmpInst::ICMP_NE;
6348 if ((RA + 1).isMaxSignedValue()) {
6349 Pred = ICmpInst::ICMP_EQ;
6350 RHS = getConstant(RA + 1);
6354 if (RA.isMaxSignedValue()) goto trivially_false;
6356 case ICmpInst::ICMP_SLT:
6357 if (RA.isMaxSignedValue()) {
6358 Pred = ICmpInst::ICMP_NE;
6362 if ((RA - 1).isMinSignedValue()) {
6363 Pred = ICmpInst::ICMP_EQ;
6364 RHS = getConstant(RA - 1);
6368 if (RA.isMinSignedValue()) goto trivially_false;
6373 // Check for obvious equality.
6374 if (HasSameValue(LHS, RHS)) {
6375 if (ICmpInst::isTrueWhenEqual(Pred))
6376 goto trivially_true;
6377 if (ICmpInst::isFalseWhenEqual(Pred))
6378 goto trivially_false;
6381 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6382 // adding or subtracting 1 from one of the operands.
6384 case ICmpInst::ICMP_SLE:
6385 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6386 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6388 Pred = ICmpInst::ICMP_SLT;
6390 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
6391 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6393 Pred = ICmpInst::ICMP_SLT;
6397 case ICmpInst::ICMP_SGE:
6398 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
6399 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6401 Pred = ICmpInst::ICMP_SGT;
6403 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6404 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6406 Pred = ICmpInst::ICMP_SGT;
6410 case ICmpInst::ICMP_ULE:
6411 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
6412 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6414 Pred = ICmpInst::ICMP_ULT;
6416 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
6417 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6419 Pred = ICmpInst::ICMP_ULT;
6423 case ICmpInst::ICMP_UGE:
6424 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
6425 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6427 Pred = ICmpInst::ICMP_UGT;
6429 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
6430 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6432 Pred = ICmpInst::ICMP_UGT;
6440 // TODO: More simplifications are possible here.
6442 // Recursively simplify until we either hit a recursion limit or nothing
6445 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6451 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6452 Pred = ICmpInst::ICMP_EQ;
6457 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6458 Pred = ICmpInst::ICMP_NE;
6462 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6463 return getSignedRange(S).getSignedMax().isNegative();
6466 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6467 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6470 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6471 return !getSignedRange(S).getSignedMin().isNegative();
6474 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6475 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6478 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6479 return isKnownNegative(S) || isKnownPositive(S);
6482 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6483 const SCEV *LHS, const SCEV *RHS) {
6484 // Canonicalize the inputs first.
6485 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6487 // If LHS or RHS is an addrec, check to see if the condition is true in
6488 // every iteration of the loop.
6489 // If LHS and RHS are both addrec, both conditions must be true in
6490 // every iteration of the loop.
6491 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6492 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6493 bool LeftGuarded = false;
6494 bool RightGuarded = false;
6496 const Loop *L = LAR->getLoop();
6497 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6498 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6499 if (!RAR) return true;
6504 const Loop *L = RAR->getLoop();
6505 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6506 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6507 if (!LAR) return true;
6508 RightGuarded = true;
6511 if (LeftGuarded && RightGuarded)
6514 // Otherwise see what can be done with known constant ranges.
6515 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6519 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6520 const SCEV *LHS, const SCEV *RHS) {
6521 if (HasSameValue(LHS, RHS))
6522 return ICmpInst::isTrueWhenEqual(Pred);
6524 // This code is split out from isKnownPredicate because it is called from
6525 // within isLoopEntryGuardedByCond.
6528 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6529 case ICmpInst::ICMP_SGT:
6530 std::swap(LHS, RHS);
6531 case ICmpInst::ICMP_SLT: {
6532 ConstantRange LHSRange = getSignedRange(LHS);
6533 ConstantRange RHSRange = getSignedRange(RHS);
6534 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6536 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6540 case ICmpInst::ICMP_SGE:
6541 std::swap(LHS, RHS);
6542 case ICmpInst::ICMP_SLE: {
6543 ConstantRange LHSRange = getSignedRange(LHS);
6544 ConstantRange RHSRange = getSignedRange(RHS);
6545 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6547 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6551 case ICmpInst::ICMP_UGT:
6552 std::swap(LHS, RHS);
6553 case ICmpInst::ICMP_ULT: {
6554 ConstantRange LHSRange = getUnsignedRange(LHS);
6555 ConstantRange RHSRange = getUnsignedRange(RHS);
6556 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6558 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6562 case ICmpInst::ICMP_UGE:
6563 std::swap(LHS, RHS);
6564 case ICmpInst::ICMP_ULE: {
6565 ConstantRange LHSRange = getUnsignedRange(LHS);
6566 ConstantRange RHSRange = getUnsignedRange(RHS);
6567 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6569 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6573 case ICmpInst::ICMP_NE: {
6574 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6576 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6579 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6580 if (isKnownNonZero(Diff))
6584 case ICmpInst::ICMP_EQ:
6585 // The check at the top of the function catches the case where
6586 // the values are known to be equal.
6592 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6593 /// protected by a conditional between LHS and RHS. This is used to
6594 /// to eliminate casts.
6596 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6597 ICmpInst::Predicate Pred,
6598 const SCEV *LHS, const SCEV *RHS) {
6599 // Interpret a null as meaning no loop, where there is obviously no guard
6600 // (interprocedural conditions notwithstanding).
6601 if (!L) return true;
6603 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6605 BasicBlock *Latch = L->getLoopLatch();
6609 BranchInst *LoopContinuePredicate =
6610 dyn_cast<BranchInst>(Latch->getTerminator());
6611 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6612 isImpliedCond(Pred, LHS, RHS,
6613 LoopContinuePredicate->getCondition(),
6614 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6617 // Check conditions due to any @llvm.assume intrinsics.
6618 for (auto &CI : AT->assumptions(F)) {
6619 if (!DT->dominates(CI, Latch->getTerminator()))
6622 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6629 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
6630 /// by a conditional between LHS and RHS. This is used to help avoid max
6631 /// expressions in loop trip counts, and to eliminate casts.
6633 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6634 ICmpInst::Predicate Pred,
6635 const SCEV *LHS, const SCEV *RHS) {
6636 // Interpret a null as meaning no loop, where there is obviously no guard
6637 // (interprocedural conditions notwithstanding).
6638 if (!L) return false;
6640 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6642 // Starting at the loop predecessor, climb up the predecessor chain, as long
6643 // as there are predecessors that can be found that have unique successors
6644 // leading to the original header.
6645 for (std::pair<BasicBlock *, BasicBlock *>
6646 Pair(L->getLoopPredecessor(), L->getHeader());
6648 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
6650 BranchInst *LoopEntryPredicate =
6651 dyn_cast<BranchInst>(Pair.first->getTerminator());
6652 if (!LoopEntryPredicate ||
6653 LoopEntryPredicate->isUnconditional())
6656 if (isImpliedCond(Pred, LHS, RHS,
6657 LoopEntryPredicate->getCondition(),
6658 LoopEntryPredicate->getSuccessor(0) != Pair.second))
6662 // Check conditions due to any @llvm.assume intrinsics.
6663 for (auto &CI : AT->assumptions(F)) {
6664 if (!DT->dominates(CI, L->getHeader()))
6667 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6674 /// RAII wrapper to prevent recursive application of isImpliedCond.
6675 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6676 /// currently evaluating isImpliedCond.
6677 struct MarkPendingLoopPredicate {
6679 DenseSet<Value*> &LoopPreds;
6682 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6683 : Cond(C), LoopPreds(LP) {
6684 Pending = !LoopPreds.insert(Cond).second;
6686 ~MarkPendingLoopPredicate() {
6688 LoopPreds.erase(Cond);
6692 /// isImpliedCond - Test whether the condition described by Pred, LHS,
6693 /// and RHS is true whenever the given Cond value evaluates to true.
6694 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
6695 const SCEV *LHS, const SCEV *RHS,
6696 Value *FoundCondValue,
6698 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6702 // Recursively handle And and Or conditions.
6703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
6704 if (BO->getOpcode() == Instruction::And) {
6706 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6707 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6708 } else if (BO->getOpcode() == Instruction::Or) {
6710 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6711 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6715 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
6716 if (!ICI) return false;
6718 // Bail if the ICmp's operands' types are wider than the needed type
6719 // before attempting to call getSCEV on them. This avoids infinite
6720 // recursion, since the analysis of widening casts can require loop
6721 // exit condition information for overflow checking, which would
6723 if (getTypeSizeInBits(LHS->getType()) <
6724 getTypeSizeInBits(ICI->getOperand(0)->getType()))
6727 // Now that we found a conditional branch that dominates the loop or controls
6728 // the loop latch. Check to see if it is the comparison we are looking for.
6729 ICmpInst::Predicate FoundPred;
6731 FoundPred = ICI->getInversePredicate();
6733 FoundPred = ICI->getPredicate();
6735 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6736 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
6738 // Balance the types. The case where FoundLHS' type is wider than
6739 // LHS' type is checked for above.
6740 if (getTypeSizeInBits(LHS->getType()) >
6741 getTypeSizeInBits(FoundLHS->getType())) {
6742 if (CmpInst::isSigned(FoundPred)) {
6743 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6744 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6746 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6747 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6751 // Canonicalize the query to match the way instcombine will have
6752 // canonicalized the comparison.
6753 if (SimplifyICmpOperands(Pred, LHS, RHS))
6755 return CmpInst::isTrueWhenEqual(Pred);
6756 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6757 if (FoundLHS == FoundRHS)
6758 return CmpInst::isFalseWhenEqual(FoundPred);
6760 // Check to see if we can make the LHS or RHS match.
6761 if (LHS == FoundRHS || RHS == FoundLHS) {
6762 if (isa<SCEVConstant>(RHS)) {
6763 std::swap(FoundLHS, FoundRHS);
6764 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6766 std::swap(LHS, RHS);
6767 Pred = ICmpInst::getSwappedPredicate(Pred);
6771 // Check whether the found predicate is the same as the desired predicate.
6772 if (FoundPred == Pred)
6773 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6775 // Check whether swapping the found predicate makes it the same as the
6776 // desired predicate.
6777 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6778 if (isa<SCEVConstant>(RHS))
6779 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6781 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6782 RHS, LHS, FoundLHS, FoundRHS);
6785 // Check if we can make progress by sharpening ranges.
6786 if (FoundPred == ICmpInst::ICMP_NE &&
6787 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
6789 const SCEVConstant *C = nullptr;
6790 const SCEV *V = nullptr;
6792 if (isa<SCEVConstant>(FoundLHS)) {
6793 C = cast<SCEVConstant>(FoundLHS);
6796 C = cast<SCEVConstant>(FoundRHS);
6800 // The guarding predicate tells us that C != V. If the known range
6801 // of V is [C, t), we can sharpen the range to [C + 1, t). The
6802 // range we consider has to correspond to same signedness as the
6803 // predicate we're interested in folding.
6805 APInt Min = ICmpInst::isSigned(Pred) ?
6806 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
6808 if (Min == C->getValue()->getValue()) {
6809 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
6810 // This is true even if (Min + 1) wraps around -- in case of
6811 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
6813 APInt SharperMin = Min + 1;
6816 case ICmpInst::ICMP_SGE:
6817 case ICmpInst::ICMP_UGE:
6818 // We know V `Pred` SharperMin. If this implies LHS `Pred`
6820 if (isImpliedCondOperands(Pred, LHS, RHS, V,
6821 getConstant(SharperMin)))
6824 case ICmpInst::ICMP_SGT:
6825 case ICmpInst::ICMP_UGT:
6826 // We know from the range information that (V `Pred` Min ||
6827 // V == Min). We know from the guarding condition that !(V
6828 // == Min). This gives us
6830 // V `Pred` Min || V == Min && !(V == Min)
6833 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
6835 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
6845 // Check whether the actual condition is beyond sufficient.
6846 if (FoundPred == ICmpInst::ICMP_EQ)
6847 if (ICmpInst::isTrueWhenEqual(Pred))
6848 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6850 if (Pred == ICmpInst::ICMP_NE)
6851 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6852 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6855 // Otherwise assume the worst.
6859 /// isImpliedCondOperands - Test whether the condition described by Pred,
6860 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
6861 /// and FoundRHS is true.
6862 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6863 const SCEV *LHS, const SCEV *RHS,
6864 const SCEV *FoundLHS,
6865 const SCEV *FoundRHS) {
6866 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6867 FoundLHS, FoundRHS) ||
6868 // ~x < ~y --> x > y
6869 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6870 getNotSCEV(FoundRHS),
6871 getNotSCEV(FoundLHS));
6874 /// isImpliedCondOperandsHelper - Test whether the condition described by
6875 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
6876 /// FoundLHS, and FoundRHS is true.
6878 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6879 const SCEV *LHS, const SCEV *RHS,
6880 const SCEV *FoundLHS,
6881 const SCEV *FoundRHS) {
6883 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6884 case ICmpInst::ICMP_EQ:
6885 case ICmpInst::ICMP_NE:
6886 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6889 case ICmpInst::ICMP_SLT:
6890 case ICmpInst::ICMP_SLE:
6891 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6892 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
6895 case ICmpInst::ICMP_SGT:
6896 case ICmpInst::ICMP_SGE:
6897 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6898 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
6901 case ICmpInst::ICMP_ULT:
6902 case ICmpInst::ICMP_ULE:
6903 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6904 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
6907 case ICmpInst::ICMP_UGT:
6908 case ICmpInst::ICMP_UGE:
6909 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6910 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
6918 // Verify if an linear IV with positive stride can overflow when in a
6919 // less-than comparison, knowing the invariant term of the comparison, the
6920 // stride and the knowledge of NSW/NUW flags on the recurrence.
6921 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
6922 bool IsSigned, bool NoWrap) {
6923 if (NoWrap) return false;
6925 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6926 const SCEV *One = getConstant(Stride->getType(), 1);
6929 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
6930 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
6931 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6934 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
6935 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
6938 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
6939 APInt MaxValue = APInt::getMaxValue(BitWidth);
6940 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6943 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
6944 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
6947 // Verify if an linear IV with negative stride can overflow when in a
6948 // greater-than comparison, knowing the invariant term of the comparison,
6949 // the stride and the knowledge of NSW/NUW flags on the recurrence.
6950 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
6951 bool IsSigned, bool NoWrap) {
6952 if (NoWrap) return false;
6954 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6955 const SCEV *One = getConstant(Stride->getType(), 1);
6958 APInt MinRHS = getSignedRange(RHS).getSignedMin();
6959 APInt MinValue = APInt::getSignedMinValue(BitWidth);
6960 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6963 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
6964 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
6967 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
6968 APInt MinValue = APInt::getMinValue(BitWidth);
6969 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6972 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
6973 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
6976 // Compute the backedge taken count knowing the interval difference, the
6977 // stride and presence of the equality in the comparison.
6978 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
6980 const SCEV *One = getConstant(Step->getType(), 1);
6981 Delta = Equality ? getAddExpr(Delta, Step)
6982 : getAddExpr(Delta, getMinusSCEV(Step, One));
6983 return getUDivExpr(Delta, Step);
6986 /// HowManyLessThans - Return the number of times a backedge containing the
6987 /// specified less-than comparison will execute. If not computable, return
6988 /// CouldNotCompute.
6990 /// @param ControlsExit is true when the LHS < RHS condition directly controls
6991 /// the branch (loops exits only if condition is true). In this case, we can use
6992 /// NoWrapFlags to skip overflow checks.
6993 ScalarEvolution::ExitLimit
6994 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
6995 const Loop *L, bool IsSigned,
6996 bool ControlsExit) {
6997 // We handle only IV < Invariant
6998 if (!isLoopInvariant(RHS, L))
6999 return getCouldNotCompute();
7001 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7003 // Avoid weird loops
7004 if (!IV || IV->getLoop() != L || !IV->isAffine())
7005 return getCouldNotCompute();
7007 bool NoWrap = ControlsExit &&
7008 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7010 const SCEV *Stride = IV->getStepRecurrence(*this);
7012 // Avoid negative or zero stride values
7013 if (!isKnownPositive(Stride))
7014 return getCouldNotCompute();
7016 // Avoid proven overflow cases: this will ensure that the backedge taken count
7017 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7018 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7019 // behaviors like the case of C language.
7020 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
7021 return getCouldNotCompute();
7023 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
7024 : ICmpInst::ICMP_ULT;
7025 const SCEV *Start = IV->getStart();
7026 const SCEV *End = RHS;
7027 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
7028 const SCEV *Diff = getMinusSCEV(RHS, Start);
7029 // If we have NoWrap set, then we can assume that the increment won't
7030 // overflow, in which case if RHS - Start is a constant, we don't need to
7031 // do a max operation since we can just figure it out statically
7032 if (NoWrap && isa<SCEVConstant>(Diff)) {
7033 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7037 End = IsSigned ? getSMaxExpr(RHS, Start)
7038 : getUMaxExpr(RHS, Start);
7041 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
7043 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
7044 : getUnsignedRange(Start).getUnsignedMin();
7046 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7047 : getUnsignedRange(Stride).getUnsignedMin();
7049 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7050 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
7051 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
7053 // Although End can be a MAX expression we estimate MaxEnd considering only
7054 // the case End = RHS. This is safe because in the other case (End - Start)
7055 // is zero, leading to a zero maximum backedge taken count.
7057 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
7058 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
7060 const SCEV *MaxBECount;
7061 if (isa<SCEVConstant>(BECount))
7062 MaxBECount = BECount;
7064 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
7065 getConstant(MinStride), false);
7067 if (isa<SCEVCouldNotCompute>(MaxBECount))
7068 MaxBECount = BECount;
7070 return ExitLimit(BECount, MaxBECount);
7073 ScalarEvolution::ExitLimit
7074 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
7075 const Loop *L, bool IsSigned,
7076 bool ControlsExit) {
7077 // We handle only IV > Invariant
7078 if (!isLoopInvariant(RHS, L))
7079 return getCouldNotCompute();
7081 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7083 // Avoid weird loops
7084 if (!IV || IV->getLoop() != L || !IV->isAffine())
7085 return getCouldNotCompute();
7087 bool NoWrap = ControlsExit &&
7088 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7090 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
7092 // Avoid negative or zero stride values
7093 if (!isKnownPositive(Stride))
7094 return getCouldNotCompute();
7096 // Avoid proven overflow cases: this will ensure that the backedge taken count
7097 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7098 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7099 // behaviors like the case of C language.
7100 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7101 return getCouldNotCompute();
7103 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7104 : ICmpInst::ICMP_UGT;
7106 const SCEV *Start = IV->getStart();
7107 const SCEV *End = RHS;
7108 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
7109 const SCEV *Diff = getMinusSCEV(RHS, Start);
7110 // If we have NoWrap set, then we can assume that the increment won't
7111 // overflow, in which case if RHS - Start is a constant, we don't need to
7112 // do a max operation since we can just figure it out statically
7113 if (NoWrap && isa<SCEVConstant>(Diff)) {
7114 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7115 if (!D.isNegative())
7118 End = IsSigned ? getSMinExpr(RHS, Start)
7119 : getUMinExpr(RHS, Start);
7122 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7124 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7125 : getUnsignedRange(Start).getUnsignedMax();
7127 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7128 : getUnsignedRange(Stride).getUnsignedMin();
7130 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7131 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7132 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7134 // Although End can be a MIN expression we estimate MinEnd considering only
7135 // the case End = RHS. This is safe because in the other case (Start - End)
7136 // is zero, leading to a zero maximum backedge taken count.
7138 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7139 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7142 const SCEV *MaxBECount = getCouldNotCompute();
7143 if (isa<SCEVConstant>(BECount))
7144 MaxBECount = BECount;
7146 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
7147 getConstant(MinStride), false);
7149 if (isa<SCEVCouldNotCompute>(MaxBECount))
7150 MaxBECount = BECount;
7152 return ExitLimit(BECount, MaxBECount);
7155 /// getNumIterationsInRange - Return the number of iterations of this loop that
7156 /// produce values in the specified constant range. Another way of looking at
7157 /// this is that it returns the first iteration number where the value is not in
7158 /// the condition, thus computing the exit count. If the iteration count can't
7159 /// be computed, an instance of SCEVCouldNotCompute is returned.
7160 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
7161 ScalarEvolution &SE) const {
7162 if (Range.isFullSet()) // Infinite loop.
7163 return SE.getCouldNotCompute();
7165 // If the start is a non-zero constant, shift the range to simplify things.
7166 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
7167 if (!SC->getValue()->isZero()) {
7168 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
7169 Operands[0] = SE.getConstant(SC->getType(), 0);
7170 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
7171 getNoWrapFlags(FlagNW));
7172 if (const SCEVAddRecExpr *ShiftedAddRec =
7173 dyn_cast<SCEVAddRecExpr>(Shifted))
7174 return ShiftedAddRec->getNumIterationsInRange(
7175 Range.subtract(SC->getValue()->getValue()), SE);
7176 // This is strange and shouldn't happen.
7177 return SE.getCouldNotCompute();
7180 // The only time we can solve this is when we have all constant indices.
7181 // Otherwise, we cannot determine the overflow conditions.
7182 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7183 if (!isa<SCEVConstant>(getOperand(i)))
7184 return SE.getCouldNotCompute();
7187 // Okay at this point we know that all elements of the chrec are constants and
7188 // that the start element is zero.
7190 // First check to see if the range contains zero. If not, the first
7192 unsigned BitWidth = SE.getTypeSizeInBits(getType());
7193 if (!Range.contains(APInt(BitWidth, 0)))
7194 return SE.getConstant(getType(), 0);
7197 // If this is an affine expression then we have this situation:
7198 // Solve {0,+,A} in Range === Ax in Range
7200 // We know that zero is in the range. If A is positive then we know that
7201 // the upper value of the range must be the first possible exit value.
7202 // If A is negative then the lower of the range is the last possible loop
7203 // value. Also note that we already checked for a full range.
7204 APInt One(BitWidth,1);
7205 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7206 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
7208 // The exit value should be (End+A)/A.
7209 APInt ExitVal = (End + A).udiv(A);
7210 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
7212 // Evaluate at the exit value. If we really did fall out of the valid
7213 // range, then we computed our trip count, otherwise wrap around or other
7214 // things must have happened.
7215 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
7216 if (Range.contains(Val->getValue()))
7217 return SE.getCouldNotCompute(); // Something strange happened
7219 // Ensure that the previous value is in the range. This is a sanity check.
7220 assert(Range.contains(
7221 EvaluateConstantChrecAtConstant(this,
7222 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
7223 "Linear scev computation is off in a bad way!");
7224 return SE.getConstant(ExitValue);
7225 } else if (isQuadratic()) {
7226 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7227 // quadratic equation to solve it. To do this, we must frame our problem in
7228 // terms of figuring out when zero is crossed, instead of when
7229 // Range.getUpper() is crossed.
7230 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
7231 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
7232 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7233 // getNoWrapFlags(FlagNW)
7236 // Next, solve the constructed addrec
7237 std::pair<const SCEV *,const SCEV *> Roots =
7238 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
7239 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7240 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
7242 // Pick the smallest positive root value.
7243 if (ConstantInt *CB =
7244 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
7245 R1->getValue(), R2->getValue()))) {
7246 if (CB->getZExtValue() == false)
7247 std::swap(R1, R2); // R1 is the minimum root now.
7249 // Make sure the root is not off by one. The returned iteration should
7250 // not be in the range, but the previous one should be. When solving
7251 // for "X*X < 5", for example, we should not return a root of 2.
7252 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
7255 if (Range.contains(R1Val->getValue())) {
7256 // The next iteration must be out of the range...
7257 ConstantInt *NextVal =
7258 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
7260 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7261 if (!Range.contains(R1Val->getValue()))
7262 return SE.getConstant(NextVal);
7263 return SE.getCouldNotCompute(); // Something strange happened
7266 // If R1 was not in the range, then it is a good return value. Make
7267 // sure that R1-1 WAS in the range though, just in case.
7268 ConstantInt *NextVal =
7269 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
7270 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7271 if (Range.contains(R1Val->getValue()))
7273 return SE.getCouldNotCompute(); // Something strange happened
7278 return SE.getCouldNotCompute();
7284 FindUndefs() : Found(false) {}
7286 bool follow(const SCEV *S) {
7287 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7288 if (isa<UndefValue>(C->getValue()))
7290 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7291 if (isa<UndefValue>(C->getValue()))
7295 // Keep looking if we haven't found it yet.
7298 bool isDone() const {
7299 // Stop recursion if we have found an undef.
7305 // Return true when S contains at least an undef value.
7307 containsUndefs(const SCEV *S) {
7309 SCEVTraversal<FindUndefs> ST(F);
7316 // Collect all steps of SCEV expressions.
7317 struct SCEVCollectStrides {
7318 ScalarEvolution &SE;
7319 SmallVectorImpl<const SCEV *> &Strides;
7321 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7322 : SE(SE), Strides(S) {}
7324 bool follow(const SCEV *S) {
7325 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7326 Strides.push_back(AR->getStepRecurrence(SE));
7329 bool isDone() const { return false; }
7332 // Collect all SCEVUnknown and SCEVMulExpr expressions.
7333 struct SCEVCollectTerms {
7334 SmallVectorImpl<const SCEV *> &Terms;
7336 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7339 bool follow(const SCEV *S) {
7340 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
7341 if (!containsUndefs(S))
7344 // Stop recursion: once we collected a term, do not walk its operands.
7351 bool isDone() const { return false; }
7355 /// Find parametric terms in this SCEVAddRecExpr.
7356 void SCEVAddRecExpr::collectParametricTerms(
7357 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7358 SmallVector<const SCEV *, 4> Strides;
7359 SCEVCollectStrides StrideCollector(SE, Strides);
7360 visitAll(this, StrideCollector);
7363 dbgs() << "Strides:\n";
7364 for (const SCEV *S : Strides)
7365 dbgs() << *S << "\n";
7368 for (const SCEV *S : Strides) {
7369 SCEVCollectTerms TermCollector(Terms);
7370 visitAll(S, TermCollector);
7374 dbgs() << "Terms:\n";
7375 for (const SCEV *T : Terms)
7376 dbgs() << *T << "\n";
7380 static bool findArrayDimensionsRec(ScalarEvolution &SE,
7381 SmallVectorImpl<const SCEV *> &Terms,
7382 SmallVectorImpl<const SCEV *> &Sizes) {
7383 int Last = Terms.size() - 1;
7384 const SCEV *Step = Terms[Last];
7386 // End of recursion.
7388 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
7389 SmallVector<const SCEV *, 2> Qs;
7390 for (const SCEV *Op : M->operands())
7391 if (!isa<SCEVConstant>(Op))
7394 Step = SE.getMulExpr(Qs);
7397 Sizes.push_back(Step);
7401 for (const SCEV *&Term : Terms) {
7402 // Normalize the terms before the next call to findArrayDimensionsRec.
7404 SCEVDivision::divide(SE, Term, Step, &Q, &R);
7406 // Bail out when GCD does not evenly divide one of the terms.
7413 // Remove all SCEVConstants.
7414 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7415 return isa<SCEVConstant>(E);
7419 if (Terms.size() > 0)
7420 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7423 Sizes.push_back(Step);
7428 struct FindParameter {
7429 bool FoundParameter;
7430 FindParameter() : FoundParameter(false) {}
7432 bool follow(const SCEV *S) {
7433 if (isa<SCEVUnknown>(S)) {
7434 FoundParameter = true;
7435 // Stop recursion: we found a parameter.
7441 bool isDone() const {
7442 // Stop recursion if we have found a parameter.
7443 return FoundParameter;
7448 // Returns true when S contains at least a SCEVUnknown parameter.
7450 containsParameters(const SCEV *S) {
7452 SCEVTraversal<FindParameter> ST(F);
7455 return F.FoundParameter;
7458 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7460 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7461 for (const SCEV *T : Terms)
7462 if (containsParameters(T))
7467 // Return the number of product terms in S.
7468 static inline int numberOfTerms(const SCEV *S) {
7469 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7470 return Expr->getNumOperands();
7474 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7475 if (isa<SCEVConstant>(T))
7478 if (isa<SCEVUnknown>(T))
7481 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7482 SmallVector<const SCEV *, 2> Factors;
7483 for (const SCEV *Op : M->operands())
7484 if (!isa<SCEVConstant>(Op))
7485 Factors.push_back(Op);
7487 return SE.getMulExpr(Factors);
7493 /// Return the size of an element read or written by Inst.
7494 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7496 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7497 Ty = Store->getValueOperand()->getType();
7498 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
7499 Ty = Load->getType();
7503 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7504 return getSizeOfExpr(ETy, Ty);
7507 /// Second step of delinearization: compute the array dimensions Sizes from the
7508 /// set of Terms extracted from the memory access function of this SCEVAddRec.
7509 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7510 SmallVectorImpl<const SCEV *> &Sizes,
7511 const SCEV *ElementSize) const {
7513 if (Terms.size() < 1 || !ElementSize)
7516 // Early return when Terms do not contain parameters: we do not delinearize
7517 // non parametric SCEVs.
7518 if (!containsParameters(Terms))
7522 dbgs() << "Terms:\n";
7523 for (const SCEV *T : Terms)
7524 dbgs() << *T << "\n";
7527 // Remove duplicates.
7528 std::sort(Terms.begin(), Terms.end());
7529 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7531 // Put larger terms first.
7532 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7533 return numberOfTerms(LHS) > numberOfTerms(RHS);
7536 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7538 // Divide all terms by the element size.
7539 for (const SCEV *&Term : Terms) {
7541 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
7545 SmallVector<const SCEV *, 4> NewTerms;
7547 // Remove constant factors.
7548 for (const SCEV *T : Terms)
7549 if (const SCEV *NewT = removeConstantFactors(SE, T))
7550 NewTerms.push_back(NewT);
7553 dbgs() << "Terms after sorting:\n";
7554 for (const SCEV *T : NewTerms)
7555 dbgs() << *T << "\n";
7558 if (NewTerms.empty() ||
7559 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
7564 // The last element to be pushed into Sizes is the size of an element.
7565 Sizes.push_back(ElementSize);
7568 dbgs() << "Sizes:\n";
7569 for (const SCEV *S : Sizes)
7570 dbgs() << *S << "\n";
7574 /// Third step of delinearization: compute the access functions for the
7575 /// Subscripts based on the dimensions in Sizes.
7576 void SCEVAddRecExpr::computeAccessFunctions(
7577 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7578 SmallVectorImpl<const SCEV *> &Sizes) const {
7580 // Early exit in case this SCEV is not an affine multivariate function.
7581 if (Sizes.empty() || !this->isAffine())
7584 const SCEV *Res = this;
7585 int Last = Sizes.size() - 1;
7586 for (int i = Last; i >= 0; i--) {
7588 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
7591 dbgs() << "Res: " << *Res << "\n";
7592 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7593 dbgs() << "Res divided by Sizes[i]:\n";
7594 dbgs() << "Quotient: " << *Q << "\n";
7595 dbgs() << "Remainder: " << *R << "\n";
7600 // Do not record the last subscript corresponding to the size of elements in
7604 // Bail out if the remainder is too complex.
7605 if (isa<SCEVAddRecExpr>(R)) {
7614 // Record the access function for the current subscript.
7615 Subscripts.push_back(R);
7618 // Also push in last position the remainder of the last division: it will be
7619 // the access function of the innermost dimension.
7620 Subscripts.push_back(Res);
7622 std::reverse(Subscripts.begin(), Subscripts.end());
7625 dbgs() << "Subscripts:\n";
7626 for (const SCEV *S : Subscripts)
7627 dbgs() << *S << "\n";
7631 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7632 /// sizes of an array access. Returns the remainder of the delinearization that
7633 /// is the offset start of the array. The SCEV->delinearize algorithm computes
7634 /// the multiples of SCEV coefficients: that is a pattern matching of sub
7635 /// expressions in the stride and base of a SCEV corresponding to the
7636 /// computation of a GCD (greatest common divisor) of base and stride. When
7637 /// SCEV->delinearize fails, it returns the SCEV unchanged.
7639 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
7641 /// void foo(long n, long m, long o, double A[n][m][o]) {
7643 /// for (long i = 0; i < n; i++)
7644 /// for (long j = 0; j < m; j++)
7645 /// for (long k = 0; k < o; k++)
7646 /// A[i][j][k] = 1.0;
7649 /// the delinearization input is the following AddRec SCEV:
7651 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7653 /// From this SCEV, we are able to say that the base offset of the access is %A
7654 /// because it appears as an offset that does not divide any of the strides in
7657 /// CHECK: Base offset: %A
7659 /// and then SCEV->delinearize determines the size of some of the dimensions of
7660 /// the array as these are the multiples by which the strides are happening:
7662 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7664 /// Note that the outermost dimension remains of UnknownSize because there are
7665 /// no strides that would help identifying the size of the last dimension: when
7666 /// the array has been statically allocated, one could compute the size of that
7667 /// dimension by dividing the overall size of the array by the size of the known
7668 /// dimensions: %m * %o * 8.
7670 /// Finally delinearize provides the access functions for the array reference
7671 /// that does correspond to A[i][j][k] of the above C testcase:
7673 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7675 /// The testcases are checking the output of a function pass:
7676 /// DelinearizationPass that walks through all loads and stores of a function
7677 /// asking for the SCEV of the memory access with respect to all enclosing
7678 /// loops, calling SCEV->delinearize on that and printing the results.
7680 void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7681 SmallVectorImpl<const SCEV *> &Subscripts,
7682 SmallVectorImpl<const SCEV *> &Sizes,
7683 const SCEV *ElementSize) const {
7684 // First step: collect parametric terms.
7685 SmallVector<const SCEV *, 4> Terms;
7686 collectParametricTerms(SE, Terms);
7691 // Second step: find subscript sizes.
7692 SE.findArrayDimensions(Terms, Sizes, ElementSize);
7697 // Third step: compute the access functions for each subscript.
7698 computeAccessFunctions(SE, Subscripts, Sizes);
7700 if (Subscripts.empty())
7704 dbgs() << "succeeded to delinearize " << *this << "\n";
7705 dbgs() << "ArrayDecl[UnknownSize]";
7706 for (const SCEV *S : Sizes)
7707 dbgs() << "[" << *S << "]";
7709 dbgs() << "\nArrayRef";
7710 for (const SCEV *S : Subscripts)
7711 dbgs() << "[" << *S << "]";
7716 //===----------------------------------------------------------------------===//
7717 // SCEVCallbackVH Class Implementation
7718 //===----------------------------------------------------------------------===//
7720 void ScalarEvolution::SCEVCallbackVH::deleted() {
7721 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7722 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7723 SE->ConstantEvolutionLoopExitValue.erase(PN);
7724 SE->ValueExprMap.erase(getValPtr());
7725 // this now dangles!
7728 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
7729 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7731 // Forget all the expressions associated with users of the old value,
7732 // so that future queries will recompute the expressions using the new
7734 Value *Old = getValPtr();
7735 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
7736 SmallPtrSet<User *, 8> Visited;
7737 while (!Worklist.empty()) {
7738 User *U = Worklist.pop_back_val();
7739 // Deleting the Old value will cause this to dangle. Postpone
7740 // that until everything else is done.
7743 if (!Visited.insert(U))
7745 if (PHINode *PN = dyn_cast<PHINode>(U))
7746 SE->ConstantEvolutionLoopExitValue.erase(PN);
7747 SE->ValueExprMap.erase(U);
7748 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
7750 // Delete the Old value.
7751 if (PHINode *PN = dyn_cast<PHINode>(Old))
7752 SE->ConstantEvolutionLoopExitValue.erase(PN);
7753 SE->ValueExprMap.erase(Old);
7754 // this now dangles!
7757 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
7758 : CallbackVH(V), SE(se) {}
7760 //===----------------------------------------------------------------------===//
7761 // ScalarEvolution Class Implementation
7762 //===----------------------------------------------------------------------===//
7764 ScalarEvolution::ScalarEvolution()
7765 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7766 BlockDispositions(64), FirstUnknown(nullptr) {
7767 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
7770 bool ScalarEvolution::runOnFunction(Function &F) {
7772 AT = &getAnalysis<AssumptionTracker>();
7773 LI = &getAnalysis<LoopInfo>();
7774 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
7775 DL = DLP ? &DLP->getDataLayout() : nullptr;
7776 TLI = &getAnalysis<TargetLibraryInfo>();
7777 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7781 void ScalarEvolution::releaseMemory() {
7782 // Iterate through all the SCEVUnknown instances and call their
7783 // destructors, so that they release their references to their values.
7784 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7786 FirstUnknown = nullptr;
7788 ValueExprMap.clear();
7790 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7791 // that a loop had multiple computable exits.
7792 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7793 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7798 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7800 BackedgeTakenCounts.clear();
7801 ConstantEvolutionLoopExitValue.clear();
7802 ValuesAtScopes.clear();
7803 LoopDispositions.clear();
7804 BlockDispositions.clear();
7805 UnsignedRanges.clear();
7806 SignedRanges.clear();
7807 UniqueSCEVs.clear();
7808 SCEVAllocator.Reset();
7811 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
7812 AU.setPreservesAll();
7813 AU.addRequired<AssumptionTracker>();
7814 AU.addRequiredTransitive<LoopInfo>();
7815 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
7816 AU.addRequired<TargetLibraryInfo>();
7819 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
7820 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
7823 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
7825 // Print all inner loops first
7826 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
7827 PrintLoopInfo(OS, SE, *I);
7830 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7833 SmallVector<BasicBlock *, 8> ExitBlocks;
7834 L->getExitBlocks(ExitBlocks);
7835 if (ExitBlocks.size() != 1)
7836 OS << "<multiple exits> ";
7838 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
7839 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
7841 OS << "Unpredictable backedge-taken count. ";
7846 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7849 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
7850 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
7852 OS << "Unpredictable max backedge-taken count. ";
7858 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
7859 // ScalarEvolution's implementation of the print method is to print
7860 // out SCEV values of all instructions that are interesting. Doing
7861 // this potentially causes it to create new SCEV objects though,
7862 // which technically conflicts with the const qualifier. This isn't
7863 // observable from outside the class though, so casting away the
7864 // const isn't dangerous.
7865 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7867 OS << "Classifying expressions for: ";
7868 F->printAsOperand(OS, /*PrintType=*/false);
7870 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
7871 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
7874 const SCEV *SV = SE.getSCEV(&*I);
7877 const Loop *L = LI->getLoopFor((*I).getParent());
7879 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
7886 OS << "\t\t" "Exits: ";
7887 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
7888 if (!SE.isLoopInvariant(ExitValue, L)) {
7889 OS << "<<Unknown>>";
7898 OS << "Determining loop execution counts for: ";
7899 F->printAsOperand(OS, /*PrintType=*/false);
7901 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
7902 PrintLoopInfo(OS, &SE, *I);
7905 ScalarEvolution::LoopDisposition
7906 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
7907 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values = LoopDispositions[S];
7908 for (unsigned u = 0; u < Values.size(); u++) {
7909 if (Values[u].first == L)
7910 return Values[u].second;
7912 Values.push_back(std::make_pair(L, LoopVariant));
7913 LoopDisposition D = computeLoopDisposition(S, L);
7914 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values2 = LoopDispositions[S];
7915 for (unsigned u = Values2.size(); u > 0; u--) {
7916 if (Values2[u - 1].first == L) {
7917 Values2[u - 1].second = D;
7924 ScalarEvolution::LoopDisposition
7925 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
7926 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
7928 return LoopInvariant;
7932 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
7933 case scAddRecExpr: {
7934 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7936 // If L is the addrec's loop, it's computable.
7937 if (AR->getLoop() == L)
7938 return LoopComputable;
7940 // Add recurrences are never invariant in the function-body (null loop).
7944 // This recurrence is variant w.r.t. L if L contains AR's loop.
7945 if (L->contains(AR->getLoop()))
7948 // This recurrence is invariant w.r.t. L if AR's loop contains L.
7949 if (AR->getLoop()->contains(L))
7950 return LoopInvariant;
7952 // This recurrence is variant w.r.t. L if any of its operands
7954 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
7956 if (!isLoopInvariant(*I, L))
7959 // Otherwise it's loop-invariant.
7960 return LoopInvariant;
7966 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
7967 bool HasVarying = false;
7968 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
7970 LoopDisposition D = getLoopDisposition(*I, L);
7971 if (D == LoopVariant)
7973 if (D == LoopComputable)
7976 return HasVarying ? LoopComputable : LoopInvariant;
7979 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
7980 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
7981 if (LD == LoopVariant)
7983 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
7984 if (RD == LoopVariant)
7986 return (LD == LoopInvariant && RD == LoopInvariant) ?
7987 LoopInvariant : LoopComputable;
7990 // All non-instruction values are loop invariant. All instructions are loop
7991 // invariant if they are not contained in the specified loop.
7992 // Instructions are never considered invariant in the function body
7993 // (null loop) because they are defined within the "loop".
7994 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
7995 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
7996 return LoopInvariant;
7997 case scCouldNotCompute:
7998 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8000 llvm_unreachable("Unknown SCEV kind!");
8003 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
8004 return getLoopDisposition(S, L) == LoopInvariant;
8007 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
8008 return getLoopDisposition(S, L) == LoopComputable;
8011 ScalarEvolution::BlockDisposition
8012 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8013 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values = BlockDispositions[S];
8014 for (unsigned u = 0; u < Values.size(); u++) {
8015 if (Values[u].first == BB)
8016 return Values[u].second;
8018 Values.push_back(std::make_pair(BB, DoesNotDominateBlock));
8019 BlockDisposition D = computeBlockDisposition(S, BB);
8020 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values2 = BlockDispositions[S];
8021 for (unsigned u = Values2.size(); u > 0; u--) {
8022 if (Values2[u - 1].first == BB) {
8023 Values2[u - 1].second = D;
8030 ScalarEvolution::BlockDisposition
8031 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8032 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8034 return ProperlyDominatesBlock;
8038 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
8039 case scAddRecExpr: {
8040 // This uses a "dominates" query instead of "properly dominates" query
8041 // to test for proper dominance too, because the instruction which
8042 // produces the addrec's value is a PHI, and a PHI effectively properly
8043 // dominates its entire containing block.
8044 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8045 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
8046 return DoesNotDominateBlock;
8048 // FALL THROUGH into SCEVNAryExpr handling.
8053 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
8055 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8057 BlockDisposition D = getBlockDisposition(*I, BB);
8058 if (D == DoesNotDominateBlock)
8059 return DoesNotDominateBlock;
8060 if (D == DominatesBlock)
8063 return Proper ? ProperlyDominatesBlock : DominatesBlock;
8066 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
8067 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
8068 BlockDisposition LD = getBlockDisposition(LHS, BB);
8069 if (LD == DoesNotDominateBlock)
8070 return DoesNotDominateBlock;
8071 BlockDisposition RD = getBlockDisposition(RHS, BB);
8072 if (RD == DoesNotDominateBlock)
8073 return DoesNotDominateBlock;
8074 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
8075 ProperlyDominatesBlock : DominatesBlock;
8078 if (Instruction *I =
8079 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
8080 if (I->getParent() == BB)
8081 return DominatesBlock;
8082 if (DT->properlyDominates(I->getParent(), BB))
8083 return ProperlyDominatesBlock;
8084 return DoesNotDominateBlock;
8086 return ProperlyDominatesBlock;
8087 case scCouldNotCompute:
8088 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8090 llvm_unreachable("Unknown SCEV kind!");
8093 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
8094 return getBlockDisposition(S, BB) >= DominatesBlock;
8097 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
8098 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
8102 // Search for a SCEV expression node within an expression tree.
8103 // Implements SCEVTraversal::Visitor.
8108 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8110 bool follow(const SCEV *S) {
8111 IsFound |= (S == Node);
8114 bool isDone() const { return IsFound; }
8118 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
8119 SCEVSearch Search(Op);
8120 visitAll(S, Search);
8121 return Search.IsFound;
8124 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8125 ValuesAtScopes.erase(S);
8126 LoopDispositions.erase(S);
8127 BlockDispositions.erase(S);
8128 UnsignedRanges.erase(S);
8129 SignedRanges.erase(S);
8131 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8132 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8133 BackedgeTakenInfo &BEInfo = I->second;
8134 if (BEInfo.hasOperand(S, this)) {
8136 BackedgeTakenCounts.erase(I++);
8143 typedef DenseMap<const Loop *, std::string> VerifyMap;
8145 /// replaceSubString - Replaces all occurrences of From in Str with To.
8146 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8148 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8149 Str.replace(Pos, From.size(), To.data(), To.size());
8154 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8156 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8157 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8158 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8160 std::string &S = Map[L];
8162 raw_string_ostream OS(S);
8163 SE.getBackedgeTakenCount(L)->print(OS);
8165 // false and 0 are semantically equivalent. This can happen in dead loops.
8166 replaceSubString(OS.str(), "false", "0");
8167 // Remove wrap flags, their use in SCEV is highly fragile.
8168 // FIXME: Remove this when SCEV gets smarter about them.
8169 replaceSubString(OS.str(), "<nw>", "");
8170 replaceSubString(OS.str(), "<nsw>", "");
8171 replaceSubString(OS.str(), "<nuw>", "");
8176 void ScalarEvolution::verifyAnalysis() const {
8180 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8182 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8183 // FIXME: It would be much better to store actual values instead of strings,
8184 // but SCEV pointers will change if we drop the caches.
8185 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8186 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8187 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8189 // Gather stringified backedge taken counts for all loops without using
8192 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8193 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8195 // Now compare whether they're the same with and without caches. This allows
8196 // verifying that no pass changed the cache.
8197 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8198 "New loops suddenly appeared!");
8200 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8201 OldE = BackedgeDumpsOld.end(),
8202 NewI = BackedgeDumpsNew.begin();
8203 OldI != OldE; ++OldI, ++NewI) {
8204 assert(OldI->first == NewI->first && "Loop order changed!");
8206 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8208 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
8209 // means that a pass is buggy or SCEV has to learn a new pattern but is
8210 // usually not harmful.
8211 if (OldI->second != NewI->second &&
8212 OldI->second.find("undef") == std::string::npos &&
8213 NewI->second.find("undef") == std::string::npos &&
8214 OldI->second != "***COULDNOTCOMPUTE***" &&
8215 NewI->second != "***COULDNOTCOMPUTE***") {
8216 dbgs() << "SCEVValidator: SCEV for loop '"
8217 << OldI->first->getHeader()->getName()
8218 << "' changed from '" << OldI->second
8219 << "' to '" << NewI->second << "'!\n";
8224 // TODO: Verify more things.