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/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/KnownBits.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Support/raw_ostream.h"
95 #include "llvm/Support/SaveAndRestore.h"
99 #define DEBUG_TYPE "scalar-evolution"
101 STATISTIC(NumArrayLenItCounts,
102 "Number of trip counts computed with array length");
103 STATISTIC(NumTripCountsComputed,
104 "Number of loops with predictable loop counts");
105 STATISTIC(NumTripCountsNotComputed,
106 "Number of loops without predictable loop counts");
107 STATISTIC(NumBruteForceTripCountsComputed,
108 "Number of loops with trip counts computed by force");
110 static cl::opt<unsigned>
111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112 cl::desc("Maximum number of iterations SCEV will "
113 "symbolically execute a constant "
117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
119 VerifySCEV("verify-scev",
120 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
122 VerifySCEVMap("verify-scev-maps",
123 cl::desc("Verify no dangling value in ScalarEvolution's "
124 "ExprValueMap (slow)"));
126 static cl::opt<unsigned> MulOpsInlineThreshold(
127 "scev-mulops-inline-threshold", cl::Hidden,
128 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
131 static cl::opt<unsigned> AddOpsInlineThreshold(
132 "scev-addops-inline-threshold", cl::Hidden,
133 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
136 static cl::opt<unsigned> MaxSCEVCompareDepth(
137 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
146 static cl::opt<unsigned> MaxValueCompareDepth(
147 "scalar-evolution-max-value-compare-depth", cl::Hidden,
148 cl::desc("Maximum depth of recursive value complexity comparisons"),
151 static cl::opt<unsigned>
152 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
153 cl::desc("Maximum depth of recursive AddExpr"),
156 static cl::opt<unsigned> MaxConstantEvolvingDepth(
157 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
160 //===----------------------------------------------------------------------===//
161 // SCEV class definitions
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
165 // Implementation of the SCEV class.
168 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
169 LLVM_DUMP_METHOD void SCEV::dump() const {
175 void SCEV::print(raw_ostream &OS) const {
176 switch (static_cast<SCEVTypes>(getSCEVType())) {
178 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
181 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
182 const SCEV *Op = Trunc->getOperand();
183 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
184 << *Trunc->getType() << ")";
188 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
189 const SCEV *Op = ZExt->getOperand();
190 OS << "(zext " << *Op->getType() << " " << *Op << " to "
191 << *ZExt->getType() << ")";
195 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
196 const SCEV *Op = SExt->getOperand();
197 OS << "(sext " << *Op->getType() << " " << *Op << " to "
198 << *SExt->getType() << ")";
202 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
203 OS << "{" << *AR->getOperand(0);
204 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
205 OS << ",+," << *AR->getOperand(i);
207 if (AR->hasNoUnsignedWrap())
209 if (AR->hasNoSignedWrap())
211 if (AR->hasNoSelfWrap() &&
212 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
214 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
222 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
223 const char *OpStr = nullptr;
224 switch (NAry->getSCEVType()) {
225 case scAddExpr: OpStr = " + "; break;
226 case scMulExpr: OpStr = " * "; break;
227 case scUMaxExpr: OpStr = " umax "; break;
228 case scSMaxExpr: OpStr = " smax "; break;
231 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
234 if (std::next(I) != E)
238 switch (NAry->getSCEVType()) {
241 if (NAry->hasNoUnsignedWrap())
243 if (NAry->hasNoSignedWrap())
249 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
250 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
254 const SCEVUnknown *U = cast<SCEVUnknown>(this);
256 if (U->isSizeOf(AllocTy)) {
257 OS << "sizeof(" << *AllocTy << ")";
260 if (U->isAlignOf(AllocTy)) {
261 OS << "alignof(" << *AllocTy << ")";
267 if (U->isOffsetOf(CTy, FieldNo)) {
268 OS << "offsetof(" << *CTy << ", ";
269 FieldNo->printAsOperand(OS, false);
274 // Otherwise just print it normally.
275 U->getValue()->printAsOperand(OS, false);
278 case scCouldNotCompute:
279 OS << "***COULDNOTCOMPUTE***";
282 llvm_unreachable("Unknown SCEV kind!");
285 Type *SCEV::getType() const {
286 switch (static_cast<SCEVTypes>(getSCEVType())) {
288 return cast<SCEVConstant>(this)->getType();
292 return cast<SCEVCastExpr>(this)->getType();
297 return cast<SCEVNAryExpr>(this)->getType();
299 return cast<SCEVAddExpr>(this)->getType();
301 return cast<SCEVUDivExpr>(this)->getType();
303 return cast<SCEVUnknown>(this)->getType();
304 case scCouldNotCompute:
305 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
307 llvm_unreachable("Unknown SCEV kind!");
310 bool SCEV::isZero() const {
311 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312 return SC->getValue()->isZero();
316 bool SCEV::isOne() const {
317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318 return SC->getValue()->isOne();
322 bool SCEV::isAllOnesValue() const {
323 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
324 return SC->getValue()->isAllOnesValue();
328 bool SCEV::isNonConstantNegative() const {
329 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
330 if (!Mul) return false;
332 // If there is a constant factor, it will be first.
333 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
334 if (!SC) return false;
336 // Return true if the value is negative, this matches things like (-42 * V).
337 return SC->getAPInt().isNegative();
340 SCEVCouldNotCompute::SCEVCouldNotCompute() :
341 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
343 bool SCEVCouldNotCompute::classof(const SCEV *S) {
344 return S->getSCEVType() == scCouldNotCompute;
347 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
349 ID.AddInteger(scConstant);
352 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
353 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
354 UniqueSCEVs.InsertNode(S, IP);
358 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
359 return getConstant(ConstantInt::get(getContext(), Val));
363 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
364 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
365 return getConstant(ConstantInt::get(ITy, V, isSigned));
368 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
369 unsigned SCEVTy, const SCEV *op, Type *ty)
370 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
372 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
373 const SCEV *op, Type *ty)
374 : SCEVCastExpr(ID, scTruncate, op, ty) {
375 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
377 "Cannot truncate non-integer value!");
380 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
381 const SCEV *op, Type *ty)
382 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
383 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
384 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
385 "Cannot zero extend non-integer value!");
388 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
389 const SCEV *op, Type *ty)
390 : SCEVCastExpr(ID, scSignExtend, op, ty) {
391 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
392 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
393 "Cannot sign extend non-integer value!");
396 void SCEVUnknown::deleted() {
397 // Clear this SCEVUnknown from various maps.
398 SE->forgetMemoizedResults(this);
400 // Remove this SCEVUnknown from the uniquing map.
401 SE->UniqueSCEVs.RemoveNode(this);
403 // Release the value.
407 void SCEVUnknown::allUsesReplacedWith(Value *New) {
408 // Clear this SCEVUnknown from various maps.
409 SE->forgetMemoizedResults(this);
411 // Remove this SCEVUnknown from the uniquing map.
412 SE->UniqueSCEVs.RemoveNode(this);
414 // Update this SCEVUnknown to point to the new value. This is needed
415 // because there may still be outstanding SCEVs which still point to
420 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
421 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
422 if (VCE->getOpcode() == Instruction::PtrToInt)
423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
424 if (CE->getOpcode() == Instruction::GetElementPtr &&
425 CE->getOperand(0)->isNullValue() &&
426 CE->getNumOperands() == 2)
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
429 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
437 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
438 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
439 if (VCE->getOpcode() == Instruction::PtrToInt)
440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
441 if (CE->getOpcode() == Instruction::GetElementPtr &&
442 CE->getOperand(0)->isNullValue()) {
444 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
445 if (StructType *STy = dyn_cast<StructType>(Ty))
446 if (!STy->isPacked() &&
447 CE->getNumOperands() == 3 &&
448 CE->getOperand(1)->isNullValue()) {
449 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
451 STy->getNumElements() == 2 &&
452 STy->getElementType(0)->isIntegerTy(1)) {
453 AllocTy = STy->getElementType(1);
462 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
463 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
464 if (VCE->getOpcode() == Instruction::PtrToInt)
465 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
466 if (CE->getOpcode() == Instruction::GetElementPtr &&
467 CE->getNumOperands() == 3 &&
468 CE->getOperand(0)->isNullValue() &&
469 CE->getOperand(1)->isNullValue()) {
471 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
472 // Ignore vector types here so that ScalarEvolutionExpander doesn't
473 // emit getelementptrs that index into vectors.
474 if (Ty->isStructTy() || Ty->isArrayTy()) {
476 FieldNo = CE->getOperand(2);
484 //===----------------------------------------------------------------------===//
486 //===----------------------------------------------------------------------===//
488 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
489 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
490 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
491 /// have been previously deemed to be "equally complex" by this routine. It is
492 /// intended to avoid exponential time complexity in cases like:
502 /// CompareValueComplexity(%f, %c)
504 /// Since we do not continue running this routine on expression trees once we
505 /// have seen unequal values, there is no need to track them in the cache.
507 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
508 const LoopInfo *const LI, Value *LV, Value *RV,
510 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
513 // Order pointer values after integer values. This helps SCEVExpander form
515 bool LIsPointer = LV->getType()->isPointerTy(),
516 RIsPointer = RV->getType()->isPointerTy();
517 if (LIsPointer != RIsPointer)
518 return (int)LIsPointer - (int)RIsPointer;
520 // Compare getValueID values.
521 unsigned LID = LV->getValueID(), RID = RV->getValueID();
523 return (int)LID - (int)RID;
525 // Sort arguments by their position.
526 if (const auto *LA = dyn_cast<Argument>(LV)) {
527 const auto *RA = cast<Argument>(RV);
528 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
529 return (int)LArgNo - (int)RArgNo;
532 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
533 const auto *RGV = cast<GlobalValue>(RV);
535 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
536 auto LT = GV->getLinkage();
537 return !(GlobalValue::isPrivateLinkage(LT) ||
538 GlobalValue::isInternalLinkage(LT));
541 // Use the names to distinguish the two values, but only if the
542 // names are semantically important.
543 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
544 return LGV->getName().compare(RGV->getName());
547 // For instructions, compare their loop depth, and their operand count. This
549 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
550 const auto *RInst = cast<Instruction>(RV);
552 // Compare loop depths.
553 const BasicBlock *LParent = LInst->getParent(),
554 *RParent = RInst->getParent();
555 if (LParent != RParent) {
556 unsigned LDepth = LI->getLoopDepth(LParent),
557 RDepth = LI->getLoopDepth(RParent);
558 if (LDepth != RDepth)
559 return (int)LDepth - (int)RDepth;
562 // Compare the number of operands.
563 unsigned LNumOps = LInst->getNumOperands(),
564 RNumOps = RInst->getNumOperands();
565 if (LNumOps != RNumOps)
566 return (int)LNumOps - (int)RNumOps;
568 for (unsigned Idx : seq(0u, LNumOps)) {
570 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
571 RInst->getOperand(Idx), Depth + 1);
577 EqCache.insert({LV, RV});
581 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
582 // than RHS, respectively. A three-way result allows recursive comparisons to be
584 static int CompareSCEVComplexity(
585 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
586 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
587 DominatorTree &DT, unsigned Depth = 0) {
588 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
592 // Primarily, sort the SCEVs by their getSCEVType().
593 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
595 return (int)LType - (int)RType;
597 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
599 // Aside from the getSCEVType() ordering, the particular ordering
600 // isn't very important except that it's beneficial to be consistent,
601 // so that (a + b) and (b + a) don't end up as different expressions.
602 switch (static_cast<SCEVTypes>(LType)) {
604 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
605 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
607 SmallSet<std::pair<Value *, Value *>, 8> EqCache;
608 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
611 EqCacheSCEV.insert({LHS, RHS});
616 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
617 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
619 // Compare constant values.
620 const APInt &LA = LC->getAPInt();
621 const APInt &RA = RC->getAPInt();
622 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
623 if (LBitWidth != RBitWidth)
624 return (int)LBitWidth - (int)RBitWidth;
625 return LA.ult(RA) ? -1 : 1;
629 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
630 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
632 // If there is a dominance relationship between the loops, sort by the
633 // dominance. Otherwise, sort by depth. We require such order in getAddExpr.
634 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
635 if (LLoop != RLoop) {
636 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
637 assert(LHead != RHead && "Two loops share the same header?");
638 if (DT.dominates(LHead, RHead))
640 else if (DT.dominates(RHead, LHead))
642 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
643 if (LDepth != RDepth)
644 return (int)LDepth - (int)RDepth;
647 // Addrec complexity grows with operand count.
648 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
649 if (LNumOps != RNumOps)
650 return (int)LNumOps - (int)RNumOps;
652 // Lexicographically compare.
653 for (unsigned i = 0; i != LNumOps; ++i) {
654 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
655 RA->getOperand(i), DT, Depth + 1);
659 EqCacheSCEV.insert({LHS, RHS});
667 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
668 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
670 // Lexicographically compare n-ary expressions.
671 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
672 if (LNumOps != RNumOps)
673 return (int)LNumOps - (int)RNumOps;
675 for (unsigned i = 0; i != LNumOps; ++i) {
678 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
679 RC->getOperand(i), DT, Depth + 1);
683 EqCacheSCEV.insert({LHS, RHS});
688 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
689 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
691 // Lexicographically compare udiv expressions.
692 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
696 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT,
699 EqCacheSCEV.insert({LHS, RHS});
706 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
707 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
709 // Compare cast expressions by operand.
710 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
711 RC->getOperand(), DT, Depth + 1);
713 EqCacheSCEV.insert({LHS, RHS});
717 case scCouldNotCompute:
718 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
720 llvm_unreachable("Unknown SCEV kind!");
723 /// Given a list of SCEV objects, order them by their complexity, and group
724 /// objects of the same complexity together by value. When this routine is
725 /// finished, we know that any duplicates in the vector are consecutive and that
726 /// complexity is monotonically increasing.
728 /// Note that we go take special precautions to ensure that we get deterministic
729 /// results from this routine. In other words, we don't want the results of
730 /// this to depend on where the addresses of various SCEV objects happened to
733 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
734 LoopInfo *LI, DominatorTree &DT) {
735 if (Ops.size() < 2) return; // Noop
737 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
738 if (Ops.size() == 2) {
739 // This is the common case, which also happens to be trivially simple.
741 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
742 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0)
747 // Do the rough sort by complexity.
748 std::stable_sort(Ops.begin(), Ops.end(),
749 [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) {
751 CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0;
754 // Now that we are sorted by complexity, group elements of the same
755 // complexity. Note that this is, at worst, N^2, but the vector is likely to
756 // be extremely short in practice. Note that we take this approach because we
757 // do not want to depend on the addresses of the objects we are grouping.
758 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
759 const SCEV *S = Ops[i];
760 unsigned Complexity = S->getSCEVType();
762 // If there are any objects of the same complexity and same value as this
764 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
765 if (Ops[j] == S) { // Found a duplicate.
766 // Move it to immediately after i'th element.
767 std::swap(Ops[i+1], Ops[j]);
768 ++i; // no need to rescan it.
769 if (i == e-2) return; // Done!
775 // Returns the size of the SCEV S.
776 static inline int sizeOfSCEV(const SCEV *S) {
777 struct FindSCEVSize {
779 FindSCEVSize() : Size(0) {}
781 bool follow(const SCEV *S) {
783 // Keep looking at all operands of S.
786 bool isDone() const {
792 SCEVTraversal<FindSCEVSize> ST(F);
799 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
801 // Computes the Quotient and Remainder of the division of Numerator by
803 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
804 const SCEV *Denominator, const SCEV **Quotient,
805 const SCEV **Remainder) {
806 assert(Numerator && Denominator && "Uninitialized SCEV");
808 SCEVDivision D(SE, Numerator, Denominator);
810 // Check for the trivial case here to avoid having to check for it in the
812 if (Numerator == Denominator) {
818 if (Numerator->isZero()) {
824 // A simple case when N/1. The quotient is N.
825 if (Denominator->isOne()) {
826 *Quotient = Numerator;
831 // Split the Denominator when it is a product.
832 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
834 *Quotient = Numerator;
835 for (const SCEV *Op : T->operands()) {
836 divide(SE, *Quotient, Op, &Q, &R);
839 // Bail out when the Numerator is not divisible by one of the terms of
843 *Remainder = Numerator;
852 *Quotient = D.Quotient;
853 *Remainder = D.Remainder;
856 // Except in the trivial case described above, we do not know how to divide
857 // Expr by Denominator for the following functions with empty implementation.
858 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
859 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
860 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
861 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
862 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
863 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
864 void visitUnknown(const SCEVUnknown *Numerator) {}
865 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
867 void visitConstant(const SCEVConstant *Numerator) {
868 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
869 APInt NumeratorVal = Numerator->getAPInt();
870 APInt DenominatorVal = D->getAPInt();
871 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
872 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
874 if (NumeratorBW > DenominatorBW)
875 DenominatorVal = DenominatorVal.sext(NumeratorBW);
876 else if (NumeratorBW < DenominatorBW)
877 NumeratorVal = NumeratorVal.sext(DenominatorBW);
879 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
880 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
881 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
882 Quotient = SE.getConstant(QuotientVal);
883 Remainder = SE.getConstant(RemainderVal);
888 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
889 const SCEV *StartQ, *StartR, *StepQ, *StepR;
890 if (!Numerator->isAffine())
891 return cannotDivide(Numerator);
892 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
893 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
894 // Bail out if the types do not match.
895 Type *Ty = Denominator->getType();
896 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
897 Ty != StepQ->getType() || Ty != StepR->getType())
898 return cannotDivide(Numerator);
899 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
900 Numerator->getNoWrapFlags());
901 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
902 Numerator->getNoWrapFlags());
905 void visitAddExpr(const SCEVAddExpr *Numerator) {
906 SmallVector<const SCEV *, 2> Qs, Rs;
907 Type *Ty = Denominator->getType();
909 for (const SCEV *Op : Numerator->operands()) {
911 divide(SE, Op, Denominator, &Q, &R);
913 // Bail out if types do not match.
914 if (Ty != Q->getType() || Ty != R->getType())
915 return cannotDivide(Numerator);
921 if (Qs.size() == 1) {
927 Quotient = SE.getAddExpr(Qs);
928 Remainder = SE.getAddExpr(Rs);
931 void visitMulExpr(const SCEVMulExpr *Numerator) {
932 SmallVector<const SCEV *, 2> Qs;
933 Type *Ty = Denominator->getType();
935 bool FoundDenominatorTerm = false;
936 for (const SCEV *Op : Numerator->operands()) {
937 // Bail out if types do not match.
938 if (Ty != Op->getType())
939 return cannotDivide(Numerator);
941 if (FoundDenominatorTerm) {
946 // Check whether Denominator divides one of the product operands.
948 divide(SE, Op, Denominator, &Q, &R);
954 // Bail out if types do not match.
955 if (Ty != Q->getType())
956 return cannotDivide(Numerator);
958 FoundDenominatorTerm = true;
962 if (FoundDenominatorTerm) {
967 Quotient = SE.getMulExpr(Qs);
971 if (!isa<SCEVUnknown>(Denominator))
972 return cannotDivide(Numerator);
974 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
975 ValueToValueMap RewriteMap;
976 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
977 cast<SCEVConstant>(Zero)->getValue();
978 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
980 if (Remainder->isZero()) {
981 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
982 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
983 cast<SCEVConstant>(One)->getValue();
985 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
989 // Quotient is (Numerator - Remainder) divided by Denominator.
991 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
992 // This SCEV does not seem to simplify: fail the division here.
993 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
994 return cannotDivide(Numerator);
995 divide(SE, Diff, Denominator, &Q, &R);
997 return cannotDivide(Numerator);
1002 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1003 const SCEV *Denominator)
1004 : SE(S), Denominator(Denominator) {
1005 Zero = SE.getZero(Denominator->getType());
1006 One = SE.getOne(Denominator->getType());
1008 // We generally do not know how to divide Expr by Denominator. We
1009 // initialize the division to a "cannot divide" state to simplify the rest
1011 cannotDivide(Numerator);
1014 // Convenience function for giving up on the division. We set the quotient to
1015 // be equal to zero and the remainder to be equal to the numerator.
1016 void cannotDivide(const SCEV *Numerator) {
1018 Remainder = Numerator;
1021 ScalarEvolution &SE;
1022 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1027 //===----------------------------------------------------------------------===//
1028 // Simple SCEV method implementations
1029 //===----------------------------------------------------------------------===//
1031 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1032 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1033 ScalarEvolution &SE,
1035 // Handle the simplest case efficiently.
1037 return SE.getTruncateOrZeroExtend(It, ResultTy);
1039 // We are using the following formula for BC(It, K):
1041 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1043 // Suppose, W is the bitwidth of the return value. We must be prepared for
1044 // overflow. Hence, we must assure that the result of our computation is
1045 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1046 // safe in modular arithmetic.
1048 // However, this code doesn't use exactly that formula; the formula it uses
1049 // is something like the following, where T is the number of factors of 2 in
1050 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1053 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1055 // This formula is trivially equivalent to the previous formula. However,
1056 // this formula can be implemented much more efficiently. The trick is that
1057 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1058 // arithmetic. To do exact division in modular arithmetic, all we have
1059 // to do is multiply by the inverse. Therefore, this step can be done at
1062 // The next issue is how to safely do the division by 2^T. The way this
1063 // is done is by doing the multiplication step at a width of at least W + T
1064 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1065 // when we perform the division by 2^T (which is equivalent to a right shift
1066 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1067 // truncated out after the division by 2^T.
1069 // In comparison to just directly using the first formula, this technique
1070 // is much more efficient; using the first formula requires W * K bits,
1071 // but this formula less than W + K bits. Also, the first formula requires
1072 // a division step, whereas this formula only requires multiplies and shifts.
1074 // It doesn't matter whether the subtraction step is done in the calculation
1075 // width or the input iteration count's width; if the subtraction overflows,
1076 // the result must be zero anyway. We prefer here to do it in the width of
1077 // the induction variable because it helps a lot for certain cases; CodeGen
1078 // isn't smart enough to ignore the overflow, which leads to much less
1079 // efficient code if the width of the subtraction is wider than the native
1082 // (It's possible to not widen at all by pulling out factors of 2 before
1083 // the multiplication; for example, K=2 can be calculated as
1084 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1085 // extra arithmetic, so it's not an obvious win, and it gets
1086 // much more complicated for K > 3.)
1088 // Protection from insane SCEVs; this bound is conservative,
1089 // but it probably doesn't matter.
1091 return SE.getCouldNotCompute();
1093 unsigned W = SE.getTypeSizeInBits(ResultTy);
1095 // Calculate K! / 2^T and T; we divide out the factors of two before
1096 // multiplying for calculating K! / 2^T to avoid overflow.
1097 // Other overflow doesn't matter because we only care about the bottom
1098 // W bits of the result.
1099 APInt OddFactorial(W, 1);
1101 for (unsigned i = 3; i <= K; ++i) {
1103 unsigned TwoFactors = Mult.countTrailingZeros();
1105 Mult.lshrInPlace(TwoFactors);
1106 OddFactorial *= Mult;
1109 // We need at least W + T bits for the multiplication step
1110 unsigned CalculationBits = W + T;
1112 // Calculate 2^T, at width T+W.
1113 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1115 // Calculate the multiplicative inverse of K! / 2^T;
1116 // this multiplication factor will perform the exact division by
1118 APInt Mod = APInt::getSignedMinValue(W+1);
1119 APInt MultiplyFactor = OddFactorial.zext(W+1);
1120 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1121 MultiplyFactor = MultiplyFactor.trunc(W);
1123 // Calculate the product, at width T+W
1124 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1126 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1127 for (unsigned i = 1; i != K; ++i) {
1128 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1129 Dividend = SE.getMulExpr(Dividend,
1130 SE.getTruncateOrZeroExtend(S, CalculationTy));
1134 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1136 // Truncate the result, and divide by K! / 2^T.
1138 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1139 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1142 /// Return the value of this chain of recurrences at the specified iteration
1143 /// number. We can evaluate this recurrence by multiplying each element in the
1144 /// chain by the binomial coefficient corresponding to it. In other words, we
1145 /// can evaluate {A,+,B,+,C,+,D} as:
1147 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1149 /// where BC(It, k) stands for binomial coefficient.
1151 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1152 ScalarEvolution &SE) const {
1153 const SCEV *Result = getStart();
1154 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1155 // The computation is correct in the face of overflow provided that the
1156 // multiplication is performed _after_ the evaluation of the binomial
1158 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1159 if (isa<SCEVCouldNotCompute>(Coeff))
1162 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1167 //===----------------------------------------------------------------------===//
1168 // SCEV Expression folder implementations
1169 //===----------------------------------------------------------------------===//
1171 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1173 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1174 "This is not a truncating conversion!");
1175 assert(isSCEVable(Ty) &&
1176 "This is not a conversion to a SCEVable type!");
1177 Ty = getEffectiveSCEVType(Ty);
1179 FoldingSetNodeID ID;
1180 ID.AddInteger(scTruncate);
1184 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1186 // Fold if the operand is constant.
1187 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1189 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1191 // trunc(trunc(x)) --> trunc(x)
1192 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1193 return getTruncateExpr(ST->getOperand(), Ty);
1195 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1196 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1197 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1199 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1200 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1201 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1203 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1204 // eliminate all the truncates, or we replace other casts with truncates.
1205 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1206 SmallVector<const SCEV *, 4> Operands;
1207 bool hasTrunc = false;
1208 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1209 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1210 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1211 hasTrunc = isa<SCEVTruncateExpr>(S);
1212 Operands.push_back(S);
1215 return getAddExpr(Operands);
1216 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1219 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1220 // eliminate all the truncates, or we replace other casts with truncates.
1221 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1222 SmallVector<const SCEV *, 4> Operands;
1223 bool hasTrunc = false;
1224 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1225 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1226 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1227 hasTrunc = isa<SCEVTruncateExpr>(S);
1228 Operands.push_back(S);
1231 return getMulExpr(Operands);
1232 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1235 // If the input value is a chrec scev, truncate the chrec's operands.
1236 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1237 SmallVector<const SCEV *, 4> Operands;
1238 for (const SCEV *Op : AddRec->operands())
1239 Operands.push_back(getTruncateExpr(Op, Ty));
1240 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1243 // The cast wasn't folded; create an explicit cast node. We can reuse
1244 // the existing insert position since if we get here, we won't have
1245 // made any changes which would invalidate it.
1246 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1248 UniqueSCEVs.InsertNode(S, IP);
1252 // Get the limit of a recurrence such that incrementing by Step cannot cause
1253 // signed overflow as long as the value of the recurrence within the
1254 // loop does not exceed this limit before incrementing.
1255 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1259 if (SE->isKnownPositive(Step)) {
1260 *Pred = ICmpInst::ICMP_SLT;
1261 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1262 SE->getSignedRange(Step).getSignedMax());
1264 if (SE->isKnownNegative(Step)) {
1265 *Pred = ICmpInst::ICMP_SGT;
1266 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1267 SE->getSignedRange(Step).getSignedMin());
1272 // Get the limit of a recurrence such that incrementing by Step cannot cause
1273 // unsigned overflow as long as the value of the recurrence within the loop does
1274 // not exceed this limit before incrementing.
1275 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1276 ICmpInst::Predicate *Pred,
1277 ScalarEvolution *SE) {
1278 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1279 *Pred = ICmpInst::ICMP_ULT;
1281 return SE->getConstant(APInt::getMinValue(BitWidth) -
1282 SE->getUnsignedRange(Step).getUnsignedMax());
1287 struct ExtendOpTraitsBase {
1288 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1289 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1292 // Used to make code generic over signed and unsigned overflow.
1293 template <typename ExtendOp> struct ExtendOpTraits {
1296 // static const SCEV::NoWrapFlags WrapType;
1298 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1300 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1301 // ICmpInst::Predicate *Pred,
1302 // ScalarEvolution *SE);
1306 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1307 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1309 static const GetExtendExprTy GetExtendExpr;
1311 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1312 ICmpInst::Predicate *Pred,
1313 ScalarEvolution *SE) {
1314 return getSignedOverflowLimitForStep(Step, Pred, SE);
1318 const ExtendOpTraitsBase::GetExtendExprTy
1319 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1320 &ScalarEvolution::getSignExtendExprCached;
1323 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1324 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1326 static const GetExtendExprTy GetExtendExpr;
1328 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1329 ICmpInst::Predicate *Pred,
1330 ScalarEvolution *SE) {
1331 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1335 const ExtendOpTraitsBase::GetExtendExprTy
1336 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1337 &ScalarEvolution::getZeroExtendExprCached;
1340 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1341 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1342 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1343 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1344 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1345 // expression "Step + sext/zext(PreIncAR)" is congruent with
1346 // "sext/zext(PostIncAR)"
1347 template <typename ExtendOpTy>
1348 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1349 ScalarEvolution *SE,
1350 ScalarEvolution::ExtendCacheTy &Cache) {
1351 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1352 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
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 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1377 // 1. NSW/NUW flags on the step increment.
1378 auto PreStartFlags =
1379 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1380 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1381 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1382 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1384 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1385 // "S+X does not sign/unsign-overflow".
1388 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1389 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1390 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1393 // 2. Direct overflow check on the step operation's expression.
1394 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1395 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1396 const SCEV *OperandExtendedStart =
1397 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1398 (SE->*GetExtendExpr)(Step, WideTy, Cache));
1399 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1400 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1401 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1402 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1403 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1404 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1409 // 3. Loop precondition.
1410 ICmpInst::Predicate Pred;
1411 const SCEV *OverflowLimit =
1412 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1414 if (OverflowLimit &&
1415 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1421 // Get the normalized zero or sign extended expression for this AddRec's Start.
1422 template <typename ExtendOpTy>
1423 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1424 ScalarEvolution *SE,
1425 ScalarEvolution::ExtendCacheTy &Cache) {
1426 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1428 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1430 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1432 return SE->getAddExpr(
1433 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1434 (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1437 // Try to prove away overflow by looking at "nearby" add recurrences. A
1438 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1439 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1443 // {S,+,X} == {S-T,+,X} + T
1444 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1446 // If ({S-T,+,X} + T) does not overflow ... (1)
1448 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1450 // If {S-T,+,X} does not overflow ... (2)
1452 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1453 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1455 // If (S-T)+T does not overflow ... (3)
1457 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1458 // == {Ext(S),+,Ext(X)} == LHS
1460 // Thus, if (1), (2) and (3) are true for some T, then
1461 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1463 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1464 // does not overflow" restricted to the 0th iteration. Therefore we only need
1465 // to check for (1) and (2).
1467 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1468 // is `Delta` (defined below).
1470 template <typename ExtendOpTy>
1471 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1474 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1476 // We restrict `Start` to a constant to prevent SCEV from spending too much
1477 // time here. It is correct (but more expensive) to continue with a
1478 // non-constant `Start` and do a general SCEV subtraction to compute
1479 // `PreStart` below.
1481 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1485 APInt StartAI = StartC->getAPInt();
1487 for (unsigned Delta : {-2, -1, 1, 2}) {
1488 const SCEV *PreStart = getConstant(StartAI - Delta);
1490 FoldingSetNodeID ID;
1491 ID.AddInteger(scAddRecExpr);
1492 ID.AddPointer(PreStart);
1493 ID.AddPointer(Step);
1497 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1499 // Give up if we don't already have the add recurrence we need because
1500 // actually constructing an add recurrence is relatively expensive.
1501 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1502 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1503 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1504 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1505 DeltaS, &Pred, this);
1506 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1514 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1515 // Use the local cache to prevent exponential behavior of
1516 // getZeroExtendExprImpl.
1517 ExtendCacheTy Cache;
1518 return getZeroExtendExprCached(Op, Ty, Cache);
1521 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1522 /// related entry in the \p Cache, call getZeroExtendExprImpl and save
1523 /// the result in the \p Cache.
1524 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1525 ExtendCacheTy &Cache) {
1526 auto It = Cache.find({Op, Ty});
1527 if (It != Cache.end())
1529 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1530 auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1531 assert(InsertResult.second && "Expect the key was not in the cache");
1536 /// The real implementation of getZeroExtendExpr.
1537 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1538 ExtendCacheTy &Cache) {
1539 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1540 "This is not an extending conversion!");
1541 assert(isSCEVable(Ty) &&
1542 "This is not a conversion to a SCEVable type!");
1543 Ty = getEffectiveSCEVType(Ty);
1545 // Fold if the operand is constant.
1546 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1548 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1550 // zext(zext(x)) --> zext(x)
1551 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1552 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1554 // Before doing any expensive analysis, check to see if we've already
1555 // computed a SCEV for this Op and Ty.
1556 FoldingSetNodeID ID;
1557 ID.AddInteger(scZeroExtend);
1561 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1563 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1564 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1565 // It's possible the bits taken off by the truncate were all zero bits. If
1566 // so, we should be able to simplify this further.
1567 const SCEV *X = ST->getOperand();
1568 ConstantRange CR = getUnsignedRange(X);
1569 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1570 unsigned NewBits = getTypeSizeInBits(Ty);
1571 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1572 CR.zextOrTrunc(NewBits)))
1573 return getTruncateOrZeroExtend(X, Ty);
1576 // If the input value is a chrec scev, and we can prove that the value
1577 // did not overflow the old, smaller, value, we can zero extend all of the
1578 // operands (often constants). This allows analysis of something like
1579 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1580 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1581 if (AR->isAffine()) {
1582 const SCEV *Start = AR->getStart();
1583 const SCEV *Step = AR->getStepRecurrence(*this);
1584 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1585 const Loop *L = AR->getLoop();
1587 if (!AR->hasNoUnsignedWrap()) {
1588 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1592 // If we have special knowledge that this addrec won't overflow,
1593 // we don't need to do any further analysis.
1594 if (AR->hasNoUnsignedWrap())
1595 return getAddRecExpr(
1596 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1597 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1599 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1600 // Note that this serves two purposes: It filters out loops that are
1601 // simply not analyzable, and it covers the case where this code is
1602 // being called from within backedge-taken count analysis, such that
1603 // attempting to ask for the backedge-taken count would likely result
1604 // in infinite recursion. In the later case, the analysis code will
1605 // cope with a conservative value, and it will take care to purge
1606 // that value once it has finished.
1607 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1608 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1609 // Manually compute the final value for AR, checking for
1612 // Check whether the backedge-taken count can be losslessly casted to
1613 // the addrec's type. The count is always unsigned.
1614 const SCEV *CastedMaxBECount =
1615 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1616 const SCEV *RecastedMaxBECount =
1617 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1618 if (MaxBECount == RecastedMaxBECount) {
1619 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1620 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1621 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1623 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1624 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1625 const SCEV *WideMaxBECount =
1626 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1627 const SCEV *OperandExtendedAdd = getAddExpr(
1628 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1629 Step, WideTy, Cache)));
1630 if (ZAdd == OperandExtendedAdd) {
1631 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1632 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1633 // Return the expression with the addrec on the outside.
1634 return getAddRecExpr(
1635 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1636 getZeroExtendExprCached(Step, Ty, Cache), L,
1637 AR->getNoWrapFlags());
1639 // Similar to above, only this time treat the step value as signed.
1640 // This covers loops that count down.
1641 OperandExtendedAdd =
1642 getAddExpr(WideStart,
1643 getMulExpr(WideMaxBECount,
1644 getSignExtendExpr(Step, WideTy)));
1645 if (ZAdd == OperandExtendedAdd) {
1646 // Cache knowledge of AR NW, which is propagated to this AddRec.
1647 // Negative step causes unsigned wrap, but it still can't self-wrap.
1648 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1649 // Return the expression with the addrec on the outside.
1650 return getAddRecExpr(
1651 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1652 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1657 // Normally, in the cases we can prove no-overflow via a
1658 // backedge guarding condition, we can also compute a backedge
1659 // taken count for the loop. The exceptions are assumptions and
1660 // guards present in the loop -- SCEV is not great at exploiting
1661 // these to compute max backedge taken counts, but can still use
1662 // these to prove lack of overflow. Use this fact to avoid
1663 // doing extra work that may not pay off.
1664 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1665 !AC.assumptions().empty()) {
1666 // If the backedge is guarded by a comparison with the pre-inc
1667 // value the addrec is safe. Also, if the entry is guarded by
1668 // a comparison with the start value and the backedge is
1669 // guarded by a comparison with the post-inc value, the addrec
1671 if (isKnownPositive(Step)) {
1672 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1673 getUnsignedRange(Step).getUnsignedMax());
1674 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1675 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1676 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1677 AR->getPostIncExpr(*this), N))) {
1678 // Cache knowledge of AR NUW, which is propagated to this
1680 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1681 // Return the expression with the addrec on the outside.
1682 return getAddRecExpr(
1683 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1684 getZeroExtendExprCached(Step, Ty, Cache), L,
1685 AR->getNoWrapFlags());
1687 } else if (isKnownNegative(Step)) {
1688 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1689 getSignedRange(Step).getSignedMin());
1690 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1691 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1692 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1693 AR->getPostIncExpr(*this), N))) {
1694 // Cache knowledge of AR NW, which is propagated to this
1695 // AddRec. Negative step causes unsigned wrap, but it
1696 // still can't self-wrap.
1697 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1698 // Return the expression with the addrec on the outside.
1699 return getAddRecExpr(
1700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1701 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1706 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1707 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1708 return getAddRecExpr(
1709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1710 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1714 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1715 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1716 if (SA->hasNoUnsignedWrap()) {
1717 // If the addition does not unsign overflow then we can, by definition,
1718 // commute the zero extension with the addition operation.
1719 SmallVector<const SCEV *, 4> Ops;
1720 for (const auto *Op : SA->operands())
1721 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1722 return getAddExpr(Ops, SCEV::FlagNUW);
1726 // The cast wasn't folded; create an explicit cast node.
1727 // Recompute the insert position, as it may have been invalidated.
1728 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1729 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1731 UniqueSCEVs.InsertNode(S, IP);
1735 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1736 // Use the local cache to prevent exponential behavior of
1737 // getSignExtendExprImpl.
1738 ExtendCacheTy Cache;
1739 return getSignExtendExprCached(Op, Ty, Cache);
1742 /// Query \p Cache before calling getSignExtendExprImpl. If there is no
1743 /// related entry in the \p Cache, call getSignExtendExprImpl and save
1744 /// the result in the \p Cache.
1745 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1746 ExtendCacheTy &Cache) {
1747 auto It = Cache.find({Op, Ty});
1748 if (It != Cache.end())
1750 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1751 auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1752 assert(InsertResult.second && "Expect the key was not in the cache");
1757 /// The real implementation of getSignExtendExpr.
1758 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1759 ExtendCacheTy &Cache) {
1760 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1761 "This is not an extending conversion!");
1762 assert(isSCEVable(Ty) &&
1763 "This is not a conversion to a SCEVable type!");
1764 Ty = getEffectiveSCEVType(Ty);
1766 // Fold if the operand is constant.
1767 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1769 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1771 // sext(sext(x)) --> sext(x)
1772 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1773 return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1775 // sext(zext(x)) --> zext(x)
1776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1777 return getZeroExtendExpr(SZ->getOperand(), Ty);
1779 // Before doing any expensive analysis, check to see if we've already
1780 // computed a SCEV for this Op and Ty.
1781 FoldingSetNodeID ID;
1782 ID.AddInteger(scSignExtend);
1786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1788 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1789 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1790 // It's possible the bits taken off by the truncate were all sign bits. If
1791 // so, we should be able to simplify this further.
1792 const SCEV *X = ST->getOperand();
1793 ConstantRange CR = getSignedRange(X);
1794 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1795 unsigned NewBits = getTypeSizeInBits(Ty);
1796 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1797 CR.sextOrTrunc(NewBits)))
1798 return getTruncateOrSignExtend(X, Ty);
1801 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1802 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1803 if (SA->getNumOperands() == 2) {
1804 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1805 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1807 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1808 const APInt &C1 = SC1->getAPInt();
1809 const APInt &C2 = SC2->getAPInt();
1810 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1811 C2.ugt(C1) && C2.isPowerOf2())
1812 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1813 getSignExtendExprCached(SMul, Ty, Cache));
1818 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1819 if (SA->hasNoSignedWrap()) {
1820 // If the addition does not sign overflow then we can, by definition,
1821 // commute the sign extension with the addition operation.
1822 SmallVector<const SCEV *, 4> Ops;
1823 for (const auto *Op : SA->operands())
1824 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1825 return getAddExpr(Ops, SCEV::FlagNSW);
1828 // If the input value is a chrec scev, and we can prove that the value
1829 // did not overflow the old, smaller, value, we can sign extend all of the
1830 // operands (often constants). This allows analysis of something like
1831 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1832 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1833 if (AR->isAffine()) {
1834 const SCEV *Start = AR->getStart();
1835 const SCEV *Step = AR->getStepRecurrence(*this);
1836 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1837 const Loop *L = AR->getLoop();
1839 if (!AR->hasNoSignedWrap()) {
1840 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1844 // If we have special knowledge that this addrec won't overflow,
1845 // we don't need to do any further analysis.
1846 if (AR->hasNoSignedWrap())
1847 return getAddRecExpr(
1848 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1849 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1851 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1852 // Note that this serves two purposes: It filters out loops that are
1853 // simply not analyzable, and it covers the case where this code is
1854 // being called from within backedge-taken count analysis, such that
1855 // attempting to ask for the backedge-taken count would likely result
1856 // in infinite recursion. In the later case, the analysis code will
1857 // cope with a conservative value, and it will take care to purge
1858 // that value once it has finished.
1859 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1860 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1861 // Manually compute the final value for AR, checking for
1864 // Check whether the backedge-taken count can be losslessly casted to
1865 // the addrec's type. The count is always unsigned.
1866 const SCEV *CastedMaxBECount =
1867 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1868 const SCEV *RecastedMaxBECount =
1869 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1870 if (MaxBECount == RecastedMaxBECount) {
1871 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1872 // Check whether Start+Step*MaxBECount has no signed overflow.
1873 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1875 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1876 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1877 const SCEV *WideMaxBECount =
1878 getZeroExtendExpr(CastedMaxBECount, WideTy);
1879 const SCEV *OperandExtendedAdd = getAddExpr(
1880 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1881 Step, WideTy, Cache)));
1882 if (SAdd == OperandExtendedAdd) {
1883 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1884 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1885 // Return the expression with the addrec on the outside.
1886 return getAddRecExpr(
1887 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1888 getSignExtendExprCached(Step, Ty, Cache), L,
1889 AR->getNoWrapFlags());
1891 // Similar to above, only this time treat the step value as unsigned.
1892 // This covers loops that count up with an unsigned step.
1893 OperandExtendedAdd =
1894 getAddExpr(WideStart,
1895 getMulExpr(WideMaxBECount,
1896 getZeroExtendExpr(Step, WideTy)));
1897 if (SAdd == OperandExtendedAdd) {
1898 // If AR wraps around then
1900 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1901 // => SAdd != OperandExtendedAdd
1903 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1904 // (SAdd == OperandExtendedAdd => AR is NW)
1906 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1908 // Return the expression with the addrec on the outside.
1909 return getAddRecExpr(
1910 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1911 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1916 // Normally, in the cases we can prove no-overflow via a
1917 // backedge guarding condition, we can also compute a backedge
1918 // taken count for the loop. The exceptions are assumptions and
1919 // guards present in the loop -- SCEV is not great at exploiting
1920 // these to compute max backedge taken counts, but can still use
1921 // these to prove lack of overflow. Use this fact to avoid
1922 // doing extra work that may not pay off.
1924 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1925 !AC.assumptions().empty()) {
1926 // If the backedge is guarded by a comparison with the pre-inc
1927 // value the addrec is safe. Also, if the entry is guarded by
1928 // a comparison with the start value and the backedge is
1929 // guarded by a comparison with the post-inc value, the addrec
1931 ICmpInst::Predicate Pred;
1932 const SCEV *OverflowLimit =
1933 getSignedOverflowLimitForStep(Step, &Pred, this);
1934 if (OverflowLimit &&
1935 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1936 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1937 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1939 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1940 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1941 return getAddRecExpr(
1942 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1943 getSignExtendExprCached(Step, Ty, Cache), L,
1944 AR->getNoWrapFlags());
1948 // If Start and Step are constants, check if we can apply this
1950 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1951 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1952 auto *SC2 = dyn_cast<SCEVConstant>(Step);
1954 const APInt &C1 = SC1->getAPInt();
1955 const APInt &C2 = SC2->getAPInt();
1956 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1958 Start = getSignExtendExprCached(Start, Ty, Cache);
1959 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1960 AR->getNoWrapFlags());
1961 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1965 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1966 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1967 return getAddRecExpr(
1968 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1969 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1973 // If the input value is provably positive and we could not simplify
1974 // away the sext build a zext instead.
1975 if (isKnownNonNegative(Op))
1976 return getZeroExtendExpr(Op, Ty);
1978 // The cast wasn't folded; create an explicit cast node.
1979 // Recompute the insert position, as it may have been invalidated.
1980 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1981 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1983 UniqueSCEVs.InsertNode(S, IP);
1987 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1988 /// unspecified bits out to the given type.
1990 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1993 "This is not an extending conversion!");
1994 assert(isSCEVable(Ty) &&
1995 "This is not a conversion to a SCEVable type!");
1996 Ty = getEffectiveSCEVType(Ty);
1998 // Sign-extend negative constants.
1999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2000 if (SC->getAPInt().isNegative())
2001 return getSignExtendExpr(Op, Ty);
2003 // Peel off a truncate cast.
2004 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2005 const SCEV *NewOp = T->getOperand();
2006 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2007 return getAnyExtendExpr(NewOp, Ty);
2008 return getTruncateOrNoop(NewOp, Ty);
2011 // Next try a zext cast. If the cast is folded, use it.
2012 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2013 if (!isa<SCEVZeroExtendExpr>(ZExt))
2016 // Next try a sext cast. If the cast is folded, use it.
2017 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2018 if (!isa<SCEVSignExtendExpr>(SExt))
2021 // Force the cast to be folded into the operands of an addrec.
2022 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2023 SmallVector<const SCEV *, 4> Ops;
2024 for (const SCEV *Op : AR->operands())
2025 Ops.push_back(getAnyExtendExpr(Op, Ty));
2026 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2029 // If the expression is obviously signed, use the sext cast value.
2030 if (isa<SCEVSMaxExpr>(Op))
2033 // Absent any other information, use the zext cast value.
2037 /// Process the given Ops list, which is a list of operands to be added under
2038 /// the given scale, update the given map. This is a helper function for
2039 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2040 /// that would form an add expression like this:
2042 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2044 /// where A and B are constants, update the map with these values:
2046 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2048 /// and add 13 + A*B*29 to AccumulatedConstant.
2049 /// This will allow getAddRecExpr to produce this:
2051 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2053 /// This form often exposes folding opportunities that are hidden in
2054 /// the original operand list.
2056 /// Return true iff it appears that any interesting folding opportunities
2057 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2058 /// the common case where no interesting opportunities are present, and
2059 /// is also used as a check to avoid infinite recursion.
2062 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2063 SmallVectorImpl<const SCEV *> &NewOps,
2064 APInt &AccumulatedConstant,
2065 const SCEV *const *Ops, size_t NumOperands,
2067 ScalarEvolution &SE) {
2068 bool Interesting = false;
2070 // Iterate over the add operands. They are sorted, with constants first.
2072 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2074 // Pull a buried constant out to the outside.
2075 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2077 AccumulatedConstant += Scale * C->getAPInt();
2080 // Next comes everything else. We're especially interested in multiplies
2081 // here, but they're in the middle, so just visit the rest with one loop.
2082 for (; i != NumOperands; ++i) {
2083 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2084 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2086 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2087 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2088 // A multiplication of a constant with another add; recurse.
2089 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2091 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2092 Add->op_begin(), Add->getNumOperands(),
2095 // A multiplication of a constant with some other value. Update
2097 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2098 const SCEV *Key = SE.getMulExpr(MulOps);
2099 auto Pair = M.insert({Key, NewScale});
2101 NewOps.push_back(Pair.first->first);
2103 Pair.first->second += NewScale;
2104 // The map already had an entry for this value, which may indicate
2105 // a folding opportunity.
2110 // An ordinary operand. Update the map.
2111 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2112 M.insert({Ops[i], Scale});
2114 NewOps.push_back(Pair.first->first);
2116 Pair.first->second += Scale;
2117 // The map already had an entry for this value, which may indicate
2118 // a folding opportunity.
2127 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2128 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2129 // can't-overflow flags for the operation if possible.
2130 static SCEV::NoWrapFlags
2131 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2132 const SmallVectorImpl<const SCEV *> &Ops,
2133 SCEV::NoWrapFlags Flags) {
2134 using namespace std::placeholders;
2135 typedef OverflowingBinaryOperator OBO;
2138 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2140 assert(CanAnalyze && "don't call from other places!");
2142 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2143 SCEV::NoWrapFlags SignOrUnsignWrap =
2144 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2146 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2147 auto IsKnownNonNegative = [&](const SCEV *S) {
2148 return SE->isKnownNonNegative(S);
2151 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2153 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2155 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2157 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2158 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2160 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2161 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2163 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2164 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2165 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2166 Instruction::Add, C, OBO::NoSignedWrap);
2167 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2168 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2170 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2171 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2172 Instruction::Add, C, OBO::NoUnsignedWrap);
2173 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2174 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2181 /// Get a canonical add expression, or something simpler if possible.
2182 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2183 SCEV::NoWrapFlags Flags,
2185 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2186 "only nuw or nsw allowed");
2187 assert(!Ops.empty() && "Cannot get empty add!");
2188 if (Ops.size() == 1) return Ops[0];
2190 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2191 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2192 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2193 "SCEVAddExpr operand types don't match!");
2196 // Sort by complexity, this groups all similar expression types together.
2197 GroupByComplexity(Ops, &LI, DT);
2199 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2201 // If there are any constants, fold them together.
2203 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2205 assert(Idx < Ops.size());
2206 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2207 // We found two constants, fold them together!
2208 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2209 if (Ops.size() == 2) return Ops[0];
2210 Ops.erase(Ops.begin()+1); // Erase the folded element
2211 LHSC = cast<SCEVConstant>(Ops[0]);
2214 // If we are left with a constant zero being added, strip it off.
2215 if (LHSC->getValue()->isZero()) {
2216 Ops.erase(Ops.begin());
2220 if (Ops.size() == 1) return Ops[0];
2223 // Limit recursion calls depth
2224 if (Depth > MaxAddExprDepth)
2225 return getOrCreateAddExpr(Ops, Flags);
2227 // Okay, check to see if the same value occurs in the operand list more than
2228 // once. If so, merge them together into an multiply expression. Since we
2229 // sorted the list, these values are required to be adjacent.
2230 Type *Ty = Ops[0]->getType();
2231 bool FoundMatch = false;
2232 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2233 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2234 // Scan ahead to count how many equal operands there are.
2236 while (i+Count != e && Ops[i+Count] == Ops[i])
2238 // Merge the values into a multiply.
2239 const SCEV *Scale = getConstant(Ty, Count);
2240 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2241 if (Ops.size() == Count)
2244 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2245 --i; e -= Count - 1;
2249 return getAddExpr(Ops, Flags);
2251 // Check for truncates. If all the operands are truncated from the same
2252 // type, see if factoring out the truncate would permit the result to be
2253 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2254 // if the contents of the resulting outer trunc fold to something simple.
2255 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2256 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2257 Type *DstType = Trunc->getType();
2258 Type *SrcType = Trunc->getOperand()->getType();
2259 SmallVector<const SCEV *, 8> LargeOps;
2261 // Check all the operands to see if they can be represented in the
2262 // source type of the truncate.
2263 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2264 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2265 if (T->getOperand()->getType() != SrcType) {
2269 LargeOps.push_back(T->getOperand());
2270 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2271 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2272 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2273 SmallVector<const SCEV *, 8> LargeMulOps;
2274 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2275 if (const SCEVTruncateExpr *T =
2276 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2277 if (T->getOperand()->getType() != SrcType) {
2281 LargeMulOps.push_back(T->getOperand());
2282 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2283 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2290 LargeOps.push_back(getMulExpr(LargeMulOps));
2297 // Evaluate the expression in the larger type.
2298 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2299 // If it folds to something simple, use it. Otherwise, don't.
2300 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2301 return getTruncateExpr(Fold, DstType);
2305 // Skip past any other cast SCEVs.
2306 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2309 // If there are add operands they would be next.
2310 if (Idx < Ops.size()) {
2311 bool DeletedAdd = false;
2312 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2313 if (Ops.size() > AddOpsInlineThreshold ||
2314 Add->getNumOperands() > AddOpsInlineThreshold)
2316 // If we have an add, expand the add operands onto the end of the operands
2318 Ops.erase(Ops.begin()+Idx);
2319 Ops.append(Add->op_begin(), Add->op_end());
2323 // If we deleted at least one add, we added operands to the end of the list,
2324 // and they are not necessarily sorted. Recurse to resort and resimplify
2325 // any operands we just acquired.
2327 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2330 // Skip over the add expression until we get to a multiply.
2331 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2334 // Check to see if there are any folding opportunities present with
2335 // operands multiplied by constant values.
2336 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2337 uint64_t BitWidth = getTypeSizeInBits(Ty);
2338 DenseMap<const SCEV *, APInt> M;
2339 SmallVector<const SCEV *, 8> NewOps;
2340 APInt AccumulatedConstant(BitWidth, 0);
2341 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2342 Ops.data(), Ops.size(),
2343 APInt(BitWidth, 1), *this)) {
2344 struct APIntCompare {
2345 bool operator()(const APInt &LHS, const APInt &RHS) const {
2346 return LHS.ult(RHS);
2350 // Some interesting folding opportunity is present, so its worthwhile to
2351 // re-generate the operands list. Group the operands by constant scale,
2352 // to avoid multiplying by the same constant scale multiple times.
2353 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2354 for (const SCEV *NewOp : NewOps)
2355 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2356 // Re-generate the operands list.
2358 if (AccumulatedConstant != 0)
2359 Ops.push_back(getConstant(AccumulatedConstant));
2360 for (auto &MulOp : MulOpLists)
2361 if (MulOp.first != 0)
2362 Ops.push_back(getMulExpr(
2363 getConstant(MulOp.first),
2364 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2367 if (Ops.size() == 1)
2369 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2373 // If we are adding something to a multiply expression, make sure the
2374 // something is not already an operand of the multiply. If so, merge it into
2376 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2377 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2378 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2379 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2380 if (isa<SCEVConstant>(MulOpSCEV))
2382 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2383 if (MulOpSCEV == Ops[AddOp]) {
2384 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2385 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2386 if (Mul->getNumOperands() != 2) {
2387 // If the multiply has more than two operands, we must get the
2389 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2390 Mul->op_begin()+MulOp);
2391 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2392 InnerMul = getMulExpr(MulOps);
2394 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2395 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2396 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2397 if (Ops.size() == 2) return OuterMul;
2399 Ops.erase(Ops.begin()+AddOp);
2400 Ops.erase(Ops.begin()+Idx-1);
2402 Ops.erase(Ops.begin()+Idx);
2403 Ops.erase(Ops.begin()+AddOp-1);
2405 Ops.push_back(OuterMul);
2406 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2409 // Check this multiply against other multiplies being added together.
2410 for (unsigned OtherMulIdx = Idx+1;
2411 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2413 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2414 // If MulOp occurs in OtherMul, we can fold the two multiplies
2416 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2417 OMulOp != e; ++OMulOp)
2418 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2419 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2420 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2421 if (Mul->getNumOperands() != 2) {
2422 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2423 Mul->op_begin()+MulOp);
2424 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2425 InnerMul1 = getMulExpr(MulOps);
2427 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2428 if (OtherMul->getNumOperands() != 2) {
2429 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2430 OtherMul->op_begin()+OMulOp);
2431 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2432 InnerMul2 = getMulExpr(MulOps);
2434 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2435 const SCEV *InnerMulSum =
2436 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2437 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2438 if (Ops.size() == 2) return OuterMul;
2439 Ops.erase(Ops.begin()+Idx);
2440 Ops.erase(Ops.begin()+OtherMulIdx-1);
2441 Ops.push_back(OuterMul);
2442 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2448 // If there are any add recurrences in the operands list, see if any other
2449 // added values are loop invariant. If so, we can fold them into the
2451 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2454 // Scan over all recurrences, trying to fold loop invariants into them.
2455 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2456 // Scan all of the other operands to this add and add them to the vector if
2457 // they are loop invariant w.r.t. the recurrence.
2458 SmallVector<const SCEV *, 8> LIOps;
2459 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2460 const Loop *AddRecLoop = AddRec->getLoop();
2461 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2462 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2463 LIOps.push_back(Ops[i]);
2464 Ops.erase(Ops.begin()+i);
2468 // If we found some loop invariants, fold them into the recurrence.
2469 if (!LIOps.empty()) {
2470 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2471 LIOps.push_back(AddRec->getStart());
2473 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2475 // This follows from the fact that the no-wrap flags on the outer add
2476 // expression are applicable on the 0th iteration, when the add recurrence
2477 // will be equal to its start value.
2478 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2480 // Build the new addrec. Propagate the NUW and NSW flags if both the
2481 // outer add and the inner addrec are guaranteed to have no overflow.
2482 // Always propagate NW.
2483 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2484 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2486 // If all of the other operands were loop invariant, we are done.
2487 if (Ops.size() == 1) return NewRec;
2489 // Otherwise, add the folded AddRec by the non-invariant parts.
2490 for (unsigned i = 0;; ++i)
2491 if (Ops[i] == AddRec) {
2495 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2498 // Okay, if there weren't any loop invariants to be folded, check to see if
2499 // there are multiple AddRec's with the same loop induction variable being
2500 // added together. If so, we can fold them.
2501 for (unsigned OtherIdx = Idx+1;
2502 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2504 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2505 // so that the 1st found AddRecExpr is dominated by all others.
2506 assert(DT.dominates(
2507 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2508 AddRec->getLoop()->getHeader()) &&
2509 "AddRecExprs are not sorted in reverse dominance order?");
2510 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2511 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2512 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2514 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2516 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2517 if (OtherAddRec->getLoop() == AddRecLoop) {
2518 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2520 if (i >= AddRecOps.size()) {
2521 AddRecOps.append(OtherAddRec->op_begin()+i,
2522 OtherAddRec->op_end());
2525 SmallVector<const SCEV *, 2> TwoOps = {
2526 AddRecOps[i], OtherAddRec->getOperand(i)};
2527 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2529 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2531 // Step size has changed, so we cannot guarantee no self-wraparound.
2532 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2533 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2537 // Otherwise couldn't fold anything into this recurrence. Move onto the
2541 // Okay, it looks like we really DO need an add expr. Check to see if we
2542 // already have one, otherwise create a new one.
2543 return getOrCreateAddExpr(Ops, Flags);
2547 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2548 SCEV::NoWrapFlags Flags) {
2549 FoldingSetNodeID ID;
2550 ID.AddInteger(scAddExpr);
2551 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2552 ID.AddPointer(Ops[i]);
2555 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2557 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2558 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2559 S = new (SCEVAllocator)
2560 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2561 UniqueSCEVs.InsertNode(S, IP);
2563 S->setNoWrapFlags(Flags);
2567 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2569 if (j > 1 && k / j != i) Overflow = true;
2573 /// Compute the result of "n choose k", the binomial coefficient. If an
2574 /// intermediate computation overflows, Overflow will be set and the return will
2575 /// be garbage. Overflow is not cleared on absence of overflow.
2576 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2577 // We use the multiplicative formula:
2578 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2579 // At each iteration, we take the n-th term of the numeral and divide by the
2580 // (k-n)th term of the denominator. This division will always produce an
2581 // integral result, and helps reduce the chance of overflow in the
2582 // intermediate computations. However, we can still overflow even when the
2583 // final result would fit.
2585 if (n == 0 || n == k) return 1;
2586 if (k > n) return 0;
2592 for (uint64_t i = 1; i <= k; ++i) {
2593 r = umul_ov(r, n-(i-1), Overflow);
2599 /// Determine if any of the operands in this SCEV are a constant or if
2600 /// any of the add or multiply expressions in this SCEV contain a constant.
2601 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2602 SmallVector<const SCEV *, 4> Ops;
2603 Ops.push_back(StartExpr);
2604 while (!Ops.empty()) {
2605 const SCEV *CurrentExpr = Ops.pop_back_val();
2606 if (isa<SCEVConstant>(*CurrentExpr))
2609 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2610 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2611 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2617 /// Get a canonical multiply expression, or something simpler if possible.
2618 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2619 SCEV::NoWrapFlags Flags) {
2620 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2621 "only nuw or nsw allowed");
2622 assert(!Ops.empty() && "Cannot get empty mul!");
2623 if (Ops.size() == 1) return Ops[0];
2625 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2626 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2627 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2628 "SCEVMulExpr operand types don't match!");
2631 // Sort by complexity, this groups all similar expression types together.
2632 GroupByComplexity(Ops, &LI, DT);
2634 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2636 // If there are any constants, fold them together.
2638 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2640 // C1*(C2+V) -> C1*C2 + C1*V
2641 if (Ops.size() == 2)
2642 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2643 // If any of Add's ops are Adds or Muls with a constant,
2644 // apply this transformation as well.
2645 if (Add->getNumOperands() == 2)
2646 if (containsConstantSomewhere(Add))
2647 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2648 getMulExpr(LHSC, Add->getOperand(1)));
2651 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2652 // We found two constants, fold them together!
2654 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2655 Ops[0] = getConstant(Fold);
2656 Ops.erase(Ops.begin()+1); // Erase the folded element
2657 if (Ops.size() == 1) return Ops[0];
2658 LHSC = cast<SCEVConstant>(Ops[0]);
2661 // If we are left with a constant one being multiplied, strip it off.
2662 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2663 Ops.erase(Ops.begin());
2665 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2666 // If we have a multiply of zero, it will always be zero.
2668 } else if (Ops[0]->isAllOnesValue()) {
2669 // If we have a mul by -1 of an add, try distributing the -1 among the
2671 if (Ops.size() == 2) {
2672 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2673 SmallVector<const SCEV *, 4> NewOps;
2674 bool AnyFolded = false;
2675 for (const SCEV *AddOp : Add->operands()) {
2676 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2677 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2678 NewOps.push_back(Mul);
2681 return getAddExpr(NewOps);
2682 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2683 // Negation preserves a recurrence's no self-wrap property.
2684 SmallVector<const SCEV *, 4> Operands;
2685 for (const SCEV *AddRecOp : AddRec->operands())
2686 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2688 return getAddRecExpr(Operands, AddRec->getLoop(),
2689 AddRec->getNoWrapFlags(SCEV::FlagNW));
2694 if (Ops.size() == 1)
2698 // Skip over the add expression until we get to a multiply.
2699 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2702 // If there are mul operands inline them all into this expression.
2703 if (Idx < Ops.size()) {
2704 bool DeletedMul = false;
2705 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2706 if (Ops.size() > MulOpsInlineThreshold)
2708 // If we have an mul, expand the mul operands onto the end of the operands
2710 Ops.erase(Ops.begin()+Idx);
2711 Ops.append(Mul->op_begin(), Mul->op_end());
2715 // If we deleted at least one mul, we added operands to the end of the list,
2716 // and they are not necessarily sorted. Recurse to resort and resimplify
2717 // any operands we just acquired.
2719 return getMulExpr(Ops);
2722 // If there are any add recurrences in the operands list, see if any other
2723 // added values are loop invariant. If so, we can fold them into the
2725 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2728 // Scan over all recurrences, trying to fold loop invariants into them.
2729 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2730 // Scan all of the other operands to this mul and add them to the vector if
2731 // they are loop invariant w.r.t. the recurrence.
2732 SmallVector<const SCEV *, 8> LIOps;
2733 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2734 const Loop *AddRecLoop = AddRec->getLoop();
2735 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2736 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2737 LIOps.push_back(Ops[i]);
2738 Ops.erase(Ops.begin()+i);
2742 // If we found some loop invariants, fold them into the recurrence.
2743 if (!LIOps.empty()) {
2744 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2745 SmallVector<const SCEV *, 4> NewOps;
2746 NewOps.reserve(AddRec->getNumOperands());
2747 const SCEV *Scale = getMulExpr(LIOps);
2748 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2749 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2751 // Build the new addrec. Propagate the NUW and NSW flags if both the
2752 // outer mul and the inner addrec are guaranteed to have no overflow.
2754 // No self-wrap cannot be guaranteed after changing the step size, but
2755 // will be inferred if either NUW or NSW is true.
2756 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2757 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2759 // If all of the other operands were loop invariant, we are done.
2760 if (Ops.size() == 1) return NewRec;
2762 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2763 for (unsigned i = 0;; ++i)
2764 if (Ops[i] == AddRec) {
2768 return getMulExpr(Ops);
2771 // Okay, if there weren't any loop invariants to be folded, check to see if
2772 // there are multiple AddRec's with the same loop induction variable being
2773 // multiplied together. If so, we can fold them.
2775 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2776 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2777 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2778 // ]]],+,...up to x=2n}.
2779 // Note that the arguments to choose() are always integers with values
2780 // known at compile time, never SCEV objects.
2782 // The implementation avoids pointless extra computations when the two
2783 // addrec's are of different length (mathematically, it's equivalent to
2784 // an infinite stream of zeros on the right).
2785 bool OpsModified = false;
2786 for (unsigned OtherIdx = Idx+1;
2787 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2789 const SCEVAddRecExpr *OtherAddRec =
2790 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2791 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2794 bool Overflow = false;
2795 Type *Ty = AddRec->getType();
2796 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2797 SmallVector<const SCEV*, 7> AddRecOps;
2798 for (int x = 0, xe = AddRec->getNumOperands() +
2799 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2800 const SCEV *Term = getZero(Ty);
2801 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2802 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2803 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2804 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2805 z < ze && !Overflow; ++z) {
2806 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2808 if (LargerThan64Bits)
2809 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2811 Coeff = Coeff1*Coeff2;
2812 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2813 const SCEV *Term1 = AddRec->getOperand(y-z);
2814 const SCEV *Term2 = OtherAddRec->getOperand(z);
2815 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2818 AddRecOps.push_back(Term);
2821 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2823 if (Ops.size() == 2) return NewAddRec;
2824 Ops[Idx] = NewAddRec;
2825 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2827 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2833 return getMulExpr(Ops);
2835 // Otherwise couldn't fold anything into this recurrence. Move onto the
2839 // Okay, it looks like we really DO need an mul expr. Check to see if we
2840 // already have one, otherwise create a new one.
2841 FoldingSetNodeID ID;
2842 ID.AddInteger(scMulExpr);
2843 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2844 ID.AddPointer(Ops[i]);
2847 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2849 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2850 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2851 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2853 UniqueSCEVs.InsertNode(S, IP);
2855 S->setNoWrapFlags(Flags);
2859 /// Get a canonical unsigned division expression, or something simpler if
2861 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2863 assert(getEffectiveSCEVType(LHS->getType()) ==
2864 getEffectiveSCEVType(RHS->getType()) &&
2865 "SCEVUDivExpr operand types don't match!");
2867 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2868 if (RHSC->getValue()->equalsInt(1))
2869 return LHS; // X udiv 1 --> x
2870 // If the denominator is zero, the result of the udiv is undefined. Don't
2871 // try to analyze it, because the resolution chosen here may differ from
2872 // the resolution chosen in other parts of the compiler.
2873 if (!RHSC->getValue()->isZero()) {
2874 // Determine if the division can be folded into the operands of
2876 // TODO: Generalize this to non-constants by using known-bits information.
2877 Type *Ty = LHS->getType();
2878 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2879 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2880 // For non-power-of-two values, effectively round the value up to the
2881 // nearest power of two.
2882 if (!RHSC->getAPInt().isPowerOf2())
2884 IntegerType *ExtTy =
2885 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2886 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2887 if (const SCEVConstant *Step =
2888 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2889 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2890 const APInt &StepInt = Step->getAPInt();
2891 const APInt &DivInt = RHSC->getAPInt();
2892 if (!StepInt.urem(DivInt) &&
2893 getZeroExtendExpr(AR, ExtTy) ==
2894 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2895 getZeroExtendExpr(Step, ExtTy),
2896 AR->getLoop(), SCEV::FlagAnyWrap)) {
2897 SmallVector<const SCEV *, 4> Operands;
2898 for (const SCEV *Op : AR->operands())
2899 Operands.push_back(getUDivExpr(Op, RHS));
2900 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2902 /// Get a canonical UDivExpr for a recurrence.
2903 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2904 // We can currently only fold X%N if X is constant.
2905 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2906 if (StartC && !DivInt.urem(StepInt) &&
2907 getZeroExtendExpr(AR, ExtTy) ==
2908 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2909 getZeroExtendExpr(Step, ExtTy),
2910 AR->getLoop(), SCEV::FlagAnyWrap)) {
2911 const APInt &StartInt = StartC->getAPInt();
2912 const APInt &StartRem = StartInt.urem(StepInt);
2914 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2915 AR->getLoop(), SCEV::FlagNW);
2918 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2919 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2920 SmallVector<const SCEV *, 4> Operands;
2921 for (const SCEV *Op : M->operands())
2922 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2923 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2924 // Find an operand that's safely divisible.
2925 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2926 const SCEV *Op = M->getOperand(i);
2927 const SCEV *Div = getUDivExpr(Op, RHSC);
2928 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2929 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2932 return getMulExpr(Operands);
2936 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2937 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2938 SmallVector<const SCEV *, 4> Operands;
2939 for (const SCEV *Op : A->operands())
2940 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2941 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2943 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2944 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2945 if (isa<SCEVUDivExpr>(Op) ||
2946 getMulExpr(Op, RHS) != A->getOperand(i))
2948 Operands.push_back(Op);
2950 if (Operands.size() == A->getNumOperands())
2951 return getAddExpr(Operands);
2955 // Fold if both operands are constant.
2956 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2957 Constant *LHSCV = LHSC->getValue();
2958 Constant *RHSCV = RHSC->getValue();
2959 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2965 FoldingSetNodeID ID;
2966 ID.AddInteger(scUDivExpr);
2970 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2971 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2973 UniqueSCEVs.InsertNode(S, IP);
2977 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2978 APInt A = C1->getAPInt().abs();
2979 APInt B = C2->getAPInt().abs();
2980 uint32_t ABW = A.getBitWidth();
2981 uint32_t BBW = B.getBitWidth();
2988 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
2991 /// Get a canonical unsigned division expression, or something simpler if
2992 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2993 /// can attempt to remove factors from the LHS and RHS. We can't do this when
2994 /// it's not exact because the udiv may be clearing bits.
2995 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2997 // TODO: we could try to find factors in all sorts of things, but for now we
2998 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2999 // end of this file for inspiration.
3001 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3002 if (!Mul || !Mul->hasNoUnsignedWrap())
3003 return getUDivExpr(LHS, RHS);
3005 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3006 // If the mulexpr multiplies by a constant, then that constant must be the
3007 // first element of the mulexpr.
3008 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3009 if (LHSCst == RHSCst) {
3010 SmallVector<const SCEV *, 2> Operands;
3011 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3012 return getMulExpr(Operands);
3015 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3016 // that there's a factor provided by one of the other terms. We need to
3018 APInt Factor = gcd(LHSCst, RHSCst);
3019 if (!Factor.isIntN(1)) {
3021 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3023 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3024 SmallVector<const SCEV *, 2> Operands;
3025 Operands.push_back(LHSCst);
3026 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3027 LHS = getMulExpr(Operands);
3029 Mul = dyn_cast<SCEVMulExpr>(LHS);
3031 return getUDivExactExpr(LHS, RHS);
3036 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3037 if (Mul->getOperand(i) == RHS) {
3038 SmallVector<const SCEV *, 2> Operands;
3039 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3040 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3041 return getMulExpr(Operands);
3045 return getUDivExpr(LHS, RHS);
3048 /// Get an add recurrence expression for the specified loop. Simplify the
3049 /// expression as much as possible.
3050 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3052 SCEV::NoWrapFlags Flags) {
3053 SmallVector<const SCEV *, 4> Operands;
3054 Operands.push_back(Start);
3055 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3056 if (StepChrec->getLoop() == L) {
3057 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3058 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3061 Operands.push_back(Step);
3062 return getAddRecExpr(Operands, L, Flags);
3065 /// Get an add recurrence expression for the specified loop. Simplify the
3066 /// expression as much as possible.
3068 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3069 const Loop *L, SCEV::NoWrapFlags Flags) {
3070 if (Operands.size() == 1) return Operands[0];
3072 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3073 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3074 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3075 "SCEVAddRecExpr operand types don't match!");
3076 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3077 assert(isLoopInvariant(Operands[i], L) &&
3078 "SCEVAddRecExpr operand is not loop-invariant!");
3081 if (Operands.back()->isZero()) {
3082 Operands.pop_back();
3083 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3086 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3087 // use that information to infer NUW and NSW flags. However, computing a
3088 // BE count requires calling getAddRecExpr, so we may not yet have a
3089 // meaningful BE count at this point (and if we don't, we'd be stuck
3090 // with a SCEVCouldNotCompute as the cached BE count).
3092 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3094 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3095 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3096 const Loop *NestedLoop = NestedAR->getLoop();
3097 if (L->contains(NestedLoop)
3098 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3099 : (!NestedLoop->contains(L) &&
3100 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3101 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3102 NestedAR->op_end());
3103 Operands[0] = NestedAR->getStart();
3104 // AddRecs require their operands be loop-invariant with respect to their
3105 // loops. Don't perform this transformation if it would break this
3107 bool AllInvariant = all_of(
3108 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3111 // Create a recurrence for the outer loop with the same step size.
3113 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3114 // inner recurrence has the same property.
3115 SCEV::NoWrapFlags OuterFlags =
3116 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3118 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3119 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3120 return isLoopInvariant(Op, NestedLoop);
3124 // Ok, both add recurrences are valid after the transformation.
3126 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3127 // the outer recurrence has the same property.
3128 SCEV::NoWrapFlags InnerFlags =
3129 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3130 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3133 // Reset Operands to its original state.
3134 Operands[0] = NestedAR;
3138 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3139 // already have one, otherwise create a new one.
3140 FoldingSetNodeID ID;
3141 ID.AddInteger(scAddRecExpr);
3142 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3143 ID.AddPointer(Operands[i]);
3147 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3149 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3150 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3151 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3152 O, Operands.size(), L);
3153 UniqueSCEVs.InsertNode(S, IP);
3155 S->setNoWrapFlags(Flags);
3160 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3161 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3162 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3163 // getSCEV(Base)->getType() has the same address space as Base->getType()
3164 // because SCEV::getType() preserves the address space.
3165 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3166 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3167 // instruction to its SCEV, because the Instruction may be guarded by control
3168 // flow and the no-overflow bits may not be valid for the expression in any
3169 // context. This can be fixed similarly to how these flags are handled for
3171 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3172 : SCEV::FlagAnyWrap;
3174 const SCEV *TotalOffset = getZero(IntPtrTy);
3175 // The array size is unimportant. The first thing we do on CurTy is getting
3176 // its element type.
3177 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3178 for (const SCEV *IndexExpr : IndexExprs) {
3179 // Compute the (potentially symbolic) offset in bytes for this index.
3180 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3181 // For a struct, add the member offset.
3182 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3183 unsigned FieldNo = Index->getZExtValue();
3184 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3186 // Add the field offset to the running total offset.
3187 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3189 // Update CurTy to the type of the field at Index.
3190 CurTy = STy->getTypeAtIndex(Index);
3192 // Update CurTy to its element type.
3193 CurTy = cast<SequentialType>(CurTy)->getElementType();
3194 // For an array, add the element offset, explicitly scaled.
3195 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3196 // Getelementptr indices are signed.
3197 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3199 // Multiply the index by the element size to compute the element offset.
3200 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3202 // Add the element offset to the running total offset.
3203 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3207 // Add the total offset from all the GEP indices to the base.
3208 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3211 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3213 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3214 return getSMaxExpr(Ops);
3218 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3219 assert(!Ops.empty() && "Cannot get empty smax!");
3220 if (Ops.size() == 1) return Ops[0];
3222 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3223 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3224 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3225 "SCEVSMaxExpr operand types don't match!");
3228 // Sort by complexity, this groups all similar expression types together.
3229 GroupByComplexity(Ops, &LI, DT);
3231 // If there are any constants, fold them together.
3233 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3235 assert(Idx < Ops.size());
3236 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3237 // We found two constants, fold them together!
3238 ConstantInt *Fold = ConstantInt::get(
3239 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3240 Ops[0] = getConstant(Fold);
3241 Ops.erase(Ops.begin()+1); // Erase the folded element
3242 if (Ops.size() == 1) return Ops[0];
3243 LHSC = cast<SCEVConstant>(Ops[0]);
3246 // If we are left with a constant minimum-int, strip it off.
3247 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3248 Ops.erase(Ops.begin());
3250 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3251 // If we have an smax with a constant maximum-int, it will always be
3256 if (Ops.size() == 1) return Ops[0];
3259 // Find the first SMax
3260 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3263 // Check to see if one of the operands is an SMax. If so, expand its operands
3264 // onto our operand list, and recurse to simplify.
3265 if (Idx < Ops.size()) {
3266 bool DeletedSMax = false;
3267 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3268 Ops.erase(Ops.begin()+Idx);
3269 Ops.append(SMax->op_begin(), SMax->op_end());
3274 return getSMaxExpr(Ops);
3277 // Okay, check to see if the same value occurs in the operand list twice. If
3278 // so, delete one. Since we sorted the list, these values are required to
3280 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3281 // X smax Y smax Y --> X smax Y
3282 // X smax Y --> X, if X is always greater than Y
3283 if (Ops[i] == Ops[i+1] ||
3284 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3285 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3287 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3288 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3292 if (Ops.size() == 1) return Ops[0];
3294 assert(!Ops.empty() && "Reduced smax down to nothing!");
3296 // Okay, it looks like we really DO need an smax expr. Check to see if we
3297 // already have one, otherwise create a new one.
3298 FoldingSetNodeID ID;
3299 ID.AddInteger(scSMaxExpr);
3300 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3301 ID.AddPointer(Ops[i]);
3303 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3304 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3305 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3306 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3308 UniqueSCEVs.InsertNode(S, IP);
3312 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3314 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3315 return getUMaxExpr(Ops);
3319 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3320 assert(!Ops.empty() && "Cannot get empty umax!");
3321 if (Ops.size() == 1) return Ops[0];
3323 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3324 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3325 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3326 "SCEVUMaxExpr operand types don't match!");
3329 // Sort by complexity, this groups all similar expression types together.
3330 GroupByComplexity(Ops, &LI, DT);
3332 // If there are any constants, fold them together.
3334 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3336 assert(Idx < Ops.size());
3337 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3338 // We found two constants, fold them together!
3339 ConstantInt *Fold = ConstantInt::get(
3340 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3341 Ops[0] = getConstant(Fold);
3342 Ops.erase(Ops.begin()+1); // Erase the folded element
3343 if (Ops.size() == 1) return Ops[0];
3344 LHSC = cast<SCEVConstant>(Ops[0]);
3347 // If we are left with a constant minimum-int, strip it off.
3348 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3349 Ops.erase(Ops.begin());
3351 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3352 // If we have an umax with a constant maximum-int, it will always be
3357 if (Ops.size() == 1) return Ops[0];
3360 // Find the first UMax
3361 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3364 // Check to see if one of the operands is a UMax. If so, expand its operands
3365 // onto our operand list, and recurse to simplify.
3366 if (Idx < Ops.size()) {
3367 bool DeletedUMax = false;
3368 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3369 Ops.erase(Ops.begin()+Idx);
3370 Ops.append(UMax->op_begin(), UMax->op_end());
3375 return getUMaxExpr(Ops);
3378 // Okay, check to see if the same value occurs in the operand list twice. If
3379 // so, delete one. Since we sorted the list, these values are required to
3381 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3382 // X umax Y umax Y --> X umax Y
3383 // X umax Y --> X, if X is always greater than Y
3384 if (Ops[i] == Ops[i+1] ||
3385 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3386 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3388 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3389 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3393 if (Ops.size() == 1) return Ops[0];
3395 assert(!Ops.empty() && "Reduced umax down to nothing!");
3397 // Okay, it looks like we really DO need a umax expr. Check to see if we
3398 // already have one, otherwise create a new one.
3399 FoldingSetNodeID ID;
3400 ID.AddInteger(scUMaxExpr);
3401 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3402 ID.AddPointer(Ops[i]);
3404 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3405 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3406 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3407 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3409 UniqueSCEVs.InsertNode(S, IP);
3413 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3415 // ~smax(~x, ~y) == smin(x, y).
3416 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3419 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3421 // ~umax(~x, ~y) == umin(x, y)
3422 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3425 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3426 // We can bypass creating a target-independent
3427 // constant expression and then folding it back into a ConstantInt.
3428 // This is just a compile-time optimization.
3429 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3432 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3435 // We can bypass creating a target-independent
3436 // constant expression and then folding it back into a ConstantInt.
3437 // This is just a compile-time optimization.
3439 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3442 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3443 // Don't attempt to do anything other than create a SCEVUnknown object
3444 // here. createSCEV only calls getUnknown after checking for all other
3445 // interesting possibilities, and any other code that calls getUnknown
3446 // is doing so in order to hide a value from SCEV canonicalization.
3448 FoldingSetNodeID ID;
3449 ID.AddInteger(scUnknown);
3452 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3453 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3454 "Stale SCEVUnknown in uniquing map!");
3457 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3459 FirstUnknown = cast<SCEVUnknown>(S);
3460 UniqueSCEVs.InsertNode(S, IP);
3464 //===----------------------------------------------------------------------===//
3465 // Basic SCEV Analysis and PHI Idiom Recognition Code
3468 /// Test if values of the given type are analyzable within the SCEV
3469 /// framework. This primarily includes integer types, and it can optionally
3470 /// include pointer types if the ScalarEvolution class has access to
3471 /// target-specific information.
3472 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3473 // Integers and pointers are always SCEVable.
3474 return Ty->isIntegerTy() || Ty->isPointerTy();
3477 /// Return the size in bits of the specified type, for which isSCEVable must
3479 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3480 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3481 return getDataLayout().getTypeSizeInBits(Ty);
3484 /// Return a type with the same bitwidth as the given type and which represents
3485 /// how SCEV will treat the given type, for which isSCEVable must return
3486 /// true. For pointer types, this is the pointer-sized integer type.
3487 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3488 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3490 if (Ty->isIntegerTy())
3493 // The only other support type is pointer.
3494 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3495 return getDataLayout().getIntPtrType(Ty);
3498 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3499 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3502 const SCEV *ScalarEvolution::getCouldNotCompute() {
3503 return CouldNotCompute.get();
3506 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3507 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3508 auto *SU = dyn_cast<SCEVUnknown>(S);
3509 return SU && SU->getValue() == nullptr;
3512 return !ContainsNulls;
3515 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3516 HasRecMapType::iterator I = HasRecMap.find(S);
3517 if (I != HasRecMap.end())
3520 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3521 HasRecMap.insert({S, FoundAddRec});
3525 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3526 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3527 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3528 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3529 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3531 return {S, nullptr};
3533 if (Add->getNumOperands() != 2)
3534 return {S, nullptr};
3536 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3538 return {S, nullptr};
3540 return {Add->getOperand(1), ConstOp->getValue()};
3543 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3544 /// by the value and offset from any ValueOffsetPair in the set.
3545 SetVector<ScalarEvolution::ValueOffsetPair> *
3546 ScalarEvolution::getSCEVValues(const SCEV *S) {
3547 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3548 if (SI == ExprValueMap.end())
3551 if (VerifySCEVMap) {
3552 // Check there is no dangling Value in the set returned.
3553 for (const auto &VE : SI->second)
3554 assert(ValueExprMap.count(VE.first));
3560 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3561 /// cannot be used separately. eraseValueFromMap should be used to remove
3562 /// V from ValueExprMap and ExprValueMap at the same time.
3563 void ScalarEvolution::eraseValueFromMap(Value *V) {
3564 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3565 if (I != ValueExprMap.end()) {
3566 const SCEV *S = I->second;
3567 // Remove {V, 0} from the set of ExprValueMap[S]
3568 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3569 SV->remove({V, nullptr});
3571 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3572 const SCEV *Stripped;
3573 ConstantInt *Offset;
3574 std::tie(Stripped, Offset) = splitAddExpr(S);
3575 if (Offset != nullptr) {
3576 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3577 SV->remove({V, Offset});
3579 ValueExprMap.erase(V);
3583 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3584 /// create a new one.
3585 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3586 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3588 const SCEV *S = getExistingSCEV(V);
3591 // During PHI resolution, it is possible to create two SCEVs for the same
3592 // V, so it is needed to double check whether V->S is inserted into
3593 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3594 std::pair<ValueExprMapType::iterator, bool> Pair =
3595 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3597 ExprValueMap[S].insert({V, nullptr});
3599 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3601 const SCEV *Stripped = S;
3602 ConstantInt *Offset = nullptr;
3603 std::tie(Stripped, Offset) = splitAddExpr(S);
3604 // If stripped is SCEVUnknown, don't bother to save
3605 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3606 // increase the complexity of the expansion code.
3607 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3608 // because it may generate add/sub instead of GEP in SCEV expansion.
3609 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3610 !isa<GetElementPtrInst>(V))
3611 ExprValueMap[Stripped].insert({V, Offset});
3617 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3618 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3620 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3621 if (I != ValueExprMap.end()) {
3622 const SCEV *S = I->second;
3623 if (checkValidity(S))
3625 eraseValueFromMap(V);
3626 forgetMemoizedResults(S);
3631 /// Return a SCEV corresponding to -V = -1*V
3633 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3634 SCEV::NoWrapFlags Flags) {
3635 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3637 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3639 Type *Ty = V->getType();
3640 Ty = getEffectiveSCEVType(Ty);
3642 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3645 /// Return a SCEV corresponding to ~V = -1-V
3646 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3647 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3649 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3651 Type *Ty = V->getType();
3652 Ty = getEffectiveSCEVType(Ty);
3653 const SCEV *AllOnes =
3654 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3655 return getMinusSCEV(AllOnes, V);
3658 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3659 SCEV::NoWrapFlags Flags) {
3660 // Fast path: X - X --> 0.
3662 return getZero(LHS->getType());
3664 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3665 // makes it so that we cannot make much use of NUW.
3666 auto AddFlags = SCEV::FlagAnyWrap;
3667 const bool RHSIsNotMinSigned =
3668 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3669 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3670 // Let M be the minimum representable signed value. Then (-1)*RHS
3671 // signed-wraps if and only if RHS is M. That can happen even for
3672 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3673 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3674 // (-1)*RHS, we need to prove that RHS != M.
3676 // If LHS is non-negative and we know that LHS - RHS does not
3677 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3678 // either by proving that RHS > M or that LHS >= 0.
3679 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3680 AddFlags = SCEV::FlagNSW;
3684 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3685 // RHS is NSW and LHS >= 0.
3687 // The difficulty here is that the NSW flag may have been proven
3688 // relative to a loop that is to be found in a recurrence in LHS and
3689 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3690 // larger scope than intended.
3691 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3693 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3697 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3698 Type *SrcTy = V->getType();
3699 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3700 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3701 "Cannot truncate or zero extend with non-integer arguments!");
3702 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3703 return V; // No conversion
3704 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3705 return getTruncateExpr(V, Ty);
3706 return getZeroExtendExpr(V, Ty);
3710 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3712 Type *SrcTy = V->getType();
3713 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3714 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3715 "Cannot truncate or zero extend with non-integer arguments!");
3716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3717 return V; // No conversion
3718 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3719 return getTruncateExpr(V, Ty);
3720 return getSignExtendExpr(V, Ty);
3724 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3725 Type *SrcTy = V->getType();
3726 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3727 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3728 "Cannot noop or zero extend with non-integer arguments!");
3729 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3730 "getNoopOrZeroExtend cannot truncate!");
3731 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3732 return V; // No conversion
3733 return getZeroExtendExpr(V, Ty);
3737 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3738 Type *SrcTy = V->getType();
3739 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3740 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3741 "Cannot noop or sign extend with non-integer arguments!");
3742 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3743 "getNoopOrSignExtend cannot truncate!");
3744 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3745 return V; // No conversion
3746 return getSignExtendExpr(V, Ty);
3750 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3751 Type *SrcTy = V->getType();
3752 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3753 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3754 "Cannot noop or any extend with non-integer arguments!");
3755 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3756 "getNoopOrAnyExtend cannot truncate!");
3757 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3758 return V; // No conversion
3759 return getAnyExtendExpr(V, Ty);
3763 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3764 Type *SrcTy = V->getType();
3765 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3766 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3767 "Cannot truncate or noop with non-integer arguments!");
3768 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3769 "getTruncateOrNoop cannot extend!");
3770 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3771 return V; // No conversion
3772 return getTruncateExpr(V, Ty);
3775 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3777 const SCEV *PromotedLHS = LHS;
3778 const SCEV *PromotedRHS = RHS;
3780 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3781 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3783 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3785 return getUMaxExpr(PromotedLHS, PromotedRHS);
3788 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3790 const SCEV *PromotedLHS = LHS;
3791 const SCEV *PromotedRHS = RHS;
3793 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3794 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3796 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3798 return getUMinExpr(PromotedLHS, PromotedRHS);
3801 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3802 // A pointer operand may evaluate to a nonpointer expression, such as null.
3803 if (!V->getType()->isPointerTy())
3806 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3807 return getPointerBase(Cast->getOperand());
3808 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3809 const SCEV *PtrOp = nullptr;
3810 for (const SCEV *NAryOp : NAry->operands()) {
3811 if (NAryOp->getType()->isPointerTy()) {
3812 // Cannot find the base of an expression with multiple pointer operands.
3820 return getPointerBase(PtrOp);
3825 /// Push users of the given Instruction onto the given Worklist.
3827 PushDefUseChildren(Instruction *I,
3828 SmallVectorImpl<Instruction *> &Worklist) {
3829 // Push the def-use children onto the Worklist stack.
3830 for (User *U : I->users())
3831 Worklist.push_back(cast<Instruction>(U));
3834 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3835 SmallVector<Instruction *, 16> Worklist;
3836 PushDefUseChildren(PN, Worklist);
3838 SmallPtrSet<Instruction *, 8> Visited;
3840 while (!Worklist.empty()) {
3841 Instruction *I = Worklist.pop_back_val();
3842 if (!Visited.insert(I).second)
3845 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3846 if (It != ValueExprMap.end()) {
3847 const SCEV *Old = It->second;
3849 // Short-circuit the def-use traversal if the symbolic name
3850 // ceases to appear in expressions.
3851 if (Old != SymName && !hasOperand(Old, SymName))
3854 // SCEVUnknown for a PHI either means that it has an unrecognized
3855 // structure, it's a PHI that's in the progress of being computed
3856 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3857 // additional loop trip count information isn't going to change anything.
3858 // In the second case, createNodeForPHI will perform the necessary
3859 // updates on its own when it gets to that point. In the third, we do
3860 // want to forget the SCEVUnknown.
3861 if (!isa<PHINode>(I) ||
3862 !isa<SCEVUnknown>(Old) ||
3863 (I != PN && Old == SymName)) {
3864 eraseValueFromMap(It->first);
3865 forgetMemoizedResults(Old);
3869 PushDefUseChildren(I, Worklist);
3874 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3876 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3877 ScalarEvolution &SE) {
3878 SCEVInitRewriter Rewriter(L, SE);
3879 const SCEV *Result = Rewriter.visit(S);
3880 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3883 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3884 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3886 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3887 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3892 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3893 // Only allow AddRecExprs for this loop.
3894 if (Expr->getLoop() == L)
3895 return Expr->getStart();
3900 bool isValid() { return Valid; }
3907 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3909 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3910 ScalarEvolution &SE) {
3911 SCEVShiftRewriter Rewriter(L, SE);
3912 const SCEV *Result = Rewriter.visit(S);
3913 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3916 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3917 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3919 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3920 // Only allow AddRecExprs for this loop.
3921 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3926 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3927 if (Expr->getLoop() == L && Expr->isAffine())
3928 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3932 bool isValid() { return Valid; }
3938 } // end anonymous namespace
3941 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3942 if (!AR->isAffine())
3943 return SCEV::FlagAnyWrap;
3945 typedef OverflowingBinaryOperator OBO;
3946 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3948 if (!AR->hasNoSignedWrap()) {
3949 ConstantRange AddRecRange = getSignedRange(AR);
3950 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3952 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3953 Instruction::Add, IncRange, OBO::NoSignedWrap);
3954 if (NSWRegion.contains(AddRecRange))
3955 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3958 if (!AR->hasNoUnsignedWrap()) {
3959 ConstantRange AddRecRange = getUnsignedRange(AR);
3960 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3962 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3963 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3964 if (NUWRegion.contains(AddRecRange))
3965 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3972 /// Represents an abstract binary operation. This may exist as a
3973 /// normal instruction or constant expression, or may have been
3974 /// derived from an expression tree.
3982 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3983 /// constant expression.
3986 explicit BinaryOp(Operator *Op)
3987 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3988 IsNSW(false), IsNUW(false), Op(Op) {
3989 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3990 IsNSW = OBO->hasNoSignedWrap();
3991 IsNUW = OBO->hasNoUnsignedWrap();
3995 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3997 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4003 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4004 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4005 auto *Op = dyn_cast<Operator>(V);
4009 // Implementation detail: all the cleverness here should happen without
4010 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4011 // SCEV expressions when possible, and we should not break that.
4013 switch (Op->getOpcode()) {
4014 case Instruction::Add:
4015 case Instruction::Sub:
4016 case Instruction::Mul:
4017 case Instruction::UDiv:
4018 case Instruction::And:
4019 case Instruction::Or:
4020 case Instruction::AShr:
4021 case Instruction::Shl:
4022 return BinaryOp(Op);
4024 case Instruction::Xor:
4025 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4026 // If the RHS of the xor is a signmask, then this is just an add.
4027 // Instcombine turns add of signmask into xor as a strength reduction step.
4028 if (RHSC->getValue().isSignMask())
4029 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4030 return BinaryOp(Op);
4032 case Instruction::LShr:
4033 // Turn logical shift right of a constant into a unsigned divide.
4034 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4035 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4037 // If the shift count is not less than the bitwidth, the result of
4038 // the shift is undefined. Don't try to analyze it, because the
4039 // resolution chosen here may differ from the resolution chosen in
4040 // other parts of the compiler.
4041 if (SA->getValue().ult(BitWidth)) {
4043 ConstantInt::get(SA->getContext(),
4044 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4045 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4048 return BinaryOp(Op);
4050 case Instruction::ExtractValue: {
4051 auto *EVI = cast<ExtractValueInst>(Op);
4052 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4055 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4059 if (auto *F = CI->getCalledFunction())
4060 switch (F->getIntrinsicID()) {
4061 case Intrinsic::sadd_with_overflow:
4062 case Intrinsic::uadd_with_overflow: {
4063 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4064 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4065 CI->getArgOperand(1));
4067 // Now that we know that all uses of the arithmetic-result component of
4068 // CI are guarded by the overflow check, we can go ahead and pretend
4069 // that the arithmetic is non-overflowing.
4070 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4071 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4072 CI->getArgOperand(1), /* IsNSW = */ true,
4073 /* IsNUW = */ false);
4075 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4076 CI->getArgOperand(1), /* IsNSW = */ false,
4080 case Intrinsic::ssub_with_overflow:
4081 case Intrinsic::usub_with_overflow:
4082 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4083 CI->getArgOperand(1));
4085 case Intrinsic::smul_with_overflow:
4086 case Intrinsic::umul_with_overflow:
4087 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4088 CI->getArgOperand(1));
4101 /// A helper function for createAddRecFromPHI to handle simple cases.
4103 /// This function tries to find an AddRec expression for the simplest (yet most
4104 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4105 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4106 /// technique for finding the AddRec expression.
4107 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4109 Value *StartValueV) {
4110 const Loop *L = LI.getLoopFor(PN->getParent());
4111 assert(L && L->getHeader() == PN->getParent());
4112 assert(BEValueV && StartValueV);
4114 auto BO = MatchBinaryOp(BEValueV, DT);
4118 if (BO->Opcode != Instruction::Add)
4121 const SCEV *Accum = nullptr;
4122 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4123 Accum = getSCEV(BO->RHS);
4124 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4125 Accum = getSCEV(BO->LHS);
4130 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4132 Flags = setFlags(Flags, SCEV::FlagNUW);
4134 Flags = setFlags(Flags, SCEV::FlagNSW);
4136 const SCEV *StartVal = getSCEV(StartValueV);
4137 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4139 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4141 // We can add Flags to the post-inc expression only if we
4142 // know that it is *undefined behavior* for BEValueV to
4144 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4145 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4146 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4151 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4152 const Loop *L = LI.getLoopFor(PN->getParent());
4153 if (!L || L->getHeader() != PN->getParent())
4156 // The loop may have multiple entrances or multiple exits; we can analyze
4157 // this phi as an addrec if it has a unique entry value and a unique
4159 Value *BEValueV = nullptr, *StartValueV = nullptr;
4160 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4161 Value *V = PN->getIncomingValue(i);
4162 if (L->contains(PN->getIncomingBlock(i))) {
4165 } else if (BEValueV != V) {
4169 } else if (!StartValueV) {
4171 } else if (StartValueV != V) {
4172 StartValueV = nullptr;
4176 if (!BEValueV || !StartValueV)
4179 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4180 "PHI node already processed?");
4182 // First, try to find AddRec expression without creating a fictituos symbolic
4184 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4187 // Handle PHI node value symbolically.
4188 const SCEV *SymbolicName = getUnknown(PN);
4189 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4191 // Using this symbolic name for the PHI, analyze the value coming around
4193 const SCEV *BEValue = getSCEV(BEValueV);
4195 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4196 // has a special value for the first iteration of the loop.
4198 // If the value coming around the backedge is an add with the symbolic
4199 // value we just inserted, then we found a simple induction variable!
4200 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4201 // If there is a single occurrence of the symbolic value, replace it
4202 // with a recurrence.
4203 unsigned FoundIndex = Add->getNumOperands();
4204 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4205 if (Add->getOperand(i) == SymbolicName)
4206 if (FoundIndex == e) {
4211 if (FoundIndex != Add->getNumOperands()) {
4212 // Create an add with everything but the specified operand.
4213 SmallVector<const SCEV *, 8> Ops;
4214 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4215 if (i != FoundIndex)
4216 Ops.push_back(Add->getOperand(i));
4217 const SCEV *Accum = getAddExpr(Ops);
4219 // This is not a valid addrec if the step amount is varying each
4220 // loop iteration, but is not itself an addrec in this loop.
4221 if (isLoopInvariant(Accum, L) ||
4222 (isa<SCEVAddRecExpr>(Accum) &&
4223 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4224 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4226 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4227 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4229 Flags = setFlags(Flags, SCEV::FlagNUW);
4231 Flags = setFlags(Flags, SCEV::FlagNSW);
4233 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4234 // If the increment is an inbounds GEP, then we know the address
4235 // space cannot be wrapped around. We cannot make any guarantee
4236 // about signed or unsigned overflow because pointers are
4237 // unsigned but we may have a negative index from the base
4238 // pointer. We can guarantee that no unsigned wrap occurs if the
4239 // indices form a positive value.
4240 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4241 Flags = setFlags(Flags, SCEV::FlagNW);
4243 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4244 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4245 Flags = setFlags(Flags, SCEV::FlagNUW);
4248 // We cannot transfer nuw and nsw flags from subtraction
4249 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4253 const SCEV *StartVal = getSCEV(StartValueV);
4254 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4256 // Okay, for the entire analysis of this edge we assumed the PHI
4257 // to be symbolic. We now need to go back and purge all of the
4258 // entries for the scalars that use the symbolic expression.
4259 forgetSymbolicName(PN, SymbolicName);
4260 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4262 // We can add Flags to the post-inc expression only if we
4263 // know that it is *undefined behavior* for BEValueV to
4265 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4266 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4267 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4273 // Otherwise, this could be a loop like this:
4274 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4275 // In this case, j = {1,+,1} and BEValue is j.
4276 // Because the other in-value of i (0) fits the evolution of BEValue
4277 // i really is an addrec evolution.
4279 // We can generalize this saying that i is the shifted value of BEValue
4280 // by one iteration:
4281 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4282 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4283 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4284 if (Shifted != getCouldNotCompute() &&
4285 Start != getCouldNotCompute()) {
4286 const SCEV *StartVal = getSCEV(StartValueV);
4287 if (Start == StartVal) {
4288 // Okay, for the entire analysis of this edge we assumed the PHI
4289 // to be symbolic. We now need to go back and purge all of the
4290 // entries for the scalars that use the symbolic expression.
4291 forgetSymbolicName(PN, SymbolicName);
4292 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4298 // Remove the temporary PHI node SCEV that has been inserted while intending
4299 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4300 // as it will prevent later (possibly simpler) SCEV expressions to be added
4301 // to the ValueExprMap.
4302 eraseValueFromMap(PN);
4307 // Checks if the SCEV S is available at BB. S is considered available at BB
4308 // if S can be materialized at BB without introducing a fault.
4309 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4311 struct CheckAvailable {
4312 bool TraversalDone = false;
4313 bool Available = true;
4315 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4316 BasicBlock *BB = nullptr;
4319 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4320 : L(L), BB(BB), DT(DT) {}
4322 bool setUnavailable() {
4323 TraversalDone = true;
4328 bool follow(const SCEV *S) {
4329 switch (S->getSCEVType()) {
4330 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4331 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4332 // These expressions are available if their operand(s) is/are.
4335 case scAddRecExpr: {
4336 // We allow add recurrences that are on the loop BB is in, or some
4337 // outer loop. This guarantees availability because the value of the
4338 // add recurrence at BB is simply the "current" value of the induction
4339 // variable. We can relax this in the future; for instance an add
4340 // recurrence on a sibling dominating loop is also available at BB.
4341 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4342 if (L && (ARLoop == L || ARLoop->contains(L)))
4345 return setUnavailable();
4349 // For SCEVUnknown, we check for simple dominance.
4350 const auto *SU = cast<SCEVUnknown>(S);
4351 Value *V = SU->getValue();
4353 if (isa<Argument>(V))
4356 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4359 return setUnavailable();
4363 case scCouldNotCompute:
4364 // We do not try to smart about these at all.
4365 return setUnavailable();
4367 llvm_unreachable("switch should be fully covered!");
4370 bool isDone() { return TraversalDone; }
4373 CheckAvailable CA(L, BB, DT);
4374 SCEVTraversal<CheckAvailable> ST(CA);
4377 return CA.Available;
4380 // Try to match a control flow sequence that branches out at BI and merges back
4381 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4383 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4384 Value *&C, Value *&LHS, Value *&RHS) {
4385 C = BI->getCondition();
4387 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4388 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4390 if (!LeftEdge.isSingleEdge())
4393 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4395 Use &LeftUse = Merge->getOperandUse(0);
4396 Use &RightUse = Merge->getOperandUse(1);
4398 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4404 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4413 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4415 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4416 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4417 const Loop *L = LI.getLoopFor(PN->getParent());
4419 // We don't want to break LCSSA, even in a SCEV expression tree.
4420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4421 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4426 // br %cond, label %left, label %right
4432 // V = phi [ %x, %left ], [ %y, %right ]
4434 // as "select %cond, %x, %y"
4436 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4437 assert(IDom && "At least the entry block should dominate PN");
4439 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4440 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4442 if (BI && BI->isConditional() &&
4443 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4444 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4445 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4446 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4452 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4453 if (const SCEV *S = createAddRecFromPHI(PN))
4456 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4459 // If the PHI has a single incoming value, follow that value, unless the
4460 // PHI's incoming blocks are in a different loop, in which case doing so
4461 // risks breaking LCSSA form. Instcombine would normally zap these, but
4462 // it doesn't have DominatorTree information, so it may miss cases.
4463 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4464 if (LI.replacementPreservesLCSSAForm(PN, V))
4467 // If it's not a loop phi, we can't handle it yet.
4468 return getUnknown(PN);
4471 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4475 // Handle "constant" branch or select. This can occur for instance when a
4476 // loop pass transforms an inner loop and moves on to process the outer loop.
4477 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4478 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4480 // Try to match some simple smax or umax patterns.
4481 auto *ICI = dyn_cast<ICmpInst>(Cond);
4483 return getUnknown(I);
4485 Value *LHS = ICI->getOperand(0);
4486 Value *RHS = ICI->getOperand(1);
4488 switch (ICI->getPredicate()) {
4489 case ICmpInst::ICMP_SLT:
4490 case ICmpInst::ICMP_SLE:
4491 std::swap(LHS, RHS);
4493 case ICmpInst::ICMP_SGT:
4494 case ICmpInst::ICMP_SGE:
4495 // a >s b ? a+x : b+x -> smax(a, b)+x
4496 // a >s b ? b+x : a+x -> smin(a, b)+x
4497 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4498 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4499 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4500 const SCEV *LA = getSCEV(TrueVal);
4501 const SCEV *RA = getSCEV(FalseVal);
4502 const SCEV *LDiff = getMinusSCEV(LA, LS);
4503 const SCEV *RDiff = getMinusSCEV(RA, RS);
4505 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4506 LDiff = getMinusSCEV(LA, RS);
4507 RDiff = getMinusSCEV(RA, LS);
4509 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4512 case ICmpInst::ICMP_ULT:
4513 case ICmpInst::ICMP_ULE:
4514 std::swap(LHS, RHS);
4516 case ICmpInst::ICMP_UGT:
4517 case ICmpInst::ICMP_UGE:
4518 // a >u b ? a+x : b+x -> umax(a, b)+x
4519 // a >u b ? b+x : a+x -> umin(a, b)+x
4520 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4521 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4522 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4523 const SCEV *LA = getSCEV(TrueVal);
4524 const SCEV *RA = getSCEV(FalseVal);
4525 const SCEV *LDiff = getMinusSCEV(LA, LS);
4526 const SCEV *RDiff = getMinusSCEV(RA, RS);
4528 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4529 LDiff = getMinusSCEV(LA, RS);
4530 RDiff = getMinusSCEV(RA, LS);
4532 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4535 case ICmpInst::ICMP_NE:
4536 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4537 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4538 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4539 const SCEV *One = getOne(I->getType());
4540 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4541 const SCEV *LA = getSCEV(TrueVal);
4542 const SCEV *RA = getSCEV(FalseVal);
4543 const SCEV *LDiff = getMinusSCEV(LA, LS);
4544 const SCEV *RDiff = getMinusSCEV(RA, One);
4546 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4549 case ICmpInst::ICMP_EQ:
4550 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4551 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4552 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4553 const SCEV *One = getOne(I->getType());
4554 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4555 const SCEV *LA = getSCEV(TrueVal);
4556 const SCEV *RA = getSCEV(FalseVal);
4557 const SCEV *LDiff = getMinusSCEV(LA, One);
4558 const SCEV *RDiff = getMinusSCEV(RA, LS);
4560 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4567 return getUnknown(I);
4570 /// Expand GEP instructions into add and multiply operations. This allows them
4571 /// to be analyzed by regular SCEV code.
4572 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4573 // Don't attempt to analyze GEPs over unsized objects.
4574 if (!GEP->getSourceElementType()->isSized())
4575 return getUnknown(GEP);
4577 SmallVector<const SCEV *, 4> IndexExprs;
4578 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4579 IndexExprs.push_back(getSCEV(*Index));
4580 return getGEPExpr(GEP, IndexExprs);
4583 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4584 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4585 return C->getAPInt().countTrailingZeros();
4587 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4588 return std::min(GetMinTrailingZeros(T->getOperand()),
4589 (uint32_t)getTypeSizeInBits(T->getType()));
4591 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4592 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4593 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4594 ? getTypeSizeInBits(E->getType())
4598 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4599 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4600 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4601 ? getTypeSizeInBits(E->getType())
4605 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4606 // The result is the min of all operands results.
4607 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4608 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4609 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4613 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4614 // The result is the sum of all operands results.
4615 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4616 uint32_t BitWidth = getTypeSizeInBits(M->getType());
4617 for (unsigned i = 1, e = M->getNumOperands();
4618 SumOpRes != BitWidth && i != e; ++i)
4620 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4624 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4625 // The result is the min of all operands results.
4626 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4627 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4628 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4632 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4633 // The result is the min of all operands results.
4634 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4635 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4636 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4640 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4641 // The result is the min of all operands results.
4642 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4643 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4644 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4648 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4649 // For a SCEVUnknown, ask ValueTracking.
4650 unsigned BitWidth = getTypeSizeInBits(U->getType());
4651 KnownBits Known(BitWidth);
4652 computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC,
4654 return Known.countMinTrailingZeros();
4661 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4662 auto I = MinTrailingZerosCache.find(S);
4663 if (I != MinTrailingZerosCache.end())
4666 uint32_t Result = GetMinTrailingZerosImpl(S);
4667 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4668 assert(InsertPair.second && "Should insert a new key");
4669 return InsertPair.first->second;
4672 /// Helper method to assign a range to V from metadata present in the IR.
4673 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4674 if (Instruction *I = dyn_cast<Instruction>(V))
4675 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4676 return getConstantRangeFromMetadata(*MD);
4681 /// Determine the range for a particular SCEV. If SignHint is
4682 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4683 /// with a "cleaner" unsigned (resp. signed) representation.
4685 ScalarEvolution::getRange(const SCEV *S,
4686 ScalarEvolution::RangeSignHint SignHint) {
4687 DenseMap<const SCEV *, ConstantRange> &Cache =
4688 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4691 // See if we've computed this range already.
4692 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4693 if (I != Cache.end())
4696 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4697 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4699 unsigned BitWidth = getTypeSizeInBits(S->getType());
4700 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4702 // If the value has known zeros, the maximum value will have those known zeros
4704 uint32_t TZ = GetMinTrailingZeros(S);
4706 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4707 ConservativeResult =
4708 ConstantRange(APInt::getMinValue(BitWidth),
4709 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4711 ConservativeResult = ConstantRange(
4712 APInt::getSignedMinValue(BitWidth),
4713 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4716 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4717 ConstantRange X = getRange(Add->getOperand(0), SignHint);
4718 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4719 X = X.add(getRange(Add->getOperand(i), SignHint));
4720 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4723 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4724 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4725 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4726 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4727 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4730 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4731 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4732 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4733 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4734 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4737 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4738 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4739 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4740 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4741 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4744 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4745 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4746 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4747 return setRange(UDiv, SignHint,
4748 ConservativeResult.intersectWith(X.udiv(Y)));
4751 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4752 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4753 return setRange(ZExt, SignHint,
4754 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4757 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4758 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4759 return setRange(SExt, SignHint,
4760 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4763 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4764 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4765 return setRange(Trunc, SignHint,
4766 ConservativeResult.intersectWith(X.truncate(BitWidth)));
4769 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4770 // If there's no unsigned wrap, the value will never be less than its
4772 if (AddRec->hasNoUnsignedWrap())
4773 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4774 if (!C->getValue()->isZero())
4775 ConservativeResult = ConservativeResult.intersectWith(
4776 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4778 // If there's no signed wrap, and all the operands have the same sign or
4779 // zero, the value won't ever change sign.
4780 if (AddRec->hasNoSignedWrap()) {
4781 bool AllNonNeg = true;
4782 bool AllNonPos = true;
4783 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4784 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4785 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4788 ConservativeResult = ConservativeResult.intersectWith(
4789 ConstantRange(APInt(BitWidth, 0),
4790 APInt::getSignedMinValue(BitWidth)));
4792 ConservativeResult = ConservativeResult.intersectWith(
4793 ConstantRange(APInt::getSignedMinValue(BitWidth),
4794 APInt(BitWidth, 1)));
4797 // TODO: non-affine addrec
4798 if (AddRec->isAffine()) {
4799 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4800 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4801 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4802 auto RangeFromAffine = getRangeForAffineAR(
4803 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4805 if (!RangeFromAffine.isFullSet())
4806 ConservativeResult =
4807 ConservativeResult.intersectWith(RangeFromAffine);
4809 auto RangeFromFactoring = getRangeViaFactoring(
4810 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4812 if (!RangeFromFactoring.isFullSet())
4813 ConservativeResult =
4814 ConservativeResult.intersectWith(RangeFromFactoring);
4818 return setRange(AddRec, SignHint, std::move(ConservativeResult));
4821 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4822 // Check if the IR explicitly contains !range metadata.
4823 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4824 if (MDRange.hasValue())
4825 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4827 // Split here to avoid paying the compile-time cost of calling both
4828 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4830 const DataLayout &DL = getDataLayout();
4831 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4832 // For a SCEVUnknown, ask ValueTracking.
4833 KnownBits Known(BitWidth);
4834 computeKnownBits(U->getValue(), Known, DL, 0, &AC, nullptr, &DT);
4835 if (Known.One != ~Known.Zero + 1)
4836 ConservativeResult =
4837 ConservativeResult.intersectWith(ConstantRange(Known.One,
4840 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4841 "generalize as needed!");
4842 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4844 ConservativeResult = ConservativeResult.intersectWith(
4845 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4846 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4849 return setRange(U, SignHint, std::move(ConservativeResult));
4852 return setRange(S, SignHint, std::move(ConservativeResult));
4855 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4856 // values that the expression can take. Initially, the expression has a value
4857 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4858 // argument defines if we treat Step as signed or unsigned.
4859 static ConstantRange getRangeForAffineARHelper(APInt Step,
4860 const ConstantRange &StartRange,
4861 const APInt &MaxBECount,
4862 unsigned BitWidth, bool Signed) {
4863 // If either Step or MaxBECount is 0, then the expression won't change, and we
4864 // just need to return the initial range.
4865 if (Step == 0 || MaxBECount == 0)
4868 // If we don't know anything about the initial value (i.e. StartRange is
4869 // FullRange), then we don't know anything about the final range either.
4870 // Return FullRange.
4871 if (StartRange.isFullSet())
4872 return ConstantRange(BitWidth, /* isFullSet = */ true);
4874 // If Step is signed and negative, then we use its absolute value, but we also
4875 // note that we're moving in the opposite direction.
4876 bool Descending = Signed && Step.isNegative();
4879 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4880 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4881 // This equations hold true due to the well-defined wrap-around behavior of
4885 // Check if Offset is more than full span of BitWidth. If it is, the
4886 // expression is guaranteed to overflow.
4887 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4888 return ConstantRange(BitWidth, /* isFullSet = */ true);
4890 // Offset is by how much the expression can change. Checks above guarantee no
4892 APInt Offset = Step * MaxBECount;
4894 // Minimum value of the final range will match the minimal value of StartRange
4895 // if the expression is increasing and will be decreased by Offset otherwise.
4896 // Maximum value of the final range will match the maximal value of StartRange
4897 // if the expression is decreasing and will be increased by Offset otherwise.
4898 APInt StartLower = StartRange.getLower();
4899 APInt StartUpper = StartRange.getUpper() - 1;
4900 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
4901 : (StartUpper + std::move(Offset));
4903 // It's possible that the new minimum/maximum value will fall into the initial
4904 // range (due to wrap around). This means that the expression can take any
4905 // value in this bitwidth, and we have to return full range.
4906 if (StartRange.contains(MovedBoundary))
4907 return ConstantRange(BitWidth, /* isFullSet = */ true);
4910 Descending ? std::move(MovedBoundary) : std::move(StartLower);
4912 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
4915 // If we end up with full range, return a proper full range.
4916 if (NewLower == NewUpper)
4917 return ConstantRange(BitWidth, /* isFullSet = */ true);
4919 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4920 return ConstantRange(std::move(NewLower), std::move(NewUpper));
4923 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4925 const SCEV *MaxBECount,
4926 unsigned BitWidth) {
4927 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4928 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4931 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4932 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4933 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4935 // First, consider step signed.
4936 ConstantRange StartSRange = getSignedRange(Start);
4937 ConstantRange StepSRange = getSignedRange(Step);
4939 // If Step can be both positive and negative, we need to find ranges for the
4940 // maximum absolute step values in both directions and union them.
4942 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4943 MaxBECountValue, BitWidth, /* Signed = */ true);
4944 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4945 StartSRange, MaxBECountValue,
4946 BitWidth, /* Signed = */ true));
4948 // Next, consider step unsigned.
4949 ConstantRange UR = getRangeForAffineARHelper(
4950 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4951 MaxBECountValue, BitWidth, /* Signed = */ false);
4953 // Finally, intersect signed and unsigned ranges.
4954 return SR.intersectWith(UR);
4957 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4959 const SCEV *MaxBECount,
4960 unsigned BitWidth) {
4961 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4962 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4964 struct SelectPattern {
4965 Value *Condition = nullptr;
4969 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4971 Optional<unsigned> CastOp;
4972 APInt Offset(BitWidth, 0);
4974 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4977 // Peel off a constant offset:
4978 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4979 // In the future we could consider being smarter here and handle
4980 // {Start+Step,+,Step} too.
4981 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4984 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4985 S = SA->getOperand(1);
4988 // Peel off a cast operation
4989 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4990 CastOp = SCast->getSCEVType();
4991 S = SCast->getOperand();
4994 using namespace llvm::PatternMatch;
4996 auto *SU = dyn_cast<SCEVUnknown>(S);
4997 const APInt *TrueVal, *FalseVal;
4999 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5000 m_APInt(FalseVal)))) {
5001 Condition = nullptr;
5005 TrueValue = *TrueVal;
5006 FalseValue = *FalseVal;
5008 // Re-apply the cast we peeled off earlier
5009 if (CastOp.hasValue())
5012 llvm_unreachable("Unknown SCEV cast type!");
5015 TrueValue = TrueValue.trunc(BitWidth);
5016 FalseValue = FalseValue.trunc(BitWidth);
5019 TrueValue = TrueValue.zext(BitWidth);
5020 FalseValue = FalseValue.zext(BitWidth);
5023 TrueValue = TrueValue.sext(BitWidth);
5024 FalseValue = FalseValue.sext(BitWidth);
5028 // Re-apply the constant offset we peeled off earlier
5029 TrueValue += Offset;
5030 FalseValue += Offset;
5033 bool isRecognized() { return Condition != nullptr; }
5036 SelectPattern StartPattern(*this, BitWidth, Start);
5037 if (!StartPattern.isRecognized())
5038 return ConstantRange(BitWidth, /* isFullSet = */ true);
5040 SelectPattern StepPattern(*this, BitWidth, Step);
5041 if (!StepPattern.isRecognized())
5042 return ConstantRange(BitWidth, /* isFullSet = */ true);
5044 if (StartPattern.Condition != StepPattern.Condition) {
5045 // We don't handle this case today; but we could, by considering four
5046 // possibilities below instead of two. I'm not sure if there are cases where
5047 // that will help over what getRange already does, though.
5048 return ConstantRange(BitWidth, /* isFullSet = */ true);
5051 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5052 // construct arbitrary general SCEV expressions here. This function is called
5053 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5054 // say) can end up caching a suboptimal value.
5056 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5057 // C2352 and C2512 (otherwise it isn't needed).
5059 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5060 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5061 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5062 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5064 ConstantRange TrueRange =
5065 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5066 ConstantRange FalseRange =
5067 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5069 return TrueRange.unionWith(FalseRange);
5072 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5073 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5074 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5076 // Return early if there are no flags to propagate to the SCEV.
5077 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5078 if (BinOp->hasNoUnsignedWrap())
5079 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5080 if (BinOp->hasNoSignedWrap())
5081 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5082 if (Flags == SCEV::FlagAnyWrap)
5083 return SCEV::FlagAnyWrap;
5085 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5088 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5089 // Here we check that I is in the header of the innermost loop containing I,
5090 // since we only deal with instructions in the loop header. The actual loop we
5091 // need to check later will come from an add recurrence, but getting that
5092 // requires computing the SCEV of the operands, which can be expensive. This
5093 // check we can do cheaply to rule out some cases early.
5094 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5095 if (InnermostContainingLoop == nullptr ||
5096 InnermostContainingLoop->getHeader() != I->getParent())
5099 // Only proceed if we can prove that I does not yield poison.
5100 if (!programUndefinedIfFullPoison(I))
5103 // At this point we know that if I is executed, then it does not wrap
5104 // according to at least one of NSW or NUW. If I is not executed, then we do
5105 // not know if the calculation that I represents would wrap. Multiple
5106 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5107 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5108 // derived from other instructions that map to the same SCEV. We cannot make
5109 // that guarantee for cases where I is not executed. So we need to find the
5110 // loop that I is considered in relation to and prove that I is executed for
5111 // every iteration of that loop. That implies that the value that I
5112 // calculates does not wrap anywhere in the loop, so then we can apply the
5113 // flags to the SCEV.
5115 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5116 // from different loops, so that we know which loop to prove that I is
5118 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5119 // I could be an extractvalue from a call to an overflow intrinsic.
5120 // TODO: We can do better here in some cases.
5121 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5123 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5124 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5125 bool AllOtherOpsLoopInvariant = true;
5126 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5128 if (OtherOpIndex != OpIndex) {
5129 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5130 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5131 AllOtherOpsLoopInvariant = false;
5136 if (AllOtherOpsLoopInvariant &&
5137 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5144 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5145 // If we know that \c I can never be poison period, then that's enough.
5146 if (isSCEVExprNeverPoison(I))
5149 // For an add recurrence specifically, we assume that infinite loops without
5150 // side effects are undefined behavior, and then reason as follows:
5152 // If the add recurrence is poison in any iteration, it is poison on all
5153 // future iterations (since incrementing poison yields poison). If the result
5154 // of the add recurrence is fed into the loop latch condition and the loop
5155 // does not contain any throws or exiting blocks other than the latch, we now
5156 // have the ability to "choose" whether the backedge is taken or not (by
5157 // choosing a sufficiently evil value for the poison feeding into the branch)
5158 // for every iteration including and after the one in which \p I first became
5159 // poison. There are two possibilities (let's call the iteration in which \p
5160 // I first became poison as K):
5162 // 1. In the set of iterations including and after K, the loop body executes
5163 // no side effects. In this case executing the backege an infinte number
5164 // of times will yield undefined behavior.
5166 // 2. In the set of iterations including and after K, the loop body executes
5167 // at least one side effect. In this case, that specific instance of side
5168 // effect is control dependent on poison, which also yields undefined
5171 auto *ExitingBB = L->getExitingBlock();
5172 auto *LatchBB = L->getLoopLatch();
5173 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5176 SmallPtrSet<const Instruction *, 16> Pushed;
5177 SmallVector<const Instruction *, 8> PoisonStack;
5179 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5180 // things that are known to be fully poison under that assumption go on the
5183 PoisonStack.push_back(I);
5185 bool LatchControlDependentOnPoison = false;
5186 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5187 const Instruction *Poison = PoisonStack.pop_back_val();
5189 for (auto *PoisonUser : Poison->users()) {
5190 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5191 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5192 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5193 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5194 assert(BI->isConditional() && "Only possibility!");
5195 if (BI->getParent() == LatchBB) {
5196 LatchControlDependentOnPoison = true;
5203 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5206 ScalarEvolution::LoopProperties
5207 ScalarEvolution::getLoopProperties(const Loop *L) {
5208 typedef ScalarEvolution::LoopProperties LoopProperties;
5210 auto Itr = LoopPropertiesCache.find(L);
5211 if (Itr == LoopPropertiesCache.end()) {
5212 auto HasSideEffects = [](Instruction *I) {
5213 if (auto *SI = dyn_cast<StoreInst>(I))
5214 return !SI->isSimple();
5216 return I->mayHaveSideEffects();
5219 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5220 /*HasNoSideEffects*/ true};
5222 for (auto *BB : L->getBlocks())
5223 for (auto &I : *BB) {
5224 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5225 LP.HasNoAbnormalExits = false;
5226 if (HasSideEffects(&I))
5227 LP.HasNoSideEffects = false;
5228 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5229 break; // We're already as pessimistic as we can get.
5232 auto InsertPair = LoopPropertiesCache.insert({L, LP});
5233 assert(InsertPair.second && "We just checked!");
5234 Itr = InsertPair.first;
5240 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5241 if (!isSCEVable(V->getType()))
5242 return getUnknown(V);
5244 if (Instruction *I = dyn_cast<Instruction>(V)) {
5245 // Don't attempt to analyze instructions in blocks that aren't
5246 // reachable. Such instructions don't matter, and they aren't required
5247 // to obey basic rules for definitions dominating uses which this
5248 // analysis depends on.
5249 if (!DT.isReachableFromEntry(I->getParent()))
5250 return getUnknown(V);
5251 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5252 return getConstant(CI);
5253 else if (isa<ConstantPointerNull>(V))
5254 return getZero(V->getType());
5255 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5256 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5257 else if (!isa<ConstantExpr>(V))
5258 return getUnknown(V);
5260 Operator *U = cast<Operator>(V);
5261 if (auto BO = MatchBinaryOp(U, DT)) {
5262 switch (BO->Opcode) {
5263 case Instruction::Add: {
5264 // The simple thing to do would be to just call getSCEV on both operands
5265 // and call getAddExpr with the result. However if we're looking at a
5266 // bunch of things all added together, this can be quite inefficient,
5267 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5268 // Instead, gather up all the operands and make a single getAddExpr call.
5269 // LLVM IR canonical form means we need only traverse the left operands.
5270 SmallVector<const SCEV *, 4> AddOps;
5273 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5274 AddOps.push_back(OpSCEV);
5278 // If a NUW or NSW flag can be applied to the SCEV for this
5279 // addition, then compute the SCEV for this addition by itself
5280 // with a separate call to getAddExpr. We need to do that
5281 // instead of pushing the operands of the addition onto AddOps,
5282 // since the flags are only known to apply to this particular
5283 // addition - they may not apply to other additions that can be
5284 // formed with operands from AddOps.
5285 const SCEV *RHS = getSCEV(BO->RHS);
5286 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5287 if (Flags != SCEV::FlagAnyWrap) {
5288 const SCEV *LHS = getSCEV(BO->LHS);
5289 if (BO->Opcode == Instruction::Sub)
5290 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5292 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5297 if (BO->Opcode == Instruction::Sub)
5298 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5300 AddOps.push_back(getSCEV(BO->RHS));
5302 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5303 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5304 NewBO->Opcode != Instruction::Sub)) {
5305 AddOps.push_back(getSCEV(BO->LHS));
5311 return getAddExpr(AddOps);
5314 case Instruction::Mul: {
5315 SmallVector<const SCEV *, 4> MulOps;
5318 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5319 MulOps.push_back(OpSCEV);
5323 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5324 if (Flags != SCEV::FlagAnyWrap) {
5326 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5331 MulOps.push_back(getSCEV(BO->RHS));
5332 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5333 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5334 MulOps.push_back(getSCEV(BO->LHS));
5340 return getMulExpr(MulOps);
5342 case Instruction::UDiv:
5343 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5344 case Instruction::Sub: {
5345 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5347 Flags = getNoWrapFlagsFromUB(BO->Op);
5348 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5350 case Instruction::And:
5351 // For an expression like x&255 that merely masks off the high bits,
5352 // use zext(trunc(x)) as the SCEV expression.
5353 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5354 if (CI->isNullValue())
5355 return getSCEV(BO->RHS);
5356 if (CI->isAllOnesValue())
5357 return getSCEV(BO->LHS);
5358 const APInt &A = CI->getValue();
5360 // Instcombine's ShrinkDemandedConstant may strip bits out of
5361 // constants, obscuring what would otherwise be a low-bits mask.
5362 // Use computeKnownBits to compute what ShrinkDemandedConstant
5363 // knew about to reconstruct a low-bits mask value.
5364 unsigned LZ = A.countLeadingZeros();
5365 unsigned TZ = A.countTrailingZeros();
5366 unsigned BitWidth = A.getBitWidth();
5367 KnownBits Known(BitWidth);
5368 computeKnownBits(BO->LHS, Known, getDataLayout(),
5369 0, &AC, nullptr, &DT);
5371 APInt EffectiveMask =
5372 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5373 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5374 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5375 const SCEV *LHS = getSCEV(BO->LHS);
5376 const SCEV *ShiftedLHS = nullptr;
5377 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5378 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5379 // For an expression like (x * 8) & 8, simplify the multiply.
5380 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5381 unsigned GCD = std::min(MulZeros, TZ);
5382 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5383 SmallVector<const SCEV*, 4> MulOps;
5384 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5385 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5386 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5387 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5391 ShiftedLHS = getUDivExpr(LHS, MulCount);
5394 getTruncateExpr(ShiftedLHS,
5395 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5396 BO->LHS->getType()),
5402 case Instruction::Or:
5403 // If the RHS of the Or is a constant, we may have something like:
5404 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5405 // optimizations will transparently handle this case.
5407 // In order for this transformation to be safe, the LHS must be of the
5408 // form X*(2^n) and the Or constant must be less than 2^n.
5409 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5410 const SCEV *LHS = getSCEV(BO->LHS);
5411 const APInt &CIVal = CI->getValue();
5412 if (GetMinTrailingZeros(LHS) >=
5413 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5414 // Build a plain add SCEV.
5415 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5416 // If the LHS of the add was an addrec and it has no-wrap flags,
5417 // transfer the no-wrap flags, since an or won't introduce a wrap.
5418 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5419 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5420 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5421 OldAR->getNoWrapFlags());
5428 case Instruction::Xor:
5429 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5430 // If the RHS of xor is -1, then this is a not operation.
5431 if (CI->isAllOnesValue())
5432 return getNotSCEV(getSCEV(BO->LHS));
5434 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5435 // This is a variant of the check for xor with -1, and it handles
5436 // the case where instcombine has trimmed non-demanded bits out
5437 // of an xor with -1.
5438 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5439 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5440 if (LBO->getOpcode() == Instruction::And &&
5441 LCI->getValue() == CI->getValue())
5442 if (const SCEVZeroExtendExpr *Z =
5443 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5444 Type *UTy = BO->LHS->getType();
5445 const SCEV *Z0 = Z->getOperand();
5446 Type *Z0Ty = Z0->getType();
5447 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5449 // If C is a low-bits mask, the zero extend is serving to
5450 // mask off the high bits. Complement the operand and
5451 // re-apply the zext.
5452 if (CI->getValue().isMask(Z0TySize))
5453 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5455 // If C is a single bit, it may be in the sign-bit position
5456 // before the zero-extend. In this case, represent the xor
5457 // using an add, which is equivalent, and re-apply the zext.
5458 APInt Trunc = CI->getValue().trunc(Z0TySize);
5459 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5461 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5467 case Instruction::Shl:
5468 // Turn shift left of a constant amount into a multiply.
5469 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5470 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5472 // If the shift count is not less than the bitwidth, the result of
5473 // the shift is undefined. Don't try to analyze it, because the
5474 // resolution chosen here may differ from the resolution chosen in
5475 // other parts of the compiler.
5476 if (SA->getValue().uge(BitWidth))
5479 // It is currently not resolved how to interpret NSW for left
5480 // shift by BitWidth - 1, so we avoid applying flags in that
5481 // case. Remove this check (or this comment) once the situation
5483 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5484 // and http://reviews.llvm.org/D8890 .
5485 auto Flags = SCEV::FlagAnyWrap;
5486 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5487 Flags = getNoWrapFlagsFromUB(BO->Op);
5489 Constant *X = ConstantInt::get(getContext(),
5490 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5491 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5495 case Instruction::AShr:
5496 // AShr X, C, where C is a constant.
5497 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5501 Type *OuterTy = BO->LHS->getType();
5502 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5503 // If the shift count is not less than the bitwidth, the result of
5504 // the shift is undefined. Don't try to analyze it, because the
5505 // resolution chosen here may differ from the resolution chosen in
5506 // other parts of the compiler.
5507 if (CI->getValue().uge(BitWidth))
5510 if (CI->isNullValue())
5511 return getSCEV(BO->LHS); // shift by zero --> noop
5513 uint64_t AShrAmt = CI->getZExtValue();
5514 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5516 Operator *L = dyn_cast<Operator>(BO->LHS);
5517 if (L && L->getOpcode() == Instruction::Shl) {
5520 // Both n and m are constant.
5522 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5523 if (L->getOperand(1) == BO->RHS)
5524 // For a two-shift sext-inreg, i.e. n = m,
5525 // use sext(trunc(x)) as the SCEV expression.
5526 return getSignExtendExpr(
5527 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5529 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5530 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5531 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5532 if (ShlAmt > AShrAmt) {
5533 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5534 // expression. We already checked that ShlAmt < BitWidth, so
5535 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5536 // ShlAmt - AShrAmt < Amt.
5537 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5539 return getSignExtendExpr(
5540 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5541 getConstant(Mul)), OuterTy);
5549 switch (U->getOpcode()) {
5550 case Instruction::Trunc:
5551 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5553 case Instruction::ZExt:
5554 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5556 case Instruction::SExt:
5557 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5559 case Instruction::BitCast:
5560 // BitCasts are no-op casts so we just eliminate the cast.
5561 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5562 return getSCEV(U->getOperand(0));
5565 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5566 // lead to pointer expressions which cannot safely be expanded to GEPs,
5567 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5568 // simplifying integer expressions.
5570 case Instruction::GetElementPtr:
5571 return createNodeForGEP(cast<GEPOperator>(U));
5573 case Instruction::PHI:
5574 return createNodeForPHI(cast<PHINode>(U));
5576 case Instruction::Select:
5577 // U can also be a select constant expr, which let fall through. Since
5578 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5579 // constant expressions cannot have instructions as operands, we'd have
5580 // returned getUnknown for a select constant expressions anyway.
5581 if (isa<Instruction>(U))
5582 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5583 U->getOperand(1), U->getOperand(2));
5586 case Instruction::Call:
5587 case Instruction::Invoke:
5588 if (Value *RV = CallSite(U).getReturnedArgOperand())
5593 return getUnknown(V);
5598 //===----------------------------------------------------------------------===//
5599 // Iteration Count Computation Code
5602 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5606 ConstantInt *ExitConst = ExitCount->getValue();
5608 // Guard against huge trip counts.
5609 if (ExitConst->getValue().getActiveBits() > 32)
5612 // In case of integer overflow, this returns 0, which is correct.
5613 return ((unsigned)ExitConst->getZExtValue()) + 1;
5616 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5617 if (BasicBlock *ExitingBB = L->getExitingBlock())
5618 return getSmallConstantTripCount(L, ExitingBB);
5620 // No trip count information for multiple exits.
5624 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5625 BasicBlock *ExitingBlock) {
5626 assert(ExitingBlock && "Must pass a non-null exiting block!");
5627 assert(L->isLoopExiting(ExitingBlock) &&
5628 "Exiting block must actually branch out of the loop!");
5629 const SCEVConstant *ExitCount =
5630 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5631 return getConstantTripCount(ExitCount);
5634 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5635 const auto *MaxExitCount =
5636 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5637 return getConstantTripCount(MaxExitCount);
5640 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5641 if (BasicBlock *ExitingBB = L->getExitingBlock())
5642 return getSmallConstantTripMultiple(L, ExitingBB);
5644 // No trip multiple information for multiple exits.
5648 /// Returns the largest constant divisor of the trip count of this loop as a
5649 /// normal unsigned value, if possible. This means that the actual trip count is
5650 /// always a multiple of the returned value (don't forget the trip count could
5651 /// very well be zero as well!).
5653 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5654 /// multiple of a constant (which is also the case if the trip count is simply
5655 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5656 /// if the trip count is very large (>= 2^32).
5658 /// As explained in the comments for getSmallConstantTripCount, this assumes
5659 /// that control exits the loop via ExitingBlock.
5661 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5662 BasicBlock *ExitingBlock) {
5663 assert(ExitingBlock && "Must pass a non-null exiting block!");
5664 assert(L->isLoopExiting(ExitingBlock) &&
5665 "Exiting block must actually branch out of the loop!");
5666 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5667 if (ExitCount == getCouldNotCompute())
5670 // Get the trip count from the BE count by adding 1.
5671 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5673 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5675 // Attempt to factor more general cases. Returns the greatest power of
5676 // two divisor. If overflow happens, the trip count expression is still
5677 // divisible by the greatest power of 2 divisor returned.
5678 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5680 ConstantInt *Result = TC->getValue();
5682 // Guard against huge trip counts (this requires checking
5683 // for zero to handle the case where the trip count == -1 and the
5685 if (!Result || Result->getValue().getActiveBits() > 32 ||
5686 Result->getValue().getActiveBits() == 0)
5689 return (unsigned)Result->getZExtValue();
5692 /// Get the expression for the number of loop iterations for which this loop is
5693 /// guaranteed not to exit via ExitingBlock. Otherwise return
5694 /// SCEVCouldNotCompute.
5695 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5696 BasicBlock *ExitingBlock) {
5697 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5701 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5702 SCEVUnionPredicate &Preds) {
5703 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5706 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5707 return getBackedgeTakenInfo(L).getExact(this);
5710 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5711 /// known never to be less than the actual backedge taken count.
5712 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5713 return getBackedgeTakenInfo(L).getMax(this);
5716 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5717 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5720 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5722 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5723 BasicBlock *Header = L->getHeader();
5725 // Push all Loop-header PHIs onto the Worklist stack.
5726 for (BasicBlock::iterator I = Header->begin();
5727 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5728 Worklist.push_back(PN);
5731 const ScalarEvolution::BackedgeTakenInfo &
5732 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5733 auto &BTI = getBackedgeTakenInfo(L);
5734 if (BTI.hasFullInfo())
5737 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5740 return Pair.first->second;
5742 BackedgeTakenInfo Result =
5743 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5745 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5748 const ScalarEvolution::BackedgeTakenInfo &
5749 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5750 // Initially insert an invalid entry for this loop. If the insertion
5751 // succeeds, proceed to actually compute a backedge-taken count and
5752 // update the value. The temporary CouldNotCompute value tells SCEV
5753 // code elsewhere that it shouldn't attempt to request a new
5754 // backedge-taken count, which could result in infinite recursion.
5755 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5756 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5758 return Pair.first->second;
5760 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5761 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5762 // must be cleared in this scope.
5763 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5765 if (Result.getExact(this) != getCouldNotCompute()) {
5766 assert(isLoopInvariant(Result.getExact(this), L) &&
5767 isLoopInvariant(Result.getMax(this), L) &&
5768 "Computed backedge-taken count isn't loop invariant for loop!");
5769 ++NumTripCountsComputed;
5771 else if (Result.getMax(this) == getCouldNotCompute() &&
5772 isa<PHINode>(L->getHeader()->begin())) {
5773 // Only count loops that have phi nodes as not being computable.
5774 ++NumTripCountsNotComputed;
5777 // Now that we know more about the trip count for this loop, forget any
5778 // existing SCEV values for PHI nodes in this loop since they are only
5779 // conservative estimates made without the benefit of trip count
5780 // information. This is similar to the code in forgetLoop, except that
5781 // it handles SCEVUnknown PHI nodes specially.
5782 if (Result.hasAnyInfo()) {
5783 SmallVector<Instruction *, 16> Worklist;
5784 PushLoopPHIs(L, Worklist);
5786 SmallPtrSet<Instruction *, 8> Visited;
5787 while (!Worklist.empty()) {
5788 Instruction *I = Worklist.pop_back_val();
5789 if (!Visited.insert(I).second)
5792 ValueExprMapType::iterator It =
5793 ValueExprMap.find_as(static_cast<Value *>(I));
5794 if (It != ValueExprMap.end()) {
5795 const SCEV *Old = It->second;
5797 // SCEVUnknown for a PHI either means that it has an unrecognized
5798 // structure, or it's a PHI that's in the progress of being computed
5799 // by createNodeForPHI. In the former case, additional loop trip
5800 // count information isn't going to change anything. In the later
5801 // case, createNodeForPHI will perform the necessary updates on its
5802 // own when it gets to that point.
5803 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5804 eraseValueFromMap(It->first);
5805 forgetMemoizedResults(Old);
5807 if (PHINode *PN = dyn_cast<PHINode>(I))
5808 ConstantEvolutionLoopExitValue.erase(PN);
5811 PushDefUseChildren(I, Worklist);
5815 // Re-lookup the insert position, since the call to
5816 // computeBackedgeTakenCount above could result in a
5817 // recusive call to getBackedgeTakenInfo (on a different
5818 // loop), which would invalidate the iterator computed
5820 return BackedgeTakenCounts.find(L)->second = std::move(Result);
5823 void ScalarEvolution::forgetLoop(const Loop *L) {
5824 // Drop any stored trip count value.
5825 auto RemoveLoopFromBackedgeMap =
5826 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5827 auto BTCPos = Map.find(L);
5828 if (BTCPos != Map.end()) {
5829 BTCPos->second.clear();
5834 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5835 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5837 // Drop information about expressions based on loop-header PHIs.
5838 SmallVector<Instruction *, 16> Worklist;
5839 PushLoopPHIs(L, Worklist);
5841 SmallPtrSet<Instruction *, 8> Visited;
5842 while (!Worklist.empty()) {
5843 Instruction *I = Worklist.pop_back_val();
5844 if (!Visited.insert(I).second)
5847 ValueExprMapType::iterator It =
5848 ValueExprMap.find_as(static_cast<Value *>(I));
5849 if (It != ValueExprMap.end()) {
5850 eraseValueFromMap(It->first);
5851 forgetMemoizedResults(It->second);
5852 if (PHINode *PN = dyn_cast<PHINode>(I))
5853 ConstantEvolutionLoopExitValue.erase(PN);
5856 PushDefUseChildren(I, Worklist);
5859 // Forget all contained loops too, to avoid dangling entries in the
5860 // ValuesAtScopes map.
5864 LoopPropertiesCache.erase(L);
5867 void ScalarEvolution::forgetValue(Value *V) {
5868 Instruction *I = dyn_cast<Instruction>(V);
5871 // Drop information about expressions based on loop-header PHIs.
5872 SmallVector<Instruction *, 16> Worklist;
5873 Worklist.push_back(I);
5875 SmallPtrSet<Instruction *, 8> Visited;
5876 while (!Worklist.empty()) {
5877 I = Worklist.pop_back_val();
5878 if (!Visited.insert(I).second)
5881 ValueExprMapType::iterator It =
5882 ValueExprMap.find_as(static_cast<Value *>(I));
5883 if (It != ValueExprMap.end()) {
5884 eraseValueFromMap(It->first);
5885 forgetMemoizedResults(It->second);
5886 if (PHINode *PN = dyn_cast<PHINode>(I))
5887 ConstantEvolutionLoopExitValue.erase(PN);
5890 PushDefUseChildren(I, Worklist);
5894 /// Get the exact loop backedge taken count considering all loop exits. A
5895 /// computable result can only be returned for loops with a single exit.
5896 /// Returning the minimum taken count among all exits is incorrect because one
5897 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5898 /// the limit of each loop test is never skipped. This is a valid assumption as
5899 /// long as the loop exits via that test. For precise results, it is the
5900 /// caller's responsibility to specify the relevant loop exit using
5901 /// getExact(ExitingBlock, SE).
5903 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5904 SCEVUnionPredicate *Preds) const {
5905 // If any exits were not computable, the loop is not computable.
5906 if (!isComplete() || ExitNotTaken.empty())
5907 return SE->getCouldNotCompute();
5909 const SCEV *BECount = nullptr;
5910 for (auto &ENT : ExitNotTaken) {
5911 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5914 BECount = ENT.ExactNotTaken;
5915 else if (BECount != ENT.ExactNotTaken)
5916 return SE->getCouldNotCompute();
5917 if (Preds && !ENT.hasAlwaysTruePredicate())
5918 Preds->add(ENT.Predicate.get());
5920 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5921 "Predicate should be always true!");
5924 assert(BECount && "Invalid not taken count for loop exit");
5928 /// Get the exact not taken count for this loop exit.
5930 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5931 ScalarEvolution *SE) const {
5932 for (auto &ENT : ExitNotTaken)
5933 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5934 return ENT.ExactNotTaken;
5936 return SE->getCouldNotCompute();
5939 /// getMax - Get the max backedge taken count for the loop.
5941 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5942 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5943 return !ENT.hasAlwaysTruePredicate();
5946 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5947 return SE->getCouldNotCompute();
5952 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5953 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5954 return !ENT.hasAlwaysTruePredicate();
5956 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5959 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5960 ScalarEvolution *SE) const {
5961 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5962 SE->hasOperand(getMax(), S))
5965 for (auto &ENT : ExitNotTaken)
5966 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5967 SE->hasOperand(ENT.ExactNotTaken, S))
5973 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
5974 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {}
5976 ScalarEvolution::ExitLimit::ExitLimit(
5977 const SCEV *E, const SCEV *M, bool MaxOrZero,
5978 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
5979 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
5980 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
5981 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
5982 "Exact is not allowed to be less precise than Max");
5983 for (auto *PredSet : PredSetList)
5984 for (auto *P : *PredSet)
5988 ScalarEvolution::ExitLimit::ExitLimit(
5989 const SCEV *E, const SCEV *M, bool MaxOrZero,
5990 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
5991 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {}
5993 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
5995 : ExitLimit(E, M, MaxOrZero, None) {}
5997 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5998 /// computable exit into a persistent ExitNotTakenInfo array.
5999 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6000 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6002 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6003 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6004 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6005 ExitNotTaken.reserve(ExitCounts.size());
6007 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6008 [&](const EdgeExitInfo &EEI) {
6009 BasicBlock *ExitBB = EEI.first;
6010 const ExitLimit &EL = EEI.second;
6011 if (EL.Predicates.empty())
6012 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6014 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6015 for (auto *Pred : EL.Predicates)
6016 Predicate->add(Pred);
6018 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6022 /// Invalidate this result and free the ExitNotTakenInfo array.
6023 void ScalarEvolution::BackedgeTakenInfo::clear() {
6024 ExitNotTaken.clear();
6027 /// Compute the number of times the backedge of the specified loop will execute.
6028 ScalarEvolution::BackedgeTakenInfo
6029 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6030 bool AllowPredicates) {
6031 SmallVector<BasicBlock *, 8> ExitingBlocks;
6032 L->getExitingBlocks(ExitingBlocks);
6034 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6036 SmallVector<EdgeExitInfo, 4> ExitCounts;
6037 bool CouldComputeBECount = true;
6038 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6039 const SCEV *MustExitMaxBECount = nullptr;
6040 const SCEV *MayExitMaxBECount = nullptr;
6041 bool MustExitMaxOrZero = false;
6043 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6044 // and compute maxBECount.
6045 // Do a union of all the predicates here.
6046 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6047 BasicBlock *ExitBB = ExitingBlocks[i];
6048 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6050 assert((AllowPredicates || EL.Predicates.empty()) &&
6051 "Predicated exit limit when predicates are not allowed!");
6053 // 1. For each exit that can be computed, add an entry to ExitCounts.
6054 // CouldComputeBECount is true only if all exits can be computed.
6055 if (EL.ExactNotTaken == getCouldNotCompute())
6056 // We couldn't compute an exact value for this exit, so
6057 // we won't be able to compute an exact value for the loop.
6058 CouldComputeBECount = false;
6060 ExitCounts.emplace_back(ExitBB, EL);
6062 // 2. Derive the loop's MaxBECount from each exit's max number of
6063 // non-exiting iterations. Partition the loop exits into two kinds:
6064 // LoopMustExits and LoopMayExits.
6066 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6067 // is a LoopMayExit. If any computable LoopMustExit is found, then
6068 // MaxBECount is the minimum EL.MaxNotTaken of computable
6069 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6070 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6071 // computable EL.MaxNotTaken.
6072 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6073 DT.dominates(ExitBB, Latch)) {
6074 if (!MustExitMaxBECount) {
6075 MustExitMaxBECount = EL.MaxNotTaken;
6076 MustExitMaxOrZero = EL.MaxOrZero;
6078 MustExitMaxBECount =
6079 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6081 } else if (MayExitMaxBECount != getCouldNotCompute()) {
6082 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6083 MayExitMaxBECount = EL.MaxNotTaken;
6086 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6090 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6091 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6092 // The loop backedge will be taken the maximum or zero times if there's
6093 // a single exit that must be taken the maximum or zero times.
6094 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6095 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6096 MaxBECount, MaxOrZero);
6099 ScalarEvolution::ExitLimit
6100 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6101 bool AllowPredicates) {
6103 // Okay, we've chosen an exiting block. See what condition causes us to exit
6104 // at this block and remember the exit block and whether all other targets
6105 // lead to the loop header.
6106 bool MustExecuteLoopHeader = true;
6107 BasicBlock *Exit = nullptr;
6108 for (auto *SBB : successors(ExitingBlock))
6109 if (!L->contains(SBB)) {
6110 if (Exit) // Multiple exit successors.
6111 return getCouldNotCompute();
6113 } else if (SBB != L->getHeader()) {
6114 MustExecuteLoopHeader = false;
6117 // At this point, we know we have a conditional branch that determines whether
6118 // the loop is exited. However, we don't know if the branch is executed each
6119 // time through the loop. If not, then the execution count of the branch will
6120 // not be equal to the trip count of the loop.
6122 // Currently we check for this by checking to see if the Exit branch goes to
6123 // the loop header. If so, we know it will always execute the same number of
6124 // times as the loop. We also handle the case where the exit block *is* the
6125 // loop header. This is common for un-rotated loops.
6127 // If both of those tests fail, walk up the unique predecessor chain to the
6128 // header, stopping if there is an edge that doesn't exit the loop. If the
6129 // header is reached, the execution count of the branch will be equal to the
6130 // trip count of the loop.
6132 // More extensive analysis could be done to handle more cases here.
6134 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6135 // The simple checks failed, try climbing the unique predecessor chain
6136 // up to the header.
6138 for (BasicBlock *BB = ExitingBlock; BB; ) {
6139 BasicBlock *Pred = BB->getUniquePredecessor();
6141 return getCouldNotCompute();
6142 TerminatorInst *PredTerm = Pred->getTerminator();
6143 for (const BasicBlock *PredSucc : PredTerm->successors()) {
6146 // If the predecessor has a successor that isn't BB and isn't
6147 // outside the loop, assume the worst.
6148 if (L->contains(PredSucc))
6149 return getCouldNotCompute();
6151 if (Pred == L->getHeader()) {
6158 return getCouldNotCompute();
6161 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6162 TerminatorInst *Term = ExitingBlock->getTerminator();
6163 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6164 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6165 // Proceed to the next level to examine the exit condition expression.
6166 return computeExitLimitFromCond(
6167 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6168 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6171 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6172 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6173 /*ControlsExit=*/IsOnlyExit);
6175 return getCouldNotCompute();
6178 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6179 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6180 bool ControlsExit, bool AllowPredicates) {
6181 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6182 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6183 ControlsExit, AllowPredicates);
6186 Optional<ScalarEvolution::ExitLimit>
6187 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6188 BasicBlock *TBB, BasicBlock *FBB,
6189 bool ControlsExit, bool AllowPredicates) {
6193 (void)this->AllowPredicates;
6195 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6196 this->AllowPredicates == AllowPredicates &&
6197 "Variance in assumed invariant key components!");
6198 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6199 if (Itr == TripCountMap.end())
6204 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6205 BasicBlock *TBB, BasicBlock *FBB,
6207 bool AllowPredicates,
6208 const ExitLimit &EL) {
6209 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6210 this->AllowPredicates == AllowPredicates &&
6211 "Variance in assumed invariant key components!");
6213 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6214 assert(InsertResult.second && "Expected successful insertion!");
6218 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6219 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6220 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6223 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6226 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6227 ControlsExit, AllowPredicates);
6228 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6232 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6233 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6234 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6235 // Check if the controlling expression for this loop is an And or Or.
6236 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6237 if (BO->getOpcode() == Instruction::And) {
6238 // Recurse on the operands of the and.
6239 bool EitherMayExit = L->contains(TBB);
6240 ExitLimit EL0 = computeExitLimitFromCondCached(
6241 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6243 ExitLimit EL1 = computeExitLimitFromCondCached(
6244 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6246 const SCEV *BECount = getCouldNotCompute();
6247 const SCEV *MaxBECount = getCouldNotCompute();
6248 if (EitherMayExit) {
6249 // Both conditions must be true for the loop to continue executing.
6250 // Choose the less conservative count.
6251 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6252 EL1.ExactNotTaken == getCouldNotCompute())
6253 BECount = getCouldNotCompute();
6256 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6257 if (EL0.MaxNotTaken == getCouldNotCompute())
6258 MaxBECount = EL1.MaxNotTaken;
6259 else if (EL1.MaxNotTaken == getCouldNotCompute())
6260 MaxBECount = EL0.MaxNotTaken;
6263 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6265 // Both conditions must be true at the same time for the loop to exit.
6266 // For now, be conservative.
6267 assert(L->contains(FBB) && "Loop block has no successor in loop!");
6268 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6269 MaxBECount = EL0.MaxNotTaken;
6270 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6271 BECount = EL0.ExactNotTaken;
6274 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6275 // to be more aggressive when computing BECount than when computing
6276 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6277 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6279 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6280 !isa<SCEVCouldNotCompute>(BECount))
6281 MaxBECount = BECount;
6283 return ExitLimit(BECount, MaxBECount, false,
6284 {&EL0.Predicates, &EL1.Predicates});
6286 if (BO->getOpcode() == Instruction::Or) {
6287 // Recurse on the operands of the or.
6288 bool EitherMayExit = L->contains(FBB);
6289 ExitLimit EL0 = computeExitLimitFromCondCached(
6290 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6292 ExitLimit EL1 = computeExitLimitFromCondCached(
6293 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6295 const SCEV *BECount = getCouldNotCompute();
6296 const SCEV *MaxBECount = getCouldNotCompute();
6297 if (EitherMayExit) {
6298 // Both conditions must be false for the loop to continue executing.
6299 // Choose the less conservative count.
6300 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6301 EL1.ExactNotTaken == getCouldNotCompute())
6302 BECount = getCouldNotCompute();
6305 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6306 if (EL0.MaxNotTaken == getCouldNotCompute())
6307 MaxBECount = EL1.MaxNotTaken;
6308 else if (EL1.MaxNotTaken == getCouldNotCompute())
6309 MaxBECount = EL0.MaxNotTaken;
6312 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6314 // Both conditions must be false at the same time for the loop to exit.
6315 // For now, be conservative.
6316 assert(L->contains(TBB) && "Loop block has no successor in loop!");
6317 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6318 MaxBECount = EL0.MaxNotTaken;
6319 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6320 BECount = EL0.ExactNotTaken;
6323 return ExitLimit(BECount, MaxBECount, false,
6324 {&EL0.Predicates, &EL1.Predicates});
6328 // With an icmp, it may be feasible to compute an exact backedge-taken count.
6329 // Proceed to the next level to examine the icmp.
6330 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6332 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6333 if (EL.hasFullInfo() || !AllowPredicates)
6336 // Try again, but use SCEV predicates this time.
6337 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6338 /*AllowPredicates=*/true);
6341 // Check for a constant condition. These are normally stripped out by
6342 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6343 // preserve the CFG and is temporarily leaving constant conditions
6345 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6346 if (L->contains(FBB) == !CI->getZExtValue())
6347 // The backedge is always taken.
6348 return getCouldNotCompute();
6350 // The backedge is never taken.
6351 return getZero(CI->getType());
6354 // If it's not an integer or pointer comparison then compute it the hard way.
6355 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6358 ScalarEvolution::ExitLimit
6359 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6364 bool AllowPredicates) {
6366 // If the condition was exit on true, convert the condition to exit on false
6367 ICmpInst::Predicate Cond;
6368 if (!L->contains(FBB))
6369 Cond = ExitCond->getPredicate();
6371 Cond = ExitCond->getInversePredicate();
6373 // Handle common loops like: for (X = "string"; *X; ++X)
6374 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6375 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6377 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6378 if (ItCnt.hasAnyInfo())
6382 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6383 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6385 // Try to evaluate any dependencies out of the loop.
6386 LHS = getSCEVAtScope(LHS, L);
6387 RHS = getSCEVAtScope(RHS, L);
6389 // At this point, we would like to compute how many iterations of the
6390 // loop the predicate will return true for these inputs.
6391 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6392 // If there is a loop-invariant, force it into the RHS.
6393 std::swap(LHS, RHS);
6394 Cond = ICmpInst::getSwappedPredicate(Cond);
6397 // Simplify the operands before analyzing them.
6398 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6400 // If we have a comparison of a chrec against a constant, try to use value
6401 // ranges to answer this query.
6402 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6403 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6404 if (AddRec->getLoop() == L) {
6405 // Form the constant range.
6406 ConstantRange CompRange =
6407 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6409 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6410 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6414 case ICmpInst::ICMP_NE: { // while (X != Y)
6415 // Convert to: while (X-Y != 0)
6416 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6418 if (EL.hasAnyInfo()) return EL;
6421 case ICmpInst::ICMP_EQ: { // while (X == Y)
6422 // Convert to: while (X-Y == 0)
6423 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6424 if (EL.hasAnyInfo()) return EL;
6427 case ICmpInst::ICMP_SLT:
6428 case ICmpInst::ICMP_ULT: { // while (X < Y)
6429 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6430 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6432 if (EL.hasAnyInfo()) return EL;
6435 case ICmpInst::ICMP_SGT:
6436 case ICmpInst::ICMP_UGT: { // while (X > Y)
6437 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6439 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6441 if (EL.hasAnyInfo()) return EL;
6448 auto *ExhaustiveCount =
6449 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6451 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6452 return ExhaustiveCount;
6454 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6455 ExitCond->getOperand(1), L, Cond);
6458 ScalarEvolution::ExitLimit
6459 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6461 BasicBlock *ExitingBlock,
6462 bool ControlsExit) {
6463 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6465 // Give up if the exit is the default dest of a switch.
6466 if (Switch->getDefaultDest() == ExitingBlock)
6467 return getCouldNotCompute();
6469 assert(L->contains(Switch->getDefaultDest()) &&
6470 "Default case must not exit the loop!");
6471 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6472 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6474 // while (X != Y) --> while (X-Y != 0)
6475 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6476 if (EL.hasAnyInfo())
6479 return getCouldNotCompute();
6482 static ConstantInt *
6483 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6484 ScalarEvolution &SE) {
6485 const SCEV *InVal = SE.getConstant(C);
6486 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6487 assert(isa<SCEVConstant>(Val) &&
6488 "Evaluation of SCEV at constant didn't fold correctly?");
6489 return cast<SCEVConstant>(Val)->getValue();
6492 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6493 /// compute the backedge execution count.
6494 ScalarEvolution::ExitLimit
6495 ScalarEvolution::computeLoadConstantCompareExitLimit(
6499 ICmpInst::Predicate predicate) {
6501 if (LI->isVolatile()) return getCouldNotCompute();
6503 // Check to see if the loaded pointer is a getelementptr of a global.
6504 // TODO: Use SCEV instead of manually grubbing with GEPs.
6505 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6506 if (!GEP) return getCouldNotCompute();
6508 // Make sure that it is really a constant global we are gepping, with an
6509 // initializer, and make sure the first IDX is really 0.
6510 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6511 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6512 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6513 !cast<Constant>(GEP->getOperand(1))->isNullValue())
6514 return getCouldNotCompute();
6516 // Okay, we allow one non-constant index into the GEP instruction.
6517 Value *VarIdx = nullptr;
6518 std::vector<Constant*> Indexes;
6519 unsigned VarIdxNum = 0;
6520 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6521 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6522 Indexes.push_back(CI);
6523 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6524 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
6525 VarIdx = GEP->getOperand(i);
6527 Indexes.push_back(nullptr);
6530 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6532 return getCouldNotCompute();
6534 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6535 // Check to see if X is a loop variant variable value now.
6536 const SCEV *Idx = getSCEV(VarIdx);
6537 Idx = getSCEVAtScope(Idx, L);
6539 // We can only recognize very limited forms of loop index expressions, in
6540 // particular, only affine AddRec's like {C1,+,C2}.
6541 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6542 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6543 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6544 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6545 return getCouldNotCompute();
6547 unsigned MaxSteps = MaxBruteForceIterations;
6548 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6549 ConstantInt *ItCst = ConstantInt::get(
6550 cast<IntegerType>(IdxExpr->getType()), IterationNum);
6551 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6553 // Form the GEP offset.
6554 Indexes[VarIdxNum] = Val;
6556 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6558 if (!Result) break; // Cannot compute!
6560 // Evaluate the condition for this iteration.
6561 Result = ConstantExpr::getICmp(predicate, Result, RHS);
6562 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
6563 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6564 ++NumArrayLenItCounts;
6565 return getConstant(ItCst); // Found terminating iteration!
6568 return getCouldNotCompute();
6571 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6572 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6573 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6575 return getCouldNotCompute();
6577 const BasicBlock *Latch = L->getLoopLatch();
6579 return getCouldNotCompute();
6581 const BasicBlock *Predecessor = L->getLoopPredecessor();
6583 return getCouldNotCompute();
6585 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6586 // Return LHS in OutLHS and shift_opt in OutOpCode.
6587 auto MatchPositiveShift =
6588 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6590 using namespace PatternMatch;
6592 ConstantInt *ShiftAmt;
6593 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6594 OutOpCode = Instruction::LShr;
6595 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6596 OutOpCode = Instruction::AShr;
6597 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6598 OutOpCode = Instruction::Shl;
6602 return ShiftAmt->getValue().isStrictlyPositive();
6605 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6608 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6609 // %iv.shifted = lshr i32 %iv, <positive constant>
6611 // Return true on a successful match. Return the corresponding PHI node (%iv
6612 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6613 auto MatchShiftRecurrence =
6614 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6615 Optional<Instruction::BinaryOps> PostShiftOpCode;
6618 Instruction::BinaryOps OpC;
6621 // If we encounter a shift instruction, "peel off" the shift operation,
6622 // and remember that we did so. Later when we inspect %iv's backedge
6623 // value, we will make sure that the backedge value uses the same
6626 // Note: the peeled shift operation does not have to be the same
6627 // instruction as the one feeding into the PHI's backedge value. We only
6628 // really care about it being the same *kind* of shift instruction --
6629 // that's all that is required for our later inferences to hold.
6630 if (MatchPositiveShift(LHS, V, OpC)) {
6631 PostShiftOpCode = OpC;
6636 PNOut = dyn_cast<PHINode>(LHS);
6637 if (!PNOut || PNOut->getParent() != L->getHeader())
6640 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6644 // The backedge value for the PHI node must be a shift by a positive
6646 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6648 // of the PHI node itself
6651 // and the kind of shift should be match the kind of shift we peeled
6653 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6657 Instruction::BinaryOps OpCode;
6658 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6659 return getCouldNotCompute();
6661 const DataLayout &DL = getDataLayout();
6663 // The key rationale for this optimization is that for some kinds of shift
6664 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6665 // within a finite number of iterations. If the condition guarding the
6666 // backedge (in the sense that the backedge is taken if the condition is true)
6667 // is false for the value the shift recurrence stabilizes to, then we know
6668 // that the backedge is taken only a finite number of times.
6670 ConstantInt *StableValue = nullptr;
6673 llvm_unreachable("Impossible case!");
6675 case Instruction::AShr: {
6676 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6677 // bitwidth(K) iterations.
6678 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6679 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
6680 Predecessor->getTerminator(), &DT);
6681 auto *Ty = cast<IntegerType>(RHS->getType());
6682 if (Known.isNonNegative())
6683 StableValue = ConstantInt::get(Ty, 0);
6684 else if (Known.isNegative())
6685 StableValue = ConstantInt::get(Ty, -1, true);
6687 return getCouldNotCompute();
6691 case Instruction::LShr:
6692 case Instruction::Shl:
6693 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6694 // stabilize to 0 in at most bitwidth(K) iterations.
6695 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6700 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6701 assert(Result->getType()->isIntegerTy(1) &&
6702 "Otherwise cannot be an operand to a branch instruction");
6704 if (Result->isZeroValue()) {
6705 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6706 const SCEV *UpperBound =
6707 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6708 return ExitLimit(getCouldNotCompute(), UpperBound, false);
6711 return getCouldNotCompute();
6714 /// Return true if we can constant fold an instruction of the specified type,
6715 /// assuming that all operands were constants.
6716 static bool CanConstantFold(const Instruction *I) {
6717 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6718 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6722 if (const CallInst *CI = dyn_cast<CallInst>(I))
6723 if (const Function *F = CI->getCalledFunction())
6724 return canConstantFoldCallTo(F);
6728 /// Determine whether this instruction can constant evolve within this loop
6729 /// assuming its operands can all constant evolve.
6730 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6731 // An instruction outside of the loop can't be derived from a loop PHI.
6732 if (!L->contains(I)) return false;
6734 if (isa<PHINode>(I)) {
6735 // We don't currently keep track of the control flow needed to evaluate
6736 // PHIs, so we cannot handle PHIs inside of loops.
6737 return L->getHeader() == I->getParent();
6740 // If we won't be able to constant fold this expression even if the operands
6741 // are constants, bail early.
6742 return CanConstantFold(I);
6745 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6746 /// recursing through each instruction operand until reaching a loop header phi.
6748 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6749 DenseMap<Instruction *, PHINode *> &PHIMap,
6751 if (Depth > MaxConstantEvolvingDepth)
6754 // Otherwise, we can evaluate this instruction if all of its operands are
6755 // constant or derived from a PHI node themselves.
6756 PHINode *PHI = nullptr;
6757 for (Value *Op : UseInst->operands()) {
6758 if (isa<Constant>(Op)) continue;
6760 Instruction *OpInst = dyn_cast<Instruction>(Op);
6761 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6763 PHINode *P = dyn_cast<PHINode>(OpInst);
6765 // If this operand is already visited, reuse the prior result.
6766 // We may have P != PHI if this is the deepest point at which the
6767 // inconsistent paths meet.
6768 P = PHIMap.lookup(OpInst);
6770 // Recurse and memoize the results, whether a phi is found or not.
6771 // This recursive call invalidates pointers into PHIMap.
6772 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6776 return nullptr; // Not evolving from PHI
6777 if (PHI && PHI != P)
6778 return nullptr; // Evolving from multiple different PHIs.
6781 // This is a expression evolving from a constant PHI!
6785 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6786 /// in the loop that V is derived from. We allow arbitrary operations along the
6787 /// way, but the operands of an operation must either be constants or a value
6788 /// derived from a constant PHI. If this expression does not fit with these
6789 /// constraints, return null.
6790 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6791 Instruction *I = dyn_cast<Instruction>(V);
6792 if (!I || !canConstantEvolve(I, L)) return nullptr;
6794 if (PHINode *PN = dyn_cast<PHINode>(I))
6797 // Record non-constant instructions contained by the loop.
6798 DenseMap<Instruction *, PHINode *> PHIMap;
6799 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6802 /// EvaluateExpression - Given an expression that passes the
6803 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6804 /// in the loop has the value PHIVal. If we can't fold this expression for some
6805 /// reason, return null.
6806 static Constant *EvaluateExpression(Value *V, const Loop *L,
6807 DenseMap<Instruction *, Constant *> &Vals,
6808 const DataLayout &DL,
6809 const TargetLibraryInfo *TLI) {
6810 // Convenient constant check, but redundant for recursive calls.
6811 if (Constant *C = dyn_cast<Constant>(V)) return C;
6812 Instruction *I = dyn_cast<Instruction>(V);
6813 if (!I) return nullptr;
6815 if (Constant *C = Vals.lookup(I)) return C;
6817 // An instruction inside the loop depends on a value outside the loop that we
6818 // weren't given a mapping for, or a value such as a call inside the loop.
6819 if (!canConstantEvolve(I, L)) return nullptr;
6821 // An unmapped PHI can be due to a branch or another loop inside this loop,
6822 // or due to this not being the initial iteration through a loop where we
6823 // couldn't compute the evolution of this particular PHI last time.
6824 if (isa<PHINode>(I)) return nullptr;
6826 std::vector<Constant*> Operands(I->getNumOperands());
6828 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6829 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6831 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6832 if (!Operands[i]) return nullptr;
6835 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6837 if (!C) return nullptr;
6841 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6842 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6843 Operands[1], DL, TLI);
6844 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6845 if (!LI->isVolatile())
6846 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6848 return ConstantFoldInstOperands(I, Operands, DL, TLI);
6852 // If every incoming value to PN except the one for BB is a specific Constant,
6853 // return that, else return nullptr.
6854 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6855 Constant *IncomingVal = nullptr;
6857 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6858 if (PN->getIncomingBlock(i) == BB)
6861 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6865 if (IncomingVal != CurrentVal) {
6868 IncomingVal = CurrentVal;
6875 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6876 /// in the header of its containing loop, we know the loop executes a
6877 /// constant number of times, and the PHI node is just a recurrence
6878 /// involving constants, fold it.
6880 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6883 auto I = ConstantEvolutionLoopExitValue.find(PN);
6884 if (I != ConstantEvolutionLoopExitValue.end())
6887 if (BEs.ugt(MaxBruteForceIterations))
6888 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
6890 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6892 DenseMap<Instruction *, Constant *> CurrentIterVals;
6893 BasicBlock *Header = L->getHeader();
6894 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6896 BasicBlock *Latch = L->getLoopLatch();
6900 for (auto &I : *Header) {
6901 PHINode *PHI = dyn_cast<PHINode>(&I);
6903 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6904 if (!StartCST) continue;
6905 CurrentIterVals[PHI] = StartCST;
6907 if (!CurrentIterVals.count(PN))
6908 return RetVal = nullptr;
6910 Value *BEValue = PN->getIncomingValueForBlock(Latch);
6912 // Execute the loop symbolically to determine the exit value.
6913 if (BEs.getActiveBits() >= 32)
6914 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6916 unsigned NumIterations = BEs.getZExtValue(); // must be in range
6917 unsigned IterationNum = 0;
6918 const DataLayout &DL = getDataLayout();
6919 for (; ; ++IterationNum) {
6920 if (IterationNum == NumIterations)
6921 return RetVal = CurrentIterVals[PN]; // Got exit value!
6923 // Compute the value of the PHIs for the next iteration.
6924 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6925 DenseMap<Instruction *, Constant *> NextIterVals;
6927 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6929 return nullptr; // Couldn't evaluate!
6930 NextIterVals[PN] = NextPHI;
6932 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6934 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6935 // cease to be able to evaluate one of them or if they stop evolving,
6936 // because that doesn't necessarily prevent us from computing PN.
6937 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6938 for (const auto &I : CurrentIterVals) {
6939 PHINode *PHI = dyn_cast<PHINode>(I.first);
6940 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6941 PHIsToCompute.emplace_back(PHI, I.second);
6943 // We use two distinct loops because EvaluateExpression may invalidate any
6944 // iterators into CurrentIterVals.
6945 for (const auto &I : PHIsToCompute) {
6946 PHINode *PHI = I.first;
6947 Constant *&NextPHI = NextIterVals[PHI];
6948 if (!NextPHI) { // Not already computed.
6949 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6950 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6952 if (NextPHI != I.second)
6953 StoppedEvolving = false;
6956 // If all entries in CurrentIterVals == NextIterVals then we can stop
6957 // iterating, the loop can't continue to change.
6958 if (StoppedEvolving)
6959 return RetVal = CurrentIterVals[PN];
6961 CurrentIterVals.swap(NextIterVals);
6965 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6968 PHINode *PN = getConstantEvolvingPHI(Cond, L);
6969 if (!PN) return getCouldNotCompute();
6971 // If the loop is canonicalized, the PHI will have exactly two entries.
6972 // That's the only form we support here.
6973 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6975 DenseMap<Instruction *, Constant *> CurrentIterVals;
6976 BasicBlock *Header = L->getHeader();
6977 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6979 BasicBlock *Latch = L->getLoopLatch();
6980 assert(Latch && "Should follow from NumIncomingValues == 2!");
6982 for (auto &I : *Header) {
6983 PHINode *PHI = dyn_cast<PHINode>(&I);
6986 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6987 if (!StartCST) continue;
6988 CurrentIterVals[PHI] = StartCST;
6990 if (!CurrentIterVals.count(PN))
6991 return getCouldNotCompute();
6993 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6994 // the loop symbolically to determine when the condition gets a value of
6996 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
6997 const DataLayout &DL = getDataLayout();
6998 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6999 auto *CondVal = dyn_cast_or_null<ConstantInt>(
7000 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7002 // Couldn't symbolically evaluate.
7003 if (!CondVal) return getCouldNotCompute();
7005 if (CondVal->getValue() == uint64_t(ExitWhen)) {
7006 ++NumBruteForceTripCountsComputed;
7007 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7010 // Update all the PHI nodes for the next iteration.
7011 DenseMap<Instruction *, Constant *> NextIterVals;
7013 // Create a list of which PHIs we need to compute. We want to do this before
7014 // calling EvaluateExpression on them because that may invalidate iterators
7015 // into CurrentIterVals.
7016 SmallVector<PHINode *, 8> PHIsToCompute;
7017 for (const auto &I : CurrentIterVals) {
7018 PHINode *PHI = dyn_cast<PHINode>(I.first);
7019 if (!PHI || PHI->getParent() != Header) continue;
7020 PHIsToCompute.push_back(PHI);
7022 for (PHINode *PHI : PHIsToCompute) {
7023 Constant *&NextPHI = NextIterVals[PHI];
7024 if (NextPHI) continue; // Already computed!
7026 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7027 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7029 CurrentIterVals.swap(NextIterVals);
7032 // Too many iterations were needed to evaluate.
7033 return getCouldNotCompute();
7036 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7037 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7039 // Check to see if we've folded this expression at this loop before.
7040 for (auto &LS : Values)
7042 return LS.second ? LS.second : V;
7044 Values.emplace_back(L, nullptr);
7046 // Otherwise compute it.
7047 const SCEV *C = computeSCEVAtScope(V, L);
7048 for (auto &LS : reverse(ValuesAtScopes[V]))
7049 if (LS.first == L) {
7056 /// This builds up a Constant using the ConstantExpr interface. That way, we
7057 /// will return Constants for objects which aren't represented by a
7058 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7059 /// Returns NULL if the SCEV isn't representable as a Constant.
7060 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7061 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7062 case scCouldNotCompute:
7066 return cast<SCEVConstant>(V)->getValue();
7068 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7069 case scSignExtend: {
7070 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7071 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7072 return ConstantExpr::getSExt(CastOp, SS->getType());
7075 case scZeroExtend: {
7076 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7077 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7078 return ConstantExpr::getZExt(CastOp, SZ->getType());
7082 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7083 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7084 return ConstantExpr::getTrunc(CastOp, ST->getType());
7088 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7089 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7090 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7091 unsigned AS = PTy->getAddressSpace();
7092 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7093 C = ConstantExpr::getBitCast(C, DestPtrTy);
7095 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7096 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7097 if (!C2) return nullptr;
7100 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7101 unsigned AS = C2->getType()->getPointerAddressSpace();
7103 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7104 // The offsets have been converted to bytes. We can add bytes to an
7105 // i8* by GEP with the byte count in the first index.
7106 C = ConstantExpr::getBitCast(C, DestPtrTy);
7109 // Don't bother trying to sum two pointers. We probably can't
7110 // statically compute a load that results from it anyway.
7111 if (C2->getType()->isPointerTy())
7114 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7115 if (PTy->getElementType()->isStructTy())
7116 C2 = ConstantExpr::getIntegerCast(
7117 C2, Type::getInt32Ty(C->getContext()), true);
7118 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7120 C = ConstantExpr::getAdd(C, C2);
7127 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7128 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7129 // Don't bother with pointers at all.
7130 if (C->getType()->isPointerTy()) return nullptr;
7131 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7132 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7133 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7134 C = ConstantExpr::getMul(C, C2);
7141 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7142 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7143 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7144 if (LHS->getType() == RHS->getType())
7145 return ConstantExpr::getUDiv(LHS, RHS);
7150 break; // TODO: smax, umax.
7155 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7156 if (isa<SCEVConstant>(V)) return V;
7158 // If this instruction is evolved from a constant-evolving PHI, compute the
7159 // exit value from the loop without using SCEVs.
7160 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7161 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7162 const Loop *LI = this->LI[I->getParent()];
7163 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
7164 if (PHINode *PN = dyn_cast<PHINode>(I))
7165 if (PN->getParent() == LI->getHeader()) {
7166 // Okay, there is no closed form solution for the PHI node. Check
7167 // to see if the loop that contains it has a known backedge-taken
7168 // count. If so, we may be able to force computation of the exit
7170 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7171 if (const SCEVConstant *BTCC =
7172 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7173 // Okay, we know how many times the containing loop executes. If
7174 // this is a constant evolving PHI node, get the final value at
7175 // the specified iteration number.
7177 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7178 if (RV) return getSCEV(RV);
7182 // Okay, this is an expression that we cannot symbolically evaluate
7183 // into a SCEV. Check to see if it's possible to symbolically evaluate
7184 // the arguments into constants, and if so, try to constant propagate the
7185 // result. This is particularly useful for computing loop exit values.
7186 if (CanConstantFold(I)) {
7187 SmallVector<Constant *, 4> Operands;
7188 bool MadeImprovement = false;
7189 for (Value *Op : I->operands()) {
7190 if (Constant *C = dyn_cast<Constant>(Op)) {
7191 Operands.push_back(C);
7195 // If any of the operands is non-constant and if they are
7196 // non-integer and non-pointer, don't even try to analyze them
7197 // with scev techniques.
7198 if (!isSCEVable(Op->getType()))
7201 const SCEV *OrigV = getSCEV(Op);
7202 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7203 MadeImprovement |= OrigV != OpV;
7205 Constant *C = BuildConstantFromSCEV(OpV);
7207 if (C->getType() != Op->getType())
7208 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7212 Operands.push_back(C);
7215 // Check to see if getSCEVAtScope actually made an improvement.
7216 if (MadeImprovement) {
7217 Constant *C = nullptr;
7218 const DataLayout &DL = getDataLayout();
7219 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7220 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7221 Operands[1], DL, &TLI);
7222 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7223 if (!LI->isVolatile())
7224 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7226 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7233 // This is some other type of SCEVUnknown, just return it.
7237 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7238 // Avoid performing the look-up in the common case where the specified
7239 // expression has no loop-variant portions.
7240 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7241 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7242 if (OpAtScope != Comm->getOperand(i)) {
7243 // Okay, at least one of these operands is loop variant but might be
7244 // foldable. Build a new instance of the folded commutative expression.
7245 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7246 Comm->op_begin()+i);
7247 NewOps.push_back(OpAtScope);
7249 for (++i; i != e; ++i) {
7250 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7251 NewOps.push_back(OpAtScope);
7253 if (isa<SCEVAddExpr>(Comm))
7254 return getAddExpr(NewOps);
7255 if (isa<SCEVMulExpr>(Comm))
7256 return getMulExpr(NewOps);
7257 if (isa<SCEVSMaxExpr>(Comm))
7258 return getSMaxExpr(NewOps);
7259 if (isa<SCEVUMaxExpr>(Comm))
7260 return getUMaxExpr(NewOps);
7261 llvm_unreachable("Unknown commutative SCEV type!");
7264 // If we got here, all operands are loop invariant.
7268 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7269 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7270 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7271 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7272 return Div; // must be loop invariant
7273 return getUDivExpr(LHS, RHS);
7276 // If this is a loop recurrence for a loop that does not contain L, then we
7277 // are dealing with the final value computed by the loop.
7278 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7279 // First, attempt to evaluate each operand.
7280 // Avoid performing the look-up in the common case where the specified
7281 // expression has no loop-variant portions.
7282 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7283 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7284 if (OpAtScope == AddRec->getOperand(i))
7287 // Okay, at least one of these operands is loop variant but might be
7288 // foldable. Build a new instance of the folded commutative expression.
7289 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7290 AddRec->op_begin()+i);
7291 NewOps.push_back(OpAtScope);
7292 for (++i; i != e; ++i)
7293 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7295 const SCEV *FoldedRec =
7296 getAddRecExpr(NewOps, AddRec->getLoop(),
7297 AddRec->getNoWrapFlags(SCEV::FlagNW));
7298 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7299 // The addrec may be folded to a nonrecurrence, for example, if the
7300 // induction variable is multiplied by zero after constant folding. Go
7301 // ahead and return the folded value.
7307 // If the scope is outside the addrec's loop, evaluate it by using the
7308 // loop exit value of the addrec.
7309 if (!AddRec->getLoop()->contains(L)) {
7310 // To evaluate this recurrence, we need to know how many times the AddRec
7311 // loop iterates. Compute this now.
7312 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7313 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7315 // Then, evaluate the AddRec.
7316 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7322 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7323 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7324 if (Op == Cast->getOperand())
7325 return Cast; // must be loop invariant
7326 return getZeroExtendExpr(Op, Cast->getType());
7329 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7330 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7331 if (Op == Cast->getOperand())
7332 return Cast; // must be loop invariant
7333 return getSignExtendExpr(Op, Cast->getType());
7336 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7337 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7338 if (Op == Cast->getOperand())
7339 return Cast; // must be loop invariant
7340 return getTruncateExpr(Op, Cast->getType());
7343 llvm_unreachable("Unknown SCEV type!");
7346 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7347 return getSCEVAtScope(getSCEV(V), L);
7350 /// Finds the minimum unsigned root of the following equation:
7352 /// A * X = B (mod N)
7354 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7355 /// A and B isn't important.
7357 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7358 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7359 ScalarEvolution &SE) {
7360 uint32_t BW = A.getBitWidth();
7361 assert(BW == SE.getTypeSizeInBits(B->getType()));
7362 assert(A != 0 && "A must be non-zero.");
7366 // The gcd of A and N may have only one prime factor: 2. The number of
7367 // trailing zeros in A is its multiplicity
7368 uint32_t Mult2 = A.countTrailingZeros();
7371 // 2. Check if B is divisible by D.
7373 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7374 // is not less than multiplicity of this prime factor for D.
7375 if (SE.GetMinTrailingZeros(B) < Mult2)
7376 return SE.getCouldNotCompute();
7378 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7381 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7382 // (N / D) in general. The inverse itself always fits into BW bits, though,
7383 // so we immediately truncate it.
7384 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7385 APInt Mod(BW + 1, 0);
7386 Mod.setBit(BW - Mult2); // Mod = N / D
7387 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7389 // 4. Compute the minimum unsigned root of the equation:
7390 // I * (B / D) mod (N / D)
7391 // To simplify the computation, we factor out the divide by D:
7392 // (I * B mod N) / D
7393 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7394 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7397 /// Find the roots of the quadratic equation for the given quadratic chrec
7398 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7399 /// two SCEVCouldNotCompute objects.
7401 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7402 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7403 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7404 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7405 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7406 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7408 // We currently can only solve this if the coefficients are constants.
7409 if (!LC || !MC || !NC)
7412 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7413 const APInt &L = LC->getAPInt();
7414 const APInt &M = MC->getAPInt();
7415 const APInt &N = NC->getAPInt();
7416 APInt Two(BitWidth, 2);
7418 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7420 // The A coefficient is N/2
7421 APInt A = N.sdiv(Two);
7423 // The B coefficient is M-N/2
7425 B -= A; // A is the same as N/2.
7427 // The C coefficient is L.
7430 // Compute the B^2-4ac term.
7433 SqrtTerm -= 4 * (A * C);
7435 if (SqrtTerm.isNegative()) {
7436 // The loop is provably infinite.
7440 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7441 // integer value or else APInt::sqrt() will assert.
7442 APInt SqrtVal = SqrtTerm.sqrt();
7444 // Compute the two solutions for the quadratic formula.
7445 // The divisions must be performed as signed divisions.
7446 APInt NegB = -std::move(B);
7447 APInt TwoA = std::move(A);
7449 if (TwoA.isNullValue())
7452 LLVMContext &Context = SE.getContext();
7454 ConstantInt *Solution1 =
7455 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7456 ConstantInt *Solution2 =
7457 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7459 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7460 cast<SCEVConstant>(SE.getConstant(Solution2)));
7463 ScalarEvolution::ExitLimit
7464 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7465 bool AllowPredicates) {
7467 // This is only used for loops with a "x != y" exit test. The exit condition
7468 // is now expressed as a single expression, V = x-y. So the exit test is
7469 // effectively V != 0. We know and take advantage of the fact that this
7470 // expression only being used in a comparison by zero context.
7472 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7473 // If the value is a constant
7474 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7475 // If the value is already zero, the branch will execute zero times.
7476 if (C->getValue()->isZero()) return C;
7477 return getCouldNotCompute(); // Otherwise it will loop infinitely.
7480 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7481 if (!AddRec && AllowPredicates)
7482 // Try to make this an AddRec using runtime tests, in the first X
7483 // iterations of this loop, where X is the SCEV expression found by the
7485 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7487 if (!AddRec || AddRec->getLoop() != L)
7488 return getCouldNotCompute();
7490 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7491 // the quadratic equation to solve it.
7492 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7493 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7494 const SCEVConstant *R1 = Roots->first;
7495 const SCEVConstant *R2 = Roots->second;
7496 // Pick the smallest positive root value.
7497 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7498 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7499 if (!CB->getZExtValue())
7500 std::swap(R1, R2); // R1 is the minimum root now.
7502 // We can only use this value if the chrec ends up with an exact zero
7503 // value at this index. When solving for "X*X != 5", for example, we
7504 // should not accept a root of 2.
7505 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7507 // We found a quadratic root!
7508 return ExitLimit(R1, R1, false, Predicates);
7511 return getCouldNotCompute();
7514 // Otherwise we can only handle this if it is affine.
7515 if (!AddRec->isAffine())
7516 return getCouldNotCompute();
7518 // If this is an affine expression, the execution count of this branch is
7519 // the minimum unsigned root of the following equation:
7521 // Start + Step*N = 0 (mod 2^BW)
7525 // Step*N = -Start (mod 2^BW)
7527 // where BW is the common bit width of Start and Step.
7529 // Get the initial value for the loop.
7530 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7531 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7533 // For now we handle only constant steps.
7535 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7536 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7537 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7538 // We have not yet seen any such cases.
7539 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7540 if (!StepC || StepC->getValue()->equalsInt(0))
7541 return getCouldNotCompute();
7543 // For positive steps (counting up until unsigned overflow):
7544 // N = -Start/Step (as unsigned)
7545 // For negative steps (counting down to zero):
7547 // First compute the unsigned distance from zero in the direction of Step.
7548 bool CountDown = StepC->getAPInt().isNegative();
7549 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7551 // Handle unitary steps, which cannot wraparound.
7552 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7553 // N = Distance (as unsigned)
7554 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7555 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7557 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7558 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7559 // case, and see if we can improve the bound.
7561 // Explicitly handling this here is necessary because getUnsignedRange
7562 // isn't context-sensitive; it doesn't know that we only care about the
7563 // range inside the loop.
7564 const SCEV *Zero = getZero(Distance->getType());
7565 const SCEV *One = getOne(Distance->getType());
7566 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7567 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7568 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7569 // as "unsigned_max(Distance + 1) - 1".
7570 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7571 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7573 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7576 // If the condition controls loop exit (the loop exits only if the expression
7577 // is true) and the addition is no-wrap we can use unsigned divide to
7578 // compute the backedge count. In this case, the step may not divide the
7579 // distance, but we don't care because if the condition is "missed" the loop
7580 // will have undefined behavior due to wrapping.
7581 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7582 loopHasNoAbnormalExits(AddRec->getLoop())) {
7584 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7585 return ExitLimit(Exact, Exact, false, Predicates);
7588 // Solve the general equation.
7589 const SCEV *E = SolveLinEquationWithOverflow(
7590 StepC->getAPInt(), getNegativeSCEV(Start), *this);
7591 return ExitLimit(E, E, false, Predicates);
7594 ScalarEvolution::ExitLimit
7595 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7596 // Loops that look like: while (X == 0) are very strange indeed. We don't
7597 // handle them yet except for the trivial case. This could be expanded in the
7598 // future as needed.
7600 // If the value is a constant, check to see if it is known to be non-zero
7601 // already. If so, the backedge will execute zero times.
7602 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7603 if (!C->getValue()->isNullValue())
7604 return getZero(C->getType());
7605 return getCouldNotCompute(); // Otherwise it will loop infinitely.
7608 // We could implement others, but I really doubt anyone writes loops like
7609 // this, and if they did, they would already be constant folded.
7610 return getCouldNotCompute();
7613 std::pair<BasicBlock *, BasicBlock *>
7614 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7615 // If the block has a unique predecessor, then there is no path from the
7616 // predecessor to the block that does not go through the direct edge
7617 // from the predecessor to the block.
7618 if (BasicBlock *Pred = BB->getSinglePredecessor())
7621 // A loop's header is defined to be a block that dominates the loop.
7622 // If the header has a unique predecessor outside the loop, it must be
7623 // a block that has exactly one successor that can reach the loop.
7624 if (Loop *L = LI.getLoopFor(BB))
7625 return {L->getLoopPredecessor(), L->getHeader()};
7627 return {nullptr, nullptr};
7630 /// SCEV structural equivalence is usually sufficient for testing whether two
7631 /// expressions are equal, however for the purposes of looking for a condition
7632 /// guarding a loop, it can be useful to be a little more general, since a
7633 /// front-end may have replicated the controlling expression.
7635 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7636 // Quick check to see if they are the same SCEV.
7637 if (A == B) return true;
7639 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7640 // Not all instructions that are "identical" compute the same value. For
7641 // instance, two distinct alloca instructions allocating the same type are
7642 // identical and do not read memory; but compute distinct values.
7643 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7646 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7647 // two different instructions with the same value. Check for this case.
7648 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7649 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7650 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7651 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7652 if (ComputesEqualValues(AI, BI))
7655 // Otherwise assume they may have a different value.
7659 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7660 const SCEV *&LHS, const SCEV *&RHS,
7662 bool Changed = false;
7664 // If we hit the max recursion limit bail out.
7668 // Canonicalize a constant to the right side.
7669 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7670 // Check for both operands constant.
7671 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7672 if (ConstantExpr::getICmp(Pred,
7674 RHSC->getValue())->isNullValue())
7675 goto trivially_false;
7677 goto trivially_true;
7679 // Otherwise swap the operands to put the constant on the right.
7680 std::swap(LHS, RHS);
7681 Pred = ICmpInst::getSwappedPredicate(Pred);
7685 // If we're comparing an addrec with a value which is loop-invariant in the
7686 // addrec's loop, put the addrec on the left. Also make a dominance check,
7687 // as both operands could be addrecs loop-invariant in each other's loop.
7688 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7689 const Loop *L = AR->getLoop();
7690 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7691 std::swap(LHS, RHS);
7692 Pred = ICmpInst::getSwappedPredicate(Pred);
7697 // If there's a constant operand, canonicalize comparisons with boundary
7698 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7699 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7700 const APInt &RA = RC->getAPInt();
7702 bool SimplifiedByConstantRange = false;
7704 if (!ICmpInst::isEquality(Pred)) {
7705 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7706 if (ExactCR.isFullSet())
7707 goto trivially_true;
7708 else if (ExactCR.isEmptySet())
7709 goto trivially_false;
7712 CmpInst::Predicate NewPred;
7713 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7714 ICmpInst::isEquality(NewPred)) {
7715 // We were able to convert an inequality to an equality.
7717 RHS = getConstant(NewRHS);
7718 Changed = SimplifiedByConstantRange = true;
7722 if (!SimplifiedByConstantRange) {
7726 case ICmpInst::ICMP_EQ:
7727 case ICmpInst::ICMP_NE:
7728 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7730 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7731 if (const SCEVMulExpr *ME =
7732 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7733 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7734 ME->getOperand(0)->isAllOnesValue()) {
7735 RHS = AE->getOperand(1);
7736 LHS = ME->getOperand(1);
7742 // The "Should have been caught earlier!" messages refer to the fact
7743 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7744 // should have fired on the corresponding cases, and canonicalized the
7745 // check to trivially_true or trivially_false.
7747 case ICmpInst::ICMP_UGE:
7748 assert(!RA.isMinValue() && "Should have been caught earlier!");
7749 Pred = ICmpInst::ICMP_UGT;
7750 RHS = getConstant(RA - 1);
7753 case ICmpInst::ICMP_ULE:
7754 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7755 Pred = ICmpInst::ICMP_ULT;
7756 RHS = getConstant(RA + 1);
7759 case ICmpInst::ICMP_SGE:
7760 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7761 Pred = ICmpInst::ICMP_SGT;
7762 RHS = getConstant(RA - 1);
7765 case ICmpInst::ICMP_SLE:
7766 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7767 Pred = ICmpInst::ICMP_SLT;
7768 RHS = getConstant(RA + 1);
7775 // Check for obvious equality.
7776 if (HasSameValue(LHS, RHS)) {
7777 if (ICmpInst::isTrueWhenEqual(Pred))
7778 goto trivially_true;
7779 if (ICmpInst::isFalseWhenEqual(Pred))
7780 goto trivially_false;
7783 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7784 // adding or subtracting 1 from one of the operands.
7786 case ICmpInst::ICMP_SLE:
7787 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7788 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7790 Pred = ICmpInst::ICMP_SLT;
7792 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7793 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7795 Pred = ICmpInst::ICMP_SLT;
7799 case ICmpInst::ICMP_SGE:
7800 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7801 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7803 Pred = ICmpInst::ICMP_SGT;
7805 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7806 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7808 Pred = ICmpInst::ICMP_SGT;
7812 case ICmpInst::ICMP_ULE:
7813 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7814 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7816 Pred = ICmpInst::ICMP_ULT;
7818 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7819 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7820 Pred = ICmpInst::ICMP_ULT;
7824 case ICmpInst::ICMP_UGE:
7825 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7826 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7827 Pred = ICmpInst::ICMP_UGT;
7829 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7830 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7832 Pred = ICmpInst::ICMP_UGT;
7840 // TODO: More simplifications are possible here.
7842 // Recursively simplify until we either hit a recursion limit or nothing
7845 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7851 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7852 Pred = ICmpInst::ICMP_EQ;
7857 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7858 Pred = ICmpInst::ICMP_NE;
7862 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7863 return getSignedRange(S).getSignedMax().isNegative();
7866 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7867 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7870 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7871 return !getSignedRange(S).getSignedMin().isNegative();
7874 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7875 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7878 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7879 return isKnownNegative(S) || isKnownPositive(S);
7882 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7883 const SCEV *LHS, const SCEV *RHS) {
7884 // Canonicalize the inputs first.
7885 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7887 // If LHS or RHS is an addrec, check to see if the condition is true in
7888 // every iteration of the loop.
7889 // If LHS and RHS are both addrec, both conditions must be true in
7890 // every iteration of the loop.
7891 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7892 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7893 bool LeftGuarded = false;
7894 bool RightGuarded = false;
7896 const Loop *L = LAR->getLoop();
7897 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7898 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7899 if (!RAR) return true;
7904 const Loop *L = RAR->getLoop();
7905 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7906 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7907 if (!LAR) return true;
7908 RightGuarded = true;
7911 if (LeftGuarded && RightGuarded)
7914 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7917 // Otherwise see what can be done with known constant ranges.
7918 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7921 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7922 ICmpInst::Predicate Pred,
7924 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7927 // Verify an invariant: inverting the predicate should turn a monotonically
7928 // increasing change to a monotonically decreasing one, and vice versa.
7929 bool IncreasingSwapped;
7930 bool ResultSwapped = isMonotonicPredicateImpl(
7931 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7933 assert(Result == ResultSwapped && "should be able to analyze both!");
7935 assert(Increasing == !IncreasingSwapped &&
7936 "monotonicity should flip as we flip the predicate");
7942 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7943 ICmpInst::Predicate Pred,
7946 // A zero step value for LHS means the induction variable is essentially a
7947 // loop invariant value. We don't really depend on the predicate actually
7948 // flipping from false to true (for increasing predicates, and the other way
7949 // around for decreasing predicates), all we care about is that *if* the
7950 // predicate changes then it only changes from false to true.
7952 // A zero step value in itself is not very useful, but there may be places
7953 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7954 // as general as possible.
7958 return false; // Conservative answer
7960 case ICmpInst::ICMP_UGT:
7961 case ICmpInst::ICMP_UGE:
7962 case ICmpInst::ICMP_ULT:
7963 case ICmpInst::ICMP_ULE:
7964 if (!LHS->hasNoUnsignedWrap())
7967 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7970 case ICmpInst::ICMP_SGT:
7971 case ICmpInst::ICMP_SGE:
7972 case ICmpInst::ICMP_SLT:
7973 case ICmpInst::ICMP_SLE: {
7974 if (!LHS->hasNoSignedWrap())
7977 const SCEV *Step = LHS->getStepRecurrence(*this);
7979 if (isKnownNonNegative(Step)) {
7980 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7984 if (isKnownNonPositive(Step)) {
7985 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7994 llvm_unreachable("switch has default clause!");
7997 bool ScalarEvolution::isLoopInvariantPredicate(
7998 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7999 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8000 const SCEV *&InvariantRHS) {
8002 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8003 if (!isLoopInvariant(RHS, L)) {
8004 if (!isLoopInvariant(LHS, L))
8007 std::swap(LHS, RHS);
8008 Pred = ICmpInst::getSwappedPredicate(Pred);
8011 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8012 if (!ArLHS || ArLHS->getLoop() != L)
8016 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8019 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8020 // true as the loop iterates, and the backedge is control dependent on
8021 // "ArLHS `Pred` RHS" == true then we can reason as follows:
8023 // * if the predicate was false in the first iteration then the predicate
8024 // is never evaluated again, since the loop exits without taking the
8026 // * if the predicate was true in the first iteration then it will
8027 // continue to be true for all future iterations since it is
8028 // monotonically increasing.
8030 // For both the above possibilities, we can replace the loop varying
8031 // predicate with its value on the first iteration of the loop (which is
8034 // A similar reasoning applies for a monotonically decreasing predicate, by
8035 // replacing true with false and false with true in the above two bullets.
8037 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8039 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8042 InvariantPred = Pred;
8043 InvariantLHS = ArLHS->getStart();
8048 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8049 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8050 if (HasSameValue(LHS, RHS))
8051 return ICmpInst::isTrueWhenEqual(Pred);
8053 // This code is split out from isKnownPredicate because it is called from
8054 // within isLoopEntryGuardedByCond.
8057 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8058 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8059 .contains(RangeLHS);
8062 // The check at the top of the function catches the case where the values are
8063 // known to be equal.
8064 if (Pred == CmpInst::ICMP_EQ)
8067 if (Pred == CmpInst::ICMP_NE)
8068 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8069 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8070 isKnownNonZero(getMinusSCEV(LHS, RHS));
8072 if (CmpInst::isSigned(Pred))
8073 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8075 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8078 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8082 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8083 // Return Y via OutY.
8084 auto MatchBinaryAddToConst =
8085 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8086 SCEV::NoWrapFlags ExpectedFlags) {
8087 const SCEV *NonConstOp, *ConstOp;
8088 SCEV::NoWrapFlags FlagsPresent;
8090 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8091 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8094 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8095 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8104 case ICmpInst::ICMP_SGE:
8105 std::swap(LHS, RHS);
8106 case ICmpInst::ICMP_SLE:
8107 // X s<= (X + C)<nsw> if C >= 0
8108 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8111 // (X + C)<nsw> s<= X if C <= 0
8112 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8113 !C.isStrictlyPositive())
8117 case ICmpInst::ICMP_SGT:
8118 std::swap(LHS, RHS);
8119 case ICmpInst::ICMP_SLT:
8120 // X s< (X + C)<nsw> if C > 0
8121 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8122 C.isStrictlyPositive())
8125 // (X + C)<nsw> s< X if C < 0
8126 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8134 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8137 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8140 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8141 // the stack can result in exponential time complexity.
8142 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8144 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8146 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8147 // isKnownPredicate. isKnownPredicate is more powerful, but also more
8148 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8149 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
8150 // use isKnownPredicate later if needed.
8151 return isKnownNonNegative(RHS) &&
8152 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8153 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8156 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8157 ICmpInst::Predicate Pred,
8158 const SCEV *LHS, const SCEV *RHS) {
8159 // No need to even try if we know the module has no guards.
8163 return any_of(*BB, [&](Instruction &I) {
8164 using namespace llvm::PatternMatch;
8167 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8168 m_Value(Condition))) &&
8169 isImpliedCond(Pred, LHS, RHS, Condition, false);
8173 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8174 /// protected by a conditional between LHS and RHS. This is used to
8175 /// to eliminate casts.
8177 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8178 ICmpInst::Predicate Pred,
8179 const SCEV *LHS, const SCEV *RHS) {
8180 // Interpret a null as meaning no loop, where there is obviously no guard
8181 // (interprocedural conditions notwithstanding).
8182 if (!L) return true;
8184 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8187 BasicBlock *Latch = L->getLoopLatch();
8191 BranchInst *LoopContinuePredicate =
8192 dyn_cast<BranchInst>(Latch->getTerminator());
8193 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8194 isImpliedCond(Pred, LHS, RHS,
8195 LoopContinuePredicate->getCondition(),
8196 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8199 // We don't want more than one activation of the following loops on the stack
8200 // -- that can lead to O(n!) time complexity.
8201 if (WalkingBEDominatingConds)
8204 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8206 // See if we can exploit a trip count to prove the predicate.
8207 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8208 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8209 if (LatchBECount != getCouldNotCompute()) {
8210 // We know that Latch branches back to the loop header exactly
8211 // LatchBECount times. This means the backdege condition at Latch is
8212 // equivalent to "{0,+,1} u< LatchBECount".
8213 Type *Ty = LatchBECount->getType();
8214 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8215 const SCEV *LoopCounter =
8216 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8217 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8222 // Check conditions due to any @llvm.assume intrinsics.
8223 for (auto &AssumeVH : AC.assumptions()) {
8226 auto *CI = cast<CallInst>(AssumeVH);
8227 if (!DT.dominates(CI, Latch->getTerminator()))
8230 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8234 // If the loop is not reachable from the entry block, we risk running into an
8235 // infinite loop as we walk up into the dom tree. These loops do not matter
8236 // anyway, so we just return a conservative answer when we see them.
8237 if (!DT.isReachableFromEntry(L->getHeader()))
8240 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8243 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8244 DTN != HeaderDTN; DTN = DTN->getIDom()) {
8246 assert(DTN && "should reach the loop header before reaching the root!");
8248 BasicBlock *BB = DTN->getBlock();
8249 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8252 BasicBlock *PBB = BB->getSinglePredecessor();
8256 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8257 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8260 Value *Condition = ContinuePredicate->getCondition();
8262 // If we have an edge `E` within the loop body that dominates the only
8263 // latch, the condition guarding `E` also guards the backedge. This
8264 // reasoning works only for loops with a single latch.
8266 BasicBlockEdge DominatingEdge(PBB, BB);
8267 if (DominatingEdge.isSingleEdge()) {
8268 // We're constructively (and conservatively) enumerating edges within the
8269 // loop body that dominate the latch. The dominator tree better agree
8271 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8273 if (isImpliedCond(Pred, LHS, RHS, Condition,
8274 BB != ContinuePredicate->getSuccessor(0)))
8283 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8284 ICmpInst::Predicate Pred,
8285 const SCEV *LHS, const SCEV *RHS) {
8286 // Interpret a null as meaning no loop, where there is obviously no guard
8287 // (interprocedural conditions notwithstanding).
8288 if (!L) return false;
8290 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8293 // Starting at the loop predecessor, climb up the predecessor chain, as long
8294 // as there are predecessors that can be found that have unique successors
8295 // leading to the original header.
8296 for (std::pair<BasicBlock *, BasicBlock *>
8297 Pair(L->getLoopPredecessor(), L->getHeader());
8299 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8301 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8304 BranchInst *LoopEntryPredicate =
8305 dyn_cast<BranchInst>(Pair.first->getTerminator());
8306 if (!LoopEntryPredicate ||
8307 LoopEntryPredicate->isUnconditional())
8310 if (isImpliedCond(Pred, LHS, RHS,
8311 LoopEntryPredicate->getCondition(),
8312 LoopEntryPredicate->getSuccessor(0) != Pair.second))
8316 // Check conditions due to any @llvm.assume intrinsics.
8317 for (auto &AssumeVH : AC.assumptions()) {
8320 auto *CI = cast<CallInst>(AssumeVH);
8321 if (!DT.dominates(CI, L->getHeader()))
8324 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8331 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8332 const SCEV *LHS, const SCEV *RHS,
8333 Value *FoundCondValue,
8335 if (!PendingLoopPredicates.insert(FoundCondValue).second)
8339 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8341 // Recursively handle And and Or conditions.
8342 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8343 if (BO->getOpcode() == Instruction::And) {
8345 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8346 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8347 } else if (BO->getOpcode() == Instruction::Or) {
8349 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8350 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8354 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8355 if (!ICI) return false;
8357 // Now that we found a conditional branch that dominates the loop or controls
8358 // the loop latch. Check to see if it is the comparison we are looking for.
8359 ICmpInst::Predicate FoundPred;
8361 FoundPred = ICI->getInversePredicate();
8363 FoundPred = ICI->getPredicate();
8365 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8366 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8368 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8371 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8373 ICmpInst::Predicate FoundPred,
8374 const SCEV *FoundLHS,
8375 const SCEV *FoundRHS) {
8376 // Balance the types.
8377 if (getTypeSizeInBits(LHS->getType()) <
8378 getTypeSizeInBits(FoundLHS->getType())) {
8379 if (CmpInst::isSigned(Pred)) {
8380 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8381 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8383 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8384 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8386 } else if (getTypeSizeInBits(LHS->getType()) >
8387 getTypeSizeInBits(FoundLHS->getType())) {
8388 if (CmpInst::isSigned(FoundPred)) {
8389 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8390 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8392 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8393 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8397 // Canonicalize the query to match the way instcombine will have
8398 // canonicalized the comparison.
8399 if (SimplifyICmpOperands(Pred, LHS, RHS))
8401 return CmpInst::isTrueWhenEqual(Pred);
8402 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8403 if (FoundLHS == FoundRHS)
8404 return CmpInst::isFalseWhenEqual(FoundPred);
8406 // Check to see if we can make the LHS or RHS match.
8407 if (LHS == FoundRHS || RHS == FoundLHS) {
8408 if (isa<SCEVConstant>(RHS)) {
8409 std::swap(FoundLHS, FoundRHS);
8410 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8412 std::swap(LHS, RHS);
8413 Pred = ICmpInst::getSwappedPredicate(Pred);
8417 // Check whether the found predicate is the same as the desired predicate.
8418 if (FoundPred == Pred)
8419 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8421 // Check whether swapping the found predicate makes it the same as the
8422 // desired predicate.
8423 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8424 if (isa<SCEVConstant>(RHS))
8425 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8427 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8428 RHS, LHS, FoundLHS, FoundRHS);
8431 // Unsigned comparison is the same as signed comparison when both the operands
8432 // are non-negative.
8433 if (CmpInst::isUnsigned(FoundPred) &&
8434 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8435 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8436 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8438 // Check if we can make progress by sharpening ranges.
8439 if (FoundPred == ICmpInst::ICMP_NE &&
8440 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8442 const SCEVConstant *C = nullptr;
8443 const SCEV *V = nullptr;
8445 if (isa<SCEVConstant>(FoundLHS)) {
8446 C = cast<SCEVConstant>(FoundLHS);
8449 C = cast<SCEVConstant>(FoundRHS);
8453 // The guarding predicate tells us that C != V. If the known range
8454 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8455 // range we consider has to correspond to same signedness as the
8456 // predicate we're interested in folding.
8458 APInt Min = ICmpInst::isSigned(Pred) ?
8459 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8461 if (Min == C->getAPInt()) {
8462 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8463 // This is true even if (Min + 1) wraps around -- in case of
8464 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8466 APInt SharperMin = Min + 1;
8469 case ICmpInst::ICMP_SGE:
8470 case ICmpInst::ICMP_UGE:
8471 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8473 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8474 getConstant(SharperMin)))
8477 case ICmpInst::ICMP_SGT:
8478 case ICmpInst::ICMP_UGT:
8479 // We know from the range information that (V `Pred` Min ||
8480 // V == Min). We know from the guarding condition that !(V
8481 // == Min). This gives us
8483 // V `Pred` Min || V == Min && !(V == Min)
8486 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8488 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8498 // Check whether the actual condition is beyond sufficient.
8499 if (FoundPred == ICmpInst::ICMP_EQ)
8500 if (ICmpInst::isTrueWhenEqual(Pred))
8501 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8503 if (Pred == ICmpInst::ICMP_NE)
8504 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8505 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8508 // Otherwise assume the worst.
8512 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8513 const SCEV *&L, const SCEV *&R,
8514 SCEV::NoWrapFlags &Flags) {
8515 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8516 if (!AE || AE->getNumOperands() != 2)
8519 L = AE->getOperand(0);
8520 R = AE->getOperand(1);
8521 Flags = AE->getNoWrapFlags();
8525 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8527 // We avoid subtracting expressions here because this function is usually
8528 // fairly deep in the call stack (i.e. is called many times).
8530 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8531 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8532 const auto *MAR = cast<SCEVAddRecExpr>(More);
8534 if (LAR->getLoop() != MAR->getLoop())
8537 // We look at affine expressions only; not for correctness but to keep
8538 // getStepRecurrence cheap.
8539 if (!LAR->isAffine() || !MAR->isAffine())
8542 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8545 Less = LAR->getStart();
8546 More = MAR->getStart();
8551 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8552 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8553 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8558 SCEV::NoWrapFlags Flags;
8559 if (splitBinaryAdd(Less, L, R, Flags))
8560 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8562 return -(LC->getAPInt());
8564 if (splitBinaryAdd(More, L, R, Flags))
8565 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8567 return LC->getAPInt();
8572 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8573 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8574 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8575 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8578 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8582 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8583 if (!AddRecFoundLHS)
8586 // We'd like to let SCEV reason about control dependencies, so we constrain
8587 // both the inequalities to be about add recurrences on the same loop. This
8588 // way we can use isLoopEntryGuardedByCond later.
8590 const Loop *L = AddRecFoundLHS->getLoop();
8591 if (L != AddRecLHS->getLoop())
8594 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8596 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8599 // Informal proof for (2), assuming (1) [*]:
8601 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8605 // FoundLHS s< FoundRHS s< INT_MIN - C
8606 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8607 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8608 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8609 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8610 // <=> FoundLHS + C s< FoundRHS + C
8612 // [*]: (1) can be proved by ruling out overflow.
8614 // [**]: This can be proved by analyzing all the four possibilities:
8615 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8616 // (A s>= 0, B s>= 0).
8619 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8620 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8621 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8622 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8623 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8626 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8627 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8628 if (!LDiff || !RDiff || *LDiff != *RDiff)
8631 if (LDiff->isMinValue())
8634 APInt FoundRHSLimit;
8636 if (Pred == CmpInst::ICMP_ULT) {
8637 FoundRHSLimit = -(*RDiff);
8639 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8640 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8643 // Try to prove (1) or (2), as needed.
8644 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8645 getConstant(FoundRHSLimit));
8648 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8649 const SCEV *LHS, const SCEV *RHS,
8650 const SCEV *FoundLHS,
8651 const SCEV *FoundRHS) {
8652 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8655 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8658 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8659 FoundLHS, FoundRHS) ||
8660 // ~x < ~y --> x > y
8661 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8662 getNotSCEV(FoundRHS),
8663 getNotSCEV(FoundLHS));
8667 /// If Expr computes ~A, return A else return nullptr
8668 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8669 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8670 if (!Add || Add->getNumOperands() != 2 ||
8671 !Add->getOperand(0)->isAllOnesValue())
8674 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8675 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8676 !AddRHS->getOperand(0)->isAllOnesValue())
8679 return AddRHS->getOperand(1);
8683 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8684 template<typename MaxExprType>
8685 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8686 const SCEV *Candidate) {
8687 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8688 if (!MaxExpr) return false;
8690 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8694 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8695 template<typename MaxExprType>
8696 static bool IsMinConsistingOf(ScalarEvolution &SE,
8697 const SCEV *MaybeMinExpr,
8698 const SCEV *Candidate) {
8699 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8703 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8706 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8707 ICmpInst::Predicate Pred,
8708 const SCEV *LHS, const SCEV *RHS) {
8710 // If both sides are affine addrecs for the same loop, with equal
8711 // steps, and we know the recurrences don't wrap, then we only
8712 // need to check the predicate on the starting values.
8714 if (!ICmpInst::isRelational(Pred))
8717 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8720 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8723 if (LAR->getLoop() != RAR->getLoop())
8725 if (!LAR->isAffine() || !RAR->isAffine())
8728 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8731 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8732 SCEV::FlagNSW : SCEV::FlagNUW;
8733 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8736 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8739 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8741 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8742 ICmpInst::Predicate Pred,
8743 const SCEV *LHS, const SCEV *RHS) {
8748 case ICmpInst::ICMP_SGE:
8749 std::swap(LHS, RHS);
8751 case ICmpInst::ICMP_SLE:
8754 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8756 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8758 case ICmpInst::ICMP_UGE:
8759 std::swap(LHS, RHS);
8761 case ICmpInst::ICMP_ULE:
8764 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8766 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8769 llvm_unreachable("covered switch fell through?!");
8772 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8773 const SCEV *LHS, const SCEV *RHS,
8774 const SCEV *FoundLHS,
8775 const SCEV *FoundRHS,
8777 assert(getTypeSizeInBits(LHS->getType()) ==
8778 getTypeSizeInBits(RHS->getType()) &&
8779 "LHS and RHS have different sizes?");
8780 assert(getTypeSizeInBits(FoundLHS->getType()) ==
8781 getTypeSizeInBits(FoundRHS->getType()) &&
8782 "FoundLHS and FoundRHS have different sizes?");
8783 // We want to avoid hurting the compile time with analysis of too big trees.
8784 if (Depth > MaxSCEVOperationsImplicationDepth)
8786 // We only want to work with ICMP_SGT comparison so far.
8787 // TODO: Extend to ICMP_UGT?
8788 if (Pred == ICmpInst::ICMP_SLT) {
8789 Pred = ICmpInst::ICMP_SGT;
8790 std::swap(LHS, RHS);
8791 std::swap(FoundLHS, FoundRHS);
8793 if (Pred != ICmpInst::ICMP_SGT)
8796 auto GetOpFromSExt = [&](const SCEV *S) {
8797 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8798 return Ext->getOperand();
8799 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8800 // the constant in some cases.
8804 // Acquire values from extensions.
8805 auto *OrigFoundLHS = FoundLHS;
8806 LHS = GetOpFromSExt(LHS);
8807 FoundLHS = GetOpFromSExt(FoundLHS);
8809 // Is the SGT predicate can be proved trivially or using the found context.
8810 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8811 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8812 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8813 FoundRHS, Depth + 1);
8816 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8817 // We want to avoid creation of any new non-constant SCEV. Since we are
8818 // going to compare the operands to RHS, we should be certain that we don't
8819 // need any size extensions for this. So let's decline all cases when the
8820 // sizes of types of LHS and RHS do not match.
8821 // TODO: Maybe try to get RHS from sext to catch more cases?
8822 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8825 // Should not overflow.
8826 if (!LHSAddExpr->hasNoSignedWrap())
8829 auto *LL = LHSAddExpr->getOperand(0);
8830 auto *LR = LHSAddExpr->getOperand(1);
8831 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8833 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8834 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8835 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8837 // Try to prove the following rule:
8838 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8839 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8840 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8842 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8844 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8845 using namespace llvm::PatternMatch;
8846 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8847 // Rules for division.
8848 // We are going to perform some comparisons with Denominator and its
8849 // derivative expressions. In general case, creating a SCEV for it may
8850 // lead to a complex analysis of the entire graph, and in particular it
8851 // can request trip count recalculation for the same loop. This would
8852 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8853 // this, we only want to create SCEVs that are constants in this section.
8854 // So we bail if Denominator is not a constant.
8855 if (!isa<ConstantInt>(LR))
8858 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8860 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8861 // then a SCEV for the numerator already exists and matches with FoundLHS.
8862 auto *Numerator = getExistingSCEV(LL);
8863 if (!Numerator || Numerator->getType() != FoundLHS->getType())
8866 // Make sure that the numerator matches with FoundLHS and the denominator
8868 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8871 auto *DTy = Denominator->getType();
8872 auto *FRHSTy = FoundRHS->getType();
8873 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8874 // One of types is a pointer and another one is not. We cannot extend
8875 // them properly to a wider type, so let us just reject this case.
8876 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8877 // to avoid this check.
8881 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8882 auto *WTy = getWiderType(DTy, FRHSTy);
8883 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8884 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8886 // Try to prove the following rule:
8887 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8888 // For example, given that FoundLHS > 2. It means that FoundLHS is at
8889 // least 3. If we divide it by Denominator < 4, we will have at least 1.
8890 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8891 if (isKnownNonPositive(RHS) &&
8892 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8895 // Try to prove the following rule:
8896 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8897 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8898 // If we divide it by Denominator > 2, then:
8899 // 1. If FoundLHS is negative, then the result is 0.
8900 // 2. If FoundLHS is non-negative, then the result is non-negative.
8901 // Anyways, the result is non-negative.
8902 auto *MinusOne = getNegativeSCEV(getOne(WTy));
8903 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8904 if (isKnownNegative(RHS) &&
8905 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8914 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8915 const SCEV *LHS, const SCEV *RHS) {
8916 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8917 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8918 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8919 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8923 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8924 const SCEV *LHS, const SCEV *RHS,
8925 const SCEV *FoundLHS,
8926 const SCEV *FoundRHS) {
8928 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8929 case ICmpInst::ICMP_EQ:
8930 case ICmpInst::ICMP_NE:
8931 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8934 case ICmpInst::ICMP_SLT:
8935 case ICmpInst::ICMP_SLE:
8936 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8937 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8940 case ICmpInst::ICMP_SGT:
8941 case ICmpInst::ICMP_SGE:
8942 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8943 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8946 case ICmpInst::ICMP_ULT:
8947 case ICmpInst::ICMP_ULE:
8948 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8949 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8952 case ICmpInst::ICMP_UGT:
8953 case ICmpInst::ICMP_UGE:
8954 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8955 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8960 // Maybe it can be proved via operations?
8961 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8967 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8970 const SCEV *FoundLHS,
8971 const SCEV *FoundRHS) {
8972 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8973 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8974 // reduce the compile time impact of this optimization.
8977 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8981 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8983 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8984 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8985 ConstantRange FoundLHSRange =
8986 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8988 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8989 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8991 // We can also compute the range of values for `LHS` that satisfy the
8992 // consequent, "`LHS` `Pred` `RHS`":
8993 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8994 ConstantRange SatisfyingLHSRange =
8995 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8997 // The antecedent implies the consequent if every value of `LHS` that
8998 // satisfies the antecedent also satisfies the consequent.
8999 return SatisfyingLHSRange.contains(LHSRange);
9002 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9003 bool IsSigned, bool NoWrap) {
9004 assert(isKnownPositive(Stride) && "Positive stride expected!");
9006 if (NoWrap) return false;
9008 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9009 const SCEV *One = getOne(Stride->getType());
9012 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
9013 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9014 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
9017 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9018 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9021 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
9022 APInt MaxValue = APInt::getMaxValue(BitWidth);
9023 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
9026 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9027 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9030 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9031 bool IsSigned, bool NoWrap) {
9032 if (NoWrap) return false;
9034 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9035 const SCEV *One = getOne(Stride->getType());
9038 APInt MinRHS = getSignedRange(RHS).getSignedMin();
9039 APInt MinValue = APInt::getSignedMinValue(BitWidth);
9040 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
9043 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9044 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9047 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
9048 APInt MinValue = APInt::getMinValue(BitWidth);
9049 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
9052 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9053 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9056 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9058 const SCEV *One = getOne(Step->getType());
9059 Delta = Equality ? getAddExpr(Delta, Step)
9060 : getAddExpr(Delta, getMinusSCEV(Step, One));
9061 return getUDivExpr(Delta, Step);
9064 ScalarEvolution::ExitLimit
9065 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9066 const Loop *L, bool IsSigned,
9067 bool ControlsExit, bool AllowPredicates) {
9068 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9069 // We handle only IV < Invariant
9070 if (!isLoopInvariant(RHS, L))
9071 return getCouldNotCompute();
9073 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9074 bool PredicatedIV = false;
9076 if (!IV && AllowPredicates) {
9077 // Try to make this an AddRec using runtime tests, in the first X
9078 // iterations of this loop, where X is the SCEV expression found by the
9080 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9081 PredicatedIV = true;
9084 // Avoid weird loops
9085 if (!IV || IV->getLoop() != L || !IV->isAffine())
9086 return getCouldNotCompute();
9088 bool NoWrap = ControlsExit &&
9089 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9091 const SCEV *Stride = IV->getStepRecurrence(*this);
9093 bool PositiveStride = isKnownPositive(Stride);
9095 // Avoid negative or zero stride values.
9096 if (!PositiveStride) {
9097 // We can compute the correct backedge taken count for loops with unknown
9098 // strides if we can prove that the loop is not an infinite loop with side
9099 // effects. Here's the loop structure we are trying to handle -
9105 // } while (i < end);
9107 // The backedge taken count for such loops is evaluated as -
9108 // (max(end, start + stride) - start - 1) /u stride
9110 // The additional preconditions that we need to check to prove correctness
9111 // of the above formula is as follows -
9113 // a) IV is either nuw or nsw depending upon signedness (indicated by the
9115 // b) loop is single exit with no side effects.
9118 // Precondition a) implies that if the stride is negative, this is a single
9119 // trip loop. The backedge taken count formula reduces to zero in this case.
9121 // Precondition b) implies that the unknown stride cannot be zero otherwise
9124 // The positive stride case is the same as isKnownPositive(Stride) returning
9125 // true (original behavior of the function).
9127 // We want to make sure that the stride is truly unknown as there are edge
9128 // cases where ScalarEvolution propagates no wrap flags to the
9129 // post-increment/decrement IV even though the increment/decrement operation
9130 // itself is wrapping. The computed backedge taken count may be wrong in
9131 // such cases. This is prevented by checking that the stride is not known to
9132 // be either positive or non-positive. For example, no wrap flags are
9133 // propagated to the post-increment IV of this loop with a trip count of 2 -
9136 // for(i=127; i<128; i+=129)
9139 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9140 !loopHasNoSideEffects(L))
9141 return getCouldNotCompute();
9143 } else if (!Stride->isOne() &&
9144 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9145 // Avoid proven overflow cases: this will ensure that the backedge taken
9146 // count will not generate any unsigned overflow. Relaxed no-overflow
9147 // conditions exploit NoWrapFlags, allowing to optimize in presence of
9148 // undefined behaviors like the case of C language.
9149 return getCouldNotCompute();
9151 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9152 : ICmpInst::ICMP_ULT;
9153 const SCEV *Start = IV->getStart();
9154 const SCEV *End = RHS;
9155 // If the backedge is taken at least once, then it will be taken
9156 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9157 // is the LHS value of the less-than comparison the first time it is evaluated
9158 // and End is the RHS.
9159 const SCEV *BECountIfBackedgeTaken =
9160 computeBECount(getMinusSCEV(End, Start), Stride, false);
9161 // If the loop entry is guarded by the result of the backedge test of the
9162 // first loop iteration, then we know the backedge will be taken at least
9163 // once and so the backedge taken count is as above. If not then we use the
9164 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9165 // as if the backedge is taken at least once max(End,Start) is End and so the
9166 // result is as above, and if not max(End,Start) is Start so we get a backedge
9168 const SCEV *BECount;
9169 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9170 BECount = BECountIfBackedgeTaken;
9172 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9173 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9176 const SCEV *MaxBECount;
9177 bool MaxOrZero = false;
9178 if (isa<SCEVConstant>(BECount))
9179 MaxBECount = BECount;
9180 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9181 // If we know exactly how many times the backedge will be taken if it's
9182 // taken at least once, then the backedge count will either be that or
9184 MaxBECount = BECountIfBackedgeTaken;
9187 // Calculate the maximum backedge count based on the range of values
9188 // permitted by Start, End, and Stride.
9189 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9190 : getUnsignedRange(Start).getUnsignedMin();
9192 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9194 APInt StrideForMaxBECount;
9197 StrideForMaxBECount =
9198 IsSigned ? getSignedRange(Stride).getSignedMin()
9199 : getUnsignedRange(Stride).getUnsignedMin();
9201 // Using a stride of 1 is safe when computing max backedge taken count for
9202 // a loop with unknown stride.
9203 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9206 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9207 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9209 // Although End can be a MAX expression we estimate MaxEnd considering only
9210 // the case End = RHS. This is safe because in the other case (End - Start)
9211 // is zero, leading to a zero maximum backedge taken count.
9213 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9214 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9216 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9217 getConstant(StrideForMaxBECount), false);
9220 if (isa<SCEVCouldNotCompute>(MaxBECount))
9221 MaxBECount = BECount;
9223 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9226 ScalarEvolution::ExitLimit
9227 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9228 const Loop *L, bool IsSigned,
9229 bool ControlsExit, bool AllowPredicates) {
9230 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9231 // We handle only IV > Invariant
9232 if (!isLoopInvariant(RHS, L))
9233 return getCouldNotCompute();
9235 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9236 if (!IV && AllowPredicates)
9237 // Try to make this an AddRec using runtime tests, in the first X
9238 // iterations of this loop, where X is the SCEV expression found by the
9240 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9242 // Avoid weird loops
9243 if (!IV || IV->getLoop() != L || !IV->isAffine())
9244 return getCouldNotCompute();
9246 bool NoWrap = ControlsExit &&
9247 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9249 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9251 // Avoid negative or zero stride values
9252 if (!isKnownPositive(Stride))
9253 return getCouldNotCompute();
9255 // Avoid proven overflow cases: this will ensure that the backedge taken count
9256 // will not generate any unsigned overflow. Relaxed no-overflow conditions
9257 // exploit NoWrapFlags, allowing to optimize in presence of undefined
9258 // behaviors like the case of C language.
9259 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9260 return getCouldNotCompute();
9262 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9263 : ICmpInst::ICMP_UGT;
9265 const SCEV *Start = IV->getStart();
9266 const SCEV *End = RHS;
9267 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9268 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9270 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9272 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9273 : getUnsignedRange(Start).getUnsignedMax();
9275 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9276 : getUnsignedRange(Stride).getUnsignedMin();
9278 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9279 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9280 : APInt::getMinValue(BitWidth) + (MinStride - 1);
9282 // Although End can be a MIN expression we estimate MinEnd considering only
9283 // the case End = RHS. This is safe because in the other case (Start - End)
9284 // is zero, leading to a zero maximum backedge taken count.
9286 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9287 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9290 const SCEV *MaxBECount = getCouldNotCompute();
9291 if (isa<SCEVConstant>(BECount))
9292 MaxBECount = BECount;
9294 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9295 getConstant(MinStride), false);
9297 if (isa<SCEVCouldNotCompute>(MaxBECount))
9298 MaxBECount = BECount;
9300 return ExitLimit(BECount, MaxBECount, false, Predicates);
9303 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9304 ScalarEvolution &SE) const {
9305 if (Range.isFullSet()) // Infinite loop.
9306 return SE.getCouldNotCompute();
9308 // If the start is a non-zero constant, shift the range to simplify things.
9309 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9310 if (!SC->getValue()->isZero()) {
9311 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9312 Operands[0] = SE.getZero(SC->getType());
9313 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9314 getNoWrapFlags(FlagNW));
9315 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9316 return ShiftedAddRec->getNumIterationsInRange(
9317 Range.subtract(SC->getAPInt()), SE);
9318 // This is strange and shouldn't happen.
9319 return SE.getCouldNotCompute();
9322 // The only time we can solve this is when we have all constant indices.
9323 // Otherwise, we cannot determine the overflow conditions.
9324 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9325 return SE.getCouldNotCompute();
9327 // Okay at this point we know that all elements of the chrec are constants and
9328 // that the start element is zero.
9330 // First check to see if the range contains zero. If not, the first
9332 unsigned BitWidth = SE.getTypeSizeInBits(getType());
9333 if (!Range.contains(APInt(BitWidth, 0)))
9334 return SE.getZero(getType());
9337 // If this is an affine expression then we have this situation:
9338 // Solve {0,+,A} in Range === Ax in Range
9340 // We know that zero is in the range. If A is positive then we know that
9341 // the upper value of the range must be the first possible exit value.
9342 // If A is negative then the lower of the range is the last possible loop
9343 // value. Also note that we already checked for a full range.
9344 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9345 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9347 // The exit value should be (End+A)/A.
9348 APInt ExitVal = (End + A).udiv(A);
9349 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9351 // Evaluate at the exit value. If we really did fall out of the valid
9352 // range, then we computed our trip count, otherwise wrap around or other
9353 // things must have happened.
9354 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9355 if (Range.contains(Val->getValue()))
9356 return SE.getCouldNotCompute(); // Something strange happened
9358 // Ensure that the previous value is in the range. This is a sanity check.
9359 assert(Range.contains(
9360 EvaluateConstantChrecAtConstant(this,
9361 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9362 "Linear scev computation is off in a bad way!");
9363 return SE.getConstant(ExitValue);
9364 } else if (isQuadratic()) {
9365 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9366 // quadratic equation to solve it. To do this, we must frame our problem in
9367 // terms of figuring out when zero is crossed, instead of when
9368 // Range.getUpper() is crossed.
9369 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9370 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9371 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9373 // Next, solve the constructed addrec
9375 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9376 const SCEVConstant *R1 = Roots->first;
9377 const SCEVConstant *R2 = Roots->second;
9378 // Pick the smallest positive root value.
9379 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9380 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9381 if (!CB->getZExtValue())
9382 std::swap(R1, R2); // R1 is the minimum root now.
9384 // Make sure the root is not off by one. The returned iteration should
9385 // not be in the range, but the previous one should be. When solving
9386 // for "X*X < 5", for example, we should not return a root of 2.
9387 ConstantInt *R1Val =
9388 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9389 if (Range.contains(R1Val->getValue())) {
9390 // The next iteration must be out of the range...
9391 ConstantInt *NextVal =
9392 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9394 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9395 if (!Range.contains(R1Val->getValue()))
9396 return SE.getConstant(NextVal);
9397 return SE.getCouldNotCompute(); // Something strange happened
9400 // If R1 was not in the range, then it is a good return value. Make
9401 // sure that R1-1 WAS in the range though, just in case.
9402 ConstantInt *NextVal =
9403 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9404 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9405 if (Range.contains(R1Val->getValue()))
9407 return SE.getCouldNotCompute(); // Something strange happened
9412 return SE.getCouldNotCompute();
9415 // Return true when S contains at least an undef value.
9416 static inline bool containsUndefs(const SCEV *S) {
9417 return SCEVExprContains(S, [](const SCEV *S) {
9418 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9419 return isa<UndefValue>(SU->getValue());
9420 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9421 return isa<UndefValue>(SC->getValue());
9427 // Collect all steps of SCEV expressions.
9428 struct SCEVCollectStrides {
9429 ScalarEvolution &SE;
9430 SmallVectorImpl<const SCEV *> &Strides;
9432 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9433 : SE(SE), Strides(S) {}
9435 bool follow(const SCEV *S) {
9436 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9437 Strides.push_back(AR->getStepRecurrence(SE));
9440 bool isDone() const { return false; }
9443 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9444 struct SCEVCollectTerms {
9445 SmallVectorImpl<const SCEV *> &Terms;
9447 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9450 bool follow(const SCEV *S) {
9451 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9452 isa<SCEVSignExtendExpr>(S)) {
9453 if (!containsUndefs(S))
9456 // Stop recursion: once we collected a term, do not walk its operands.
9463 bool isDone() const { return false; }
9466 // Check if a SCEV contains an AddRecExpr.
9467 struct SCEVHasAddRec {
9468 bool &ContainsAddRec;
9470 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9471 ContainsAddRec = false;
9474 bool follow(const SCEV *S) {
9475 if (isa<SCEVAddRecExpr>(S)) {
9476 ContainsAddRec = true;
9478 // Stop recursion: once we collected a term, do not walk its operands.
9485 bool isDone() const { return false; }
9488 // Find factors that are multiplied with an expression that (possibly as a
9489 // subexpression) contains an AddRecExpr. In the expression:
9491 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9493 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9494 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9495 // parameters as they form a product with an induction variable.
9497 // This collector expects all array size parameters to be in the same MulExpr.
9498 // It might be necessary to later add support for collecting parameters that are
9499 // spread over different nested MulExpr.
9500 struct SCEVCollectAddRecMultiplies {
9501 SmallVectorImpl<const SCEV *> &Terms;
9502 ScalarEvolution &SE;
9504 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9505 : Terms(T), SE(SE) {}
9507 bool follow(const SCEV *S) {
9508 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9509 bool HasAddRec = false;
9510 SmallVector<const SCEV *, 0> Operands;
9511 for (auto Op : Mul->operands()) {
9512 if (isa<SCEVUnknown>(Op)) {
9513 Operands.push_back(Op);
9515 bool ContainsAddRec;
9516 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9517 visitAll(Op, ContiansAddRec);
9518 HasAddRec |= ContainsAddRec;
9521 if (Operands.size() == 0)
9527 Terms.push_back(SE.getMulExpr(Operands));
9528 // Stop recursion: once we collected a term, do not walk its operands.
9535 bool isDone() const { return false; }
9539 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9541 /// 1) The strides of AddRec expressions.
9542 /// 2) Unknowns that are multiplied with AddRec expressions.
9543 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9544 SmallVectorImpl<const SCEV *> &Terms) {
9545 SmallVector<const SCEV *, 4> Strides;
9546 SCEVCollectStrides StrideCollector(*this, Strides);
9547 visitAll(Expr, StrideCollector);
9550 dbgs() << "Strides:\n";
9551 for (const SCEV *S : Strides)
9552 dbgs() << *S << "\n";
9555 for (const SCEV *S : Strides) {
9556 SCEVCollectTerms TermCollector(Terms);
9557 visitAll(S, TermCollector);
9561 dbgs() << "Terms:\n";
9562 for (const SCEV *T : Terms)
9563 dbgs() << *T << "\n";
9566 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9567 visitAll(Expr, MulCollector);
9570 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9571 SmallVectorImpl<const SCEV *> &Terms,
9572 SmallVectorImpl<const SCEV *> &Sizes) {
9573 int Last = Terms.size() - 1;
9574 const SCEV *Step = Terms[Last];
9576 // End of recursion.
9578 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9579 SmallVector<const SCEV *, 2> Qs;
9580 for (const SCEV *Op : M->operands())
9581 if (!isa<SCEVConstant>(Op))
9584 Step = SE.getMulExpr(Qs);
9587 Sizes.push_back(Step);
9591 for (const SCEV *&Term : Terms) {
9592 // Normalize the terms before the next call to findArrayDimensionsRec.
9594 SCEVDivision::divide(SE, Term, Step, &Q, &R);
9596 // Bail out when GCD does not evenly divide one of the terms.
9603 // Remove all SCEVConstants.
9605 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9608 if (Terms.size() > 0)
9609 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9612 Sizes.push_back(Step);
9617 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9618 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9619 for (const SCEV *T : Terms)
9620 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9625 // Return the number of product terms in S.
9626 static inline int numberOfTerms(const SCEV *S) {
9627 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9628 return Expr->getNumOperands();
9632 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9633 if (isa<SCEVConstant>(T))
9636 if (isa<SCEVUnknown>(T))
9639 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9640 SmallVector<const SCEV *, 2> Factors;
9641 for (const SCEV *Op : M->operands())
9642 if (!isa<SCEVConstant>(Op))
9643 Factors.push_back(Op);
9645 return SE.getMulExpr(Factors);
9651 /// Return the size of an element read or written by Inst.
9652 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9654 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9655 Ty = Store->getValueOperand()->getType();
9656 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9657 Ty = Load->getType();
9661 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9662 return getSizeOfExpr(ETy, Ty);
9665 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9666 SmallVectorImpl<const SCEV *> &Sizes,
9667 const SCEV *ElementSize) {
9668 if (Terms.size() < 1 || !ElementSize)
9671 // Early return when Terms do not contain parameters: we do not delinearize
9672 // non parametric SCEVs.
9673 if (!containsParameters(Terms))
9677 dbgs() << "Terms:\n";
9678 for (const SCEV *T : Terms)
9679 dbgs() << *T << "\n";
9682 // Remove duplicates.
9683 array_pod_sort(Terms.begin(), Terms.end());
9684 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9686 // Put larger terms first.
9687 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9688 return numberOfTerms(LHS) > numberOfTerms(RHS);
9691 // Try to divide all terms by the element size. If term is not divisible by
9692 // element size, proceed with the original term.
9693 for (const SCEV *&Term : Terms) {
9695 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
9700 SmallVector<const SCEV *, 4> NewTerms;
9702 // Remove constant factors.
9703 for (const SCEV *T : Terms)
9704 if (const SCEV *NewT = removeConstantFactors(*this, T))
9705 NewTerms.push_back(NewT);
9708 dbgs() << "Terms after sorting:\n";
9709 for (const SCEV *T : NewTerms)
9710 dbgs() << *T << "\n";
9713 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
9718 // The last element to be pushed into Sizes is the size of an element.
9719 Sizes.push_back(ElementSize);
9722 dbgs() << "Sizes:\n";
9723 for (const SCEV *S : Sizes)
9724 dbgs() << *S << "\n";
9728 void ScalarEvolution::computeAccessFunctions(
9729 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9730 SmallVectorImpl<const SCEV *> &Sizes) {
9732 // Early exit in case this SCEV is not an affine multivariate function.
9736 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9737 if (!AR->isAffine())
9740 const SCEV *Res = Expr;
9741 int Last = Sizes.size() - 1;
9742 for (int i = Last; i >= 0; i--) {
9744 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9747 dbgs() << "Res: " << *Res << "\n";
9748 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9749 dbgs() << "Res divided by Sizes[i]:\n";
9750 dbgs() << "Quotient: " << *Q << "\n";
9751 dbgs() << "Remainder: " << *R << "\n";
9756 // Do not record the last subscript corresponding to the size of elements in
9760 // Bail out if the remainder is too complex.
9761 if (isa<SCEVAddRecExpr>(R)) {
9770 // Record the access function for the current subscript.
9771 Subscripts.push_back(R);
9774 // Also push in last position the remainder of the last division: it will be
9775 // the access function of the innermost dimension.
9776 Subscripts.push_back(Res);
9778 std::reverse(Subscripts.begin(), Subscripts.end());
9781 dbgs() << "Subscripts:\n";
9782 for (const SCEV *S : Subscripts)
9783 dbgs() << *S << "\n";
9787 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9788 /// sizes of an array access. Returns the remainder of the delinearization that
9789 /// is the offset start of the array. The SCEV->delinearize algorithm computes
9790 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9791 /// expressions in the stride and base of a SCEV corresponding to the
9792 /// computation of a GCD (greatest common divisor) of base and stride. When
9793 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9795 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9797 /// void foo(long n, long m, long o, double A[n][m][o]) {
9799 /// for (long i = 0; i < n; i++)
9800 /// for (long j = 0; j < m; j++)
9801 /// for (long k = 0; k < o; k++)
9802 /// A[i][j][k] = 1.0;
9805 /// the delinearization input is the following AddRec SCEV:
9807 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9809 /// From this SCEV, we are able to say that the base offset of the access is %A
9810 /// because it appears as an offset that does not divide any of the strides in
9813 /// CHECK: Base offset: %A
9815 /// and then SCEV->delinearize determines the size of some of the dimensions of
9816 /// the array as these are the multiples by which the strides are happening:
9818 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9820 /// Note that the outermost dimension remains of UnknownSize because there are
9821 /// no strides that would help identifying the size of the last dimension: when
9822 /// the array has been statically allocated, one could compute the size of that
9823 /// dimension by dividing the overall size of the array by the size of the known
9824 /// dimensions: %m * %o * 8.
9826 /// Finally delinearize provides the access functions for the array reference
9827 /// that does correspond to A[i][j][k] of the above C testcase:
9829 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9831 /// The testcases are checking the output of a function pass:
9832 /// DelinearizationPass that walks through all loads and stores of a function
9833 /// asking for the SCEV of the memory access with respect to all enclosing
9834 /// loops, calling SCEV->delinearize on that and printing the results.
9836 void ScalarEvolution::delinearize(const SCEV *Expr,
9837 SmallVectorImpl<const SCEV *> &Subscripts,
9838 SmallVectorImpl<const SCEV *> &Sizes,
9839 const SCEV *ElementSize) {
9840 // First step: collect parametric terms.
9841 SmallVector<const SCEV *, 4> Terms;
9842 collectParametricTerms(Expr, Terms);
9847 // Second step: find subscript sizes.
9848 findArrayDimensions(Terms, Sizes, ElementSize);
9853 // Third step: compute the access functions for each subscript.
9854 computeAccessFunctions(Expr, Subscripts, Sizes);
9856 if (Subscripts.empty())
9860 dbgs() << "succeeded to delinearize " << *Expr << "\n";
9861 dbgs() << "ArrayDecl[UnknownSize]";
9862 for (const SCEV *S : Sizes)
9863 dbgs() << "[" << *S << "]";
9865 dbgs() << "\nArrayRef";
9866 for (const SCEV *S : Subscripts)
9867 dbgs() << "[" << *S << "]";
9872 //===----------------------------------------------------------------------===//
9873 // SCEVCallbackVH Class Implementation
9874 //===----------------------------------------------------------------------===//
9876 void ScalarEvolution::SCEVCallbackVH::deleted() {
9877 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9878 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9879 SE->ConstantEvolutionLoopExitValue.erase(PN);
9880 SE->eraseValueFromMap(getValPtr());
9881 // this now dangles!
9884 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9885 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9887 // Forget all the expressions associated with users of the old value,
9888 // so that future queries will recompute the expressions using the new
9890 Value *Old = getValPtr();
9891 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9892 SmallPtrSet<User *, 8> Visited;
9893 while (!Worklist.empty()) {
9894 User *U = Worklist.pop_back_val();
9895 // Deleting the Old value will cause this to dangle. Postpone
9896 // that until everything else is done.
9899 if (!Visited.insert(U).second)
9901 if (PHINode *PN = dyn_cast<PHINode>(U))
9902 SE->ConstantEvolutionLoopExitValue.erase(PN);
9903 SE->eraseValueFromMap(U);
9904 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9906 // Delete the Old value.
9907 if (PHINode *PN = dyn_cast<PHINode>(Old))
9908 SE->ConstantEvolutionLoopExitValue.erase(PN);
9909 SE->eraseValueFromMap(Old);
9910 // this now dangles!
9913 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9914 : CallbackVH(V), SE(se) {}
9916 //===----------------------------------------------------------------------===//
9917 // ScalarEvolution Class Implementation
9918 //===----------------------------------------------------------------------===//
9920 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9921 AssumptionCache &AC, DominatorTree &DT,
9923 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9924 CouldNotCompute(new SCEVCouldNotCompute()),
9925 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9926 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9927 FirstUnknown(nullptr) {
9929 // To use guards for proving predicates, we need to scan every instruction in
9930 // relevant basic blocks, and not just terminators. Doing this is a waste of
9931 // time if the IR does not actually contain any calls to
9932 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9934 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9935 // to _add_ guards to the module when there weren't any before, and wants
9936 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9937 // efficient in lieu of being smart in that rather obscure case.
9939 auto *GuardDecl = F.getParent()->getFunction(
9940 Intrinsic::getName(Intrinsic::experimental_guard));
9941 HasGuards = GuardDecl && !GuardDecl->use_empty();
9944 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9945 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9946 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9947 ValueExprMap(std::move(Arg.ValueExprMap)),
9948 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9949 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9950 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9951 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9952 PredicatedBackedgeTakenCounts(
9953 std::move(Arg.PredicatedBackedgeTakenCounts)),
9954 ConstantEvolutionLoopExitValue(
9955 std::move(Arg.ConstantEvolutionLoopExitValue)),
9956 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9957 LoopDispositions(std::move(Arg.LoopDispositions)),
9958 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9959 BlockDispositions(std::move(Arg.BlockDispositions)),
9960 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9961 SignedRanges(std::move(Arg.SignedRanges)),
9962 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9963 UniquePreds(std::move(Arg.UniquePreds)),
9964 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9965 FirstUnknown(Arg.FirstUnknown) {
9966 Arg.FirstUnknown = nullptr;
9969 ScalarEvolution::~ScalarEvolution() {
9970 // Iterate through all the SCEVUnknown instances and call their
9971 // destructors, so that they release their references to their values.
9972 for (SCEVUnknown *U = FirstUnknown; U;) {
9973 SCEVUnknown *Tmp = U;
9975 Tmp->~SCEVUnknown();
9977 FirstUnknown = nullptr;
9979 ExprValueMap.clear();
9980 ValueExprMap.clear();
9983 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9984 // that a loop had multiple computable exits.
9985 for (auto &BTCI : BackedgeTakenCounts)
9986 BTCI.second.clear();
9987 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9988 BTCI.second.clear();
9990 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9991 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9992 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9995 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9996 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9999 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10001 // Print all inner loops first
10003 PrintLoopInfo(OS, SE, I);
10006 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10009 SmallVector<BasicBlock *, 8> ExitBlocks;
10010 L->getExitBlocks(ExitBlocks);
10011 if (ExitBlocks.size() != 1)
10012 OS << "<multiple exits> ";
10014 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10015 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10017 OS << "Unpredictable backedge-taken count. ";
10022 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10025 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10026 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10027 if (SE->isBackedgeTakenCountMaxOrZero(L))
10028 OS << ", actual taken count either this or zero.";
10030 OS << "Unpredictable max backedge-taken count. ";
10035 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10038 SCEVUnionPredicate Pred;
10039 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10040 if (!isa<SCEVCouldNotCompute>(PBT)) {
10041 OS << "Predicated backedge-taken count is " << *PBT << "\n";
10042 OS << " Predicates:\n";
10045 OS << "Unpredictable predicated backedge-taken count. ";
10049 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10051 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10053 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10057 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10059 case ScalarEvolution::LoopVariant:
10061 case ScalarEvolution::LoopInvariant:
10062 return "Invariant";
10063 case ScalarEvolution::LoopComputable:
10064 return "Computable";
10066 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10069 void ScalarEvolution::print(raw_ostream &OS) const {
10070 // ScalarEvolution's implementation of the print method is to print
10071 // out SCEV values of all instructions that are interesting. Doing
10072 // this potentially causes it to create new SCEV objects though,
10073 // which technically conflicts with the const qualifier. This isn't
10074 // observable from outside the class though, so casting away the
10075 // const isn't dangerous.
10076 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10078 OS << "Classifying expressions for: ";
10079 F.printAsOperand(OS, /*PrintType=*/false);
10081 for (Instruction &I : instructions(F))
10082 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10085 const SCEV *SV = SE.getSCEV(&I);
10087 if (!isa<SCEVCouldNotCompute>(SV)) {
10089 SE.getUnsignedRange(SV).print(OS);
10091 SE.getSignedRange(SV).print(OS);
10094 const Loop *L = LI.getLoopFor(I.getParent());
10096 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10100 if (!isa<SCEVCouldNotCompute>(AtUse)) {
10102 SE.getUnsignedRange(AtUse).print(OS);
10104 SE.getSignedRange(AtUse).print(OS);
10109 OS << "\t\t" "Exits: ";
10110 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10111 if (!SE.isLoopInvariant(ExitValue, L)) {
10112 OS << "<<Unknown>>";
10118 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10120 OS << "\t\t" "LoopDispositions: { ";
10126 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10127 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10130 for (auto *InnerL : depth_first(L)) {
10134 OS << "\t\t" "LoopDispositions: { ";
10140 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10141 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10150 OS << "Determining loop execution counts for: ";
10151 F.printAsOperand(OS, /*PrintType=*/false);
10154 PrintLoopInfo(OS, &SE, I);
10157 ScalarEvolution::LoopDisposition
10158 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10159 auto &Values = LoopDispositions[S];
10160 for (auto &V : Values) {
10161 if (V.getPointer() == L)
10164 Values.emplace_back(L, LoopVariant);
10165 LoopDisposition D = computeLoopDisposition(S, L);
10166 auto &Values2 = LoopDispositions[S];
10167 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10168 if (V.getPointer() == L) {
10176 ScalarEvolution::LoopDisposition
10177 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10178 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10180 return LoopInvariant;
10184 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10185 case scAddRecExpr: {
10186 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10188 // If L is the addrec's loop, it's computable.
10189 if (AR->getLoop() == L)
10190 return LoopComputable;
10192 // Add recurrences are never invariant in the function-body (null loop).
10194 return LoopVariant;
10196 // This recurrence is variant w.r.t. L if L contains AR's loop.
10197 if (L->contains(AR->getLoop()))
10198 return LoopVariant;
10200 // This recurrence is invariant w.r.t. L if AR's loop contains L.
10201 if (AR->getLoop()->contains(L))
10202 return LoopInvariant;
10204 // This recurrence is variant w.r.t. L if any of its operands
10206 for (auto *Op : AR->operands())
10207 if (!isLoopInvariant(Op, L))
10208 return LoopVariant;
10210 // Otherwise it's loop-invariant.
10211 return LoopInvariant;
10217 bool HasVarying = false;
10218 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10219 LoopDisposition D = getLoopDisposition(Op, L);
10220 if (D == LoopVariant)
10221 return LoopVariant;
10222 if (D == LoopComputable)
10225 return HasVarying ? LoopComputable : LoopInvariant;
10228 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10229 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10230 if (LD == LoopVariant)
10231 return LoopVariant;
10232 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10233 if (RD == LoopVariant)
10234 return LoopVariant;
10235 return (LD == LoopInvariant && RD == LoopInvariant) ?
10236 LoopInvariant : LoopComputable;
10239 // All non-instruction values are loop invariant. All instructions are loop
10240 // invariant if they are not contained in the specified loop.
10241 // Instructions are never considered invariant in the function body
10242 // (null loop) because they are defined within the "loop".
10243 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10244 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10245 return LoopInvariant;
10246 case scCouldNotCompute:
10247 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10249 llvm_unreachable("Unknown SCEV kind!");
10252 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10253 return getLoopDisposition(S, L) == LoopInvariant;
10256 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10257 return getLoopDisposition(S, L) == LoopComputable;
10260 ScalarEvolution::BlockDisposition
10261 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10262 auto &Values = BlockDispositions[S];
10263 for (auto &V : Values) {
10264 if (V.getPointer() == BB)
10267 Values.emplace_back(BB, DoesNotDominateBlock);
10268 BlockDisposition D = computeBlockDisposition(S, BB);
10269 auto &Values2 = BlockDispositions[S];
10270 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10271 if (V.getPointer() == BB) {
10279 ScalarEvolution::BlockDisposition
10280 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10281 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10283 return ProperlyDominatesBlock;
10287 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10288 case scAddRecExpr: {
10289 // This uses a "dominates" query instead of "properly dominates" query
10290 // to test for proper dominance too, because the instruction which
10291 // produces the addrec's value is a PHI, and a PHI effectively properly
10292 // dominates its entire containing block.
10293 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10294 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10295 return DoesNotDominateBlock;
10297 // Fall through into SCEVNAryExpr handling.
10304 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10305 bool Proper = true;
10306 for (const SCEV *NAryOp : NAry->operands()) {
10307 BlockDisposition D = getBlockDisposition(NAryOp, BB);
10308 if (D == DoesNotDominateBlock)
10309 return DoesNotDominateBlock;
10310 if (D == DominatesBlock)
10313 return Proper ? ProperlyDominatesBlock : DominatesBlock;
10316 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10317 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10318 BlockDisposition LD = getBlockDisposition(LHS, BB);
10319 if (LD == DoesNotDominateBlock)
10320 return DoesNotDominateBlock;
10321 BlockDisposition RD = getBlockDisposition(RHS, BB);
10322 if (RD == DoesNotDominateBlock)
10323 return DoesNotDominateBlock;
10324 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10325 ProperlyDominatesBlock : DominatesBlock;
10328 if (Instruction *I =
10329 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10330 if (I->getParent() == BB)
10331 return DominatesBlock;
10332 if (DT.properlyDominates(I->getParent(), BB))
10333 return ProperlyDominatesBlock;
10334 return DoesNotDominateBlock;
10336 return ProperlyDominatesBlock;
10337 case scCouldNotCompute:
10338 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10340 llvm_unreachable("Unknown SCEV kind!");
10343 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10344 return getBlockDisposition(S, BB) >= DominatesBlock;
10347 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10348 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10351 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10352 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10355 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10356 ValuesAtScopes.erase(S);
10357 LoopDispositions.erase(S);
10358 BlockDispositions.erase(S);
10359 UnsignedRanges.erase(S);
10360 SignedRanges.erase(S);
10361 ExprValueMap.erase(S);
10362 HasRecMap.erase(S);
10363 MinTrailingZerosCache.erase(S);
10365 auto RemoveSCEVFromBackedgeMap =
10366 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10367 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10368 BackedgeTakenInfo &BEInfo = I->second;
10369 if (BEInfo.hasOperand(S, this)) {
10377 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10378 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10381 void ScalarEvolution::verify() const {
10382 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10383 ScalarEvolution SE2(F, TLI, AC, DT, LI);
10385 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
10387 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10388 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10389 const SCEV *visitConstant(const SCEVConstant *Constant) {
10390 return SE.getConstant(Constant->getAPInt());
10392 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10393 return SE.getUnknown(Expr->getValue());
10396 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10397 return SE.getCouldNotCompute();
10399 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10402 SCEVMapper SCM(SE2);
10404 while (!LoopStack.empty()) {
10405 auto *L = LoopStack.pop_back_val();
10406 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10408 auto *CurBECount = SCM.visit(
10409 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10410 auto *NewBECount = SE2.getBackedgeTakenCount(L);
10412 if (CurBECount == SE2.getCouldNotCompute() ||
10413 NewBECount == SE2.getCouldNotCompute()) {
10414 // NB! This situation is legal, but is very suspicious -- whatever pass
10415 // change the loop to make a trip count go from could not compute to
10416 // computable or vice-versa *should have* invalidated SCEV. However, we
10417 // choose not to assert here (for now) since we don't want false
10422 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10423 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10424 // not propagate undef aggressively). This means we can (and do) fail
10425 // verification in cases where a transform makes the trip count of a loop
10426 // go from "undef" to "undef+1" (say). The transform is fine, since in
10427 // both cases the loop iterates "undef" times, but SCEV thinks we
10428 // increased the trip count of the loop by 1 incorrectly.
10432 if (SE.getTypeSizeInBits(CurBECount->getType()) >
10433 SE.getTypeSizeInBits(NewBECount->getType()))
10434 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10435 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10436 SE.getTypeSizeInBits(NewBECount->getType()))
10437 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10439 auto *ConstantDelta =
10440 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10442 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10443 dbgs() << "Trip Count Changed!\n";
10444 dbgs() << "Old: " << *CurBECount << "\n";
10445 dbgs() << "New: " << *NewBECount << "\n";
10446 dbgs() << "Delta: " << *ConstantDelta << "\n";
10452 bool ScalarEvolution::invalidate(
10453 Function &F, const PreservedAnalyses &PA,
10454 FunctionAnalysisManager::Invalidator &Inv) {
10455 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10456 // of its dependencies is invalidated.
10457 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10458 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10459 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10460 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10461 Inv.invalidate<LoopAnalysis>(F, PA);
10464 AnalysisKey ScalarEvolutionAnalysis::Key;
10466 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10467 FunctionAnalysisManager &AM) {
10468 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10469 AM.getResult<AssumptionAnalysis>(F),
10470 AM.getResult<DominatorTreeAnalysis>(F),
10471 AM.getResult<LoopAnalysis>(F));
10475 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10476 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10477 return PreservedAnalyses::all();
10480 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10481 "Scalar Evolution Analysis", false, true)
10482 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10483 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10484 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10485 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10486 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10487 "Scalar Evolution Analysis", false, true)
10488 char ScalarEvolutionWrapperPass::ID = 0;
10490 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10491 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10494 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10495 SE.reset(new ScalarEvolution(
10496 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10497 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10498 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10499 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10503 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10505 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10509 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10516 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10517 AU.setPreservesAll();
10518 AU.addRequiredTransitive<AssumptionCacheTracker>();
10519 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10520 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10521 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10524 const SCEVPredicate *
10525 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10526 const SCEVConstant *RHS) {
10527 FoldingSetNodeID ID;
10528 // Unique this node based on the arguments
10529 ID.AddInteger(SCEVPredicate::P_Equal);
10530 ID.AddPointer(LHS);
10531 ID.AddPointer(RHS);
10532 void *IP = nullptr;
10533 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10535 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10536 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10537 UniquePreds.InsertNode(Eq, IP);
10541 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10542 const SCEVAddRecExpr *AR,
10543 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10544 FoldingSetNodeID ID;
10545 // Unique this node based on the arguments
10546 ID.AddInteger(SCEVPredicate::P_Wrap);
10548 ID.AddInteger(AddedFlags);
10549 void *IP = nullptr;
10550 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10552 auto *OF = new (SCEVAllocator)
10553 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10554 UniquePreds.InsertNode(OF, IP);
10560 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10562 /// Rewrites \p S in the context of a loop L and the SCEV predication
10563 /// infrastructure.
10565 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10566 /// equivalences present in \p Pred.
10568 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10569 /// \p NewPreds such that the result will be an AddRecExpr.
10570 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10571 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10572 SCEVUnionPredicate *Pred) {
10573 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10574 return Rewriter.visit(S);
10577 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10578 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10579 SCEVUnionPredicate *Pred)
10580 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10582 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10584 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10585 for (auto *Pred : ExprPreds)
10586 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10587 if (IPred->getLHS() == Expr)
10588 return IPred->getRHS();
10594 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10595 const SCEV *Operand = visit(Expr->getOperand());
10596 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10597 if (AR && AR->getLoop() == L && AR->isAffine()) {
10598 // This couldn't be folded because the operand didn't have the nuw
10599 // flag. Add the nusw flag as an assumption that we could make.
10600 const SCEV *Step = AR->getStepRecurrence(SE);
10601 Type *Ty = Expr->getType();
10602 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10603 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10604 SE.getSignExtendExpr(Step, Ty), L,
10605 AR->getNoWrapFlags());
10607 return SE.getZeroExtendExpr(Operand, Expr->getType());
10610 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10611 const SCEV *Operand = visit(Expr->getOperand());
10612 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10613 if (AR && AR->getLoop() == L && AR->isAffine()) {
10614 // This couldn't be folded because the operand didn't have the nsw
10615 // flag. Add the nssw flag as an assumption that we could make.
10616 const SCEV *Step = AR->getStepRecurrence(SE);
10617 Type *Ty = Expr->getType();
10618 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10619 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10620 SE.getSignExtendExpr(Step, Ty), L,
10621 AR->getNoWrapFlags());
10623 return SE.getSignExtendExpr(Operand, Expr->getType());
10627 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10628 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10629 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10631 // Check if we've already made this assumption.
10632 return Pred && Pred->implies(A);
10634 NewPreds->insert(A);
10638 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10639 SCEVUnionPredicate *Pred;
10642 } // end anonymous namespace
10644 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10645 SCEVUnionPredicate &Preds) {
10646 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10649 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10650 const SCEV *S, const Loop *L,
10651 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10653 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10654 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10655 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10660 // Since the transformation was successful, we can now transfer the SCEV
10662 for (auto *P : TransformPreds)
10668 /// SCEV predicates
10669 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10670 SCEVPredicateKind Kind)
10671 : FastID(ID), Kind(Kind) {}
10673 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10674 const SCEVUnknown *LHS,
10675 const SCEVConstant *RHS)
10676 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10678 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10679 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10684 return Op->LHS == LHS && Op->RHS == RHS;
10687 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10689 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10691 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10692 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10695 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10696 const SCEVAddRecExpr *AR,
10697 IncrementWrapFlags Flags)
10698 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10700 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10702 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10703 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10705 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10708 bool SCEVWrapPredicate::isAlwaysTrue() const {
10709 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10710 IncrementWrapFlags IFlags = Flags;
10712 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10713 IFlags = clearFlags(IFlags, IncrementNSSW);
10715 return IFlags == IncrementAnyWrap;
10718 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10719 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10720 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10722 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10727 SCEVWrapPredicate::IncrementWrapFlags
10728 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10729 ScalarEvolution &SE) {
10730 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10731 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10733 // We can safely transfer the NSW flag as NSSW.
10734 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10735 ImpliedFlags = IncrementNSSW;
10737 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10738 // If the increment is positive, the SCEV NUW flag will also imply the
10739 // WrapPredicate NUSW flag.
10740 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10741 if (Step->getValue()->getValue().isNonNegative())
10742 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10745 return ImpliedFlags;
10748 /// Union predicates don't get cached so create a dummy set ID for it.
10749 SCEVUnionPredicate::SCEVUnionPredicate()
10750 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10752 bool SCEVUnionPredicate::isAlwaysTrue() const {
10753 return all_of(Preds,
10754 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10757 ArrayRef<const SCEVPredicate *>
10758 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10759 auto I = SCEVToPreds.find(Expr);
10760 if (I == SCEVToPreds.end())
10761 return ArrayRef<const SCEVPredicate *>();
10765 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10766 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10767 return all_of(Set->Preds,
10768 [this](const SCEVPredicate *I) { return this->implies(I); });
10770 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10771 if (ScevPredsIt == SCEVToPreds.end())
10773 auto &SCEVPreds = ScevPredsIt->second;
10775 return any_of(SCEVPreds,
10776 [N](const SCEVPredicate *I) { return I->implies(N); });
10779 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10781 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10782 for (auto Pred : Preds)
10783 Pred->print(OS, Depth);
10786 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10787 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10788 for (auto Pred : Set->Preds)
10796 const SCEV *Key = N->getExpr();
10797 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10798 " associated expression!");
10800 SCEVToPreds[Key].push_back(N);
10801 Preds.push_back(N);
10804 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10806 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10808 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10809 const SCEV *Expr = SE.getSCEV(V);
10810 RewriteEntry &Entry = RewriteMap[Expr];
10812 // If we already have an entry and the version matches, return it.
10813 if (Entry.second && Generation == Entry.first)
10814 return Entry.second;
10816 // We found an entry but it's stale. Rewrite the stale entry
10817 // according to the current predicate.
10819 Expr = Entry.second;
10821 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10822 Entry = {Generation, NewSCEV};
10827 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10828 if (!BackedgeCount) {
10829 SCEVUnionPredicate BackedgePred;
10830 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10831 addPredicate(BackedgePred);
10833 return BackedgeCount;
10836 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10837 if (Preds.implies(&Pred))
10840 updateGeneration();
10843 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10847 void PredicatedScalarEvolution::updateGeneration() {
10848 // If the generation number wrapped recompute everything.
10849 if (++Generation == 0) {
10850 for (auto &II : RewriteMap) {
10851 const SCEV *Rewritten = II.second.second;
10852 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10857 void PredicatedScalarEvolution::setNoOverflow(
10858 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10859 const SCEV *Expr = getSCEV(V);
10860 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10862 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10864 // Clear the statically implied flags.
10865 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10866 addPredicate(*SE.getWrapPredicate(AR, Flags));
10868 auto II = FlagsMap.insert({V, Flags});
10870 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10873 bool PredicatedScalarEvolution::hasNoOverflow(
10874 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10875 const SCEV *Expr = getSCEV(V);
10876 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10878 Flags = SCEVWrapPredicate::clearFlags(
10879 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10881 auto II = FlagsMap.find(V);
10883 if (II != FlagsMap.end())
10884 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10886 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10889 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10890 const SCEV *Expr = this->getSCEV(V);
10891 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10892 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10897 for (auto *P : NewPreds)
10900 updateGeneration();
10901 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10905 PredicatedScalarEvolution::PredicatedScalarEvolution(
10906 const PredicatedScalarEvolution &Init)
10907 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10908 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10909 for (const auto &I : Init.FlagsMap)
10910 FlagsMap.insert(I);
10913 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10915 for (auto *BB : L.getBlocks())
10916 for (auto &I : *BB) {
10917 if (!SE.isSCEVable(I.getType()))
10920 auto *Expr = SE.getSCEV(&I);
10921 auto II = RewriteMap.find(Expr);
10923 if (II == RewriteMap.end())
10926 // Don't print things that are not interesting.
10927 if (II->second.second == Expr)
10930 OS.indent(Depth) << "[PSE]" << I << ":\n";
10931 OS.indent(Depth + 2) << *Expr << "\n";
10932 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";