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 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 // Compare addrec loop depths.
633 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
634 if (LLoop != RLoop) {
635 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
636 if (LDepth != RDepth)
637 return (int)LDepth - (int)RDepth;
640 // Addrec complexity grows with operand count.
641 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
642 if (LNumOps != RNumOps)
643 return (int)LNumOps - (int)RNumOps;
645 // Lexicographically compare.
646 for (unsigned i = 0; i != LNumOps; ++i) {
647 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
648 RA->getOperand(i), Depth + 1);
652 EqCacheSCEV.insert({LHS, RHS});
660 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
661 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
663 // Lexicographically compare n-ary expressions.
664 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
665 if (LNumOps != RNumOps)
666 return (int)LNumOps - (int)RNumOps;
668 for (unsigned i = 0; i != LNumOps; ++i) {
671 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
672 RC->getOperand(i), Depth + 1);
676 EqCacheSCEV.insert({LHS, RHS});
681 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
682 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
684 // Lexicographically compare udiv expressions.
685 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
689 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
692 EqCacheSCEV.insert({LHS, RHS});
699 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
700 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
702 // Compare cast expressions by operand.
703 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
704 RC->getOperand(), Depth + 1);
706 EqCacheSCEV.insert({LHS, RHS});
710 case scCouldNotCompute:
711 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
713 llvm_unreachable("Unknown SCEV kind!");
716 /// Given a list of SCEV objects, order them by their complexity, and group
717 /// objects of the same complexity together by value. When this routine is
718 /// finished, we know that any duplicates in the vector are consecutive and that
719 /// complexity is monotonically increasing.
721 /// Note that we go take special precautions to ensure that we get deterministic
722 /// results from this routine. In other words, we don't want the results of
723 /// this to depend on where the addresses of various SCEV objects happened to
726 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
728 if (Ops.size() < 2) return; // Noop
730 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
731 if (Ops.size() == 2) {
732 // This is the common case, which also happens to be trivially simple.
734 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
735 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
740 // Do the rough sort by complexity.
741 std::stable_sort(Ops.begin(), Ops.end(),
742 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
743 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
746 // Now that we are sorted by complexity, group elements of the same
747 // complexity. Note that this is, at worst, N^2, but the vector is likely to
748 // be extremely short in practice. Note that we take this approach because we
749 // do not want to depend on the addresses of the objects we are grouping.
750 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
751 const SCEV *S = Ops[i];
752 unsigned Complexity = S->getSCEVType();
754 // If there are any objects of the same complexity and same value as this
756 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
757 if (Ops[j] == S) { // Found a duplicate.
758 // Move it to immediately after i'th element.
759 std::swap(Ops[i+1], Ops[j]);
760 ++i; // no need to rescan it.
761 if (i == e-2) return; // Done!
767 // Returns the size of the SCEV S.
768 static inline int sizeOfSCEV(const SCEV *S) {
769 struct FindSCEVSize {
771 FindSCEVSize() : Size(0) {}
773 bool follow(const SCEV *S) {
775 // Keep looking at all operands of S.
778 bool isDone() const {
784 SCEVTraversal<FindSCEVSize> ST(F);
791 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
793 // Computes the Quotient and Remainder of the division of Numerator by
795 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
796 const SCEV *Denominator, const SCEV **Quotient,
797 const SCEV **Remainder) {
798 assert(Numerator && Denominator && "Uninitialized SCEV");
800 SCEVDivision D(SE, Numerator, Denominator);
802 // Check for the trivial case here to avoid having to check for it in the
804 if (Numerator == Denominator) {
810 if (Numerator->isZero()) {
816 // A simple case when N/1. The quotient is N.
817 if (Denominator->isOne()) {
818 *Quotient = Numerator;
823 // Split the Denominator when it is a product.
824 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
826 *Quotient = Numerator;
827 for (const SCEV *Op : T->operands()) {
828 divide(SE, *Quotient, Op, &Q, &R);
831 // Bail out when the Numerator is not divisible by one of the terms of
835 *Remainder = Numerator;
844 *Quotient = D.Quotient;
845 *Remainder = D.Remainder;
848 // Except in the trivial case described above, we do not know how to divide
849 // Expr by Denominator for the following functions with empty implementation.
850 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
851 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
852 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
853 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
854 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
855 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
856 void visitUnknown(const SCEVUnknown *Numerator) {}
857 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
859 void visitConstant(const SCEVConstant *Numerator) {
860 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
861 APInt NumeratorVal = Numerator->getAPInt();
862 APInt DenominatorVal = D->getAPInt();
863 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
864 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
866 if (NumeratorBW > DenominatorBW)
867 DenominatorVal = DenominatorVal.sext(NumeratorBW);
868 else if (NumeratorBW < DenominatorBW)
869 NumeratorVal = NumeratorVal.sext(DenominatorBW);
871 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
872 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
873 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
874 Quotient = SE.getConstant(QuotientVal);
875 Remainder = SE.getConstant(RemainderVal);
880 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
881 const SCEV *StartQ, *StartR, *StepQ, *StepR;
882 if (!Numerator->isAffine())
883 return cannotDivide(Numerator);
884 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
885 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
886 // Bail out if the types do not match.
887 Type *Ty = Denominator->getType();
888 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
889 Ty != StepQ->getType() || Ty != StepR->getType())
890 return cannotDivide(Numerator);
891 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
892 Numerator->getNoWrapFlags());
893 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
894 Numerator->getNoWrapFlags());
897 void visitAddExpr(const SCEVAddExpr *Numerator) {
898 SmallVector<const SCEV *, 2> Qs, Rs;
899 Type *Ty = Denominator->getType();
901 for (const SCEV *Op : Numerator->operands()) {
903 divide(SE, Op, Denominator, &Q, &R);
905 // Bail out if types do not match.
906 if (Ty != Q->getType() || Ty != R->getType())
907 return cannotDivide(Numerator);
913 if (Qs.size() == 1) {
919 Quotient = SE.getAddExpr(Qs);
920 Remainder = SE.getAddExpr(Rs);
923 void visitMulExpr(const SCEVMulExpr *Numerator) {
924 SmallVector<const SCEV *, 2> Qs;
925 Type *Ty = Denominator->getType();
927 bool FoundDenominatorTerm = false;
928 for (const SCEV *Op : Numerator->operands()) {
929 // Bail out if types do not match.
930 if (Ty != Op->getType())
931 return cannotDivide(Numerator);
933 if (FoundDenominatorTerm) {
938 // Check whether Denominator divides one of the product operands.
940 divide(SE, Op, Denominator, &Q, &R);
946 // Bail out if types do not match.
947 if (Ty != Q->getType())
948 return cannotDivide(Numerator);
950 FoundDenominatorTerm = true;
954 if (FoundDenominatorTerm) {
959 Quotient = SE.getMulExpr(Qs);
963 if (!isa<SCEVUnknown>(Denominator))
964 return cannotDivide(Numerator);
966 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
967 ValueToValueMap RewriteMap;
968 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
969 cast<SCEVConstant>(Zero)->getValue();
970 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
972 if (Remainder->isZero()) {
973 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
974 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
975 cast<SCEVConstant>(One)->getValue();
977 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
981 // Quotient is (Numerator - Remainder) divided by Denominator.
983 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
984 // This SCEV does not seem to simplify: fail the division here.
985 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
986 return cannotDivide(Numerator);
987 divide(SE, Diff, Denominator, &Q, &R);
989 return cannotDivide(Numerator);
994 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
995 const SCEV *Denominator)
996 : SE(S), Denominator(Denominator) {
997 Zero = SE.getZero(Denominator->getType());
998 One = SE.getOne(Denominator->getType());
1000 // We generally do not know how to divide Expr by Denominator. We
1001 // initialize the division to a "cannot divide" state to simplify the rest
1003 cannotDivide(Numerator);
1006 // Convenience function for giving up on the division. We set the quotient to
1007 // be equal to zero and the remainder to be equal to the numerator.
1008 void cannotDivide(const SCEV *Numerator) {
1010 Remainder = Numerator;
1013 ScalarEvolution &SE;
1014 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1019 //===----------------------------------------------------------------------===//
1020 // Simple SCEV method implementations
1021 //===----------------------------------------------------------------------===//
1023 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1024 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1025 ScalarEvolution &SE,
1027 // Handle the simplest case efficiently.
1029 return SE.getTruncateOrZeroExtend(It, ResultTy);
1031 // We are using the following formula for BC(It, K):
1033 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1035 // Suppose, W is the bitwidth of the return value. We must be prepared for
1036 // overflow. Hence, we must assure that the result of our computation is
1037 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1038 // safe in modular arithmetic.
1040 // However, this code doesn't use exactly that formula; the formula it uses
1041 // is something like the following, where T is the number of factors of 2 in
1042 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1045 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1047 // This formula is trivially equivalent to the previous formula. However,
1048 // this formula can be implemented much more efficiently. The trick is that
1049 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1050 // arithmetic. To do exact division in modular arithmetic, all we have
1051 // to do is multiply by the inverse. Therefore, this step can be done at
1054 // The next issue is how to safely do the division by 2^T. The way this
1055 // is done is by doing the multiplication step at a width of at least W + T
1056 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1057 // when we perform the division by 2^T (which is equivalent to a right shift
1058 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1059 // truncated out after the division by 2^T.
1061 // In comparison to just directly using the first formula, this technique
1062 // is much more efficient; using the first formula requires W * K bits,
1063 // but this formula less than W + K bits. Also, the first formula requires
1064 // a division step, whereas this formula only requires multiplies and shifts.
1066 // It doesn't matter whether the subtraction step is done in the calculation
1067 // width or the input iteration count's width; if the subtraction overflows,
1068 // the result must be zero anyway. We prefer here to do it in the width of
1069 // the induction variable because it helps a lot for certain cases; CodeGen
1070 // isn't smart enough to ignore the overflow, which leads to much less
1071 // efficient code if the width of the subtraction is wider than the native
1074 // (It's possible to not widen at all by pulling out factors of 2 before
1075 // the multiplication; for example, K=2 can be calculated as
1076 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1077 // extra arithmetic, so it's not an obvious win, and it gets
1078 // much more complicated for K > 3.)
1080 // Protection from insane SCEVs; this bound is conservative,
1081 // but it probably doesn't matter.
1083 return SE.getCouldNotCompute();
1085 unsigned W = SE.getTypeSizeInBits(ResultTy);
1087 // Calculate K! / 2^T and T; we divide out the factors of two before
1088 // multiplying for calculating K! / 2^T to avoid overflow.
1089 // Other overflow doesn't matter because we only care about the bottom
1090 // W bits of the result.
1091 APInt OddFactorial(W, 1);
1093 for (unsigned i = 3; i <= K; ++i) {
1095 unsigned TwoFactors = Mult.countTrailingZeros();
1097 Mult.lshrInPlace(TwoFactors);
1098 OddFactorial *= Mult;
1101 // We need at least W + T bits for the multiplication step
1102 unsigned CalculationBits = W + T;
1104 // Calculate 2^T, at width T+W.
1105 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1107 // Calculate the multiplicative inverse of K! / 2^T;
1108 // this multiplication factor will perform the exact division by
1110 APInt Mod = APInt::getSignedMinValue(W+1);
1111 APInt MultiplyFactor = OddFactorial.zext(W+1);
1112 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1113 MultiplyFactor = MultiplyFactor.trunc(W);
1115 // Calculate the product, at width T+W
1116 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1118 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1119 for (unsigned i = 1; i != K; ++i) {
1120 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1121 Dividend = SE.getMulExpr(Dividend,
1122 SE.getTruncateOrZeroExtend(S, CalculationTy));
1126 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1128 // Truncate the result, and divide by K! / 2^T.
1130 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1131 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1134 /// Return the value of this chain of recurrences at the specified iteration
1135 /// number. We can evaluate this recurrence by multiplying each element in the
1136 /// chain by the binomial coefficient corresponding to it. In other words, we
1137 /// can evaluate {A,+,B,+,C,+,D} as:
1139 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1141 /// where BC(It, k) stands for binomial coefficient.
1143 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1144 ScalarEvolution &SE) const {
1145 const SCEV *Result = getStart();
1146 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1147 // The computation is correct in the face of overflow provided that the
1148 // multiplication is performed _after_ the evaluation of the binomial
1150 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1151 if (isa<SCEVCouldNotCompute>(Coeff))
1154 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1159 //===----------------------------------------------------------------------===//
1160 // SCEV Expression folder implementations
1161 //===----------------------------------------------------------------------===//
1163 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1165 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1166 "This is not a truncating conversion!");
1167 assert(isSCEVable(Ty) &&
1168 "This is not a conversion to a SCEVable type!");
1169 Ty = getEffectiveSCEVType(Ty);
1171 FoldingSetNodeID ID;
1172 ID.AddInteger(scTruncate);
1176 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1178 // Fold if the operand is constant.
1179 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1181 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1183 // trunc(trunc(x)) --> trunc(x)
1184 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1185 return getTruncateExpr(ST->getOperand(), Ty);
1187 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1188 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1189 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1191 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1192 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1193 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1195 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1196 // eliminate all the truncates, or we replace other casts with truncates.
1197 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1198 SmallVector<const SCEV *, 4> Operands;
1199 bool hasTrunc = false;
1200 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1201 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1202 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1203 hasTrunc = isa<SCEVTruncateExpr>(S);
1204 Operands.push_back(S);
1207 return getAddExpr(Operands);
1208 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1211 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1212 // eliminate all the truncates, or we replace other casts with truncates.
1213 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1214 SmallVector<const SCEV *, 4> Operands;
1215 bool hasTrunc = false;
1216 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1217 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1218 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1219 hasTrunc = isa<SCEVTruncateExpr>(S);
1220 Operands.push_back(S);
1223 return getMulExpr(Operands);
1224 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1227 // If the input value is a chrec scev, truncate the chrec's operands.
1228 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1229 SmallVector<const SCEV *, 4> Operands;
1230 for (const SCEV *Op : AddRec->operands())
1231 Operands.push_back(getTruncateExpr(Op, Ty));
1232 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1235 // The cast wasn't folded; create an explicit cast node. We can reuse
1236 // the existing insert position since if we get here, we won't have
1237 // made any changes which would invalidate it.
1238 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1240 UniqueSCEVs.InsertNode(S, IP);
1244 // Get the limit of a recurrence such that incrementing by Step cannot cause
1245 // signed overflow as long as the value of the recurrence within the
1246 // loop does not exceed this limit before incrementing.
1247 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1248 ICmpInst::Predicate *Pred,
1249 ScalarEvolution *SE) {
1250 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1251 if (SE->isKnownPositive(Step)) {
1252 *Pred = ICmpInst::ICMP_SLT;
1253 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1254 SE->getSignedRange(Step).getSignedMax());
1256 if (SE->isKnownNegative(Step)) {
1257 *Pred = ICmpInst::ICMP_SGT;
1258 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1259 SE->getSignedRange(Step).getSignedMin());
1264 // Get the limit of a recurrence such that incrementing by Step cannot cause
1265 // unsigned overflow as long as the value of the recurrence within the loop does
1266 // not exceed this limit before incrementing.
1267 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1268 ICmpInst::Predicate *Pred,
1269 ScalarEvolution *SE) {
1270 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1271 *Pred = ICmpInst::ICMP_ULT;
1273 return SE->getConstant(APInt::getMinValue(BitWidth) -
1274 SE->getUnsignedRange(Step).getUnsignedMax());
1279 struct ExtendOpTraitsBase {
1280 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1281 const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1284 // Used to make code generic over signed and unsigned overflow.
1285 template <typename ExtendOp> struct ExtendOpTraits {
1288 // static const SCEV::NoWrapFlags WrapType;
1290 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1292 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1293 // ICmpInst::Predicate *Pred,
1294 // ScalarEvolution *SE);
1298 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1299 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1301 static const GetExtendExprTy GetExtendExpr;
1303 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1304 ICmpInst::Predicate *Pred,
1305 ScalarEvolution *SE) {
1306 return getSignedOverflowLimitForStep(Step, Pred, SE);
1310 const ExtendOpTraitsBase::GetExtendExprTy
1311 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1312 &ScalarEvolution::getSignExtendExprCached;
1315 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1316 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1318 static const GetExtendExprTy GetExtendExpr;
1320 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1321 ICmpInst::Predicate *Pred,
1322 ScalarEvolution *SE) {
1323 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1327 const ExtendOpTraitsBase::GetExtendExprTy
1328 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1329 &ScalarEvolution::getZeroExtendExprCached;
1332 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1333 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1334 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1335 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1336 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1337 // expression "Step + sext/zext(PreIncAR)" is congruent with
1338 // "sext/zext(PostIncAR)"
1339 template <typename ExtendOpTy>
1340 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1341 ScalarEvolution *SE,
1342 ScalarEvolution::ExtendCacheTy &Cache) {
1343 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1344 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1346 const Loop *L = AR->getLoop();
1347 const SCEV *Start = AR->getStart();
1348 const SCEV *Step = AR->getStepRecurrence(*SE);
1350 // Check for a simple looking step prior to loop entry.
1351 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1355 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1356 // subtraction is expensive. For this purpose, perform a quick and dirty
1357 // difference, by checking for Step in the operand list.
1358 SmallVector<const SCEV *, 4> DiffOps;
1359 for (const SCEV *Op : SA->operands())
1361 DiffOps.push_back(Op);
1363 if (DiffOps.size() == SA->getNumOperands())
1366 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1369 // 1. NSW/NUW flags on the step increment.
1370 auto PreStartFlags =
1371 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1372 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1373 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1374 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1376 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1377 // "S+X does not sign/unsign-overflow".
1380 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1381 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1382 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1385 // 2. Direct overflow check on the step operation's expression.
1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1388 const SCEV *OperandExtendedStart =
1389 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1390 (SE->*GetExtendExpr)(Step, WideTy, Cache));
1391 if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1392 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1393 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1394 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1395 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1396 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1401 // 3. Loop precondition.
1402 ICmpInst::Predicate Pred;
1403 const SCEV *OverflowLimit =
1404 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1406 if (OverflowLimit &&
1407 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1413 // Get the normalized zero or sign extended expression for this AddRec's Start.
1414 template <typename ExtendOpTy>
1415 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1416 ScalarEvolution *SE,
1417 ScalarEvolution::ExtendCacheTy &Cache) {
1418 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1420 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1422 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1424 return SE->getAddExpr(
1425 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1426 (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1429 // Try to prove away overflow by looking at "nearby" add recurrences. A
1430 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1431 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1435 // {S,+,X} == {S-T,+,X} + T
1436 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1438 // If ({S-T,+,X} + T) does not overflow ... (1)
1440 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1442 // If {S-T,+,X} does not overflow ... (2)
1444 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1445 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1447 // If (S-T)+T does not overflow ... (3)
1449 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1450 // == {Ext(S),+,Ext(X)} == LHS
1452 // Thus, if (1), (2) and (3) are true for some T, then
1453 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1455 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1456 // does not overflow" restricted to the 0th iteration. Therefore we only need
1457 // to check for (1) and (2).
1459 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1460 // is `Delta` (defined below).
1462 template <typename ExtendOpTy>
1463 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1466 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1468 // We restrict `Start` to a constant to prevent SCEV from spending too much
1469 // time here. It is correct (but more expensive) to continue with a
1470 // non-constant `Start` and do a general SCEV subtraction to compute
1471 // `PreStart` below.
1473 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1477 APInt StartAI = StartC->getAPInt();
1479 for (unsigned Delta : {-2, -1, 1, 2}) {
1480 const SCEV *PreStart = getConstant(StartAI - Delta);
1482 FoldingSetNodeID ID;
1483 ID.AddInteger(scAddRecExpr);
1484 ID.AddPointer(PreStart);
1485 ID.AddPointer(Step);
1489 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1491 // Give up if we don't already have the add recurrence we need because
1492 // actually constructing an add recurrence is relatively expensive.
1493 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1494 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1495 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1496 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1497 DeltaS, &Pred, this);
1498 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1506 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1507 // Use the local cache to prevent exponential behavior of
1508 // getZeroExtendExprImpl.
1509 ExtendCacheTy Cache;
1510 return getZeroExtendExprCached(Op, Ty, Cache);
1513 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1514 /// related entry in the \p Cache, call getZeroExtendExprImpl and save
1515 /// the result in the \p Cache.
1516 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1517 ExtendCacheTy &Cache) {
1518 auto It = Cache.find({Op, Ty});
1519 if (It != Cache.end())
1521 const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1522 auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1523 assert(InsertResult.second && "Expect the key was not in the cache");
1528 /// The real implementation of getZeroExtendExpr.
1529 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1530 ExtendCacheTy &Cache) {
1531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1532 "This is not an extending conversion!");
1533 assert(isSCEVable(Ty) &&
1534 "This is not a conversion to a SCEVable type!");
1535 Ty = getEffectiveSCEVType(Ty);
1537 // Fold if the operand is constant.
1538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1542 // zext(zext(x)) --> zext(x)
1543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1544 return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1546 // Before doing any expensive analysis, check to see if we've already
1547 // computed a SCEV for this Op and Ty.
1548 FoldingSetNodeID ID;
1549 ID.AddInteger(scZeroExtend);
1553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1555 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1556 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1557 // It's possible the bits taken off by the truncate were all zero bits. If
1558 // so, we should be able to simplify this further.
1559 const SCEV *X = ST->getOperand();
1560 ConstantRange CR = getUnsignedRange(X);
1561 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1562 unsigned NewBits = getTypeSizeInBits(Ty);
1563 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1564 CR.zextOrTrunc(NewBits)))
1565 return getTruncateOrZeroExtend(X, Ty);
1568 // If the input value is a chrec scev, and we can prove that the value
1569 // did not overflow the old, smaller, value, we can zero extend all of the
1570 // operands (often constants). This allows analysis of something like
1571 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1572 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1573 if (AR->isAffine()) {
1574 const SCEV *Start = AR->getStart();
1575 const SCEV *Step = AR->getStepRecurrence(*this);
1576 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1577 const Loop *L = AR->getLoop();
1579 if (!AR->hasNoUnsignedWrap()) {
1580 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1581 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1584 // If we have special knowledge that this addrec won't overflow,
1585 // we don't need to do any further analysis.
1586 if (AR->hasNoUnsignedWrap())
1587 return getAddRecExpr(
1588 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1589 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1591 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1592 // Note that this serves two purposes: It filters out loops that are
1593 // simply not analyzable, and it covers the case where this code is
1594 // being called from within backedge-taken count analysis, such that
1595 // attempting to ask for the backedge-taken count would likely result
1596 // in infinite recursion. In the later case, the analysis code will
1597 // cope with a conservative value, and it will take care to purge
1598 // that value once it has finished.
1599 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1600 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1601 // Manually compute the final value for AR, checking for
1604 // Check whether the backedge-taken count can be losslessly casted to
1605 // the addrec's type. The count is always unsigned.
1606 const SCEV *CastedMaxBECount =
1607 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1608 const SCEV *RecastedMaxBECount =
1609 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1610 if (MaxBECount == RecastedMaxBECount) {
1611 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1612 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1613 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1615 getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1616 const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1617 const SCEV *WideMaxBECount =
1618 getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1619 const SCEV *OperandExtendedAdd = getAddExpr(
1620 WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1621 Step, WideTy, Cache)));
1622 if (ZAdd == OperandExtendedAdd) {
1623 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1624 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1625 // Return the expression with the addrec on the outside.
1626 return getAddRecExpr(
1627 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1628 getZeroExtendExprCached(Step, Ty, Cache), L,
1629 AR->getNoWrapFlags());
1631 // Similar to above, only this time treat the step value as signed.
1632 // This covers loops that count down.
1633 OperandExtendedAdd =
1634 getAddExpr(WideStart,
1635 getMulExpr(WideMaxBECount,
1636 getSignExtendExpr(Step, WideTy)));
1637 if (ZAdd == OperandExtendedAdd) {
1638 // Cache knowledge of AR NW, which is propagated to this AddRec.
1639 // Negative step causes unsigned wrap, but it still can't self-wrap.
1640 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1641 // Return the expression with the addrec on the outside.
1642 return getAddRecExpr(
1643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1644 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1649 // Normally, in the cases we can prove no-overflow via a
1650 // backedge guarding condition, we can also compute a backedge
1651 // taken count for the loop. The exceptions are assumptions and
1652 // guards present in the loop -- SCEV is not great at exploiting
1653 // these to compute max backedge taken counts, but can still use
1654 // these to prove lack of overflow. Use this fact to avoid
1655 // doing extra work that may not pay off.
1656 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1657 !AC.assumptions().empty()) {
1658 // If the backedge is guarded by a comparison with the pre-inc
1659 // value the addrec is safe. Also, if the entry is guarded by
1660 // a comparison with the start value and the backedge is
1661 // guarded by a comparison with the post-inc value, the addrec
1663 if (isKnownPositive(Step)) {
1664 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1665 getUnsignedRange(Step).getUnsignedMax());
1666 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1667 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1668 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1669 AR->getPostIncExpr(*this), N))) {
1670 // Cache knowledge of AR NUW, which is propagated to this
1672 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1673 // Return the expression with the addrec on the outside.
1674 return getAddRecExpr(
1675 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1676 getZeroExtendExprCached(Step, Ty, Cache), L,
1677 AR->getNoWrapFlags());
1679 } else if (isKnownNegative(Step)) {
1680 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1681 getSignedRange(Step).getSignedMin());
1682 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1683 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1684 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1685 AR->getPostIncExpr(*this), N))) {
1686 // Cache knowledge of AR NW, which is propagated to this
1687 // AddRec. Negative step causes unsigned wrap, but it
1688 // still can't self-wrap.
1689 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1690 // Return the expression with the addrec on the outside.
1691 return getAddRecExpr(
1692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1693 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1698 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1700 return getAddRecExpr(
1701 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1702 getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1706 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1707 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1708 if (SA->hasNoUnsignedWrap()) {
1709 // If the addition does not unsign overflow then we can, by definition,
1710 // commute the zero extension with the addition operation.
1711 SmallVector<const SCEV *, 4> Ops;
1712 for (const auto *Op : SA->operands())
1713 Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1714 return getAddExpr(Ops, SCEV::FlagNUW);
1718 // The cast wasn't folded; create an explicit cast node.
1719 // Recompute the insert position, as it may have been invalidated.
1720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1721 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1723 UniqueSCEVs.InsertNode(S, IP);
1727 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1728 // Use the local cache to prevent exponential behavior of
1729 // getSignExtendExprImpl.
1730 ExtendCacheTy Cache;
1731 return getSignExtendExprCached(Op, Ty, Cache);
1734 /// Query \p Cache before calling getSignExtendExprImpl. If there is no
1735 /// related entry in the \p Cache, call getSignExtendExprImpl and save
1736 /// the result in the \p Cache.
1737 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1738 ExtendCacheTy &Cache) {
1739 auto It = Cache.find({Op, Ty});
1740 if (It != Cache.end())
1742 const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1743 auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1744 assert(InsertResult.second && "Expect the key was not in the cache");
1749 /// The real implementation of getSignExtendExpr.
1750 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1751 ExtendCacheTy &Cache) {
1752 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1753 "This is not an extending conversion!");
1754 assert(isSCEVable(Ty) &&
1755 "This is not a conversion to a SCEVable type!");
1756 Ty = getEffectiveSCEVType(Ty);
1758 // Fold if the operand is constant.
1759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1761 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1763 // sext(sext(x)) --> sext(x)
1764 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1765 return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1767 // sext(zext(x)) --> zext(x)
1768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1769 return getZeroExtendExpr(SZ->getOperand(), Ty);
1771 // Before doing any expensive analysis, check to see if we've already
1772 // computed a SCEV for this Op and Ty.
1773 FoldingSetNodeID ID;
1774 ID.AddInteger(scSignExtend);
1778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1780 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1781 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1782 // It's possible the bits taken off by the truncate were all sign bits. If
1783 // so, we should be able to simplify this further.
1784 const SCEV *X = ST->getOperand();
1785 ConstantRange CR = getSignedRange(X);
1786 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1787 unsigned NewBits = getTypeSizeInBits(Ty);
1788 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1789 CR.sextOrTrunc(NewBits)))
1790 return getTruncateOrSignExtend(X, Ty);
1793 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1794 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1795 if (SA->getNumOperands() == 2) {
1796 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1797 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1799 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1800 const APInt &C1 = SC1->getAPInt();
1801 const APInt &C2 = SC2->getAPInt();
1802 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1803 C2.ugt(C1) && C2.isPowerOf2())
1804 return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1805 getSignExtendExprCached(SMul, Ty, Cache));
1810 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1811 if (SA->hasNoSignedWrap()) {
1812 // If the addition does not sign overflow then we can, by definition,
1813 // commute the sign extension with the addition operation.
1814 SmallVector<const SCEV *, 4> Ops;
1815 for (const auto *Op : SA->operands())
1816 Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1817 return getAddExpr(Ops, SCEV::FlagNSW);
1820 // If the input value is a chrec scev, and we can prove that the value
1821 // did not overflow the old, smaller, value, we can sign extend all of the
1822 // operands (often constants). This allows analysis of something like
1823 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1824 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1825 if (AR->isAffine()) {
1826 const SCEV *Start = AR->getStart();
1827 const SCEV *Step = AR->getStepRecurrence(*this);
1828 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1829 const Loop *L = AR->getLoop();
1831 if (!AR->hasNoSignedWrap()) {
1832 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1833 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1836 // If we have special knowledge that this addrec won't overflow,
1837 // we don't need to do any further analysis.
1838 if (AR->hasNoSignedWrap())
1839 return getAddRecExpr(
1840 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1841 getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1843 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1844 // Note that this serves two purposes: It filters out loops that are
1845 // simply not analyzable, and it covers the case where this code is
1846 // being called from within backedge-taken count analysis, such that
1847 // attempting to ask for the backedge-taken count would likely result
1848 // in infinite recursion. In the later case, the analysis code will
1849 // cope with a conservative value, and it will take care to purge
1850 // that value once it has finished.
1851 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1852 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1853 // Manually compute the final value for AR, checking for
1856 // Check whether the backedge-taken count can be losslessly casted to
1857 // the addrec's type. The count is always unsigned.
1858 const SCEV *CastedMaxBECount =
1859 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1860 const SCEV *RecastedMaxBECount =
1861 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1862 if (MaxBECount == RecastedMaxBECount) {
1863 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1864 // Check whether Start+Step*MaxBECount has no signed overflow.
1865 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1867 getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1868 const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1869 const SCEV *WideMaxBECount =
1870 getZeroExtendExpr(CastedMaxBECount, WideTy);
1871 const SCEV *OperandExtendedAdd = getAddExpr(
1872 WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1873 Step, WideTy, Cache)));
1874 if (SAdd == OperandExtendedAdd) {
1875 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1877 // Return the expression with the addrec on the outside.
1878 return getAddRecExpr(
1879 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1880 getSignExtendExprCached(Step, Ty, Cache), L,
1881 AR->getNoWrapFlags());
1883 // Similar to above, only this time treat the step value as unsigned.
1884 // This covers loops that count up with an unsigned step.
1885 OperandExtendedAdd =
1886 getAddExpr(WideStart,
1887 getMulExpr(WideMaxBECount,
1888 getZeroExtendExpr(Step, WideTy)));
1889 if (SAdd == OperandExtendedAdd) {
1890 // If AR wraps around then
1892 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1893 // => SAdd != OperandExtendedAdd
1895 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1896 // (SAdd == OperandExtendedAdd => AR is NW)
1898 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1900 // Return the expression with the addrec on the outside.
1901 return getAddRecExpr(
1902 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1903 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1908 // Normally, in the cases we can prove no-overflow via a
1909 // backedge guarding condition, we can also compute a backedge
1910 // taken count for the loop. The exceptions are assumptions and
1911 // guards present in the loop -- SCEV is not great at exploiting
1912 // these to compute max backedge taken counts, but can still use
1913 // these to prove lack of overflow. Use this fact to avoid
1914 // doing extra work that may not pay off.
1916 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1917 !AC.assumptions().empty()) {
1918 // If the backedge is guarded by a comparison with the pre-inc
1919 // value the addrec is safe. Also, if the entry is guarded by
1920 // a comparison with the start value and the backedge is
1921 // guarded by a comparison with the post-inc value, the addrec
1923 ICmpInst::Predicate Pred;
1924 const SCEV *OverflowLimit =
1925 getSignedOverflowLimitForStep(Step, &Pred, this);
1926 if (OverflowLimit &&
1927 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1928 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1929 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1931 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1932 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1933 return getAddRecExpr(
1934 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1935 getSignExtendExprCached(Step, Ty, Cache), L,
1936 AR->getNoWrapFlags());
1940 // If Start and Step are constants, check if we can apply this
1942 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1943 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1944 auto *SC2 = dyn_cast<SCEVConstant>(Step);
1946 const APInt &C1 = SC1->getAPInt();
1947 const APInt &C2 = SC2->getAPInt();
1948 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1950 Start = getSignExtendExprCached(Start, Ty, Cache);
1951 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1952 AR->getNoWrapFlags());
1953 return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1957 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1958 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1959 return getAddRecExpr(
1960 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1961 getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1965 // If the input value is provably positive and we could not simplify
1966 // away the sext build a zext instead.
1967 if (isKnownNonNegative(Op))
1968 return getZeroExtendExpr(Op, Ty);
1970 // The cast wasn't folded; create an explicit cast node.
1971 // Recompute the insert position, as it may have been invalidated.
1972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1973 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1975 UniqueSCEVs.InsertNode(S, IP);
1979 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1980 /// unspecified bits out to the given type.
1982 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1984 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1985 "This is not an extending conversion!");
1986 assert(isSCEVable(Ty) &&
1987 "This is not a conversion to a SCEVable type!");
1988 Ty = getEffectiveSCEVType(Ty);
1990 // Sign-extend negative constants.
1991 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1992 if (SC->getAPInt().isNegative())
1993 return getSignExtendExpr(Op, Ty);
1995 // Peel off a truncate cast.
1996 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1997 const SCEV *NewOp = T->getOperand();
1998 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1999 return getAnyExtendExpr(NewOp, Ty);
2000 return getTruncateOrNoop(NewOp, Ty);
2003 // Next try a zext cast. If the cast is folded, use it.
2004 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2005 if (!isa<SCEVZeroExtendExpr>(ZExt))
2008 // Next try a sext cast. If the cast is folded, use it.
2009 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2010 if (!isa<SCEVSignExtendExpr>(SExt))
2013 // Force the cast to be folded into the operands of an addrec.
2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2015 SmallVector<const SCEV *, 4> Ops;
2016 for (const SCEV *Op : AR->operands())
2017 Ops.push_back(getAnyExtendExpr(Op, Ty));
2018 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2021 // If the expression is obviously signed, use the sext cast value.
2022 if (isa<SCEVSMaxExpr>(Op))
2025 // Absent any other information, use the zext cast value.
2029 /// Process the given Ops list, which is a list of operands to be added under
2030 /// the given scale, update the given map. This is a helper function for
2031 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2032 /// that would form an add expression like this:
2034 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2036 /// where A and B are constants, update the map with these values:
2038 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2040 /// and add 13 + A*B*29 to AccumulatedConstant.
2041 /// This will allow getAddRecExpr to produce this:
2043 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2045 /// This form often exposes folding opportunities that are hidden in
2046 /// the original operand list.
2048 /// Return true iff it appears that any interesting folding opportunities
2049 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2050 /// the common case where no interesting opportunities are present, and
2051 /// is also used as a check to avoid infinite recursion.
2054 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2055 SmallVectorImpl<const SCEV *> &NewOps,
2056 APInt &AccumulatedConstant,
2057 const SCEV *const *Ops, size_t NumOperands,
2059 ScalarEvolution &SE) {
2060 bool Interesting = false;
2062 // Iterate over the add operands. They are sorted, with constants first.
2064 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2066 // Pull a buried constant out to the outside.
2067 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2069 AccumulatedConstant += Scale * C->getAPInt();
2072 // Next comes everything else. We're especially interested in multiplies
2073 // here, but they're in the middle, so just visit the rest with one loop.
2074 for (; i != NumOperands; ++i) {
2075 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2076 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2078 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2079 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2080 // A multiplication of a constant with another add; recurse.
2081 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2083 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2084 Add->op_begin(), Add->getNumOperands(),
2087 // A multiplication of a constant with some other value. Update
2089 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2090 const SCEV *Key = SE.getMulExpr(MulOps);
2091 auto Pair = M.insert({Key, NewScale});
2093 NewOps.push_back(Pair.first->first);
2095 Pair.first->second += NewScale;
2096 // The map already had an entry for this value, which may indicate
2097 // a folding opportunity.
2102 // An ordinary operand. Update the map.
2103 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2104 M.insert({Ops[i], Scale});
2106 NewOps.push_back(Pair.first->first);
2108 Pair.first->second += Scale;
2109 // The map already had an entry for this value, which may indicate
2110 // a folding opportunity.
2119 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2120 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2121 // can't-overflow flags for the operation if possible.
2122 static SCEV::NoWrapFlags
2123 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2124 const SmallVectorImpl<const SCEV *> &Ops,
2125 SCEV::NoWrapFlags Flags) {
2126 using namespace std::placeholders;
2127 typedef OverflowingBinaryOperator OBO;
2130 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2132 assert(CanAnalyze && "don't call from other places!");
2134 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2135 SCEV::NoWrapFlags SignOrUnsignWrap =
2136 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2138 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2139 auto IsKnownNonNegative = [&](const SCEV *S) {
2140 return SE->isKnownNonNegative(S);
2143 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2145 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2147 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2149 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2150 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2152 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2153 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2155 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2156 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2157 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2158 Instruction::Add, C, OBO::NoSignedWrap);
2159 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2160 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2162 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2163 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2164 Instruction::Add, C, OBO::NoUnsignedWrap);
2165 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2173 /// Get a canonical add expression, or something simpler if possible.
2174 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2175 SCEV::NoWrapFlags Flags,
2177 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2178 "only nuw or nsw allowed");
2179 assert(!Ops.empty() && "Cannot get empty add!");
2180 if (Ops.size() == 1) return Ops[0];
2182 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2183 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2184 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2185 "SCEVAddExpr operand types don't match!");
2188 // Sort by complexity, this groups all similar expression types together.
2189 GroupByComplexity(Ops, &LI);
2191 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2193 // If there are any constants, fold them together.
2195 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2197 assert(Idx < Ops.size());
2198 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2199 // We found two constants, fold them together!
2200 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2201 if (Ops.size() == 2) return Ops[0];
2202 Ops.erase(Ops.begin()+1); // Erase the folded element
2203 LHSC = cast<SCEVConstant>(Ops[0]);
2206 // If we are left with a constant zero being added, strip it off.
2207 if (LHSC->getValue()->isZero()) {
2208 Ops.erase(Ops.begin());
2212 if (Ops.size() == 1) return Ops[0];
2215 // Limit recursion calls depth
2216 if (Depth > MaxAddExprDepth)
2217 return getOrCreateAddExpr(Ops, Flags);
2219 // Okay, check to see if the same value occurs in the operand list more than
2220 // once. If so, merge them together into an multiply expression. Since we
2221 // sorted the list, these values are required to be adjacent.
2222 Type *Ty = Ops[0]->getType();
2223 bool FoundMatch = false;
2224 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2225 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2226 // Scan ahead to count how many equal operands there are.
2228 while (i+Count != e && Ops[i+Count] == Ops[i])
2230 // Merge the values into a multiply.
2231 const SCEV *Scale = getConstant(Ty, Count);
2232 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2233 if (Ops.size() == Count)
2236 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2237 --i; e -= Count - 1;
2241 return getAddExpr(Ops, Flags);
2243 // Check for truncates. If all the operands are truncated from the same
2244 // type, see if factoring out the truncate would permit the result to be
2245 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2246 // if the contents of the resulting outer trunc fold to something simple.
2247 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2248 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2249 Type *DstType = Trunc->getType();
2250 Type *SrcType = Trunc->getOperand()->getType();
2251 SmallVector<const SCEV *, 8> LargeOps;
2253 // Check all the operands to see if they can be represented in the
2254 // source type of the truncate.
2255 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2256 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2257 if (T->getOperand()->getType() != SrcType) {
2261 LargeOps.push_back(T->getOperand());
2262 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2263 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2264 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2265 SmallVector<const SCEV *, 8> LargeMulOps;
2266 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2267 if (const SCEVTruncateExpr *T =
2268 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2269 if (T->getOperand()->getType() != SrcType) {
2273 LargeMulOps.push_back(T->getOperand());
2274 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2275 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2282 LargeOps.push_back(getMulExpr(LargeMulOps));
2289 // Evaluate the expression in the larger type.
2290 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2291 // If it folds to something simple, use it. Otherwise, don't.
2292 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2293 return getTruncateExpr(Fold, DstType);
2297 // Skip past any other cast SCEVs.
2298 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2301 // If there are add operands they would be next.
2302 if (Idx < Ops.size()) {
2303 bool DeletedAdd = false;
2304 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2305 if (Ops.size() > AddOpsInlineThreshold ||
2306 Add->getNumOperands() > AddOpsInlineThreshold)
2308 // If we have an add, expand the add operands onto the end of the operands
2310 Ops.erase(Ops.begin()+Idx);
2311 Ops.append(Add->op_begin(), Add->op_end());
2315 // If we deleted at least one add, we added operands to the end of the list,
2316 // and they are not necessarily sorted. Recurse to resort and resimplify
2317 // any operands we just acquired.
2319 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2322 // Skip over the add expression until we get to a multiply.
2323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2326 // Check to see if there are any folding opportunities present with
2327 // operands multiplied by constant values.
2328 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2329 uint64_t BitWidth = getTypeSizeInBits(Ty);
2330 DenseMap<const SCEV *, APInt> M;
2331 SmallVector<const SCEV *, 8> NewOps;
2332 APInt AccumulatedConstant(BitWidth, 0);
2333 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2334 Ops.data(), Ops.size(),
2335 APInt(BitWidth, 1), *this)) {
2336 struct APIntCompare {
2337 bool operator()(const APInt &LHS, const APInt &RHS) const {
2338 return LHS.ult(RHS);
2342 // Some interesting folding opportunity is present, so its worthwhile to
2343 // re-generate the operands list. Group the operands by constant scale,
2344 // to avoid multiplying by the same constant scale multiple times.
2345 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2346 for (const SCEV *NewOp : NewOps)
2347 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2348 // Re-generate the operands list.
2350 if (AccumulatedConstant != 0)
2351 Ops.push_back(getConstant(AccumulatedConstant));
2352 for (auto &MulOp : MulOpLists)
2353 if (MulOp.first != 0)
2354 Ops.push_back(getMulExpr(
2355 getConstant(MulOp.first),
2356 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2359 if (Ops.size() == 1)
2361 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2365 // If we are adding something to a multiply expression, make sure the
2366 // something is not already an operand of the multiply. If so, merge it into
2368 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2369 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2370 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2371 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2372 if (isa<SCEVConstant>(MulOpSCEV))
2374 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2375 if (MulOpSCEV == Ops[AddOp]) {
2376 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2377 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2378 if (Mul->getNumOperands() != 2) {
2379 // If the multiply has more than two operands, we must get the
2381 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2382 Mul->op_begin()+MulOp);
2383 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2384 InnerMul = getMulExpr(MulOps);
2386 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2387 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2388 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2389 if (Ops.size() == 2) return OuterMul;
2391 Ops.erase(Ops.begin()+AddOp);
2392 Ops.erase(Ops.begin()+Idx-1);
2394 Ops.erase(Ops.begin()+Idx);
2395 Ops.erase(Ops.begin()+AddOp-1);
2397 Ops.push_back(OuterMul);
2398 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2401 // Check this multiply against other multiplies being added together.
2402 for (unsigned OtherMulIdx = Idx+1;
2403 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2405 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2406 // If MulOp occurs in OtherMul, we can fold the two multiplies
2408 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2409 OMulOp != e; ++OMulOp)
2410 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2411 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2412 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2413 if (Mul->getNumOperands() != 2) {
2414 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2415 Mul->op_begin()+MulOp);
2416 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2417 InnerMul1 = getMulExpr(MulOps);
2419 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2420 if (OtherMul->getNumOperands() != 2) {
2421 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2422 OtherMul->op_begin()+OMulOp);
2423 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2424 InnerMul2 = getMulExpr(MulOps);
2426 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2427 const SCEV *InnerMulSum =
2428 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2429 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2430 if (Ops.size() == 2) return OuterMul;
2431 Ops.erase(Ops.begin()+Idx);
2432 Ops.erase(Ops.begin()+OtherMulIdx-1);
2433 Ops.push_back(OuterMul);
2434 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2440 // If there are any add recurrences in the operands list, see if any other
2441 // added values are loop invariant. If so, we can fold them into the
2443 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2446 // Scan over all recurrences, trying to fold loop invariants into them.
2447 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2448 // Scan all of the other operands to this add and add them to the vector if
2449 // they are loop invariant w.r.t. the recurrence.
2450 SmallVector<const SCEV *, 8> LIOps;
2451 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2452 const Loop *AddRecLoop = AddRec->getLoop();
2453 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2454 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2455 LIOps.push_back(Ops[i]);
2456 Ops.erase(Ops.begin()+i);
2460 // If we found some loop invariants, fold them into the recurrence.
2461 if (!LIOps.empty()) {
2462 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2463 LIOps.push_back(AddRec->getStart());
2465 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2467 // This follows from the fact that the no-wrap flags on the outer add
2468 // expression are applicable on the 0th iteration, when the add recurrence
2469 // will be equal to its start value.
2470 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2472 // Build the new addrec. Propagate the NUW and NSW flags if both the
2473 // outer add and the inner addrec are guaranteed to have no overflow.
2474 // Always propagate NW.
2475 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2476 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2478 // If all of the other operands were loop invariant, we are done.
2479 if (Ops.size() == 1) return NewRec;
2481 // Otherwise, add the folded AddRec by the non-invariant parts.
2482 for (unsigned i = 0;; ++i)
2483 if (Ops[i] == AddRec) {
2487 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2490 // Okay, if there weren't any loop invariants to be folded, check to see if
2491 // there are multiple AddRec's with the same loop induction variable being
2492 // added together. If so, we can fold them.
2493 for (unsigned OtherIdx = Idx+1;
2494 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2496 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2497 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2498 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2500 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2502 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2503 if (OtherAddRec->getLoop() == AddRecLoop) {
2504 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2506 if (i >= AddRecOps.size()) {
2507 AddRecOps.append(OtherAddRec->op_begin()+i,
2508 OtherAddRec->op_end());
2511 SmallVector<const SCEV *, 2> TwoOps = {
2512 AddRecOps[i], OtherAddRec->getOperand(i)};
2513 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2515 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2517 // Step size has changed, so we cannot guarantee no self-wraparound.
2518 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2519 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2522 // Otherwise couldn't fold anything into this recurrence. Move onto the
2526 // Okay, it looks like we really DO need an add expr. Check to see if we
2527 // already have one, otherwise create a new one.
2528 return getOrCreateAddExpr(Ops, Flags);
2532 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2533 SCEV::NoWrapFlags Flags) {
2534 FoldingSetNodeID ID;
2535 ID.AddInteger(scAddExpr);
2536 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2537 ID.AddPointer(Ops[i]);
2540 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2542 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2543 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2544 S = new (SCEVAllocator)
2545 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2546 UniqueSCEVs.InsertNode(S, IP);
2548 S->setNoWrapFlags(Flags);
2552 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2554 if (j > 1 && k / j != i) Overflow = true;
2558 /// Compute the result of "n choose k", the binomial coefficient. If an
2559 /// intermediate computation overflows, Overflow will be set and the return will
2560 /// be garbage. Overflow is not cleared on absence of overflow.
2561 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2562 // We use the multiplicative formula:
2563 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2564 // At each iteration, we take the n-th term of the numeral and divide by the
2565 // (k-n)th term of the denominator. This division will always produce an
2566 // integral result, and helps reduce the chance of overflow in the
2567 // intermediate computations. However, we can still overflow even when the
2568 // final result would fit.
2570 if (n == 0 || n == k) return 1;
2571 if (k > n) return 0;
2577 for (uint64_t i = 1; i <= k; ++i) {
2578 r = umul_ov(r, n-(i-1), Overflow);
2584 /// Determine if any of the operands in this SCEV are a constant or if
2585 /// any of the add or multiply expressions in this SCEV contain a constant.
2586 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2587 SmallVector<const SCEV *, 4> Ops;
2588 Ops.push_back(StartExpr);
2589 while (!Ops.empty()) {
2590 const SCEV *CurrentExpr = Ops.pop_back_val();
2591 if (isa<SCEVConstant>(*CurrentExpr))
2594 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2595 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2596 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2602 /// Get a canonical multiply expression, or something simpler if possible.
2603 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2604 SCEV::NoWrapFlags Flags) {
2605 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2606 "only nuw or nsw allowed");
2607 assert(!Ops.empty() && "Cannot get empty mul!");
2608 if (Ops.size() == 1) return Ops[0];
2610 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2611 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2612 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2613 "SCEVMulExpr operand types don't match!");
2616 // Sort by complexity, this groups all similar expression types together.
2617 GroupByComplexity(Ops, &LI);
2619 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2621 // If there are any constants, fold them together.
2623 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2625 // C1*(C2+V) -> C1*C2 + C1*V
2626 if (Ops.size() == 2)
2627 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2628 // If any of Add's ops are Adds or Muls with a constant,
2629 // apply this transformation as well.
2630 if (Add->getNumOperands() == 2)
2631 if (containsConstantSomewhere(Add))
2632 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2633 getMulExpr(LHSC, Add->getOperand(1)));
2636 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2637 // We found two constants, fold them together!
2639 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2640 Ops[0] = getConstant(Fold);
2641 Ops.erase(Ops.begin()+1); // Erase the folded element
2642 if (Ops.size() == 1) return Ops[0];
2643 LHSC = cast<SCEVConstant>(Ops[0]);
2646 // If we are left with a constant one being multiplied, strip it off.
2647 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2648 Ops.erase(Ops.begin());
2650 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2651 // If we have a multiply of zero, it will always be zero.
2653 } else if (Ops[0]->isAllOnesValue()) {
2654 // If we have a mul by -1 of an add, try distributing the -1 among the
2656 if (Ops.size() == 2) {
2657 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2658 SmallVector<const SCEV *, 4> NewOps;
2659 bool AnyFolded = false;
2660 for (const SCEV *AddOp : Add->operands()) {
2661 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2662 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2663 NewOps.push_back(Mul);
2666 return getAddExpr(NewOps);
2667 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2668 // Negation preserves a recurrence's no self-wrap property.
2669 SmallVector<const SCEV *, 4> Operands;
2670 for (const SCEV *AddRecOp : AddRec->operands())
2671 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2673 return getAddRecExpr(Operands, AddRec->getLoop(),
2674 AddRec->getNoWrapFlags(SCEV::FlagNW));
2679 if (Ops.size() == 1)
2683 // Skip over the add expression until we get to a multiply.
2684 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2687 // If there are mul operands inline them all into this expression.
2688 if (Idx < Ops.size()) {
2689 bool DeletedMul = false;
2690 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2691 if (Ops.size() > MulOpsInlineThreshold)
2693 // If we have an mul, expand the mul operands onto the end of the operands
2695 Ops.erase(Ops.begin()+Idx);
2696 Ops.append(Mul->op_begin(), Mul->op_end());
2700 // If we deleted at least one mul, we added operands to the end of the list,
2701 // and they are not necessarily sorted. Recurse to resort and resimplify
2702 // any operands we just acquired.
2704 return getMulExpr(Ops);
2707 // If there are any add recurrences in the operands list, see if any other
2708 // added values are loop invariant. If so, we can fold them into the
2710 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2713 // Scan over all recurrences, trying to fold loop invariants into them.
2714 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2715 // Scan all of the other operands to this mul and add them to the vector if
2716 // they are loop invariant w.r.t. the recurrence.
2717 SmallVector<const SCEV *, 8> LIOps;
2718 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2719 const Loop *AddRecLoop = AddRec->getLoop();
2720 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2721 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2722 LIOps.push_back(Ops[i]);
2723 Ops.erase(Ops.begin()+i);
2727 // If we found some loop invariants, fold them into the recurrence.
2728 if (!LIOps.empty()) {
2729 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2730 SmallVector<const SCEV *, 4> NewOps;
2731 NewOps.reserve(AddRec->getNumOperands());
2732 const SCEV *Scale = getMulExpr(LIOps);
2733 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2734 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2736 // Build the new addrec. Propagate the NUW and NSW flags if both the
2737 // outer mul and the inner addrec are guaranteed to have no overflow.
2739 // No self-wrap cannot be guaranteed after changing the step size, but
2740 // will be inferred if either NUW or NSW is true.
2741 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2742 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2744 // If all of the other operands were loop invariant, we are done.
2745 if (Ops.size() == 1) return NewRec;
2747 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2748 for (unsigned i = 0;; ++i)
2749 if (Ops[i] == AddRec) {
2753 return getMulExpr(Ops);
2756 // Okay, if there weren't any loop invariants to be folded, check to see if
2757 // there are multiple AddRec's with the same loop induction variable being
2758 // multiplied together. If so, we can fold them.
2760 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2761 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2762 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2763 // ]]],+,...up to x=2n}.
2764 // Note that the arguments to choose() are always integers with values
2765 // known at compile time, never SCEV objects.
2767 // The implementation avoids pointless extra computations when the two
2768 // addrec's are of different length (mathematically, it's equivalent to
2769 // an infinite stream of zeros on the right).
2770 bool OpsModified = false;
2771 for (unsigned OtherIdx = Idx+1;
2772 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2774 const SCEVAddRecExpr *OtherAddRec =
2775 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2776 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2779 bool Overflow = false;
2780 Type *Ty = AddRec->getType();
2781 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2782 SmallVector<const SCEV*, 7> AddRecOps;
2783 for (int x = 0, xe = AddRec->getNumOperands() +
2784 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2785 const SCEV *Term = getZero(Ty);
2786 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2787 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2788 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2789 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2790 z < ze && !Overflow; ++z) {
2791 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2793 if (LargerThan64Bits)
2794 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2796 Coeff = Coeff1*Coeff2;
2797 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2798 const SCEV *Term1 = AddRec->getOperand(y-z);
2799 const SCEV *Term2 = OtherAddRec->getOperand(z);
2800 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2803 AddRecOps.push_back(Term);
2806 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2808 if (Ops.size() == 2) return NewAddRec;
2809 Ops[Idx] = NewAddRec;
2810 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2812 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2818 return getMulExpr(Ops);
2820 // Otherwise couldn't fold anything into this recurrence. Move onto the
2824 // Okay, it looks like we really DO need an mul expr. Check to see if we
2825 // already have one, otherwise create a new one.
2826 FoldingSetNodeID ID;
2827 ID.AddInteger(scMulExpr);
2828 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2829 ID.AddPointer(Ops[i]);
2832 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2834 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2835 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2836 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2838 UniqueSCEVs.InsertNode(S, IP);
2840 S->setNoWrapFlags(Flags);
2844 /// Get a canonical unsigned division expression, or something simpler if
2846 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2848 assert(getEffectiveSCEVType(LHS->getType()) ==
2849 getEffectiveSCEVType(RHS->getType()) &&
2850 "SCEVUDivExpr operand types don't match!");
2852 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2853 if (RHSC->getValue()->equalsInt(1))
2854 return LHS; // X udiv 1 --> x
2855 // If the denominator is zero, the result of the udiv is undefined. Don't
2856 // try to analyze it, because the resolution chosen here may differ from
2857 // the resolution chosen in other parts of the compiler.
2858 if (!RHSC->getValue()->isZero()) {
2859 // Determine if the division can be folded into the operands of
2861 // TODO: Generalize this to non-constants by using known-bits information.
2862 Type *Ty = LHS->getType();
2863 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2864 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2865 // For non-power-of-two values, effectively round the value up to the
2866 // nearest power of two.
2867 if (!RHSC->getAPInt().isPowerOf2())
2869 IntegerType *ExtTy =
2870 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2872 if (const SCEVConstant *Step =
2873 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2874 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2875 const APInt &StepInt = Step->getAPInt();
2876 const APInt &DivInt = RHSC->getAPInt();
2877 if (!StepInt.urem(DivInt) &&
2878 getZeroExtendExpr(AR, ExtTy) ==
2879 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2880 getZeroExtendExpr(Step, ExtTy),
2881 AR->getLoop(), SCEV::FlagAnyWrap)) {
2882 SmallVector<const SCEV *, 4> Operands;
2883 for (const SCEV *Op : AR->operands())
2884 Operands.push_back(getUDivExpr(Op, RHS));
2885 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2887 /// Get a canonical UDivExpr for a recurrence.
2888 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2889 // We can currently only fold X%N if X is constant.
2890 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2891 if (StartC && !DivInt.urem(StepInt) &&
2892 getZeroExtendExpr(AR, ExtTy) ==
2893 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2894 getZeroExtendExpr(Step, ExtTy),
2895 AR->getLoop(), SCEV::FlagAnyWrap)) {
2896 const APInt &StartInt = StartC->getAPInt();
2897 const APInt &StartRem = StartInt.urem(StepInt);
2899 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2900 AR->getLoop(), SCEV::FlagNW);
2903 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2904 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2905 SmallVector<const SCEV *, 4> Operands;
2906 for (const SCEV *Op : M->operands())
2907 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2908 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2909 // Find an operand that's safely divisible.
2910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2911 const SCEV *Op = M->getOperand(i);
2912 const SCEV *Div = getUDivExpr(Op, RHSC);
2913 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2914 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2917 return getMulExpr(Operands);
2921 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2922 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2923 SmallVector<const SCEV *, 4> Operands;
2924 for (const SCEV *Op : A->operands())
2925 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2926 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2929 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2930 if (isa<SCEVUDivExpr>(Op) ||
2931 getMulExpr(Op, RHS) != A->getOperand(i))
2933 Operands.push_back(Op);
2935 if (Operands.size() == A->getNumOperands())
2936 return getAddExpr(Operands);
2940 // Fold if both operands are constant.
2941 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2942 Constant *LHSCV = LHSC->getValue();
2943 Constant *RHSCV = RHSC->getValue();
2944 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2950 FoldingSetNodeID ID;
2951 ID.AddInteger(scUDivExpr);
2955 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2956 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2958 UniqueSCEVs.InsertNode(S, IP);
2962 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2963 APInt A = C1->getAPInt().abs();
2964 APInt B = C2->getAPInt().abs();
2965 uint32_t ABW = A.getBitWidth();
2966 uint32_t BBW = B.getBitWidth();
2973 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
2976 /// Get a canonical unsigned division expression, or something simpler if
2977 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2978 /// can attempt to remove factors from the LHS and RHS. We can't do this when
2979 /// it's not exact because the udiv may be clearing bits.
2980 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2982 // TODO: we could try to find factors in all sorts of things, but for now we
2983 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2984 // end of this file for inspiration.
2986 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2987 if (!Mul || !Mul->hasNoUnsignedWrap())
2988 return getUDivExpr(LHS, RHS);
2990 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2991 // If the mulexpr multiplies by a constant, then that constant must be the
2992 // first element of the mulexpr.
2993 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2994 if (LHSCst == RHSCst) {
2995 SmallVector<const SCEV *, 2> Operands;
2996 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2997 return getMulExpr(Operands);
3000 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3001 // that there's a factor provided by one of the other terms. We need to
3003 APInt Factor = gcd(LHSCst, RHSCst);
3004 if (!Factor.isIntN(1)) {
3006 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3008 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3009 SmallVector<const SCEV *, 2> Operands;
3010 Operands.push_back(LHSCst);
3011 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3012 LHS = getMulExpr(Operands);
3014 Mul = dyn_cast<SCEVMulExpr>(LHS);
3016 return getUDivExactExpr(LHS, RHS);
3021 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3022 if (Mul->getOperand(i) == RHS) {
3023 SmallVector<const SCEV *, 2> Operands;
3024 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3025 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3026 return getMulExpr(Operands);
3030 return getUDivExpr(LHS, RHS);
3033 /// Get an add recurrence expression for the specified loop. Simplify the
3034 /// expression as much as possible.
3035 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3037 SCEV::NoWrapFlags Flags) {
3038 SmallVector<const SCEV *, 4> Operands;
3039 Operands.push_back(Start);
3040 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3041 if (StepChrec->getLoop() == L) {
3042 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3043 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3046 Operands.push_back(Step);
3047 return getAddRecExpr(Operands, L, Flags);
3050 /// Get an add recurrence expression for the specified loop. Simplify the
3051 /// expression as much as possible.
3053 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3054 const Loop *L, SCEV::NoWrapFlags Flags) {
3055 if (Operands.size() == 1) return Operands[0];
3057 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3058 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3059 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3060 "SCEVAddRecExpr operand types don't match!");
3061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3062 assert(isLoopInvariant(Operands[i], L) &&
3063 "SCEVAddRecExpr operand is not loop-invariant!");
3066 if (Operands.back()->isZero()) {
3067 Operands.pop_back();
3068 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3071 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3072 // use that information to infer NUW and NSW flags. However, computing a
3073 // BE count requires calling getAddRecExpr, so we may not yet have a
3074 // meaningful BE count at this point (and if we don't, we'd be stuck
3075 // with a SCEVCouldNotCompute as the cached BE count).
3077 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3079 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3080 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3081 const Loop *NestedLoop = NestedAR->getLoop();
3082 if (L->contains(NestedLoop)
3083 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3084 : (!NestedLoop->contains(L) &&
3085 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3086 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3087 NestedAR->op_end());
3088 Operands[0] = NestedAR->getStart();
3089 // AddRecs require their operands be loop-invariant with respect to their
3090 // loops. Don't perform this transformation if it would break this
3092 bool AllInvariant = all_of(
3093 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3096 // Create a recurrence for the outer loop with the same step size.
3098 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3099 // inner recurrence has the same property.
3100 SCEV::NoWrapFlags OuterFlags =
3101 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3103 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3104 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3105 return isLoopInvariant(Op, NestedLoop);
3109 // Ok, both add recurrences are valid after the transformation.
3111 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3112 // the outer recurrence has the same property.
3113 SCEV::NoWrapFlags InnerFlags =
3114 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3115 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3118 // Reset Operands to its original state.
3119 Operands[0] = NestedAR;
3123 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3124 // already have one, otherwise create a new one.
3125 FoldingSetNodeID ID;
3126 ID.AddInteger(scAddRecExpr);
3127 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3128 ID.AddPointer(Operands[i]);
3132 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3134 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3135 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3136 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3137 O, Operands.size(), L);
3138 UniqueSCEVs.InsertNode(S, IP);
3140 S->setNoWrapFlags(Flags);
3145 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3146 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3147 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3148 // getSCEV(Base)->getType() has the same address space as Base->getType()
3149 // because SCEV::getType() preserves the address space.
3150 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3151 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3152 // instruction to its SCEV, because the Instruction may be guarded by control
3153 // flow and the no-overflow bits may not be valid for the expression in any
3154 // context. This can be fixed similarly to how these flags are handled for
3156 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3157 : SCEV::FlagAnyWrap;
3159 const SCEV *TotalOffset = getZero(IntPtrTy);
3160 // The array size is unimportant. The first thing we do on CurTy is getting
3161 // its element type.
3162 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3163 for (const SCEV *IndexExpr : IndexExprs) {
3164 // Compute the (potentially symbolic) offset in bytes for this index.
3165 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3166 // For a struct, add the member offset.
3167 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3168 unsigned FieldNo = Index->getZExtValue();
3169 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3171 // Add the field offset to the running total offset.
3172 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3174 // Update CurTy to the type of the field at Index.
3175 CurTy = STy->getTypeAtIndex(Index);
3177 // Update CurTy to its element type.
3178 CurTy = cast<SequentialType>(CurTy)->getElementType();
3179 // For an array, add the element offset, explicitly scaled.
3180 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3181 // Getelementptr indices are signed.
3182 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3184 // Multiply the index by the element size to compute the element offset.
3185 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3187 // Add the element offset to the running total offset.
3188 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3192 // Add the total offset from all the GEP indices to the base.
3193 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3196 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3198 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3199 return getSMaxExpr(Ops);
3203 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3204 assert(!Ops.empty() && "Cannot get empty smax!");
3205 if (Ops.size() == 1) return Ops[0];
3207 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3208 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3209 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3210 "SCEVSMaxExpr operand types don't match!");
3213 // Sort by complexity, this groups all similar expression types together.
3214 GroupByComplexity(Ops, &LI);
3216 // If there are any constants, fold them together.
3218 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3220 assert(Idx < Ops.size());
3221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3222 // We found two constants, fold them together!
3223 ConstantInt *Fold = ConstantInt::get(
3224 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3225 Ops[0] = getConstant(Fold);
3226 Ops.erase(Ops.begin()+1); // Erase the folded element
3227 if (Ops.size() == 1) return Ops[0];
3228 LHSC = cast<SCEVConstant>(Ops[0]);
3231 // If we are left with a constant minimum-int, strip it off.
3232 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3233 Ops.erase(Ops.begin());
3235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3236 // If we have an smax with a constant maximum-int, it will always be
3241 if (Ops.size() == 1) return Ops[0];
3244 // Find the first SMax
3245 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3248 // Check to see if one of the operands is an SMax. If so, expand its operands
3249 // onto our operand list, and recurse to simplify.
3250 if (Idx < Ops.size()) {
3251 bool DeletedSMax = false;
3252 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3253 Ops.erase(Ops.begin()+Idx);
3254 Ops.append(SMax->op_begin(), SMax->op_end());
3259 return getSMaxExpr(Ops);
3262 // Okay, check to see if the same value occurs in the operand list twice. If
3263 // so, delete one. Since we sorted the list, these values are required to
3265 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3266 // X smax Y smax Y --> X smax Y
3267 // X smax Y --> X, if X is always greater than Y
3268 if (Ops[i] == Ops[i+1] ||
3269 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3270 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3272 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3273 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3277 if (Ops.size() == 1) return Ops[0];
3279 assert(!Ops.empty() && "Reduced smax down to nothing!");
3281 // Okay, it looks like we really DO need an smax expr. Check to see if we
3282 // already have one, otherwise create a new one.
3283 FoldingSetNodeID ID;
3284 ID.AddInteger(scSMaxExpr);
3285 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3286 ID.AddPointer(Ops[i]);
3288 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3289 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3290 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3291 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3293 UniqueSCEVs.InsertNode(S, IP);
3297 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3299 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3300 return getUMaxExpr(Ops);
3304 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3305 assert(!Ops.empty() && "Cannot get empty umax!");
3306 if (Ops.size() == 1) return Ops[0];
3308 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3309 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3310 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3311 "SCEVUMaxExpr operand types don't match!");
3314 // Sort by complexity, this groups all similar expression types together.
3315 GroupByComplexity(Ops, &LI);
3317 // If there are any constants, fold them together.
3319 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3321 assert(Idx < Ops.size());
3322 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3323 // We found two constants, fold them together!
3324 ConstantInt *Fold = ConstantInt::get(
3325 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3326 Ops[0] = getConstant(Fold);
3327 Ops.erase(Ops.begin()+1); // Erase the folded element
3328 if (Ops.size() == 1) return Ops[0];
3329 LHSC = cast<SCEVConstant>(Ops[0]);
3332 // If we are left with a constant minimum-int, strip it off.
3333 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3334 Ops.erase(Ops.begin());
3336 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3337 // If we have an umax with a constant maximum-int, it will always be
3342 if (Ops.size() == 1) return Ops[0];
3345 // Find the first UMax
3346 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3349 // Check to see if one of the operands is a UMax. If so, expand its operands
3350 // onto our operand list, and recurse to simplify.
3351 if (Idx < Ops.size()) {
3352 bool DeletedUMax = false;
3353 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3354 Ops.erase(Ops.begin()+Idx);
3355 Ops.append(UMax->op_begin(), UMax->op_end());
3360 return getUMaxExpr(Ops);
3363 // Okay, check to see if the same value occurs in the operand list twice. If
3364 // so, delete one. Since we sorted the list, these values are required to
3366 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3367 // X umax Y umax Y --> X umax Y
3368 // X umax Y --> X, if X is always greater than Y
3369 if (Ops[i] == Ops[i+1] ||
3370 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3371 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3373 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3374 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3378 if (Ops.size() == 1) return Ops[0];
3380 assert(!Ops.empty() && "Reduced umax down to nothing!");
3382 // Okay, it looks like we really DO need a umax expr. Check to see if we
3383 // already have one, otherwise create a new one.
3384 FoldingSetNodeID ID;
3385 ID.AddInteger(scUMaxExpr);
3386 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3387 ID.AddPointer(Ops[i]);
3389 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3390 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3391 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3392 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3394 UniqueSCEVs.InsertNode(S, IP);
3398 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3400 // ~smax(~x, ~y) == smin(x, y).
3401 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3404 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3406 // ~umax(~x, ~y) == umin(x, y)
3407 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3410 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3411 // We can bypass creating a target-independent
3412 // constant expression and then folding it back into a ConstantInt.
3413 // This is just a compile-time optimization.
3414 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3417 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3420 // We can bypass creating a target-independent
3421 // constant expression and then folding it back into a ConstantInt.
3422 // This is just a compile-time optimization.
3424 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3427 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3428 // Don't attempt to do anything other than create a SCEVUnknown object
3429 // here. createSCEV only calls getUnknown after checking for all other
3430 // interesting possibilities, and any other code that calls getUnknown
3431 // is doing so in order to hide a value from SCEV canonicalization.
3433 FoldingSetNodeID ID;
3434 ID.AddInteger(scUnknown);
3437 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3438 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3439 "Stale SCEVUnknown in uniquing map!");
3442 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3444 FirstUnknown = cast<SCEVUnknown>(S);
3445 UniqueSCEVs.InsertNode(S, IP);
3449 //===----------------------------------------------------------------------===//
3450 // Basic SCEV Analysis and PHI Idiom Recognition Code
3453 /// Test if values of the given type are analyzable within the SCEV
3454 /// framework. This primarily includes integer types, and it can optionally
3455 /// include pointer types if the ScalarEvolution class has access to
3456 /// target-specific information.
3457 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3458 // Integers and pointers are always SCEVable.
3459 return Ty->isIntegerTy() || Ty->isPointerTy();
3462 /// Return the size in bits of the specified type, for which isSCEVable must
3464 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3465 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3466 return getDataLayout().getTypeSizeInBits(Ty);
3469 /// Return a type with the same bitwidth as the given type and which represents
3470 /// how SCEV will treat the given type, for which isSCEVable must return
3471 /// true. For pointer types, this is the pointer-sized integer type.
3472 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3473 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3475 if (Ty->isIntegerTy())
3478 // The only other support type is pointer.
3479 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3480 return getDataLayout().getIntPtrType(Ty);
3483 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3484 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3487 const SCEV *ScalarEvolution::getCouldNotCompute() {
3488 return CouldNotCompute.get();
3491 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3492 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3493 auto *SU = dyn_cast<SCEVUnknown>(S);
3494 return SU && SU->getValue() == nullptr;
3497 return !ContainsNulls;
3500 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3501 HasRecMapType::iterator I = HasRecMap.find(S);
3502 if (I != HasRecMap.end())
3505 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3506 HasRecMap.insert({S, FoundAddRec});
3510 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3511 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3512 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3513 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3514 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3516 return {S, nullptr};
3518 if (Add->getNumOperands() != 2)
3519 return {S, nullptr};
3521 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3523 return {S, nullptr};
3525 return {Add->getOperand(1), ConstOp->getValue()};
3528 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3529 /// by the value and offset from any ValueOffsetPair in the set.
3530 SetVector<ScalarEvolution::ValueOffsetPair> *
3531 ScalarEvolution::getSCEVValues(const SCEV *S) {
3532 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3533 if (SI == ExprValueMap.end())
3536 if (VerifySCEVMap) {
3537 // Check there is no dangling Value in the set returned.
3538 for (const auto &VE : SI->second)
3539 assert(ValueExprMap.count(VE.first));
3545 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3546 /// cannot be used separately. eraseValueFromMap should be used to remove
3547 /// V from ValueExprMap and ExprValueMap at the same time.
3548 void ScalarEvolution::eraseValueFromMap(Value *V) {
3549 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3550 if (I != ValueExprMap.end()) {
3551 const SCEV *S = I->second;
3552 // Remove {V, 0} from the set of ExprValueMap[S]
3553 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3554 SV->remove({V, nullptr});
3556 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3557 const SCEV *Stripped;
3558 ConstantInt *Offset;
3559 std::tie(Stripped, Offset) = splitAddExpr(S);
3560 if (Offset != nullptr) {
3561 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3562 SV->remove({V, Offset});
3564 ValueExprMap.erase(V);
3568 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3569 /// create a new one.
3570 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3571 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3573 const SCEV *S = getExistingSCEV(V);
3576 // During PHI resolution, it is possible to create two SCEVs for the same
3577 // V, so it is needed to double check whether V->S is inserted into
3578 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3579 std::pair<ValueExprMapType::iterator, bool> Pair =
3580 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3582 ExprValueMap[S].insert({V, nullptr});
3584 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3586 const SCEV *Stripped = S;
3587 ConstantInt *Offset = nullptr;
3588 std::tie(Stripped, Offset) = splitAddExpr(S);
3589 // If stripped is SCEVUnknown, don't bother to save
3590 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3591 // increase the complexity of the expansion code.
3592 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3593 // because it may generate add/sub instead of GEP in SCEV expansion.
3594 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3595 !isa<GetElementPtrInst>(V))
3596 ExprValueMap[Stripped].insert({V, Offset});
3602 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3603 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3605 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3606 if (I != ValueExprMap.end()) {
3607 const SCEV *S = I->second;
3608 if (checkValidity(S))
3610 eraseValueFromMap(V);
3611 forgetMemoizedResults(S);
3616 /// Return a SCEV corresponding to -V = -1*V
3618 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3619 SCEV::NoWrapFlags Flags) {
3620 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3622 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3624 Type *Ty = V->getType();
3625 Ty = getEffectiveSCEVType(Ty);
3627 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3630 /// Return a SCEV corresponding to ~V = -1-V
3631 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3632 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3634 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3636 Type *Ty = V->getType();
3637 Ty = getEffectiveSCEVType(Ty);
3638 const SCEV *AllOnes =
3639 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3640 return getMinusSCEV(AllOnes, V);
3643 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3644 SCEV::NoWrapFlags Flags) {
3645 // Fast path: X - X --> 0.
3647 return getZero(LHS->getType());
3649 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3650 // makes it so that we cannot make much use of NUW.
3651 auto AddFlags = SCEV::FlagAnyWrap;
3652 const bool RHSIsNotMinSigned =
3653 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3654 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3655 // Let M be the minimum representable signed value. Then (-1)*RHS
3656 // signed-wraps if and only if RHS is M. That can happen even for
3657 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3658 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3659 // (-1)*RHS, we need to prove that RHS != M.
3661 // If LHS is non-negative and we know that LHS - RHS does not
3662 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3663 // either by proving that RHS > M or that LHS >= 0.
3664 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3665 AddFlags = SCEV::FlagNSW;
3669 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3670 // RHS is NSW and LHS >= 0.
3672 // The difficulty here is that the NSW flag may have been proven
3673 // relative to a loop that is to be found in a recurrence in LHS and
3674 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3675 // larger scope than intended.
3676 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3678 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3682 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3683 Type *SrcTy = V->getType();
3684 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3685 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3686 "Cannot truncate or zero extend with non-integer arguments!");
3687 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3688 return V; // No conversion
3689 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3690 return getTruncateExpr(V, Ty);
3691 return getZeroExtendExpr(V, Ty);
3695 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3697 Type *SrcTy = V->getType();
3698 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3699 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3700 "Cannot truncate or zero extend with non-integer arguments!");
3701 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3702 return V; // No conversion
3703 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3704 return getTruncateExpr(V, Ty);
3705 return getSignExtendExpr(V, Ty);
3709 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3710 Type *SrcTy = V->getType();
3711 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3712 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3713 "Cannot noop or zero extend with non-integer arguments!");
3714 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3715 "getNoopOrZeroExtend cannot truncate!");
3716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3717 return V; // No conversion
3718 return getZeroExtendExpr(V, Ty);
3722 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3723 Type *SrcTy = V->getType();
3724 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3725 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3726 "Cannot noop or sign extend with non-integer arguments!");
3727 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3728 "getNoopOrSignExtend cannot truncate!");
3729 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3730 return V; // No conversion
3731 return getSignExtendExpr(V, Ty);
3735 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3736 Type *SrcTy = V->getType();
3737 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3738 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3739 "Cannot noop or any extend with non-integer arguments!");
3740 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3741 "getNoopOrAnyExtend cannot truncate!");
3742 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3743 return V; // No conversion
3744 return getAnyExtendExpr(V, Ty);
3748 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3749 Type *SrcTy = V->getType();
3750 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3751 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3752 "Cannot truncate or noop with non-integer arguments!");
3753 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3754 "getTruncateOrNoop cannot extend!");
3755 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3756 return V; // No conversion
3757 return getTruncateExpr(V, Ty);
3760 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3762 const SCEV *PromotedLHS = LHS;
3763 const SCEV *PromotedRHS = RHS;
3765 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3766 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3768 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3770 return getUMaxExpr(PromotedLHS, PromotedRHS);
3773 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3775 const SCEV *PromotedLHS = LHS;
3776 const SCEV *PromotedRHS = RHS;
3778 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3779 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3781 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3783 return getUMinExpr(PromotedLHS, PromotedRHS);
3786 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3787 // A pointer operand may evaluate to a nonpointer expression, such as null.
3788 if (!V->getType()->isPointerTy())
3791 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3792 return getPointerBase(Cast->getOperand());
3793 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3794 const SCEV *PtrOp = nullptr;
3795 for (const SCEV *NAryOp : NAry->operands()) {
3796 if (NAryOp->getType()->isPointerTy()) {
3797 // Cannot find the base of an expression with multiple pointer operands.
3805 return getPointerBase(PtrOp);
3810 /// Push users of the given Instruction onto the given Worklist.
3812 PushDefUseChildren(Instruction *I,
3813 SmallVectorImpl<Instruction *> &Worklist) {
3814 // Push the def-use children onto the Worklist stack.
3815 for (User *U : I->users())
3816 Worklist.push_back(cast<Instruction>(U));
3819 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3820 SmallVector<Instruction *, 16> Worklist;
3821 PushDefUseChildren(PN, Worklist);
3823 SmallPtrSet<Instruction *, 8> Visited;
3825 while (!Worklist.empty()) {
3826 Instruction *I = Worklist.pop_back_val();
3827 if (!Visited.insert(I).second)
3830 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3831 if (It != ValueExprMap.end()) {
3832 const SCEV *Old = It->second;
3834 // Short-circuit the def-use traversal if the symbolic name
3835 // ceases to appear in expressions.
3836 if (Old != SymName && !hasOperand(Old, SymName))
3839 // SCEVUnknown for a PHI either means that it has an unrecognized
3840 // structure, it's a PHI that's in the progress of being computed
3841 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3842 // additional loop trip count information isn't going to change anything.
3843 // In the second case, createNodeForPHI will perform the necessary
3844 // updates on its own when it gets to that point. In the third, we do
3845 // want to forget the SCEVUnknown.
3846 if (!isa<PHINode>(I) ||
3847 !isa<SCEVUnknown>(Old) ||
3848 (I != PN && Old == SymName)) {
3849 eraseValueFromMap(It->first);
3850 forgetMemoizedResults(Old);
3854 PushDefUseChildren(I, Worklist);
3859 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3861 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3862 ScalarEvolution &SE) {
3863 SCEVInitRewriter Rewriter(L, SE);
3864 const SCEV *Result = Rewriter.visit(S);
3865 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3868 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3869 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3871 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3872 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3877 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3878 // Only allow AddRecExprs for this loop.
3879 if (Expr->getLoop() == L)
3880 return Expr->getStart();
3885 bool isValid() { return Valid; }
3892 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3894 static const SCEV *rewrite(const SCEV *S, const Loop *L,
3895 ScalarEvolution &SE) {
3896 SCEVShiftRewriter Rewriter(L, SE);
3897 const SCEV *Result = Rewriter.visit(S);
3898 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3901 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3902 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3904 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3905 // Only allow AddRecExprs for this loop.
3906 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3911 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3912 if (Expr->getLoop() == L && Expr->isAffine())
3913 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3917 bool isValid() { return Valid; }
3923 } // end anonymous namespace
3926 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3927 if (!AR->isAffine())
3928 return SCEV::FlagAnyWrap;
3930 typedef OverflowingBinaryOperator OBO;
3931 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3933 if (!AR->hasNoSignedWrap()) {
3934 ConstantRange AddRecRange = getSignedRange(AR);
3935 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3937 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3938 Instruction::Add, IncRange, OBO::NoSignedWrap);
3939 if (NSWRegion.contains(AddRecRange))
3940 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3943 if (!AR->hasNoUnsignedWrap()) {
3944 ConstantRange AddRecRange = getUnsignedRange(AR);
3945 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3947 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3948 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3949 if (NUWRegion.contains(AddRecRange))
3950 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3957 /// Represents an abstract binary operation. This may exist as a
3958 /// normal instruction or constant expression, or may have been
3959 /// derived from an expression tree.
3967 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3968 /// constant expression.
3971 explicit BinaryOp(Operator *Op)
3972 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3973 IsNSW(false), IsNUW(false), Op(Op) {
3974 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3975 IsNSW = OBO->hasNoSignedWrap();
3976 IsNUW = OBO->hasNoUnsignedWrap();
3980 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3982 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3988 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3989 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3990 auto *Op = dyn_cast<Operator>(V);
3994 // Implementation detail: all the cleverness here should happen without
3995 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3996 // SCEV expressions when possible, and we should not break that.
3998 switch (Op->getOpcode()) {
3999 case Instruction::Add:
4000 case Instruction::Sub:
4001 case Instruction::Mul:
4002 case Instruction::UDiv:
4003 case Instruction::And:
4004 case Instruction::Or:
4005 case Instruction::AShr:
4006 case Instruction::Shl:
4007 return BinaryOp(Op);
4009 case Instruction::Xor:
4010 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4011 // If the RHS of the xor is a signmask, then this is just an add.
4012 // Instcombine turns add of signmask into xor as a strength reduction step.
4013 if (RHSC->getValue().isSignMask())
4014 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4015 return BinaryOp(Op);
4017 case Instruction::LShr:
4018 // Turn logical shift right of a constant into a unsigned divide.
4019 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4020 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4022 // If the shift count is not less than the bitwidth, the result of
4023 // the shift is undefined. Don't try to analyze it, because the
4024 // resolution chosen here may differ from the resolution chosen in
4025 // other parts of the compiler.
4026 if (SA->getValue().ult(BitWidth)) {
4028 ConstantInt::get(SA->getContext(),
4029 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4030 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4033 return BinaryOp(Op);
4035 case Instruction::ExtractValue: {
4036 auto *EVI = cast<ExtractValueInst>(Op);
4037 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4040 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4044 if (auto *F = CI->getCalledFunction())
4045 switch (F->getIntrinsicID()) {
4046 case Intrinsic::sadd_with_overflow:
4047 case Intrinsic::uadd_with_overflow: {
4048 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4049 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4050 CI->getArgOperand(1));
4052 // Now that we know that all uses of the arithmetic-result component of
4053 // CI are guarded by the overflow check, we can go ahead and pretend
4054 // that the arithmetic is non-overflowing.
4055 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4056 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4057 CI->getArgOperand(1), /* IsNSW = */ true,
4058 /* IsNUW = */ false);
4060 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4061 CI->getArgOperand(1), /* IsNSW = */ false,
4065 case Intrinsic::ssub_with_overflow:
4066 case Intrinsic::usub_with_overflow:
4067 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4068 CI->getArgOperand(1));
4070 case Intrinsic::smul_with_overflow:
4071 case Intrinsic::umul_with_overflow:
4072 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4073 CI->getArgOperand(1));
4086 /// A helper function for createAddRecFromPHI to handle simple cases.
4088 /// This function tries to find an AddRec expression for the simplest (yet most
4089 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4090 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4091 /// technique for finding the AddRec expression.
4092 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4094 Value *StartValueV) {
4095 const Loop *L = LI.getLoopFor(PN->getParent());
4096 assert(L && L->getHeader() == PN->getParent());
4097 assert(BEValueV && StartValueV);
4099 auto BO = MatchBinaryOp(BEValueV, DT);
4103 if (BO->Opcode != Instruction::Add)
4106 const SCEV *Accum = nullptr;
4107 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4108 Accum = getSCEV(BO->RHS);
4109 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4110 Accum = getSCEV(BO->LHS);
4115 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4117 Flags = setFlags(Flags, SCEV::FlagNUW);
4119 Flags = setFlags(Flags, SCEV::FlagNSW);
4121 const SCEV *StartVal = getSCEV(StartValueV);
4122 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4124 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4126 // We can add Flags to the post-inc expression only if we
4127 // know that it is *undefined behavior* for BEValueV to
4129 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4130 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4131 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4136 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4137 const Loop *L = LI.getLoopFor(PN->getParent());
4138 if (!L || L->getHeader() != PN->getParent())
4141 // The loop may have multiple entrances or multiple exits; we can analyze
4142 // this phi as an addrec if it has a unique entry value and a unique
4144 Value *BEValueV = nullptr, *StartValueV = nullptr;
4145 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4146 Value *V = PN->getIncomingValue(i);
4147 if (L->contains(PN->getIncomingBlock(i))) {
4150 } else if (BEValueV != V) {
4154 } else if (!StartValueV) {
4156 } else if (StartValueV != V) {
4157 StartValueV = nullptr;
4161 if (!BEValueV || !StartValueV)
4164 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4165 "PHI node already processed?");
4167 // First, try to find AddRec expression without creating a fictituos symbolic
4169 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4172 // Handle PHI node value symbolically.
4173 const SCEV *SymbolicName = getUnknown(PN);
4174 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4176 // Using this symbolic name for the PHI, analyze the value coming around
4178 const SCEV *BEValue = getSCEV(BEValueV);
4180 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4181 // has a special value for the first iteration of the loop.
4183 // If the value coming around the backedge is an add with the symbolic
4184 // value we just inserted, then we found a simple induction variable!
4185 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4186 // If there is a single occurrence of the symbolic value, replace it
4187 // with a recurrence.
4188 unsigned FoundIndex = Add->getNumOperands();
4189 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4190 if (Add->getOperand(i) == SymbolicName)
4191 if (FoundIndex == e) {
4196 if (FoundIndex != Add->getNumOperands()) {
4197 // Create an add with everything but the specified operand.
4198 SmallVector<const SCEV *, 8> Ops;
4199 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4200 if (i != FoundIndex)
4201 Ops.push_back(Add->getOperand(i));
4202 const SCEV *Accum = getAddExpr(Ops);
4204 // This is not a valid addrec if the step amount is varying each
4205 // loop iteration, but is not itself an addrec in this loop.
4206 if (isLoopInvariant(Accum, L) ||
4207 (isa<SCEVAddRecExpr>(Accum) &&
4208 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4209 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4211 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4212 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4214 Flags = setFlags(Flags, SCEV::FlagNUW);
4216 Flags = setFlags(Flags, SCEV::FlagNSW);
4218 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4219 // If the increment is an inbounds GEP, then we know the address
4220 // space cannot be wrapped around. We cannot make any guarantee
4221 // about signed or unsigned overflow because pointers are
4222 // unsigned but we may have a negative index from the base
4223 // pointer. We can guarantee that no unsigned wrap occurs if the
4224 // indices form a positive value.
4225 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4226 Flags = setFlags(Flags, SCEV::FlagNW);
4228 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4229 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4230 Flags = setFlags(Flags, SCEV::FlagNUW);
4233 // We cannot transfer nuw and nsw flags from subtraction
4234 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4238 const SCEV *StartVal = getSCEV(StartValueV);
4239 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4241 // Okay, for the entire analysis of this edge we assumed the PHI
4242 // to be symbolic. We now need to go back and purge all of the
4243 // entries for the scalars that use the symbolic expression.
4244 forgetSymbolicName(PN, SymbolicName);
4245 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4247 // We can add Flags to the post-inc expression only if we
4248 // know that it is *undefined behavior* for BEValueV to
4250 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4251 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4252 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4258 // Otherwise, this could be a loop like this:
4259 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4260 // In this case, j = {1,+,1} and BEValue is j.
4261 // Because the other in-value of i (0) fits the evolution of BEValue
4262 // i really is an addrec evolution.
4264 // We can generalize this saying that i is the shifted value of BEValue
4265 // by one iteration:
4266 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4267 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4268 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4269 if (Shifted != getCouldNotCompute() &&
4270 Start != getCouldNotCompute()) {
4271 const SCEV *StartVal = getSCEV(StartValueV);
4272 if (Start == StartVal) {
4273 // Okay, for the entire analysis of this edge we assumed the PHI
4274 // to be symbolic. We now need to go back and purge all of the
4275 // entries for the scalars that use the symbolic expression.
4276 forgetSymbolicName(PN, SymbolicName);
4277 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4283 // Remove the temporary PHI node SCEV that has been inserted while intending
4284 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4285 // as it will prevent later (possibly simpler) SCEV expressions to be added
4286 // to the ValueExprMap.
4287 eraseValueFromMap(PN);
4292 // Checks if the SCEV S is available at BB. S is considered available at BB
4293 // if S can be materialized at BB without introducing a fault.
4294 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4296 struct CheckAvailable {
4297 bool TraversalDone = false;
4298 bool Available = true;
4300 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4301 BasicBlock *BB = nullptr;
4304 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4305 : L(L), BB(BB), DT(DT) {}
4307 bool setUnavailable() {
4308 TraversalDone = true;
4313 bool follow(const SCEV *S) {
4314 switch (S->getSCEVType()) {
4315 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4316 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4317 // These expressions are available if their operand(s) is/are.
4320 case scAddRecExpr: {
4321 // We allow add recurrences that are on the loop BB is in, or some
4322 // outer loop. This guarantees availability because the value of the
4323 // add recurrence at BB is simply the "current" value of the induction
4324 // variable. We can relax this in the future; for instance an add
4325 // recurrence on a sibling dominating loop is also available at BB.
4326 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4327 if (L && (ARLoop == L || ARLoop->contains(L)))
4330 return setUnavailable();
4334 // For SCEVUnknown, we check for simple dominance.
4335 const auto *SU = cast<SCEVUnknown>(S);
4336 Value *V = SU->getValue();
4338 if (isa<Argument>(V))
4341 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4344 return setUnavailable();
4348 case scCouldNotCompute:
4349 // We do not try to smart about these at all.
4350 return setUnavailable();
4352 llvm_unreachable("switch should be fully covered!");
4355 bool isDone() { return TraversalDone; }
4358 CheckAvailable CA(L, BB, DT);
4359 SCEVTraversal<CheckAvailable> ST(CA);
4362 return CA.Available;
4365 // Try to match a control flow sequence that branches out at BI and merges back
4366 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4368 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4369 Value *&C, Value *&LHS, Value *&RHS) {
4370 C = BI->getCondition();
4372 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4373 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4375 if (!LeftEdge.isSingleEdge())
4378 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4380 Use &LeftUse = Merge->getOperandUse(0);
4381 Use &RightUse = Merge->getOperandUse(1);
4383 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4389 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4398 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4400 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4401 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4402 const Loop *L = LI.getLoopFor(PN->getParent());
4404 // We don't want to break LCSSA, even in a SCEV expression tree.
4405 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4406 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4411 // br %cond, label %left, label %right
4417 // V = phi [ %x, %left ], [ %y, %right ]
4419 // as "select %cond, %x, %y"
4421 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4422 assert(IDom && "At least the entry block should dominate PN");
4424 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4425 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4427 if (BI && BI->isConditional() &&
4428 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4429 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4430 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4431 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4437 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4438 if (const SCEV *S = createAddRecFromPHI(PN))
4441 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4444 // If the PHI has a single incoming value, follow that value, unless the
4445 // PHI's incoming blocks are in a different loop, in which case doing so
4446 // risks breaking LCSSA form. Instcombine would normally zap these, but
4447 // it doesn't have DominatorTree information, so it may miss cases.
4448 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4449 if (LI.replacementPreservesLCSSAForm(PN, V))
4452 // If it's not a loop phi, we can't handle it yet.
4453 return getUnknown(PN);
4456 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4460 // Handle "constant" branch or select. This can occur for instance when a
4461 // loop pass transforms an inner loop and moves on to process the outer loop.
4462 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4463 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4465 // Try to match some simple smax or umax patterns.
4466 auto *ICI = dyn_cast<ICmpInst>(Cond);
4468 return getUnknown(I);
4470 Value *LHS = ICI->getOperand(0);
4471 Value *RHS = ICI->getOperand(1);
4473 switch (ICI->getPredicate()) {
4474 case ICmpInst::ICMP_SLT:
4475 case ICmpInst::ICMP_SLE:
4476 std::swap(LHS, RHS);
4478 case ICmpInst::ICMP_SGT:
4479 case ICmpInst::ICMP_SGE:
4480 // a >s b ? a+x : b+x -> smax(a, b)+x
4481 // a >s b ? b+x : a+x -> smin(a, b)+x
4482 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4483 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4484 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4485 const SCEV *LA = getSCEV(TrueVal);
4486 const SCEV *RA = getSCEV(FalseVal);
4487 const SCEV *LDiff = getMinusSCEV(LA, LS);
4488 const SCEV *RDiff = getMinusSCEV(RA, RS);
4490 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4491 LDiff = getMinusSCEV(LA, RS);
4492 RDiff = getMinusSCEV(RA, LS);
4494 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4497 case ICmpInst::ICMP_ULT:
4498 case ICmpInst::ICMP_ULE:
4499 std::swap(LHS, RHS);
4501 case ICmpInst::ICMP_UGT:
4502 case ICmpInst::ICMP_UGE:
4503 // a >u b ? a+x : b+x -> umax(a, b)+x
4504 // a >u b ? b+x : a+x -> umin(a, b)+x
4505 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4506 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4507 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4508 const SCEV *LA = getSCEV(TrueVal);
4509 const SCEV *RA = getSCEV(FalseVal);
4510 const SCEV *LDiff = getMinusSCEV(LA, LS);
4511 const SCEV *RDiff = getMinusSCEV(RA, RS);
4513 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4514 LDiff = getMinusSCEV(LA, RS);
4515 RDiff = getMinusSCEV(RA, LS);
4517 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4520 case ICmpInst::ICMP_NE:
4521 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4522 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4523 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4524 const SCEV *One = getOne(I->getType());
4525 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4526 const SCEV *LA = getSCEV(TrueVal);
4527 const SCEV *RA = getSCEV(FalseVal);
4528 const SCEV *LDiff = getMinusSCEV(LA, LS);
4529 const SCEV *RDiff = getMinusSCEV(RA, One);
4531 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4534 case ICmpInst::ICMP_EQ:
4535 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4536 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4537 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4538 const SCEV *One = getOne(I->getType());
4539 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4540 const SCEV *LA = getSCEV(TrueVal);
4541 const SCEV *RA = getSCEV(FalseVal);
4542 const SCEV *LDiff = getMinusSCEV(LA, One);
4543 const SCEV *RDiff = getMinusSCEV(RA, LS);
4545 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4552 return getUnknown(I);
4555 /// Expand GEP instructions into add and multiply operations. This allows them
4556 /// to be analyzed by regular SCEV code.
4557 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4558 // Don't attempt to analyze GEPs over unsized objects.
4559 if (!GEP->getSourceElementType()->isSized())
4560 return getUnknown(GEP);
4562 SmallVector<const SCEV *, 4> IndexExprs;
4563 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4564 IndexExprs.push_back(getSCEV(*Index));
4565 return getGEPExpr(GEP, IndexExprs);
4568 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4569 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4570 return C->getAPInt().countTrailingZeros();
4572 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4573 return std::min(GetMinTrailingZeros(T->getOperand()),
4574 (uint32_t)getTypeSizeInBits(T->getType()));
4576 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4577 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4578 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4579 ? getTypeSizeInBits(E->getType())
4583 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4584 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4585 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4586 ? getTypeSizeInBits(E->getType())
4590 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4591 // The result is the min of all operands results.
4592 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4593 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4594 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4598 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4599 // The result is the sum of all operands results.
4600 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4601 uint32_t BitWidth = getTypeSizeInBits(M->getType());
4602 for (unsigned i = 1, e = M->getNumOperands();
4603 SumOpRes != BitWidth && i != e; ++i)
4605 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4609 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4610 // The result is the min of all operands results.
4611 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4612 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4613 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4617 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4618 // The result is the min of all operands results.
4619 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4620 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4621 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4625 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4626 // The result is the min of all operands results.
4627 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4628 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4629 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4633 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4634 // For a SCEVUnknown, ask ValueTracking.
4635 unsigned BitWidth = getTypeSizeInBits(U->getType());
4636 KnownBits Known(BitWidth);
4637 computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC,
4639 return Known.Zero.countTrailingOnes();
4646 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4647 auto I = MinTrailingZerosCache.find(S);
4648 if (I != MinTrailingZerosCache.end())
4651 uint32_t Result = GetMinTrailingZerosImpl(S);
4652 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4653 assert(InsertPair.second && "Should insert a new key");
4654 return InsertPair.first->second;
4657 /// Helper method to assign a range to V from metadata present in the IR.
4658 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4659 if (Instruction *I = dyn_cast<Instruction>(V))
4660 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4661 return getConstantRangeFromMetadata(*MD);
4666 /// Determine the range for a particular SCEV. If SignHint is
4667 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4668 /// with a "cleaner" unsigned (resp. signed) representation.
4670 ScalarEvolution::getRange(const SCEV *S,
4671 ScalarEvolution::RangeSignHint SignHint) {
4672 DenseMap<const SCEV *, ConstantRange> &Cache =
4673 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4676 // See if we've computed this range already.
4677 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4678 if (I != Cache.end())
4681 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4682 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4684 unsigned BitWidth = getTypeSizeInBits(S->getType());
4685 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4687 // If the value has known zeros, the maximum value will have those known zeros
4689 uint32_t TZ = GetMinTrailingZeros(S);
4691 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4692 ConservativeResult =
4693 ConstantRange(APInt::getMinValue(BitWidth),
4694 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4696 ConservativeResult = ConstantRange(
4697 APInt::getSignedMinValue(BitWidth),
4698 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4701 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4702 ConstantRange X = getRange(Add->getOperand(0), SignHint);
4703 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4704 X = X.add(getRange(Add->getOperand(i), SignHint));
4705 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4708 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4709 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4710 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4711 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4712 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4715 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4716 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4717 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4718 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4719 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4722 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4723 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4724 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4725 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4726 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4729 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4730 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4731 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4732 return setRange(UDiv, SignHint,
4733 ConservativeResult.intersectWith(X.udiv(Y)));
4736 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4737 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4738 return setRange(ZExt, SignHint,
4739 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4742 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4743 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4744 return setRange(SExt, SignHint,
4745 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4748 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4749 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4750 return setRange(Trunc, SignHint,
4751 ConservativeResult.intersectWith(X.truncate(BitWidth)));
4754 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4755 // If there's no unsigned wrap, the value will never be less than its
4757 if (AddRec->hasNoUnsignedWrap())
4758 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4759 if (!C->getValue()->isZero())
4760 ConservativeResult = ConservativeResult.intersectWith(
4761 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4763 // If there's no signed wrap, and all the operands have the same sign or
4764 // zero, the value won't ever change sign.
4765 if (AddRec->hasNoSignedWrap()) {
4766 bool AllNonNeg = true;
4767 bool AllNonPos = true;
4768 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4769 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4770 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4773 ConservativeResult = ConservativeResult.intersectWith(
4774 ConstantRange(APInt(BitWidth, 0),
4775 APInt::getSignedMinValue(BitWidth)));
4777 ConservativeResult = ConservativeResult.intersectWith(
4778 ConstantRange(APInt::getSignedMinValue(BitWidth),
4779 APInt(BitWidth, 1)));
4782 // TODO: non-affine addrec
4783 if (AddRec->isAffine()) {
4784 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4785 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4786 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4787 auto RangeFromAffine = getRangeForAffineAR(
4788 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4790 if (!RangeFromAffine.isFullSet())
4791 ConservativeResult =
4792 ConservativeResult.intersectWith(RangeFromAffine);
4794 auto RangeFromFactoring = getRangeViaFactoring(
4795 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4797 if (!RangeFromFactoring.isFullSet())
4798 ConservativeResult =
4799 ConservativeResult.intersectWith(RangeFromFactoring);
4803 return setRange(AddRec, SignHint, std::move(ConservativeResult));
4806 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4807 // Check if the IR explicitly contains !range metadata.
4808 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4809 if (MDRange.hasValue())
4810 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4812 // Split here to avoid paying the compile-time cost of calling both
4813 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4815 const DataLayout &DL = getDataLayout();
4816 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4817 // For a SCEVUnknown, ask ValueTracking.
4818 KnownBits Known(BitWidth);
4819 computeKnownBits(U->getValue(), Known, DL, 0, &AC, nullptr, &DT);
4820 if (Known.One != ~Known.Zero + 1)
4821 ConservativeResult =
4822 ConservativeResult.intersectWith(ConstantRange(Known.One,
4825 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4826 "generalize as needed!");
4827 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4829 ConservativeResult = ConservativeResult.intersectWith(
4830 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4831 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4834 return setRange(U, SignHint, std::move(ConservativeResult));
4837 return setRange(S, SignHint, std::move(ConservativeResult));
4840 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4841 // values that the expression can take. Initially, the expression has a value
4842 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4843 // argument defines if we treat Step as signed or unsigned.
4844 static ConstantRange getRangeForAffineARHelper(APInt Step,
4845 const ConstantRange &StartRange,
4846 const APInt &MaxBECount,
4847 unsigned BitWidth, bool Signed) {
4848 // If either Step or MaxBECount is 0, then the expression won't change, and we
4849 // just need to return the initial range.
4850 if (Step == 0 || MaxBECount == 0)
4853 // If we don't know anything about the initial value (i.e. StartRange is
4854 // FullRange), then we don't know anything about the final range either.
4855 // Return FullRange.
4856 if (StartRange.isFullSet())
4857 return ConstantRange(BitWidth, /* isFullSet = */ true);
4859 // If Step is signed and negative, then we use its absolute value, but we also
4860 // note that we're moving in the opposite direction.
4861 bool Descending = Signed && Step.isNegative();
4864 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4865 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4866 // This equations hold true due to the well-defined wrap-around behavior of
4870 // Check if Offset is more than full span of BitWidth. If it is, the
4871 // expression is guaranteed to overflow.
4872 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4873 return ConstantRange(BitWidth, /* isFullSet = */ true);
4875 // Offset is by how much the expression can change. Checks above guarantee no
4877 APInt Offset = Step * MaxBECount;
4879 // Minimum value of the final range will match the minimal value of StartRange
4880 // if the expression is increasing and will be decreased by Offset otherwise.
4881 // Maximum value of the final range will match the maximal value of StartRange
4882 // if the expression is decreasing and will be increased by Offset otherwise.
4883 APInt StartLower = StartRange.getLower();
4884 APInt StartUpper = StartRange.getUpper() - 1;
4885 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
4886 : (StartUpper + std::move(Offset));
4888 // It's possible that the new minimum/maximum value will fall into the initial
4889 // range (due to wrap around). This means that the expression can take any
4890 // value in this bitwidth, and we have to return full range.
4891 if (StartRange.contains(MovedBoundary))
4892 return ConstantRange(BitWidth, /* isFullSet = */ true);
4895 Descending ? std::move(MovedBoundary) : std::move(StartLower);
4897 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
4900 // If we end up with full range, return a proper full range.
4901 if (NewLower == NewUpper)
4902 return ConstantRange(BitWidth, /* isFullSet = */ true);
4904 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4905 return ConstantRange(std::move(NewLower), std::move(NewUpper));
4908 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4910 const SCEV *MaxBECount,
4911 unsigned BitWidth) {
4912 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4913 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4916 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4917 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4918 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4920 // First, consider step signed.
4921 ConstantRange StartSRange = getSignedRange(Start);
4922 ConstantRange StepSRange = getSignedRange(Step);
4924 // If Step can be both positive and negative, we need to find ranges for the
4925 // maximum absolute step values in both directions and union them.
4927 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4928 MaxBECountValue, BitWidth, /* Signed = */ true);
4929 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4930 StartSRange, MaxBECountValue,
4931 BitWidth, /* Signed = */ true));
4933 // Next, consider step unsigned.
4934 ConstantRange UR = getRangeForAffineARHelper(
4935 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4936 MaxBECountValue, BitWidth, /* Signed = */ false);
4938 // Finally, intersect signed and unsigned ranges.
4939 return SR.intersectWith(UR);
4942 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4944 const SCEV *MaxBECount,
4945 unsigned BitWidth) {
4946 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4947 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4949 struct SelectPattern {
4950 Value *Condition = nullptr;
4954 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4956 Optional<unsigned> CastOp;
4957 APInt Offset(BitWidth, 0);
4959 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4962 // Peel off a constant offset:
4963 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4964 // In the future we could consider being smarter here and handle
4965 // {Start+Step,+,Step} too.
4966 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4969 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4970 S = SA->getOperand(1);
4973 // Peel off a cast operation
4974 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4975 CastOp = SCast->getSCEVType();
4976 S = SCast->getOperand();
4979 using namespace llvm::PatternMatch;
4981 auto *SU = dyn_cast<SCEVUnknown>(S);
4982 const APInt *TrueVal, *FalseVal;
4984 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4985 m_APInt(FalseVal)))) {
4986 Condition = nullptr;
4990 TrueValue = *TrueVal;
4991 FalseValue = *FalseVal;
4993 // Re-apply the cast we peeled off earlier
4994 if (CastOp.hasValue())
4997 llvm_unreachable("Unknown SCEV cast type!");
5000 TrueValue = TrueValue.trunc(BitWidth);
5001 FalseValue = FalseValue.trunc(BitWidth);
5004 TrueValue = TrueValue.zext(BitWidth);
5005 FalseValue = FalseValue.zext(BitWidth);
5008 TrueValue = TrueValue.sext(BitWidth);
5009 FalseValue = FalseValue.sext(BitWidth);
5013 // Re-apply the constant offset we peeled off earlier
5014 TrueValue += Offset;
5015 FalseValue += Offset;
5018 bool isRecognized() { return Condition != nullptr; }
5021 SelectPattern StartPattern(*this, BitWidth, Start);
5022 if (!StartPattern.isRecognized())
5023 return ConstantRange(BitWidth, /* isFullSet = */ true);
5025 SelectPattern StepPattern(*this, BitWidth, Step);
5026 if (!StepPattern.isRecognized())
5027 return ConstantRange(BitWidth, /* isFullSet = */ true);
5029 if (StartPattern.Condition != StepPattern.Condition) {
5030 // We don't handle this case today; but we could, by considering four
5031 // possibilities below instead of two. I'm not sure if there are cases where
5032 // that will help over what getRange already does, though.
5033 return ConstantRange(BitWidth, /* isFullSet = */ true);
5036 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5037 // construct arbitrary general SCEV expressions here. This function is called
5038 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5039 // say) can end up caching a suboptimal value.
5041 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5042 // C2352 and C2512 (otherwise it isn't needed).
5044 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5045 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5046 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5047 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5049 ConstantRange TrueRange =
5050 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5051 ConstantRange FalseRange =
5052 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5054 return TrueRange.unionWith(FalseRange);
5057 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5058 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5059 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5061 // Return early if there are no flags to propagate to the SCEV.
5062 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5063 if (BinOp->hasNoUnsignedWrap())
5064 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5065 if (BinOp->hasNoSignedWrap())
5066 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5067 if (Flags == SCEV::FlagAnyWrap)
5068 return SCEV::FlagAnyWrap;
5070 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5073 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5074 // Here we check that I is in the header of the innermost loop containing I,
5075 // since we only deal with instructions in the loop header. The actual loop we
5076 // need to check later will come from an add recurrence, but getting that
5077 // requires computing the SCEV of the operands, which can be expensive. This
5078 // check we can do cheaply to rule out some cases early.
5079 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5080 if (InnermostContainingLoop == nullptr ||
5081 InnermostContainingLoop->getHeader() != I->getParent())
5084 // Only proceed if we can prove that I does not yield poison.
5085 if (!programUndefinedIfFullPoison(I))
5088 // At this point we know that if I is executed, then it does not wrap
5089 // according to at least one of NSW or NUW. If I is not executed, then we do
5090 // not know if the calculation that I represents would wrap. Multiple
5091 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5092 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5093 // derived from other instructions that map to the same SCEV. We cannot make
5094 // that guarantee for cases where I is not executed. So we need to find the
5095 // loop that I is considered in relation to and prove that I is executed for
5096 // every iteration of that loop. That implies that the value that I
5097 // calculates does not wrap anywhere in the loop, so then we can apply the
5098 // flags to the SCEV.
5100 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5101 // from different loops, so that we know which loop to prove that I is
5103 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5104 // I could be an extractvalue from a call to an overflow intrinsic.
5105 // TODO: We can do better here in some cases.
5106 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5108 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5109 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5110 bool AllOtherOpsLoopInvariant = true;
5111 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5113 if (OtherOpIndex != OpIndex) {
5114 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5115 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5116 AllOtherOpsLoopInvariant = false;
5121 if (AllOtherOpsLoopInvariant &&
5122 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5129 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5130 // If we know that \c I can never be poison period, then that's enough.
5131 if (isSCEVExprNeverPoison(I))
5134 // For an add recurrence specifically, we assume that infinite loops without
5135 // side effects are undefined behavior, and then reason as follows:
5137 // If the add recurrence is poison in any iteration, it is poison on all
5138 // future iterations (since incrementing poison yields poison). If the result
5139 // of the add recurrence is fed into the loop latch condition and the loop
5140 // does not contain any throws or exiting blocks other than the latch, we now
5141 // have the ability to "choose" whether the backedge is taken or not (by
5142 // choosing a sufficiently evil value for the poison feeding into the branch)
5143 // for every iteration including and after the one in which \p I first became
5144 // poison. There are two possibilities (let's call the iteration in which \p
5145 // I first became poison as K):
5147 // 1. In the set of iterations including and after K, the loop body executes
5148 // no side effects. In this case executing the backege an infinte number
5149 // of times will yield undefined behavior.
5151 // 2. In the set of iterations including and after K, the loop body executes
5152 // at least one side effect. In this case, that specific instance of side
5153 // effect is control dependent on poison, which also yields undefined
5156 auto *ExitingBB = L->getExitingBlock();
5157 auto *LatchBB = L->getLoopLatch();
5158 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5161 SmallPtrSet<const Instruction *, 16> Pushed;
5162 SmallVector<const Instruction *, 8> PoisonStack;
5164 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5165 // things that are known to be fully poison under that assumption go on the
5168 PoisonStack.push_back(I);
5170 bool LatchControlDependentOnPoison = false;
5171 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5172 const Instruction *Poison = PoisonStack.pop_back_val();
5174 for (auto *PoisonUser : Poison->users()) {
5175 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5176 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5177 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5178 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5179 assert(BI->isConditional() && "Only possibility!");
5180 if (BI->getParent() == LatchBB) {
5181 LatchControlDependentOnPoison = true;
5188 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5191 ScalarEvolution::LoopProperties
5192 ScalarEvolution::getLoopProperties(const Loop *L) {
5193 typedef ScalarEvolution::LoopProperties LoopProperties;
5195 auto Itr = LoopPropertiesCache.find(L);
5196 if (Itr == LoopPropertiesCache.end()) {
5197 auto HasSideEffects = [](Instruction *I) {
5198 if (auto *SI = dyn_cast<StoreInst>(I))
5199 return !SI->isSimple();
5201 return I->mayHaveSideEffects();
5204 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5205 /*HasNoSideEffects*/ true};
5207 for (auto *BB : L->getBlocks())
5208 for (auto &I : *BB) {
5209 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5210 LP.HasNoAbnormalExits = false;
5211 if (HasSideEffects(&I))
5212 LP.HasNoSideEffects = false;
5213 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5214 break; // We're already as pessimistic as we can get.
5217 auto InsertPair = LoopPropertiesCache.insert({L, LP});
5218 assert(InsertPair.second && "We just checked!");
5219 Itr = InsertPair.first;
5225 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5226 if (!isSCEVable(V->getType()))
5227 return getUnknown(V);
5229 if (Instruction *I = dyn_cast<Instruction>(V)) {
5230 // Don't attempt to analyze instructions in blocks that aren't
5231 // reachable. Such instructions don't matter, and they aren't required
5232 // to obey basic rules for definitions dominating uses which this
5233 // analysis depends on.
5234 if (!DT.isReachableFromEntry(I->getParent()))
5235 return getUnknown(V);
5236 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5237 return getConstant(CI);
5238 else if (isa<ConstantPointerNull>(V))
5239 return getZero(V->getType());
5240 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5241 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5242 else if (!isa<ConstantExpr>(V))
5243 return getUnknown(V);
5245 Operator *U = cast<Operator>(V);
5246 if (auto BO = MatchBinaryOp(U, DT)) {
5247 switch (BO->Opcode) {
5248 case Instruction::Add: {
5249 // The simple thing to do would be to just call getSCEV on both operands
5250 // and call getAddExpr with the result. However if we're looking at a
5251 // bunch of things all added together, this can be quite inefficient,
5252 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5253 // Instead, gather up all the operands and make a single getAddExpr call.
5254 // LLVM IR canonical form means we need only traverse the left operands.
5255 SmallVector<const SCEV *, 4> AddOps;
5258 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5259 AddOps.push_back(OpSCEV);
5263 // If a NUW or NSW flag can be applied to the SCEV for this
5264 // addition, then compute the SCEV for this addition by itself
5265 // with a separate call to getAddExpr. We need to do that
5266 // instead of pushing the operands of the addition onto AddOps,
5267 // since the flags are only known to apply to this particular
5268 // addition - they may not apply to other additions that can be
5269 // formed with operands from AddOps.
5270 const SCEV *RHS = getSCEV(BO->RHS);
5271 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5272 if (Flags != SCEV::FlagAnyWrap) {
5273 const SCEV *LHS = getSCEV(BO->LHS);
5274 if (BO->Opcode == Instruction::Sub)
5275 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5277 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5282 if (BO->Opcode == Instruction::Sub)
5283 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5285 AddOps.push_back(getSCEV(BO->RHS));
5287 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5288 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5289 NewBO->Opcode != Instruction::Sub)) {
5290 AddOps.push_back(getSCEV(BO->LHS));
5296 return getAddExpr(AddOps);
5299 case Instruction::Mul: {
5300 SmallVector<const SCEV *, 4> MulOps;
5303 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5304 MulOps.push_back(OpSCEV);
5308 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5309 if (Flags != SCEV::FlagAnyWrap) {
5311 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5316 MulOps.push_back(getSCEV(BO->RHS));
5317 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5318 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5319 MulOps.push_back(getSCEV(BO->LHS));
5325 return getMulExpr(MulOps);
5327 case Instruction::UDiv:
5328 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5329 case Instruction::Sub: {
5330 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5332 Flags = getNoWrapFlagsFromUB(BO->Op);
5333 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5335 case Instruction::And:
5336 // For an expression like x&255 that merely masks off the high bits,
5337 // use zext(trunc(x)) as the SCEV expression.
5338 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5339 if (CI->isNullValue())
5340 return getSCEV(BO->RHS);
5341 if (CI->isAllOnesValue())
5342 return getSCEV(BO->LHS);
5343 const APInt &A = CI->getValue();
5345 // Instcombine's ShrinkDemandedConstant may strip bits out of
5346 // constants, obscuring what would otherwise be a low-bits mask.
5347 // Use computeKnownBits to compute what ShrinkDemandedConstant
5348 // knew about to reconstruct a low-bits mask value.
5349 unsigned LZ = A.countLeadingZeros();
5350 unsigned TZ = A.countTrailingZeros();
5351 unsigned BitWidth = A.getBitWidth();
5352 KnownBits Known(BitWidth);
5353 computeKnownBits(BO->LHS, Known, getDataLayout(),
5354 0, &AC, nullptr, &DT);
5356 APInt EffectiveMask =
5357 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5358 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5359 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5360 const SCEV *LHS = getSCEV(BO->LHS);
5361 const SCEV *ShiftedLHS = nullptr;
5362 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5363 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5364 // For an expression like (x * 8) & 8, simplify the multiply.
5365 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5366 unsigned GCD = std::min(MulZeros, TZ);
5367 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5368 SmallVector<const SCEV*, 4> MulOps;
5369 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5370 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5371 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5372 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5376 ShiftedLHS = getUDivExpr(LHS, MulCount);
5379 getTruncateExpr(ShiftedLHS,
5380 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5381 BO->LHS->getType()),
5387 case Instruction::Or:
5388 // If the RHS of the Or is a constant, we may have something like:
5389 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5390 // optimizations will transparently handle this case.
5392 // In order for this transformation to be safe, the LHS must be of the
5393 // form X*(2^n) and the Or constant must be less than 2^n.
5394 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5395 const SCEV *LHS = getSCEV(BO->LHS);
5396 const APInt &CIVal = CI->getValue();
5397 if (GetMinTrailingZeros(LHS) >=
5398 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5399 // Build a plain add SCEV.
5400 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5401 // If the LHS of the add was an addrec and it has no-wrap flags,
5402 // transfer the no-wrap flags, since an or won't introduce a wrap.
5403 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5404 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5405 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5406 OldAR->getNoWrapFlags());
5413 case Instruction::Xor:
5414 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5415 // If the RHS of xor is -1, then this is a not operation.
5416 if (CI->isAllOnesValue())
5417 return getNotSCEV(getSCEV(BO->LHS));
5419 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5420 // This is a variant of the check for xor with -1, and it handles
5421 // the case where instcombine has trimmed non-demanded bits out
5422 // of an xor with -1.
5423 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5424 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5425 if (LBO->getOpcode() == Instruction::And &&
5426 LCI->getValue() == CI->getValue())
5427 if (const SCEVZeroExtendExpr *Z =
5428 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5429 Type *UTy = BO->LHS->getType();
5430 const SCEV *Z0 = Z->getOperand();
5431 Type *Z0Ty = Z0->getType();
5432 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5434 // If C is a low-bits mask, the zero extend is serving to
5435 // mask off the high bits. Complement the operand and
5436 // re-apply the zext.
5437 if (CI->getValue().isMask(Z0TySize))
5438 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5440 // If C is a single bit, it may be in the sign-bit position
5441 // before the zero-extend. In this case, represent the xor
5442 // using an add, which is equivalent, and re-apply the zext.
5443 APInt Trunc = CI->getValue().trunc(Z0TySize);
5444 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5446 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5452 case Instruction::Shl:
5453 // Turn shift left of a constant amount into a multiply.
5454 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5455 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5457 // If the shift count is not less than the bitwidth, the result of
5458 // the shift is undefined. Don't try to analyze it, because the
5459 // resolution chosen here may differ from the resolution chosen in
5460 // other parts of the compiler.
5461 if (SA->getValue().uge(BitWidth))
5464 // It is currently not resolved how to interpret NSW for left
5465 // shift by BitWidth - 1, so we avoid applying flags in that
5466 // case. Remove this check (or this comment) once the situation
5468 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5469 // and http://reviews.llvm.org/D8890 .
5470 auto Flags = SCEV::FlagAnyWrap;
5471 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5472 Flags = getNoWrapFlagsFromUB(BO->Op);
5474 Constant *X = ConstantInt::get(getContext(),
5475 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5476 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5480 case Instruction::AShr:
5481 // AShr X, C, where C is a constant.
5482 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5486 Type *OuterTy = BO->LHS->getType();
5487 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5488 // If the shift count is not less than the bitwidth, the result of
5489 // the shift is undefined. Don't try to analyze it, because the
5490 // resolution chosen here may differ from the resolution chosen in
5491 // other parts of the compiler.
5492 if (CI->getValue().uge(BitWidth))
5495 if (CI->isNullValue())
5496 return getSCEV(BO->LHS); // shift by zero --> noop
5498 uint64_t AShrAmt = CI->getZExtValue();
5499 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5501 Operator *L = dyn_cast<Operator>(BO->LHS);
5502 if (L && L->getOpcode() == Instruction::Shl) {
5505 // Both n and m are constant.
5507 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5508 if (L->getOperand(1) == BO->RHS)
5509 // For a two-shift sext-inreg, i.e. n = m,
5510 // use sext(trunc(x)) as the SCEV expression.
5511 return getSignExtendExpr(
5512 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5514 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5515 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5516 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5517 if (ShlAmt > AShrAmt) {
5518 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5519 // expression. We already checked that ShlAmt < BitWidth, so
5520 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5521 // ShlAmt - AShrAmt < Amt.
5522 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5524 return getSignExtendExpr(
5525 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5526 getConstant(Mul)), OuterTy);
5534 switch (U->getOpcode()) {
5535 case Instruction::Trunc:
5536 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5538 case Instruction::ZExt:
5539 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5541 case Instruction::SExt:
5542 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5544 case Instruction::BitCast:
5545 // BitCasts are no-op casts so we just eliminate the cast.
5546 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5547 return getSCEV(U->getOperand(0));
5550 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5551 // lead to pointer expressions which cannot safely be expanded to GEPs,
5552 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5553 // simplifying integer expressions.
5555 case Instruction::GetElementPtr:
5556 return createNodeForGEP(cast<GEPOperator>(U));
5558 case Instruction::PHI:
5559 return createNodeForPHI(cast<PHINode>(U));
5561 case Instruction::Select:
5562 // U can also be a select constant expr, which let fall through. Since
5563 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5564 // constant expressions cannot have instructions as operands, we'd have
5565 // returned getUnknown for a select constant expressions anyway.
5566 if (isa<Instruction>(U))
5567 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5568 U->getOperand(1), U->getOperand(2));
5571 case Instruction::Call:
5572 case Instruction::Invoke:
5573 if (Value *RV = CallSite(U).getReturnedArgOperand())
5578 return getUnknown(V);
5583 //===----------------------------------------------------------------------===//
5584 // Iteration Count Computation Code
5587 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5591 ConstantInt *ExitConst = ExitCount->getValue();
5593 // Guard against huge trip counts.
5594 if (ExitConst->getValue().getActiveBits() > 32)
5597 // In case of integer overflow, this returns 0, which is correct.
5598 return ((unsigned)ExitConst->getZExtValue()) + 1;
5601 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5602 if (BasicBlock *ExitingBB = L->getExitingBlock())
5603 return getSmallConstantTripCount(L, ExitingBB);
5605 // No trip count information for multiple exits.
5609 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5610 BasicBlock *ExitingBlock) {
5611 assert(ExitingBlock && "Must pass a non-null exiting block!");
5612 assert(L->isLoopExiting(ExitingBlock) &&
5613 "Exiting block must actually branch out of the loop!");
5614 const SCEVConstant *ExitCount =
5615 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5616 return getConstantTripCount(ExitCount);
5619 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5620 const auto *MaxExitCount =
5621 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5622 return getConstantTripCount(MaxExitCount);
5625 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5626 if (BasicBlock *ExitingBB = L->getExitingBlock())
5627 return getSmallConstantTripMultiple(L, ExitingBB);
5629 // No trip multiple information for multiple exits.
5633 /// Returns the largest constant divisor of the trip count of this loop as a
5634 /// normal unsigned value, if possible. This means that the actual trip count is
5635 /// always a multiple of the returned value (don't forget the trip count could
5636 /// very well be zero as well!).
5638 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5639 /// multiple of a constant (which is also the case if the trip count is simply
5640 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5641 /// if the trip count is very large (>= 2^32).
5643 /// As explained in the comments for getSmallConstantTripCount, this assumes
5644 /// that control exits the loop via ExitingBlock.
5646 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5647 BasicBlock *ExitingBlock) {
5648 assert(ExitingBlock && "Must pass a non-null exiting block!");
5649 assert(L->isLoopExiting(ExitingBlock) &&
5650 "Exiting block must actually branch out of the loop!");
5651 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5652 if (ExitCount == getCouldNotCompute())
5655 // Get the trip count from the BE count by adding 1.
5656 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5658 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5660 // Attempt to factor more general cases. Returns the greatest power of
5661 // two divisor. If overflow happens, the trip count expression is still
5662 // divisible by the greatest power of 2 divisor returned.
5663 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5665 ConstantInt *Result = TC->getValue();
5667 // Guard against huge trip counts (this requires checking
5668 // for zero to handle the case where the trip count == -1 and the
5670 if (!Result || Result->getValue().getActiveBits() > 32 ||
5671 Result->getValue().getActiveBits() == 0)
5674 return (unsigned)Result->getZExtValue();
5677 /// Get the expression for the number of loop iterations for which this loop is
5678 /// guaranteed not to exit via ExitingBlock. Otherwise return
5679 /// SCEVCouldNotCompute.
5680 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5681 BasicBlock *ExitingBlock) {
5682 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5686 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5687 SCEVUnionPredicate &Preds) {
5688 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5691 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5692 return getBackedgeTakenInfo(L).getExact(this);
5695 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5696 /// known never to be less than the actual backedge taken count.
5697 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5698 return getBackedgeTakenInfo(L).getMax(this);
5701 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5702 return getBackedgeTakenInfo(L).isMaxOrZero(this);
5705 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5707 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5708 BasicBlock *Header = L->getHeader();
5710 // Push all Loop-header PHIs onto the Worklist stack.
5711 for (BasicBlock::iterator I = Header->begin();
5712 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5713 Worklist.push_back(PN);
5716 const ScalarEvolution::BackedgeTakenInfo &
5717 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5718 auto &BTI = getBackedgeTakenInfo(L);
5719 if (BTI.hasFullInfo())
5722 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5725 return Pair.first->second;
5727 BackedgeTakenInfo Result =
5728 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5730 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5733 const ScalarEvolution::BackedgeTakenInfo &
5734 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5735 // Initially insert an invalid entry for this loop. If the insertion
5736 // succeeds, proceed to actually compute a backedge-taken count and
5737 // update the value. The temporary CouldNotCompute value tells SCEV
5738 // code elsewhere that it shouldn't attempt to request a new
5739 // backedge-taken count, which could result in infinite recursion.
5740 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5741 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5743 return Pair.first->second;
5745 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5746 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5747 // must be cleared in this scope.
5748 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5750 if (Result.getExact(this) != getCouldNotCompute()) {
5751 assert(isLoopInvariant(Result.getExact(this), L) &&
5752 isLoopInvariant(Result.getMax(this), L) &&
5753 "Computed backedge-taken count isn't loop invariant for loop!");
5754 ++NumTripCountsComputed;
5756 else if (Result.getMax(this) == getCouldNotCompute() &&
5757 isa<PHINode>(L->getHeader()->begin())) {
5758 // Only count loops that have phi nodes as not being computable.
5759 ++NumTripCountsNotComputed;
5762 // Now that we know more about the trip count for this loop, forget any
5763 // existing SCEV values for PHI nodes in this loop since they are only
5764 // conservative estimates made without the benefit of trip count
5765 // information. This is similar to the code in forgetLoop, except that
5766 // it handles SCEVUnknown PHI nodes specially.
5767 if (Result.hasAnyInfo()) {
5768 SmallVector<Instruction *, 16> Worklist;
5769 PushLoopPHIs(L, Worklist);
5771 SmallPtrSet<Instruction *, 8> Visited;
5772 while (!Worklist.empty()) {
5773 Instruction *I = Worklist.pop_back_val();
5774 if (!Visited.insert(I).second)
5777 ValueExprMapType::iterator It =
5778 ValueExprMap.find_as(static_cast<Value *>(I));
5779 if (It != ValueExprMap.end()) {
5780 const SCEV *Old = It->second;
5782 // SCEVUnknown for a PHI either means that it has an unrecognized
5783 // structure, or it's a PHI that's in the progress of being computed
5784 // by createNodeForPHI. In the former case, additional loop trip
5785 // count information isn't going to change anything. In the later
5786 // case, createNodeForPHI will perform the necessary updates on its
5787 // own when it gets to that point.
5788 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5789 eraseValueFromMap(It->first);
5790 forgetMemoizedResults(Old);
5792 if (PHINode *PN = dyn_cast<PHINode>(I))
5793 ConstantEvolutionLoopExitValue.erase(PN);
5796 PushDefUseChildren(I, Worklist);
5800 // Re-lookup the insert position, since the call to
5801 // computeBackedgeTakenCount above could result in a
5802 // recusive call to getBackedgeTakenInfo (on a different
5803 // loop), which would invalidate the iterator computed
5805 return BackedgeTakenCounts.find(L)->second = std::move(Result);
5808 void ScalarEvolution::forgetLoop(const Loop *L) {
5809 // Drop any stored trip count value.
5810 auto RemoveLoopFromBackedgeMap =
5811 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5812 auto BTCPos = Map.find(L);
5813 if (BTCPos != Map.end()) {
5814 BTCPos->second.clear();
5819 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5820 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5822 // Drop information about expressions based on loop-header PHIs.
5823 SmallVector<Instruction *, 16> Worklist;
5824 PushLoopPHIs(L, Worklist);
5826 SmallPtrSet<Instruction *, 8> Visited;
5827 while (!Worklist.empty()) {
5828 Instruction *I = Worklist.pop_back_val();
5829 if (!Visited.insert(I).second)
5832 ValueExprMapType::iterator It =
5833 ValueExprMap.find_as(static_cast<Value *>(I));
5834 if (It != ValueExprMap.end()) {
5835 eraseValueFromMap(It->first);
5836 forgetMemoizedResults(It->second);
5837 if (PHINode *PN = dyn_cast<PHINode>(I))
5838 ConstantEvolutionLoopExitValue.erase(PN);
5841 PushDefUseChildren(I, Worklist);
5844 // Forget all contained loops too, to avoid dangling entries in the
5845 // ValuesAtScopes map.
5849 LoopPropertiesCache.erase(L);
5852 void ScalarEvolution::forgetValue(Value *V) {
5853 Instruction *I = dyn_cast<Instruction>(V);
5856 // Drop information about expressions based on loop-header PHIs.
5857 SmallVector<Instruction *, 16> Worklist;
5858 Worklist.push_back(I);
5860 SmallPtrSet<Instruction *, 8> Visited;
5861 while (!Worklist.empty()) {
5862 I = Worklist.pop_back_val();
5863 if (!Visited.insert(I).second)
5866 ValueExprMapType::iterator It =
5867 ValueExprMap.find_as(static_cast<Value *>(I));
5868 if (It != ValueExprMap.end()) {
5869 eraseValueFromMap(It->first);
5870 forgetMemoizedResults(It->second);
5871 if (PHINode *PN = dyn_cast<PHINode>(I))
5872 ConstantEvolutionLoopExitValue.erase(PN);
5875 PushDefUseChildren(I, Worklist);
5879 /// Get the exact loop backedge taken count considering all loop exits. A
5880 /// computable result can only be returned for loops with a single exit.
5881 /// Returning the minimum taken count among all exits is incorrect because one
5882 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5883 /// the limit of each loop test is never skipped. This is a valid assumption as
5884 /// long as the loop exits via that test. For precise results, it is the
5885 /// caller's responsibility to specify the relevant loop exit using
5886 /// getExact(ExitingBlock, SE).
5888 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5889 SCEVUnionPredicate *Preds) const {
5890 // If any exits were not computable, the loop is not computable.
5891 if (!isComplete() || ExitNotTaken.empty())
5892 return SE->getCouldNotCompute();
5894 const SCEV *BECount = nullptr;
5895 for (auto &ENT : ExitNotTaken) {
5896 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5899 BECount = ENT.ExactNotTaken;
5900 else if (BECount != ENT.ExactNotTaken)
5901 return SE->getCouldNotCompute();
5902 if (Preds && !ENT.hasAlwaysTruePredicate())
5903 Preds->add(ENT.Predicate.get());
5905 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5906 "Predicate should be always true!");
5909 assert(BECount && "Invalid not taken count for loop exit");
5913 /// Get the exact not taken count for this loop exit.
5915 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5916 ScalarEvolution *SE) const {
5917 for (auto &ENT : ExitNotTaken)
5918 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5919 return ENT.ExactNotTaken;
5921 return SE->getCouldNotCompute();
5924 /// getMax - Get the max backedge taken count for the loop.
5926 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5927 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5928 return !ENT.hasAlwaysTruePredicate();
5931 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5932 return SE->getCouldNotCompute();
5937 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5938 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5939 return !ENT.hasAlwaysTruePredicate();
5941 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5944 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5945 ScalarEvolution *SE) const {
5946 if (getMax() && getMax() != SE->getCouldNotCompute() &&
5947 SE->hasOperand(getMax(), S))
5950 for (auto &ENT : ExitNotTaken)
5951 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5952 SE->hasOperand(ENT.ExactNotTaken, S))
5958 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5959 /// computable exit into a persistent ExitNotTakenInfo array.
5960 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5961 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5963 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5964 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5965 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5966 ExitNotTaken.reserve(ExitCounts.size());
5968 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5969 [&](const EdgeExitInfo &EEI) {
5970 BasicBlock *ExitBB = EEI.first;
5971 const ExitLimit &EL = EEI.second;
5972 if (EL.Predicates.empty())
5973 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5975 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5976 for (auto *Pred : EL.Predicates)
5977 Predicate->add(Pred);
5979 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5983 /// Invalidate this result and free the ExitNotTakenInfo array.
5984 void ScalarEvolution::BackedgeTakenInfo::clear() {
5985 ExitNotTaken.clear();
5988 /// Compute the number of times the backedge of the specified loop will execute.
5989 ScalarEvolution::BackedgeTakenInfo
5990 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5991 bool AllowPredicates) {
5992 SmallVector<BasicBlock *, 8> ExitingBlocks;
5993 L->getExitingBlocks(ExitingBlocks);
5995 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5997 SmallVector<EdgeExitInfo, 4> ExitCounts;
5998 bool CouldComputeBECount = true;
5999 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6000 const SCEV *MustExitMaxBECount = nullptr;
6001 const SCEV *MayExitMaxBECount = nullptr;
6002 bool MustExitMaxOrZero = false;
6004 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6005 // and compute maxBECount.
6006 // Do a union of all the predicates here.
6007 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6008 BasicBlock *ExitBB = ExitingBlocks[i];
6009 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6011 assert((AllowPredicates || EL.Predicates.empty()) &&
6012 "Predicated exit limit when predicates are not allowed!");
6014 // 1. For each exit that can be computed, add an entry to ExitCounts.
6015 // CouldComputeBECount is true only if all exits can be computed.
6016 if (EL.ExactNotTaken == getCouldNotCompute())
6017 // We couldn't compute an exact value for this exit, so
6018 // we won't be able to compute an exact value for the loop.
6019 CouldComputeBECount = false;
6021 ExitCounts.emplace_back(ExitBB, EL);
6023 // 2. Derive the loop's MaxBECount from each exit's max number of
6024 // non-exiting iterations. Partition the loop exits into two kinds:
6025 // LoopMustExits and LoopMayExits.
6027 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6028 // is a LoopMayExit. If any computable LoopMustExit is found, then
6029 // MaxBECount is the minimum EL.MaxNotTaken of computable
6030 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6031 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6032 // computable EL.MaxNotTaken.
6033 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6034 DT.dominates(ExitBB, Latch)) {
6035 if (!MustExitMaxBECount) {
6036 MustExitMaxBECount = EL.MaxNotTaken;
6037 MustExitMaxOrZero = EL.MaxOrZero;
6039 MustExitMaxBECount =
6040 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6042 } else if (MayExitMaxBECount != getCouldNotCompute()) {
6043 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6044 MayExitMaxBECount = EL.MaxNotTaken;
6047 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6051 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6052 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6053 // The loop backedge will be taken the maximum or zero times if there's
6054 // a single exit that must be taken the maximum or zero times.
6055 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6056 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6057 MaxBECount, MaxOrZero);
6060 ScalarEvolution::ExitLimit
6061 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6062 bool AllowPredicates) {
6064 // Okay, we've chosen an exiting block. See what condition causes us to exit
6065 // at this block and remember the exit block and whether all other targets
6066 // lead to the loop header.
6067 bool MustExecuteLoopHeader = true;
6068 BasicBlock *Exit = nullptr;
6069 for (auto *SBB : successors(ExitingBlock))
6070 if (!L->contains(SBB)) {
6071 if (Exit) // Multiple exit successors.
6072 return getCouldNotCompute();
6074 } else if (SBB != L->getHeader()) {
6075 MustExecuteLoopHeader = false;
6078 // At this point, we know we have a conditional branch that determines whether
6079 // the loop is exited. However, we don't know if the branch is executed each
6080 // time through the loop. If not, then the execution count of the branch will
6081 // not be equal to the trip count of the loop.
6083 // Currently we check for this by checking to see if the Exit branch goes to
6084 // the loop header. If so, we know it will always execute the same number of
6085 // times as the loop. We also handle the case where the exit block *is* the
6086 // loop header. This is common for un-rotated loops.
6088 // If both of those tests fail, walk up the unique predecessor chain to the
6089 // header, stopping if there is an edge that doesn't exit the loop. If the
6090 // header is reached, the execution count of the branch will be equal to the
6091 // trip count of the loop.
6093 // More extensive analysis could be done to handle more cases here.
6095 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6096 // The simple checks failed, try climbing the unique predecessor chain
6097 // up to the header.
6099 for (BasicBlock *BB = ExitingBlock; BB; ) {
6100 BasicBlock *Pred = BB->getUniquePredecessor();
6102 return getCouldNotCompute();
6103 TerminatorInst *PredTerm = Pred->getTerminator();
6104 for (const BasicBlock *PredSucc : PredTerm->successors()) {
6107 // If the predecessor has a successor that isn't BB and isn't
6108 // outside the loop, assume the worst.
6109 if (L->contains(PredSucc))
6110 return getCouldNotCompute();
6112 if (Pred == L->getHeader()) {
6119 return getCouldNotCompute();
6122 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6123 TerminatorInst *Term = ExitingBlock->getTerminator();
6124 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6125 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6126 // Proceed to the next level to examine the exit condition expression.
6127 return computeExitLimitFromCond(
6128 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6129 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6132 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6133 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6134 /*ControlsExit=*/IsOnlyExit);
6136 return getCouldNotCompute();
6139 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6140 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6141 bool ControlsExit, bool AllowPredicates) {
6142 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6143 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6144 ControlsExit, AllowPredicates);
6147 Optional<ScalarEvolution::ExitLimit>
6148 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6149 BasicBlock *TBB, BasicBlock *FBB,
6150 bool ControlsExit, bool AllowPredicates) {
6154 (void)this->AllowPredicates;
6156 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6157 this->AllowPredicates == AllowPredicates &&
6158 "Variance in assumed invariant key components!");
6159 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6160 if (Itr == TripCountMap.end())
6165 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6166 BasicBlock *TBB, BasicBlock *FBB,
6168 bool AllowPredicates,
6169 const ExitLimit &EL) {
6170 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6171 this->AllowPredicates == AllowPredicates &&
6172 "Variance in assumed invariant key components!");
6174 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6175 assert(InsertResult.second && "Expected successful insertion!");
6179 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6180 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6181 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6184 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6187 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6188 ControlsExit, AllowPredicates);
6189 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6193 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6194 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6195 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6196 // Check if the controlling expression for this loop is an And or Or.
6197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6198 if (BO->getOpcode() == Instruction::And) {
6199 // Recurse on the operands of the and.
6200 bool EitherMayExit = L->contains(TBB);
6201 ExitLimit EL0 = computeExitLimitFromCondCached(
6202 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6204 ExitLimit EL1 = computeExitLimitFromCondCached(
6205 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6207 const SCEV *BECount = getCouldNotCompute();
6208 const SCEV *MaxBECount = getCouldNotCompute();
6209 if (EitherMayExit) {
6210 // Both conditions must be true for the loop to continue executing.
6211 // Choose the less conservative count.
6212 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6213 EL1.ExactNotTaken == getCouldNotCompute())
6214 BECount = getCouldNotCompute();
6217 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6218 if (EL0.MaxNotTaken == getCouldNotCompute())
6219 MaxBECount = EL1.MaxNotTaken;
6220 else if (EL1.MaxNotTaken == getCouldNotCompute())
6221 MaxBECount = EL0.MaxNotTaken;
6224 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6226 // Both conditions must be true at the same time for the loop to exit.
6227 // For now, be conservative.
6228 assert(L->contains(FBB) && "Loop block has no successor in loop!");
6229 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6230 MaxBECount = EL0.MaxNotTaken;
6231 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6232 BECount = EL0.ExactNotTaken;
6235 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6236 // to be more aggressive when computing BECount than when computing
6237 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
6238 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6240 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6241 !isa<SCEVCouldNotCompute>(BECount))
6242 MaxBECount = BECount;
6244 return ExitLimit(BECount, MaxBECount, false,
6245 {&EL0.Predicates, &EL1.Predicates});
6247 if (BO->getOpcode() == Instruction::Or) {
6248 // Recurse on the operands of the or.
6249 bool EitherMayExit = L->contains(FBB);
6250 ExitLimit EL0 = computeExitLimitFromCondCached(
6251 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6253 ExitLimit EL1 = computeExitLimitFromCondCached(
6254 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6256 const SCEV *BECount = getCouldNotCompute();
6257 const SCEV *MaxBECount = getCouldNotCompute();
6258 if (EitherMayExit) {
6259 // Both conditions must be false for the loop to continue executing.
6260 // Choose the less conservative count.
6261 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6262 EL1.ExactNotTaken == getCouldNotCompute())
6263 BECount = getCouldNotCompute();
6266 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6267 if (EL0.MaxNotTaken == getCouldNotCompute())
6268 MaxBECount = EL1.MaxNotTaken;
6269 else if (EL1.MaxNotTaken == getCouldNotCompute())
6270 MaxBECount = EL0.MaxNotTaken;
6273 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6275 // Both conditions must be false at the same time for the loop to exit.
6276 // For now, be conservative.
6277 assert(L->contains(TBB) && "Loop block has no successor in loop!");
6278 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6279 MaxBECount = EL0.MaxNotTaken;
6280 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6281 BECount = EL0.ExactNotTaken;
6284 return ExitLimit(BECount, MaxBECount, false,
6285 {&EL0.Predicates, &EL1.Predicates});
6289 // With an icmp, it may be feasible to compute an exact backedge-taken count.
6290 // Proceed to the next level to examine the icmp.
6291 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6293 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6294 if (EL.hasFullInfo() || !AllowPredicates)
6297 // Try again, but use SCEV predicates this time.
6298 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6299 /*AllowPredicates=*/true);
6302 // Check for a constant condition. These are normally stripped out by
6303 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6304 // preserve the CFG and is temporarily leaving constant conditions
6306 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6307 if (L->contains(FBB) == !CI->getZExtValue())
6308 // The backedge is always taken.
6309 return getCouldNotCompute();
6311 // The backedge is never taken.
6312 return getZero(CI->getType());
6315 // If it's not an integer or pointer comparison then compute it the hard way.
6316 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6319 ScalarEvolution::ExitLimit
6320 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6325 bool AllowPredicates) {
6327 // If the condition was exit on true, convert the condition to exit on false
6328 ICmpInst::Predicate Cond;
6329 if (!L->contains(FBB))
6330 Cond = ExitCond->getPredicate();
6332 Cond = ExitCond->getInversePredicate();
6334 // Handle common loops like: for (X = "string"; *X; ++X)
6335 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6336 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6338 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6339 if (ItCnt.hasAnyInfo())
6343 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6344 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6346 // Try to evaluate any dependencies out of the loop.
6347 LHS = getSCEVAtScope(LHS, L);
6348 RHS = getSCEVAtScope(RHS, L);
6350 // At this point, we would like to compute how many iterations of the
6351 // loop the predicate will return true for these inputs.
6352 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6353 // If there is a loop-invariant, force it into the RHS.
6354 std::swap(LHS, RHS);
6355 Cond = ICmpInst::getSwappedPredicate(Cond);
6358 // Simplify the operands before analyzing them.
6359 (void)SimplifyICmpOperands(Cond, LHS, RHS);
6361 // If we have a comparison of a chrec against a constant, try to use value
6362 // ranges to answer this query.
6363 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6364 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6365 if (AddRec->getLoop() == L) {
6366 // Form the constant range.
6367 ConstantRange CompRange =
6368 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6370 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6371 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6375 case ICmpInst::ICMP_NE: { // while (X != Y)
6376 // Convert to: while (X-Y != 0)
6377 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6379 if (EL.hasAnyInfo()) return EL;
6382 case ICmpInst::ICMP_EQ: { // while (X == Y)
6383 // Convert to: while (X-Y == 0)
6384 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6385 if (EL.hasAnyInfo()) return EL;
6388 case ICmpInst::ICMP_SLT:
6389 case ICmpInst::ICMP_ULT: { // while (X < Y)
6390 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6391 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6393 if (EL.hasAnyInfo()) return EL;
6396 case ICmpInst::ICMP_SGT:
6397 case ICmpInst::ICMP_UGT: { // while (X > Y)
6398 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6400 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6402 if (EL.hasAnyInfo()) return EL;
6409 auto *ExhaustiveCount =
6410 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6412 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6413 return ExhaustiveCount;
6415 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6416 ExitCond->getOperand(1), L, Cond);
6419 ScalarEvolution::ExitLimit
6420 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6422 BasicBlock *ExitingBlock,
6423 bool ControlsExit) {
6424 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6426 // Give up if the exit is the default dest of a switch.
6427 if (Switch->getDefaultDest() == ExitingBlock)
6428 return getCouldNotCompute();
6430 assert(L->contains(Switch->getDefaultDest()) &&
6431 "Default case must not exit the loop!");
6432 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6433 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6435 // while (X != Y) --> while (X-Y != 0)
6436 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6437 if (EL.hasAnyInfo())
6440 return getCouldNotCompute();
6443 static ConstantInt *
6444 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6445 ScalarEvolution &SE) {
6446 const SCEV *InVal = SE.getConstant(C);
6447 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6448 assert(isa<SCEVConstant>(Val) &&
6449 "Evaluation of SCEV at constant didn't fold correctly?");
6450 return cast<SCEVConstant>(Val)->getValue();
6453 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6454 /// compute the backedge execution count.
6455 ScalarEvolution::ExitLimit
6456 ScalarEvolution::computeLoadConstantCompareExitLimit(
6460 ICmpInst::Predicate predicate) {
6462 if (LI->isVolatile()) return getCouldNotCompute();
6464 // Check to see if the loaded pointer is a getelementptr of a global.
6465 // TODO: Use SCEV instead of manually grubbing with GEPs.
6466 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6467 if (!GEP) return getCouldNotCompute();
6469 // Make sure that it is really a constant global we are gepping, with an
6470 // initializer, and make sure the first IDX is really 0.
6471 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6472 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6473 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6474 !cast<Constant>(GEP->getOperand(1))->isNullValue())
6475 return getCouldNotCompute();
6477 // Okay, we allow one non-constant index into the GEP instruction.
6478 Value *VarIdx = nullptr;
6479 std::vector<Constant*> Indexes;
6480 unsigned VarIdxNum = 0;
6481 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6482 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6483 Indexes.push_back(CI);
6484 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6485 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
6486 VarIdx = GEP->getOperand(i);
6488 Indexes.push_back(nullptr);
6491 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6493 return getCouldNotCompute();
6495 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6496 // Check to see if X is a loop variant variable value now.
6497 const SCEV *Idx = getSCEV(VarIdx);
6498 Idx = getSCEVAtScope(Idx, L);
6500 // We can only recognize very limited forms of loop index expressions, in
6501 // particular, only affine AddRec's like {C1,+,C2}.
6502 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6503 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6504 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6505 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6506 return getCouldNotCompute();
6508 unsigned MaxSteps = MaxBruteForceIterations;
6509 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6510 ConstantInt *ItCst = ConstantInt::get(
6511 cast<IntegerType>(IdxExpr->getType()), IterationNum);
6512 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6514 // Form the GEP offset.
6515 Indexes[VarIdxNum] = Val;
6517 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6519 if (!Result) break; // Cannot compute!
6521 // Evaluate the condition for this iteration.
6522 Result = ConstantExpr::getICmp(predicate, Result, RHS);
6523 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
6524 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6525 ++NumArrayLenItCounts;
6526 return getConstant(ItCst); // Found terminating iteration!
6529 return getCouldNotCompute();
6532 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6533 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6534 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6536 return getCouldNotCompute();
6538 const BasicBlock *Latch = L->getLoopLatch();
6540 return getCouldNotCompute();
6542 const BasicBlock *Predecessor = L->getLoopPredecessor();
6544 return getCouldNotCompute();
6546 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6547 // Return LHS in OutLHS and shift_opt in OutOpCode.
6548 auto MatchPositiveShift =
6549 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6551 using namespace PatternMatch;
6553 ConstantInt *ShiftAmt;
6554 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6555 OutOpCode = Instruction::LShr;
6556 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6557 OutOpCode = Instruction::AShr;
6558 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6559 OutOpCode = Instruction::Shl;
6563 return ShiftAmt->getValue().isStrictlyPositive();
6566 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6569 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6570 // %iv.shifted = lshr i32 %iv, <positive constant>
6572 // Return true on a successful match. Return the corresponding PHI node (%iv
6573 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6574 auto MatchShiftRecurrence =
6575 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6576 Optional<Instruction::BinaryOps> PostShiftOpCode;
6579 Instruction::BinaryOps OpC;
6582 // If we encounter a shift instruction, "peel off" the shift operation,
6583 // and remember that we did so. Later when we inspect %iv's backedge
6584 // value, we will make sure that the backedge value uses the same
6587 // Note: the peeled shift operation does not have to be the same
6588 // instruction as the one feeding into the PHI's backedge value. We only
6589 // really care about it being the same *kind* of shift instruction --
6590 // that's all that is required for our later inferences to hold.
6591 if (MatchPositiveShift(LHS, V, OpC)) {
6592 PostShiftOpCode = OpC;
6597 PNOut = dyn_cast<PHINode>(LHS);
6598 if (!PNOut || PNOut->getParent() != L->getHeader())
6601 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6605 // The backedge value for the PHI node must be a shift by a positive
6607 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6609 // of the PHI node itself
6612 // and the kind of shift should be match the kind of shift we peeled
6614 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6618 Instruction::BinaryOps OpCode;
6619 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6620 return getCouldNotCompute();
6622 const DataLayout &DL = getDataLayout();
6624 // The key rationale for this optimization is that for some kinds of shift
6625 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6626 // within a finite number of iterations. If the condition guarding the
6627 // backedge (in the sense that the backedge is taken if the condition is true)
6628 // is false for the value the shift recurrence stabilizes to, then we know
6629 // that the backedge is taken only a finite number of times.
6631 ConstantInt *StableValue = nullptr;
6634 llvm_unreachable("Impossible case!");
6636 case Instruction::AShr: {
6637 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6638 // bitwidth(K) iterations.
6639 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6640 bool KnownZero, KnownOne;
6641 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6642 Predecessor->getTerminator(), &DT);
6643 auto *Ty = cast<IntegerType>(RHS->getType());
6645 StableValue = ConstantInt::get(Ty, 0);
6647 StableValue = ConstantInt::get(Ty, -1, true);
6649 return getCouldNotCompute();
6653 case Instruction::LShr:
6654 case Instruction::Shl:
6655 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6656 // stabilize to 0 in at most bitwidth(K) iterations.
6657 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6662 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6663 assert(Result->getType()->isIntegerTy(1) &&
6664 "Otherwise cannot be an operand to a branch instruction");
6666 if (Result->isZeroValue()) {
6667 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6668 const SCEV *UpperBound =
6669 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6670 return ExitLimit(getCouldNotCompute(), UpperBound, false);
6673 return getCouldNotCompute();
6676 /// Return true if we can constant fold an instruction of the specified type,
6677 /// assuming that all operands were constants.
6678 static bool CanConstantFold(const Instruction *I) {
6679 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6680 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6684 if (const CallInst *CI = dyn_cast<CallInst>(I))
6685 if (const Function *F = CI->getCalledFunction())
6686 return canConstantFoldCallTo(F);
6690 /// Determine whether this instruction can constant evolve within this loop
6691 /// assuming its operands can all constant evolve.
6692 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6693 // An instruction outside of the loop can't be derived from a loop PHI.
6694 if (!L->contains(I)) return false;
6696 if (isa<PHINode>(I)) {
6697 // We don't currently keep track of the control flow needed to evaluate
6698 // PHIs, so we cannot handle PHIs inside of loops.
6699 return L->getHeader() == I->getParent();
6702 // If we won't be able to constant fold this expression even if the operands
6703 // are constants, bail early.
6704 return CanConstantFold(I);
6707 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6708 /// recursing through each instruction operand until reaching a loop header phi.
6710 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6711 DenseMap<Instruction *, PHINode *> &PHIMap,
6713 if (Depth > MaxConstantEvolvingDepth)
6716 // Otherwise, we can evaluate this instruction if all of its operands are
6717 // constant or derived from a PHI node themselves.
6718 PHINode *PHI = nullptr;
6719 for (Value *Op : UseInst->operands()) {
6720 if (isa<Constant>(Op)) continue;
6722 Instruction *OpInst = dyn_cast<Instruction>(Op);
6723 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6725 PHINode *P = dyn_cast<PHINode>(OpInst);
6727 // If this operand is already visited, reuse the prior result.
6728 // We may have P != PHI if this is the deepest point at which the
6729 // inconsistent paths meet.
6730 P = PHIMap.lookup(OpInst);
6732 // Recurse and memoize the results, whether a phi is found or not.
6733 // This recursive call invalidates pointers into PHIMap.
6734 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6738 return nullptr; // Not evolving from PHI
6739 if (PHI && PHI != P)
6740 return nullptr; // Evolving from multiple different PHIs.
6743 // This is a expression evolving from a constant PHI!
6747 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6748 /// in the loop that V is derived from. We allow arbitrary operations along the
6749 /// way, but the operands of an operation must either be constants or a value
6750 /// derived from a constant PHI. If this expression does not fit with these
6751 /// constraints, return null.
6752 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6753 Instruction *I = dyn_cast<Instruction>(V);
6754 if (!I || !canConstantEvolve(I, L)) return nullptr;
6756 if (PHINode *PN = dyn_cast<PHINode>(I))
6759 // Record non-constant instructions contained by the loop.
6760 DenseMap<Instruction *, PHINode *> PHIMap;
6761 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6764 /// EvaluateExpression - Given an expression that passes the
6765 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6766 /// in the loop has the value PHIVal. If we can't fold this expression for some
6767 /// reason, return null.
6768 static Constant *EvaluateExpression(Value *V, const Loop *L,
6769 DenseMap<Instruction *, Constant *> &Vals,
6770 const DataLayout &DL,
6771 const TargetLibraryInfo *TLI) {
6772 // Convenient constant check, but redundant for recursive calls.
6773 if (Constant *C = dyn_cast<Constant>(V)) return C;
6774 Instruction *I = dyn_cast<Instruction>(V);
6775 if (!I) return nullptr;
6777 if (Constant *C = Vals.lookup(I)) return C;
6779 // An instruction inside the loop depends on a value outside the loop that we
6780 // weren't given a mapping for, or a value such as a call inside the loop.
6781 if (!canConstantEvolve(I, L)) return nullptr;
6783 // An unmapped PHI can be due to a branch or another loop inside this loop,
6784 // or due to this not being the initial iteration through a loop where we
6785 // couldn't compute the evolution of this particular PHI last time.
6786 if (isa<PHINode>(I)) return nullptr;
6788 std::vector<Constant*> Operands(I->getNumOperands());
6790 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6791 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6793 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6794 if (!Operands[i]) return nullptr;
6797 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6799 if (!C) return nullptr;
6803 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6804 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6805 Operands[1], DL, TLI);
6806 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6807 if (!LI->isVolatile())
6808 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6810 return ConstantFoldInstOperands(I, Operands, DL, TLI);
6814 // If every incoming value to PN except the one for BB is a specific Constant,
6815 // return that, else return nullptr.
6816 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6817 Constant *IncomingVal = nullptr;
6819 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6820 if (PN->getIncomingBlock(i) == BB)
6823 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6827 if (IncomingVal != CurrentVal) {
6830 IncomingVal = CurrentVal;
6837 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6838 /// in the header of its containing loop, we know the loop executes a
6839 /// constant number of times, and the PHI node is just a recurrence
6840 /// involving constants, fold it.
6842 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6845 auto I = ConstantEvolutionLoopExitValue.find(PN);
6846 if (I != ConstantEvolutionLoopExitValue.end())
6849 if (BEs.ugt(MaxBruteForceIterations))
6850 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
6852 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6854 DenseMap<Instruction *, Constant *> CurrentIterVals;
6855 BasicBlock *Header = L->getHeader();
6856 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6858 BasicBlock *Latch = L->getLoopLatch();
6862 for (auto &I : *Header) {
6863 PHINode *PHI = dyn_cast<PHINode>(&I);
6865 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6866 if (!StartCST) continue;
6867 CurrentIterVals[PHI] = StartCST;
6869 if (!CurrentIterVals.count(PN))
6870 return RetVal = nullptr;
6872 Value *BEValue = PN->getIncomingValueForBlock(Latch);
6874 // Execute the loop symbolically to determine the exit value.
6875 if (BEs.getActiveBits() >= 32)
6876 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6878 unsigned NumIterations = BEs.getZExtValue(); // must be in range
6879 unsigned IterationNum = 0;
6880 const DataLayout &DL = getDataLayout();
6881 for (; ; ++IterationNum) {
6882 if (IterationNum == NumIterations)
6883 return RetVal = CurrentIterVals[PN]; // Got exit value!
6885 // Compute the value of the PHIs for the next iteration.
6886 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6887 DenseMap<Instruction *, Constant *> NextIterVals;
6889 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6891 return nullptr; // Couldn't evaluate!
6892 NextIterVals[PN] = NextPHI;
6894 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6896 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6897 // cease to be able to evaluate one of them or if they stop evolving,
6898 // because that doesn't necessarily prevent us from computing PN.
6899 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6900 for (const auto &I : CurrentIterVals) {
6901 PHINode *PHI = dyn_cast<PHINode>(I.first);
6902 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6903 PHIsToCompute.emplace_back(PHI, I.second);
6905 // We use two distinct loops because EvaluateExpression may invalidate any
6906 // iterators into CurrentIterVals.
6907 for (const auto &I : PHIsToCompute) {
6908 PHINode *PHI = I.first;
6909 Constant *&NextPHI = NextIterVals[PHI];
6910 if (!NextPHI) { // Not already computed.
6911 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6912 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6914 if (NextPHI != I.second)
6915 StoppedEvolving = false;
6918 // If all entries in CurrentIterVals == NextIterVals then we can stop
6919 // iterating, the loop can't continue to change.
6920 if (StoppedEvolving)
6921 return RetVal = CurrentIterVals[PN];
6923 CurrentIterVals.swap(NextIterVals);
6927 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6930 PHINode *PN = getConstantEvolvingPHI(Cond, L);
6931 if (!PN) return getCouldNotCompute();
6933 // If the loop is canonicalized, the PHI will have exactly two entries.
6934 // That's the only form we support here.
6935 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6937 DenseMap<Instruction *, Constant *> CurrentIterVals;
6938 BasicBlock *Header = L->getHeader();
6939 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6941 BasicBlock *Latch = L->getLoopLatch();
6942 assert(Latch && "Should follow from NumIncomingValues == 2!");
6944 for (auto &I : *Header) {
6945 PHINode *PHI = dyn_cast<PHINode>(&I);
6948 auto *StartCST = getOtherIncomingValue(PHI, Latch);
6949 if (!StartCST) continue;
6950 CurrentIterVals[PHI] = StartCST;
6952 if (!CurrentIterVals.count(PN))
6953 return getCouldNotCompute();
6955 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6956 // the loop symbolically to determine when the condition gets a value of
6958 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
6959 const DataLayout &DL = getDataLayout();
6960 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6961 auto *CondVal = dyn_cast_or_null<ConstantInt>(
6962 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6964 // Couldn't symbolically evaluate.
6965 if (!CondVal) return getCouldNotCompute();
6967 if (CondVal->getValue() == uint64_t(ExitWhen)) {
6968 ++NumBruteForceTripCountsComputed;
6969 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6972 // Update all the PHI nodes for the next iteration.
6973 DenseMap<Instruction *, Constant *> NextIterVals;
6975 // Create a list of which PHIs we need to compute. We want to do this before
6976 // calling EvaluateExpression on them because that may invalidate iterators
6977 // into CurrentIterVals.
6978 SmallVector<PHINode *, 8> PHIsToCompute;
6979 for (const auto &I : CurrentIterVals) {
6980 PHINode *PHI = dyn_cast<PHINode>(I.first);
6981 if (!PHI || PHI->getParent() != Header) continue;
6982 PHIsToCompute.push_back(PHI);
6984 for (PHINode *PHI : PHIsToCompute) {
6985 Constant *&NextPHI = NextIterVals[PHI];
6986 if (NextPHI) continue; // Already computed!
6988 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6989 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6991 CurrentIterVals.swap(NextIterVals);
6994 // Too many iterations were needed to evaluate.
6995 return getCouldNotCompute();
6998 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6999 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7001 // Check to see if we've folded this expression at this loop before.
7002 for (auto &LS : Values)
7004 return LS.second ? LS.second : V;
7006 Values.emplace_back(L, nullptr);
7008 // Otherwise compute it.
7009 const SCEV *C = computeSCEVAtScope(V, L);
7010 for (auto &LS : reverse(ValuesAtScopes[V]))
7011 if (LS.first == L) {
7018 /// This builds up a Constant using the ConstantExpr interface. That way, we
7019 /// will return Constants for objects which aren't represented by a
7020 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7021 /// Returns NULL if the SCEV isn't representable as a Constant.
7022 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7023 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7024 case scCouldNotCompute:
7028 return cast<SCEVConstant>(V)->getValue();
7030 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7031 case scSignExtend: {
7032 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7033 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7034 return ConstantExpr::getSExt(CastOp, SS->getType());
7037 case scZeroExtend: {
7038 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7039 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7040 return ConstantExpr::getZExt(CastOp, SZ->getType());
7044 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7045 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7046 return ConstantExpr::getTrunc(CastOp, ST->getType());
7050 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7051 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7052 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7053 unsigned AS = PTy->getAddressSpace();
7054 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7055 C = ConstantExpr::getBitCast(C, DestPtrTy);
7057 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7058 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7059 if (!C2) return nullptr;
7062 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7063 unsigned AS = C2->getType()->getPointerAddressSpace();
7065 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7066 // The offsets have been converted to bytes. We can add bytes to an
7067 // i8* by GEP with the byte count in the first index.
7068 C = ConstantExpr::getBitCast(C, DestPtrTy);
7071 // Don't bother trying to sum two pointers. We probably can't
7072 // statically compute a load that results from it anyway.
7073 if (C2->getType()->isPointerTy())
7076 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7077 if (PTy->getElementType()->isStructTy())
7078 C2 = ConstantExpr::getIntegerCast(
7079 C2, Type::getInt32Ty(C->getContext()), true);
7080 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7082 C = ConstantExpr::getAdd(C, C2);
7089 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7090 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7091 // Don't bother with pointers at all.
7092 if (C->getType()->isPointerTy()) return nullptr;
7093 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7094 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7095 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7096 C = ConstantExpr::getMul(C, C2);
7103 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7104 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7105 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7106 if (LHS->getType() == RHS->getType())
7107 return ConstantExpr::getUDiv(LHS, RHS);
7112 break; // TODO: smax, umax.
7117 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7118 if (isa<SCEVConstant>(V)) return V;
7120 // If this instruction is evolved from a constant-evolving PHI, compute the
7121 // exit value from the loop without using SCEVs.
7122 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7123 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7124 const Loop *LI = this->LI[I->getParent()];
7125 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
7126 if (PHINode *PN = dyn_cast<PHINode>(I))
7127 if (PN->getParent() == LI->getHeader()) {
7128 // Okay, there is no closed form solution for the PHI node. Check
7129 // to see if the loop that contains it has a known backedge-taken
7130 // count. If so, we may be able to force computation of the exit
7132 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7133 if (const SCEVConstant *BTCC =
7134 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7135 // Okay, we know how many times the containing loop executes. If
7136 // this is a constant evolving PHI node, get the final value at
7137 // the specified iteration number.
7139 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7140 if (RV) return getSCEV(RV);
7144 // Okay, this is an expression that we cannot symbolically evaluate
7145 // into a SCEV. Check to see if it's possible to symbolically evaluate
7146 // the arguments into constants, and if so, try to constant propagate the
7147 // result. This is particularly useful for computing loop exit values.
7148 if (CanConstantFold(I)) {
7149 SmallVector<Constant *, 4> Operands;
7150 bool MadeImprovement = false;
7151 for (Value *Op : I->operands()) {
7152 if (Constant *C = dyn_cast<Constant>(Op)) {
7153 Operands.push_back(C);
7157 // If any of the operands is non-constant and if they are
7158 // non-integer and non-pointer, don't even try to analyze them
7159 // with scev techniques.
7160 if (!isSCEVable(Op->getType()))
7163 const SCEV *OrigV = getSCEV(Op);
7164 const SCEV *OpV = getSCEVAtScope(OrigV, L);
7165 MadeImprovement |= OrigV != OpV;
7167 Constant *C = BuildConstantFromSCEV(OpV);
7169 if (C->getType() != Op->getType())
7170 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7174 Operands.push_back(C);
7177 // Check to see if getSCEVAtScope actually made an improvement.
7178 if (MadeImprovement) {
7179 Constant *C = nullptr;
7180 const DataLayout &DL = getDataLayout();
7181 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7182 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7183 Operands[1], DL, &TLI);
7184 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7185 if (!LI->isVolatile())
7186 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7188 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7195 // This is some other type of SCEVUnknown, just return it.
7199 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7200 // Avoid performing the look-up in the common case where the specified
7201 // expression has no loop-variant portions.
7202 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7203 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7204 if (OpAtScope != Comm->getOperand(i)) {
7205 // Okay, at least one of these operands is loop variant but might be
7206 // foldable. Build a new instance of the folded commutative expression.
7207 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7208 Comm->op_begin()+i);
7209 NewOps.push_back(OpAtScope);
7211 for (++i; i != e; ++i) {
7212 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7213 NewOps.push_back(OpAtScope);
7215 if (isa<SCEVAddExpr>(Comm))
7216 return getAddExpr(NewOps);
7217 if (isa<SCEVMulExpr>(Comm))
7218 return getMulExpr(NewOps);
7219 if (isa<SCEVSMaxExpr>(Comm))
7220 return getSMaxExpr(NewOps);
7221 if (isa<SCEVUMaxExpr>(Comm))
7222 return getUMaxExpr(NewOps);
7223 llvm_unreachable("Unknown commutative SCEV type!");
7226 // If we got here, all operands are loop invariant.
7230 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7231 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7232 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7233 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7234 return Div; // must be loop invariant
7235 return getUDivExpr(LHS, RHS);
7238 // If this is a loop recurrence for a loop that does not contain L, then we
7239 // are dealing with the final value computed by the loop.
7240 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7241 // First, attempt to evaluate each operand.
7242 // Avoid performing the look-up in the common case where the specified
7243 // expression has no loop-variant portions.
7244 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7245 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7246 if (OpAtScope == AddRec->getOperand(i))
7249 // Okay, at least one of these operands is loop variant but might be
7250 // foldable. Build a new instance of the folded commutative expression.
7251 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7252 AddRec->op_begin()+i);
7253 NewOps.push_back(OpAtScope);
7254 for (++i; i != e; ++i)
7255 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7257 const SCEV *FoldedRec =
7258 getAddRecExpr(NewOps, AddRec->getLoop(),
7259 AddRec->getNoWrapFlags(SCEV::FlagNW));
7260 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7261 // The addrec may be folded to a nonrecurrence, for example, if the
7262 // induction variable is multiplied by zero after constant folding. Go
7263 // ahead and return the folded value.
7269 // If the scope is outside the addrec's loop, evaluate it by using the
7270 // loop exit value of the addrec.
7271 if (!AddRec->getLoop()->contains(L)) {
7272 // To evaluate this recurrence, we need to know how many times the AddRec
7273 // loop iterates. Compute this now.
7274 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7275 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7277 // Then, evaluate the AddRec.
7278 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7284 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7285 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7286 if (Op == Cast->getOperand())
7287 return Cast; // must be loop invariant
7288 return getZeroExtendExpr(Op, Cast->getType());
7291 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7292 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7293 if (Op == Cast->getOperand())
7294 return Cast; // must be loop invariant
7295 return getSignExtendExpr(Op, Cast->getType());
7298 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7299 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7300 if (Op == Cast->getOperand())
7301 return Cast; // must be loop invariant
7302 return getTruncateExpr(Op, Cast->getType());
7305 llvm_unreachable("Unknown SCEV type!");
7308 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7309 return getSCEVAtScope(getSCEV(V), L);
7312 /// Finds the minimum unsigned root of the following equation:
7314 /// A * X = B (mod N)
7316 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7317 /// A and B isn't important.
7319 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7320 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7321 ScalarEvolution &SE) {
7322 uint32_t BW = A.getBitWidth();
7323 assert(BW == SE.getTypeSizeInBits(B->getType()));
7324 assert(A != 0 && "A must be non-zero.");
7328 // The gcd of A and N may have only one prime factor: 2. The number of
7329 // trailing zeros in A is its multiplicity
7330 uint32_t Mult2 = A.countTrailingZeros();
7333 // 2. Check if B is divisible by D.
7335 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7336 // is not less than multiplicity of this prime factor for D.
7337 if (SE.GetMinTrailingZeros(B) < Mult2)
7338 return SE.getCouldNotCompute();
7340 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7343 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7344 // (N / D) in general. The inverse itself always fits into BW bits, though,
7345 // so we immediately truncate it.
7346 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
7347 APInt Mod(BW + 1, 0);
7348 Mod.setBit(BW - Mult2); // Mod = N / D
7349 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7351 // 4. Compute the minimum unsigned root of the equation:
7352 // I * (B / D) mod (N / D)
7353 // To simplify the computation, we factor out the divide by D:
7354 // (I * B mod N) / D
7355 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7356 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7359 /// Find the roots of the quadratic equation for the given quadratic chrec
7360 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or
7361 /// two SCEVCouldNotCompute objects.
7363 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7364 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7365 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7366 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7367 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7368 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7370 // We currently can only solve this if the coefficients are constants.
7371 if (!LC || !MC || !NC)
7374 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7375 const APInt &L = LC->getAPInt();
7376 const APInt &M = MC->getAPInt();
7377 const APInt &N = NC->getAPInt();
7378 APInt Two(BitWidth, 2);
7381 using namespace APIntOps;
7383 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7384 // The B coefficient is M-N/2
7388 // The A coefficient is N/2
7389 APInt A(N.sdiv(Two));
7391 // Compute the B^2-4ac term.
7394 SqrtTerm -= 4 * (A * C);
7396 if (SqrtTerm.isNegative()) {
7397 // The loop is provably infinite.
7401 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7402 // integer value or else APInt::sqrt() will assert.
7403 APInt SqrtVal(SqrtTerm.sqrt());
7405 // Compute the two solutions for the quadratic formula.
7406 // The divisions must be performed as signed divisions.
7409 if (TwoA.isMinValue())
7412 LLVMContext &Context = SE.getContext();
7414 ConstantInt *Solution1 =
7415 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7416 ConstantInt *Solution2 =
7417 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7419 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7420 cast<SCEVConstant>(SE.getConstant(Solution2)));
7421 } // end APIntOps namespace
7424 ScalarEvolution::ExitLimit
7425 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7426 bool AllowPredicates) {
7428 // This is only used for loops with a "x != y" exit test. The exit condition
7429 // is now expressed as a single expression, V = x-y. So the exit test is
7430 // effectively V != 0. We know and take advantage of the fact that this
7431 // expression only being used in a comparison by zero context.
7433 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7434 // If the value is a constant
7435 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7436 // If the value is already zero, the branch will execute zero times.
7437 if (C->getValue()->isZero()) return C;
7438 return getCouldNotCompute(); // Otherwise it will loop infinitely.
7441 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7442 if (!AddRec && AllowPredicates)
7443 // Try to make this an AddRec using runtime tests, in the first X
7444 // iterations of this loop, where X is the SCEV expression found by the
7446 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7448 if (!AddRec || AddRec->getLoop() != L)
7449 return getCouldNotCompute();
7451 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7452 // the quadratic equation to solve it.
7453 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7454 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7455 const SCEVConstant *R1 = Roots->first;
7456 const SCEVConstant *R2 = Roots->second;
7457 // Pick the smallest positive root value.
7458 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7459 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7460 if (!CB->getZExtValue())
7461 std::swap(R1, R2); // R1 is the minimum root now.
7463 // We can only use this value if the chrec ends up with an exact zero
7464 // value at this index. When solving for "X*X != 5", for example, we
7465 // should not accept a root of 2.
7466 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7468 // We found a quadratic root!
7469 return ExitLimit(R1, R1, false, Predicates);
7472 return getCouldNotCompute();
7475 // Otherwise we can only handle this if it is affine.
7476 if (!AddRec->isAffine())
7477 return getCouldNotCompute();
7479 // If this is an affine expression, the execution count of this branch is
7480 // the minimum unsigned root of the following equation:
7482 // Start + Step*N = 0 (mod 2^BW)
7486 // Step*N = -Start (mod 2^BW)
7488 // where BW is the common bit width of Start and Step.
7490 // Get the initial value for the loop.
7491 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7492 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7494 // For now we handle only constant steps.
7496 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7497 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7498 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7499 // We have not yet seen any such cases.
7500 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7501 if (!StepC || StepC->getValue()->equalsInt(0))
7502 return getCouldNotCompute();
7504 // For positive steps (counting up until unsigned overflow):
7505 // N = -Start/Step (as unsigned)
7506 // For negative steps (counting down to zero):
7508 // First compute the unsigned distance from zero in the direction of Step.
7509 bool CountDown = StepC->getAPInt().isNegative();
7510 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7512 // Handle unitary steps, which cannot wraparound.
7513 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7514 // N = Distance (as unsigned)
7515 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7516 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7518 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7519 // we end up with a loop whose backedge-taken count is n - 1. Detect this
7520 // case, and see if we can improve the bound.
7522 // Explicitly handling this here is necessary because getUnsignedRange
7523 // isn't context-sensitive; it doesn't know that we only care about the
7524 // range inside the loop.
7525 const SCEV *Zero = getZero(Distance->getType());
7526 const SCEV *One = getOne(Distance->getType());
7527 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7528 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7529 // If Distance + 1 doesn't overflow, we can compute the maximum distance
7530 // as "unsigned_max(Distance + 1) - 1".
7531 ConstantRange CR = getUnsignedRange(DistancePlusOne);
7532 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7534 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7537 // If the condition controls loop exit (the loop exits only if the expression
7538 // is true) and the addition is no-wrap we can use unsigned divide to
7539 // compute the backedge count. In this case, the step may not divide the
7540 // distance, but we don't care because if the condition is "missed" the loop
7541 // will have undefined behavior due to wrapping.
7542 if (ControlsExit && AddRec->hasNoSelfWrap() &&
7543 loopHasNoAbnormalExits(AddRec->getLoop())) {
7545 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7546 return ExitLimit(Exact, Exact, false, Predicates);
7549 // Solve the general equation.
7550 const SCEV *E = SolveLinEquationWithOverflow(
7551 StepC->getAPInt(), getNegativeSCEV(Start), *this);
7552 return ExitLimit(E, E, false, Predicates);
7555 ScalarEvolution::ExitLimit
7556 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7557 // Loops that look like: while (X == 0) are very strange indeed. We don't
7558 // handle them yet except for the trivial case. This could be expanded in the
7559 // future as needed.
7561 // If the value is a constant, check to see if it is known to be non-zero
7562 // already. If so, the backedge will execute zero times.
7563 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7564 if (!C->getValue()->isNullValue())
7565 return getZero(C->getType());
7566 return getCouldNotCompute(); // Otherwise it will loop infinitely.
7569 // We could implement others, but I really doubt anyone writes loops like
7570 // this, and if they did, they would already be constant folded.
7571 return getCouldNotCompute();
7574 std::pair<BasicBlock *, BasicBlock *>
7575 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7576 // If the block has a unique predecessor, then there is no path from the
7577 // predecessor to the block that does not go through the direct edge
7578 // from the predecessor to the block.
7579 if (BasicBlock *Pred = BB->getSinglePredecessor())
7582 // A loop's header is defined to be a block that dominates the loop.
7583 // If the header has a unique predecessor outside the loop, it must be
7584 // a block that has exactly one successor that can reach the loop.
7585 if (Loop *L = LI.getLoopFor(BB))
7586 return {L->getLoopPredecessor(), L->getHeader()};
7588 return {nullptr, nullptr};
7591 /// SCEV structural equivalence is usually sufficient for testing whether two
7592 /// expressions are equal, however for the purposes of looking for a condition
7593 /// guarding a loop, it can be useful to be a little more general, since a
7594 /// front-end may have replicated the controlling expression.
7596 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7597 // Quick check to see if they are the same SCEV.
7598 if (A == B) return true;
7600 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7601 // Not all instructions that are "identical" compute the same value. For
7602 // instance, two distinct alloca instructions allocating the same type are
7603 // identical and do not read memory; but compute distinct values.
7604 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7607 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7608 // two different instructions with the same value. Check for this case.
7609 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7610 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7611 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7612 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7613 if (ComputesEqualValues(AI, BI))
7616 // Otherwise assume they may have a different value.
7620 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7621 const SCEV *&LHS, const SCEV *&RHS,
7623 bool Changed = false;
7625 // If we hit the max recursion limit bail out.
7629 // Canonicalize a constant to the right side.
7630 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7631 // Check for both operands constant.
7632 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7633 if (ConstantExpr::getICmp(Pred,
7635 RHSC->getValue())->isNullValue())
7636 goto trivially_false;
7638 goto trivially_true;
7640 // Otherwise swap the operands to put the constant on the right.
7641 std::swap(LHS, RHS);
7642 Pred = ICmpInst::getSwappedPredicate(Pred);
7646 // If we're comparing an addrec with a value which is loop-invariant in the
7647 // addrec's loop, put the addrec on the left. Also make a dominance check,
7648 // as both operands could be addrecs loop-invariant in each other's loop.
7649 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7650 const Loop *L = AR->getLoop();
7651 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7652 std::swap(LHS, RHS);
7653 Pred = ICmpInst::getSwappedPredicate(Pred);
7658 // If there's a constant operand, canonicalize comparisons with boundary
7659 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7660 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7661 const APInt &RA = RC->getAPInt();
7663 bool SimplifiedByConstantRange = false;
7665 if (!ICmpInst::isEquality(Pred)) {
7666 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7667 if (ExactCR.isFullSet())
7668 goto trivially_true;
7669 else if (ExactCR.isEmptySet())
7670 goto trivially_false;
7673 CmpInst::Predicate NewPred;
7674 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7675 ICmpInst::isEquality(NewPred)) {
7676 // We were able to convert an inequality to an equality.
7678 RHS = getConstant(NewRHS);
7679 Changed = SimplifiedByConstantRange = true;
7683 if (!SimplifiedByConstantRange) {
7687 case ICmpInst::ICMP_EQ:
7688 case ICmpInst::ICMP_NE:
7689 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7691 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7692 if (const SCEVMulExpr *ME =
7693 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7694 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7695 ME->getOperand(0)->isAllOnesValue()) {
7696 RHS = AE->getOperand(1);
7697 LHS = ME->getOperand(1);
7703 // The "Should have been caught earlier!" messages refer to the fact
7704 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7705 // should have fired on the corresponding cases, and canonicalized the
7706 // check to trivially_true or trivially_false.
7708 case ICmpInst::ICMP_UGE:
7709 assert(!RA.isMinValue() && "Should have been caught earlier!");
7710 Pred = ICmpInst::ICMP_UGT;
7711 RHS = getConstant(RA - 1);
7714 case ICmpInst::ICMP_ULE:
7715 assert(!RA.isMaxValue() && "Should have been caught earlier!");
7716 Pred = ICmpInst::ICMP_ULT;
7717 RHS = getConstant(RA + 1);
7720 case ICmpInst::ICMP_SGE:
7721 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7722 Pred = ICmpInst::ICMP_SGT;
7723 RHS = getConstant(RA - 1);
7726 case ICmpInst::ICMP_SLE:
7727 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7728 Pred = ICmpInst::ICMP_SLT;
7729 RHS = getConstant(RA + 1);
7736 // Check for obvious equality.
7737 if (HasSameValue(LHS, RHS)) {
7738 if (ICmpInst::isTrueWhenEqual(Pred))
7739 goto trivially_true;
7740 if (ICmpInst::isFalseWhenEqual(Pred))
7741 goto trivially_false;
7744 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7745 // adding or subtracting 1 from one of the operands.
7747 case ICmpInst::ICMP_SLE:
7748 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7749 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7751 Pred = ICmpInst::ICMP_SLT;
7753 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7754 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7756 Pred = ICmpInst::ICMP_SLT;
7760 case ICmpInst::ICMP_SGE:
7761 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7762 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7764 Pred = ICmpInst::ICMP_SGT;
7766 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7767 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7769 Pred = ICmpInst::ICMP_SGT;
7773 case ICmpInst::ICMP_ULE:
7774 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7775 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7777 Pred = ICmpInst::ICMP_ULT;
7779 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7780 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7781 Pred = ICmpInst::ICMP_ULT;
7785 case ICmpInst::ICMP_UGE:
7786 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7787 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7788 Pred = ICmpInst::ICMP_UGT;
7790 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7791 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7793 Pred = ICmpInst::ICMP_UGT;
7801 // TODO: More simplifications are possible here.
7803 // Recursively simplify until we either hit a recursion limit or nothing
7806 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7812 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7813 Pred = ICmpInst::ICMP_EQ;
7818 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7819 Pred = ICmpInst::ICMP_NE;
7823 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7824 return getSignedRange(S).getSignedMax().isNegative();
7827 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7828 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7831 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7832 return !getSignedRange(S).getSignedMin().isNegative();
7835 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7836 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7839 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7840 return isKnownNegative(S) || isKnownPositive(S);
7843 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7844 const SCEV *LHS, const SCEV *RHS) {
7845 // Canonicalize the inputs first.
7846 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7848 // If LHS or RHS is an addrec, check to see if the condition is true in
7849 // every iteration of the loop.
7850 // If LHS and RHS are both addrec, both conditions must be true in
7851 // every iteration of the loop.
7852 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7853 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7854 bool LeftGuarded = false;
7855 bool RightGuarded = false;
7857 const Loop *L = LAR->getLoop();
7858 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7859 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7860 if (!RAR) return true;
7865 const Loop *L = RAR->getLoop();
7866 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7867 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7868 if (!LAR) return true;
7869 RightGuarded = true;
7872 if (LeftGuarded && RightGuarded)
7875 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7878 // Otherwise see what can be done with known constant ranges.
7879 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7882 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7883 ICmpInst::Predicate Pred,
7885 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7888 // Verify an invariant: inverting the predicate should turn a monotonically
7889 // increasing change to a monotonically decreasing one, and vice versa.
7890 bool IncreasingSwapped;
7891 bool ResultSwapped = isMonotonicPredicateImpl(
7892 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7894 assert(Result == ResultSwapped && "should be able to analyze both!");
7896 assert(Increasing == !IncreasingSwapped &&
7897 "monotonicity should flip as we flip the predicate");
7903 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7904 ICmpInst::Predicate Pred,
7907 // A zero step value for LHS means the induction variable is essentially a
7908 // loop invariant value. We don't really depend on the predicate actually
7909 // flipping from false to true (for increasing predicates, and the other way
7910 // around for decreasing predicates), all we care about is that *if* the
7911 // predicate changes then it only changes from false to true.
7913 // A zero step value in itself is not very useful, but there may be places
7914 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7915 // as general as possible.
7919 return false; // Conservative answer
7921 case ICmpInst::ICMP_UGT:
7922 case ICmpInst::ICMP_UGE:
7923 case ICmpInst::ICMP_ULT:
7924 case ICmpInst::ICMP_ULE:
7925 if (!LHS->hasNoUnsignedWrap())
7928 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7931 case ICmpInst::ICMP_SGT:
7932 case ICmpInst::ICMP_SGE:
7933 case ICmpInst::ICMP_SLT:
7934 case ICmpInst::ICMP_SLE: {
7935 if (!LHS->hasNoSignedWrap())
7938 const SCEV *Step = LHS->getStepRecurrence(*this);
7940 if (isKnownNonNegative(Step)) {
7941 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7945 if (isKnownNonPositive(Step)) {
7946 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7955 llvm_unreachable("switch has default clause!");
7958 bool ScalarEvolution::isLoopInvariantPredicate(
7959 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7960 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7961 const SCEV *&InvariantRHS) {
7963 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7964 if (!isLoopInvariant(RHS, L)) {
7965 if (!isLoopInvariant(LHS, L))
7968 std::swap(LHS, RHS);
7969 Pred = ICmpInst::getSwappedPredicate(Pred);
7972 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7973 if (!ArLHS || ArLHS->getLoop() != L)
7977 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7980 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7981 // true as the loop iterates, and the backedge is control dependent on
7982 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7984 // * if the predicate was false in the first iteration then the predicate
7985 // is never evaluated again, since the loop exits without taking the
7987 // * if the predicate was true in the first iteration then it will
7988 // continue to be true for all future iterations since it is
7989 // monotonically increasing.
7991 // For both the above possibilities, we can replace the loop varying
7992 // predicate with its value on the first iteration of the loop (which is
7995 // A similar reasoning applies for a monotonically decreasing predicate, by
7996 // replacing true with false and false with true in the above two bullets.
7998 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8000 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8003 InvariantPred = Pred;
8004 InvariantLHS = ArLHS->getStart();
8009 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8010 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8011 if (HasSameValue(LHS, RHS))
8012 return ICmpInst::isTrueWhenEqual(Pred);
8014 // This code is split out from isKnownPredicate because it is called from
8015 // within isLoopEntryGuardedByCond.
8018 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8019 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8020 .contains(RangeLHS);
8023 // The check at the top of the function catches the case where the values are
8024 // known to be equal.
8025 if (Pred == CmpInst::ICMP_EQ)
8028 if (Pred == CmpInst::ICMP_NE)
8029 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8030 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8031 isKnownNonZero(getMinusSCEV(LHS, RHS));
8033 if (CmpInst::isSigned(Pred))
8034 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8036 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8039 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8043 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8044 // Return Y via OutY.
8045 auto MatchBinaryAddToConst =
8046 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8047 SCEV::NoWrapFlags ExpectedFlags) {
8048 const SCEV *NonConstOp, *ConstOp;
8049 SCEV::NoWrapFlags FlagsPresent;
8051 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8052 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8055 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8056 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8065 case ICmpInst::ICMP_SGE:
8066 std::swap(LHS, RHS);
8067 case ICmpInst::ICMP_SLE:
8068 // X s<= (X + C)<nsw> if C >= 0
8069 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8072 // (X + C)<nsw> s<= X if C <= 0
8073 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8074 !C.isStrictlyPositive())
8078 case ICmpInst::ICMP_SGT:
8079 std::swap(LHS, RHS);
8080 case ICmpInst::ICMP_SLT:
8081 // X s< (X + C)<nsw> if C > 0
8082 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8083 C.isStrictlyPositive())
8086 // (X + C)<nsw> s< X if C < 0
8087 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8095 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8098 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8101 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8102 // the stack can result in exponential time complexity.
8103 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8105 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8107 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8108 // isKnownPredicate. isKnownPredicate is more powerful, but also more
8109 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8110 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
8111 // use isKnownPredicate later if needed.
8112 return isKnownNonNegative(RHS) &&
8113 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8114 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8117 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8118 ICmpInst::Predicate Pred,
8119 const SCEV *LHS, const SCEV *RHS) {
8120 // No need to even try if we know the module has no guards.
8124 return any_of(*BB, [&](Instruction &I) {
8125 using namespace llvm::PatternMatch;
8128 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8129 m_Value(Condition))) &&
8130 isImpliedCond(Pred, LHS, RHS, Condition, false);
8134 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8135 /// protected by a conditional between LHS and RHS. This is used to
8136 /// to eliminate casts.
8138 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8139 ICmpInst::Predicate Pred,
8140 const SCEV *LHS, const SCEV *RHS) {
8141 // Interpret a null as meaning no loop, where there is obviously no guard
8142 // (interprocedural conditions notwithstanding).
8143 if (!L) return true;
8145 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8148 BasicBlock *Latch = L->getLoopLatch();
8152 BranchInst *LoopContinuePredicate =
8153 dyn_cast<BranchInst>(Latch->getTerminator());
8154 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8155 isImpliedCond(Pred, LHS, RHS,
8156 LoopContinuePredicate->getCondition(),
8157 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8160 // We don't want more than one activation of the following loops on the stack
8161 // -- that can lead to O(n!) time complexity.
8162 if (WalkingBEDominatingConds)
8165 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8167 // See if we can exploit a trip count to prove the predicate.
8168 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8169 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8170 if (LatchBECount != getCouldNotCompute()) {
8171 // We know that Latch branches back to the loop header exactly
8172 // LatchBECount times. This means the backdege condition at Latch is
8173 // equivalent to "{0,+,1} u< LatchBECount".
8174 Type *Ty = LatchBECount->getType();
8175 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8176 const SCEV *LoopCounter =
8177 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8178 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8183 // Check conditions due to any @llvm.assume intrinsics.
8184 for (auto &AssumeVH : AC.assumptions()) {
8187 auto *CI = cast<CallInst>(AssumeVH);
8188 if (!DT.dominates(CI, Latch->getTerminator()))
8191 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8195 // If the loop is not reachable from the entry block, we risk running into an
8196 // infinite loop as we walk up into the dom tree. These loops do not matter
8197 // anyway, so we just return a conservative answer when we see them.
8198 if (!DT.isReachableFromEntry(L->getHeader()))
8201 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8204 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8205 DTN != HeaderDTN; DTN = DTN->getIDom()) {
8207 assert(DTN && "should reach the loop header before reaching the root!");
8209 BasicBlock *BB = DTN->getBlock();
8210 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8213 BasicBlock *PBB = BB->getSinglePredecessor();
8217 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8218 if (!ContinuePredicate || !ContinuePredicate->isConditional())
8221 Value *Condition = ContinuePredicate->getCondition();
8223 // If we have an edge `E` within the loop body that dominates the only
8224 // latch, the condition guarding `E` also guards the backedge. This
8225 // reasoning works only for loops with a single latch.
8227 BasicBlockEdge DominatingEdge(PBB, BB);
8228 if (DominatingEdge.isSingleEdge()) {
8229 // We're constructively (and conservatively) enumerating edges within the
8230 // loop body that dominate the latch. The dominator tree better agree
8232 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8234 if (isImpliedCond(Pred, LHS, RHS, Condition,
8235 BB != ContinuePredicate->getSuccessor(0)))
8244 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8245 ICmpInst::Predicate Pred,
8246 const SCEV *LHS, const SCEV *RHS) {
8247 // Interpret a null as meaning no loop, where there is obviously no guard
8248 // (interprocedural conditions notwithstanding).
8249 if (!L) return false;
8251 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8254 // Starting at the loop predecessor, climb up the predecessor chain, as long
8255 // as there are predecessors that can be found that have unique successors
8256 // leading to the original header.
8257 for (std::pair<BasicBlock *, BasicBlock *>
8258 Pair(L->getLoopPredecessor(), L->getHeader());
8260 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8262 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8265 BranchInst *LoopEntryPredicate =
8266 dyn_cast<BranchInst>(Pair.first->getTerminator());
8267 if (!LoopEntryPredicate ||
8268 LoopEntryPredicate->isUnconditional())
8271 if (isImpliedCond(Pred, LHS, RHS,
8272 LoopEntryPredicate->getCondition(),
8273 LoopEntryPredicate->getSuccessor(0) != Pair.second))
8277 // Check conditions due to any @llvm.assume intrinsics.
8278 for (auto &AssumeVH : AC.assumptions()) {
8281 auto *CI = cast<CallInst>(AssumeVH);
8282 if (!DT.dominates(CI, L->getHeader()))
8285 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8292 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8293 const SCEV *LHS, const SCEV *RHS,
8294 Value *FoundCondValue,
8296 if (!PendingLoopPredicates.insert(FoundCondValue).second)
8300 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8302 // Recursively handle And and Or conditions.
8303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8304 if (BO->getOpcode() == Instruction::And) {
8306 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8307 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8308 } else if (BO->getOpcode() == Instruction::Or) {
8310 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8311 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8315 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8316 if (!ICI) return false;
8318 // Now that we found a conditional branch that dominates the loop or controls
8319 // the loop latch. Check to see if it is the comparison we are looking for.
8320 ICmpInst::Predicate FoundPred;
8322 FoundPred = ICI->getInversePredicate();
8324 FoundPred = ICI->getPredicate();
8326 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8327 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8329 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8332 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8334 ICmpInst::Predicate FoundPred,
8335 const SCEV *FoundLHS,
8336 const SCEV *FoundRHS) {
8337 // Balance the types.
8338 if (getTypeSizeInBits(LHS->getType()) <
8339 getTypeSizeInBits(FoundLHS->getType())) {
8340 if (CmpInst::isSigned(Pred)) {
8341 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8342 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8344 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8345 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8347 } else if (getTypeSizeInBits(LHS->getType()) >
8348 getTypeSizeInBits(FoundLHS->getType())) {
8349 if (CmpInst::isSigned(FoundPred)) {
8350 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8351 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8353 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8354 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8358 // Canonicalize the query to match the way instcombine will have
8359 // canonicalized the comparison.
8360 if (SimplifyICmpOperands(Pred, LHS, RHS))
8362 return CmpInst::isTrueWhenEqual(Pred);
8363 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8364 if (FoundLHS == FoundRHS)
8365 return CmpInst::isFalseWhenEqual(FoundPred);
8367 // Check to see if we can make the LHS or RHS match.
8368 if (LHS == FoundRHS || RHS == FoundLHS) {
8369 if (isa<SCEVConstant>(RHS)) {
8370 std::swap(FoundLHS, FoundRHS);
8371 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8373 std::swap(LHS, RHS);
8374 Pred = ICmpInst::getSwappedPredicate(Pred);
8378 // Check whether the found predicate is the same as the desired predicate.
8379 if (FoundPred == Pred)
8380 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8382 // Check whether swapping the found predicate makes it the same as the
8383 // desired predicate.
8384 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8385 if (isa<SCEVConstant>(RHS))
8386 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8388 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8389 RHS, LHS, FoundLHS, FoundRHS);
8392 // Unsigned comparison is the same as signed comparison when both the operands
8393 // are non-negative.
8394 if (CmpInst::isUnsigned(FoundPred) &&
8395 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8396 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8397 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8399 // Check if we can make progress by sharpening ranges.
8400 if (FoundPred == ICmpInst::ICMP_NE &&
8401 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8403 const SCEVConstant *C = nullptr;
8404 const SCEV *V = nullptr;
8406 if (isa<SCEVConstant>(FoundLHS)) {
8407 C = cast<SCEVConstant>(FoundLHS);
8410 C = cast<SCEVConstant>(FoundRHS);
8414 // The guarding predicate tells us that C != V. If the known range
8415 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8416 // range we consider has to correspond to same signedness as the
8417 // predicate we're interested in folding.
8419 APInt Min = ICmpInst::isSigned(Pred) ?
8420 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8422 if (Min == C->getAPInt()) {
8423 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8424 // This is true even if (Min + 1) wraps around -- in case of
8425 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8427 APInt SharperMin = Min + 1;
8430 case ICmpInst::ICMP_SGE:
8431 case ICmpInst::ICMP_UGE:
8432 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8434 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8435 getConstant(SharperMin)))
8438 case ICmpInst::ICMP_SGT:
8439 case ICmpInst::ICMP_UGT:
8440 // We know from the range information that (V `Pred` Min ||
8441 // V == Min). We know from the guarding condition that !(V
8442 // == Min). This gives us
8444 // V `Pred` Min || V == Min && !(V == Min)
8447 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8449 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8459 // Check whether the actual condition is beyond sufficient.
8460 if (FoundPred == ICmpInst::ICMP_EQ)
8461 if (ICmpInst::isTrueWhenEqual(Pred))
8462 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8464 if (Pred == ICmpInst::ICMP_NE)
8465 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8466 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8469 // Otherwise assume the worst.
8473 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8474 const SCEV *&L, const SCEV *&R,
8475 SCEV::NoWrapFlags &Flags) {
8476 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8477 if (!AE || AE->getNumOperands() != 2)
8480 L = AE->getOperand(0);
8481 R = AE->getOperand(1);
8482 Flags = AE->getNoWrapFlags();
8486 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8488 // We avoid subtracting expressions here because this function is usually
8489 // fairly deep in the call stack (i.e. is called many times).
8491 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8492 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8493 const auto *MAR = cast<SCEVAddRecExpr>(More);
8495 if (LAR->getLoop() != MAR->getLoop())
8498 // We look at affine expressions only; not for correctness but to keep
8499 // getStepRecurrence cheap.
8500 if (!LAR->isAffine() || !MAR->isAffine())
8503 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8506 Less = LAR->getStart();
8507 More = MAR->getStart();
8512 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8513 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8514 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8519 SCEV::NoWrapFlags Flags;
8520 if (splitBinaryAdd(Less, L, R, Flags))
8521 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8523 return -(LC->getAPInt());
8525 if (splitBinaryAdd(More, L, R, Flags))
8526 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8528 return LC->getAPInt();
8533 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8534 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8535 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8536 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8539 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8543 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8544 if (!AddRecFoundLHS)
8547 // We'd like to let SCEV reason about control dependencies, so we constrain
8548 // both the inequalities to be about add recurrences on the same loop. This
8549 // way we can use isLoopEntryGuardedByCond later.
8551 const Loop *L = AddRecFoundLHS->getLoop();
8552 if (L != AddRecLHS->getLoop())
8555 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8557 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8560 // Informal proof for (2), assuming (1) [*]:
8562 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8566 // FoundLHS s< FoundRHS s< INT_MIN - C
8567 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8568 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8569 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8570 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8571 // <=> FoundLHS + C s< FoundRHS + C
8573 // [*]: (1) can be proved by ruling out overflow.
8575 // [**]: This can be proved by analyzing all the four possibilities:
8576 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8577 // (A s>= 0, B s>= 0).
8580 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8581 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8582 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8583 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8584 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8587 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8588 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8589 if (!LDiff || !RDiff || *LDiff != *RDiff)
8592 if (LDiff->isMinValue())
8595 APInt FoundRHSLimit;
8597 if (Pred == CmpInst::ICMP_ULT) {
8598 FoundRHSLimit = -(*RDiff);
8600 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8601 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8604 // Try to prove (1) or (2), as needed.
8605 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8606 getConstant(FoundRHSLimit));
8609 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8610 const SCEV *LHS, const SCEV *RHS,
8611 const SCEV *FoundLHS,
8612 const SCEV *FoundRHS) {
8613 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8616 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8619 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8620 FoundLHS, FoundRHS) ||
8621 // ~x < ~y --> x > y
8622 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8623 getNotSCEV(FoundRHS),
8624 getNotSCEV(FoundLHS));
8628 /// If Expr computes ~A, return A else return nullptr
8629 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8630 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8631 if (!Add || Add->getNumOperands() != 2 ||
8632 !Add->getOperand(0)->isAllOnesValue())
8635 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8636 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8637 !AddRHS->getOperand(0)->isAllOnesValue())
8640 return AddRHS->getOperand(1);
8644 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8645 template<typename MaxExprType>
8646 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8647 const SCEV *Candidate) {
8648 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8649 if (!MaxExpr) return false;
8651 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8655 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8656 template<typename MaxExprType>
8657 static bool IsMinConsistingOf(ScalarEvolution &SE,
8658 const SCEV *MaybeMinExpr,
8659 const SCEV *Candidate) {
8660 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8664 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8667 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8668 ICmpInst::Predicate Pred,
8669 const SCEV *LHS, const SCEV *RHS) {
8671 // If both sides are affine addrecs for the same loop, with equal
8672 // steps, and we know the recurrences don't wrap, then we only
8673 // need to check the predicate on the starting values.
8675 if (!ICmpInst::isRelational(Pred))
8678 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8681 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8684 if (LAR->getLoop() != RAR->getLoop())
8686 if (!LAR->isAffine() || !RAR->isAffine())
8689 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8692 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8693 SCEV::FlagNSW : SCEV::FlagNUW;
8694 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8697 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8700 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8702 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8703 ICmpInst::Predicate Pred,
8704 const SCEV *LHS, const SCEV *RHS) {
8709 case ICmpInst::ICMP_SGE:
8710 std::swap(LHS, RHS);
8712 case ICmpInst::ICMP_SLE:
8715 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8717 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8719 case ICmpInst::ICMP_UGE:
8720 std::swap(LHS, RHS);
8722 case ICmpInst::ICMP_ULE:
8725 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8727 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8730 llvm_unreachable("covered switch fell through?!");
8733 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8734 const SCEV *LHS, const SCEV *RHS,
8735 const SCEV *FoundLHS,
8736 const SCEV *FoundRHS,
8738 assert(getTypeSizeInBits(LHS->getType()) ==
8739 getTypeSizeInBits(RHS->getType()) &&
8740 "LHS and RHS have different sizes?");
8741 assert(getTypeSizeInBits(FoundLHS->getType()) ==
8742 getTypeSizeInBits(FoundRHS->getType()) &&
8743 "FoundLHS and FoundRHS have different sizes?");
8744 // We want to avoid hurting the compile time with analysis of too big trees.
8745 if (Depth > MaxSCEVOperationsImplicationDepth)
8747 // We only want to work with ICMP_SGT comparison so far.
8748 // TODO: Extend to ICMP_UGT?
8749 if (Pred == ICmpInst::ICMP_SLT) {
8750 Pred = ICmpInst::ICMP_SGT;
8751 std::swap(LHS, RHS);
8752 std::swap(FoundLHS, FoundRHS);
8754 if (Pred != ICmpInst::ICMP_SGT)
8757 auto GetOpFromSExt = [&](const SCEV *S) {
8758 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8759 return Ext->getOperand();
8760 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8761 // the constant in some cases.
8765 // Acquire values from extensions.
8766 auto *OrigFoundLHS = FoundLHS;
8767 LHS = GetOpFromSExt(LHS);
8768 FoundLHS = GetOpFromSExt(FoundLHS);
8770 // Is the SGT predicate can be proved trivially or using the found context.
8771 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8772 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8773 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8774 FoundRHS, Depth + 1);
8777 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8778 // We want to avoid creation of any new non-constant SCEV. Since we are
8779 // going to compare the operands to RHS, we should be certain that we don't
8780 // need any size extensions for this. So let's decline all cases when the
8781 // sizes of types of LHS and RHS do not match.
8782 // TODO: Maybe try to get RHS from sext to catch more cases?
8783 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8786 // Should not overflow.
8787 if (!LHSAddExpr->hasNoSignedWrap())
8790 auto *LL = LHSAddExpr->getOperand(0);
8791 auto *LR = LHSAddExpr->getOperand(1);
8792 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8794 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8795 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8796 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8798 // Try to prove the following rule:
8799 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8800 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8801 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8803 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8805 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8806 using namespace llvm::PatternMatch;
8807 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8808 // Rules for division.
8809 // We are going to perform some comparisons with Denominator and its
8810 // derivative expressions. In general case, creating a SCEV for it may
8811 // lead to a complex analysis of the entire graph, and in particular it
8812 // can request trip count recalculation for the same loop. This would
8813 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8814 // this, we only want to create SCEVs that are constants in this section.
8815 // So we bail if Denominator is not a constant.
8816 if (!isa<ConstantInt>(LR))
8819 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8821 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8822 // then a SCEV for the numerator already exists and matches with FoundLHS.
8823 auto *Numerator = getExistingSCEV(LL);
8824 if (!Numerator || Numerator->getType() != FoundLHS->getType())
8827 // Make sure that the numerator matches with FoundLHS and the denominator
8829 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8832 auto *DTy = Denominator->getType();
8833 auto *FRHSTy = FoundRHS->getType();
8834 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8835 // One of types is a pointer and another one is not. We cannot extend
8836 // them properly to a wider type, so let us just reject this case.
8837 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8838 // to avoid this check.
8842 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8843 auto *WTy = getWiderType(DTy, FRHSTy);
8844 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8845 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8847 // Try to prove the following rule:
8848 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8849 // For example, given that FoundLHS > 2. It means that FoundLHS is at
8850 // least 3. If we divide it by Denominator < 4, we will have at least 1.
8851 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8852 if (isKnownNonPositive(RHS) &&
8853 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8856 // Try to prove the following rule:
8857 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8858 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8859 // If we divide it by Denominator > 2, then:
8860 // 1. If FoundLHS is negative, then the result is 0.
8861 // 2. If FoundLHS is non-negative, then the result is non-negative.
8862 // Anyways, the result is non-negative.
8863 auto *MinusOne = getNegativeSCEV(getOne(WTy));
8864 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8865 if (isKnownNegative(RHS) &&
8866 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8875 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8876 const SCEV *LHS, const SCEV *RHS) {
8877 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8878 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8879 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8880 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8884 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8885 const SCEV *LHS, const SCEV *RHS,
8886 const SCEV *FoundLHS,
8887 const SCEV *FoundRHS) {
8889 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8890 case ICmpInst::ICMP_EQ:
8891 case ICmpInst::ICMP_NE:
8892 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8895 case ICmpInst::ICMP_SLT:
8896 case ICmpInst::ICMP_SLE:
8897 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8898 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8901 case ICmpInst::ICMP_SGT:
8902 case ICmpInst::ICMP_SGE:
8903 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8904 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8907 case ICmpInst::ICMP_ULT:
8908 case ICmpInst::ICMP_ULE:
8909 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8910 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8913 case ICmpInst::ICMP_UGT:
8914 case ICmpInst::ICMP_UGE:
8915 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8916 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8921 // Maybe it can be proved via operations?
8922 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8928 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8931 const SCEV *FoundLHS,
8932 const SCEV *FoundRHS) {
8933 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8934 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8935 // reduce the compile time impact of this optimization.
8938 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8942 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8944 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8945 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8946 ConstantRange FoundLHSRange =
8947 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8949 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8950 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8952 // We can also compute the range of values for `LHS` that satisfy the
8953 // consequent, "`LHS` `Pred` `RHS`":
8954 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8955 ConstantRange SatisfyingLHSRange =
8956 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8958 // The antecedent implies the consequent if every value of `LHS` that
8959 // satisfies the antecedent also satisfies the consequent.
8960 return SatisfyingLHSRange.contains(LHSRange);
8963 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8964 bool IsSigned, bool NoWrap) {
8965 assert(isKnownPositive(Stride) && "Positive stride expected!");
8967 if (NoWrap) return false;
8969 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8970 const SCEV *One = getOne(Stride->getType());
8973 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8974 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8975 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8978 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8979 return (std::move(MaxValue) - std::move(MaxStrideMinusOne)).slt(MaxRHS);
8982 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8983 APInt MaxValue = APInt::getMaxValue(BitWidth);
8984 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8987 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8988 return (std::move(MaxValue) - std::move(MaxStrideMinusOne)).ult(MaxRHS);
8991 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8992 bool IsSigned, bool NoWrap) {
8993 if (NoWrap) return false;
8995 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8996 const SCEV *One = getOne(Stride->getType());
8999 APInt MinRHS = getSignedRange(RHS).getSignedMin();
9000 APInt MinValue = APInt::getSignedMinValue(BitWidth);
9001 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
9004 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9005 return (std::move(MinValue) + std::move(MaxStrideMinusOne)).sgt(MinRHS);
9008 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
9009 APInt MinValue = APInt::getMinValue(BitWidth);
9010 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
9013 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9014 return (std::move(MinValue) + std::move(MaxStrideMinusOne)).ugt(MinRHS);
9017 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9019 const SCEV *One = getOne(Step->getType());
9020 Delta = Equality ? getAddExpr(Delta, Step)
9021 : getAddExpr(Delta, getMinusSCEV(Step, One));
9022 return getUDivExpr(Delta, Step);
9025 ScalarEvolution::ExitLimit
9026 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9027 const Loop *L, bool IsSigned,
9028 bool ControlsExit, bool AllowPredicates) {
9029 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9030 // We handle only IV < Invariant
9031 if (!isLoopInvariant(RHS, L))
9032 return getCouldNotCompute();
9034 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9035 bool PredicatedIV = false;
9037 if (!IV && AllowPredicates) {
9038 // Try to make this an AddRec using runtime tests, in the first X
9039 // iterations of this loop, where X is the SCEV expression found by the
9041 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9042 PredicatedIV = true;
9045 // Avoid weird loops
9046 if (!IV || IV->getLoop() != L || !IV->isAffine())
9047 return getCouldNotCompute();
9049 bool NoWrap = ControlsExit &&
9050 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9052 const SCEV *Stride = IV->getStepRecurrence(*this);
9054 bool PositiveStride = isKnownPositive(Stride);
9056 // Avoid negative or zero stride values.
9057 if (!PositiveStride) {
9058 // We can compute the correct backedge taken count for loops with unknown
9059 // strides if we can prove that the loop is not an infinite loop with side
9060 // effects. Here's the loop structure we are trying to handle -
9066 // } while (i < end);
9068 // The backedge taken count for such loops is evaluated as -
9069 // (max(end, start + stride) - start - 1) /u stride
9071 // The additional preconditions that we need to check to prove correctness
9072 // of the above formula is as follows -
9074 // a) IV is either nuw or nsw depending upon signedness (indicated by the
9076 // b) loop is single exit with no side effects.
9079 // Precondition a) implies that if the stride is negative, this is a single
9080 // trip loop. The backedge taken count formula reduces to zero in this case.
9082 // Precondition b) implies that the unknown stride cannot be zero otherwise
9085 // The positive stride case is the same as isKnownPositive(Stride) returning
9086 // true (original behavior of the function).
9088 // We want to make sure that the stride is truly unknown as there are edge
9089 // cases where ScalarEvolution propagates no wrap flags to the
9090 // post-increment/decrement IV even though the increment/decrement operation
9091 // itself is wrapping. The computed backedge taken count may be wrong in
9092 // such cases. This is prevented by checking that the stride is not known to
9093 // be either positive or non-positive. For example, no wrap flags are
9094 // propagated to the post-increment IV of this loop with a trip count of 2 -
9097 // for(i=127; i<128; i+=129)
9100 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9101 !loopHasNoSideEffects(L))
9102 return getCouldNotCompute();
9104 } else if (!Stride->isOne() &&
9105 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9106 // Avoid proven overflow cases: this will ensure that the backedge taken
9107 // count will not generate any unsigned overflow. Relaxed no-overflow
9108 // conditions exploit NoWrapFlags, allowing to optimize in presence of
9109 // undefined behaviors like the case of C language.
9110 return getCouldNotCompute();
9112 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9113 : ICmpInst::ICMP_ULT;
9114 const SCEV *Start = IV->getStart();
9115 const SCEV *End = RHS;
9116 // If the backedge is taken at least once, then it will be taken
9117 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9118 // is the LHS value of the less-than comparison the first time it is evaluated
9119 // and End is the RHS.
9120 const SCEV *BECountIfBackedgeTaken =
9121 computeBECount(getMinusSCEV(End, Start), Stride, false);
9122 // If the loop entry is guarded by the result of the backedge test of the
9123 // first loop iteration, then we know the backedge will be taken at least
9124 // once and so the backedge taken count is as above. If not then we use the
9125 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9126 // as if the backedge is taken at least once max(End,Start) is End and so the
9127 // result is as above, and if not max(End,Start) is Start so we get a backedge
9129 const SCEV *BECount;
9130 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9131 BECount = BECountIfBackedgeTaken;
9133 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9134 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9137 const SCEV *MaxBECount;
9138 bool MaxOrZero = false;
9139 if (isa<SCEVConstant>(BECount))
9140 MaxBECount = BECount;
9141 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9142 // If we know exactly how many times the backedge will be taken if it's
9143 // taken at least once, then the backedge count will either be that or
9145 MaxBECount = BECountIfBackedgeTaken;
9148 // Calculate the maximum backedge count based on the range of values
9149 // permitted by Start, End, and Stride.
9150 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9151 : getUnsignedRange(Start).getUnsignedMin();
9153 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9155 APInt StrideForMaxBECount;
9158 StrideForMaxBECount =
9159 IsSigned ? getSignedRange(Stride).getSignedMin()
9160 : getUnsignedRange(Stride).getUnsignedMin();
9162 // Using a stride of 1 is safe when computing max backedge taken count for
9163 // a loop with unknown stride.
9164 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9167 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9168 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9170 // Although End can be a MAX expression we estimate MaxEnd considering only
9171 // the case End = RHS. This is safe because in the other case (End - Start)
9172 // is zero, leading to a zero maximum backedge taken count.
9174 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9175 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9177 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9178 getConstant(StrideForMaxBECount), false);
9181 if (isa<SCEVCouldNotCompute>(MaxBECount))
9182 MaxBECount = BECount;
9184 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9187 ScalarEvolution::ExitLimit
9188 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9189 const Loop *L, bool IsSigned,
9190 bool ControlsExit, bool AllowPredicates) {
9191 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9192 // We handle only IV > Invariant
9193 if (!isLoopInvariant(RHS, L))
9194 return getCouldNotCompute();
9196 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9197 if (!IV && AllowPredicates)
9198 // Try to make this an AddRec using runtime tests, in the first X
9199 // iterations of this loop, where X is the SCEV expression found by the
9201 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9203 // Avoid weird loops
9204 if (!IV || IV->getLoop() != L || !IV->isAffine())
9205 return getCouldNotCompute();
9207 bool NoWrap = ControlsExit &&
9208 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9210 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9212 // Avoid negative or zero stride values
9213 if (!isKnownPositive(Stride))
9214 return getCouldNotCompute();
9216 // Avoid proven overflow cases: this will ensure that the backedge taken count
9217 // will not generate any unsigned overflow. Relaxed no-overflow conditions
9218 // exploit NoWrapFlags, allowing to optimize in presence of undefined
9219 // behaviors like the case of C language.
9220 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9221 return getCouldNotCompute();
9223 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9224 : ICmpInst::ICMP_UGT;
9226 const SCEV *Start = IV->getStart();
9227 const SCEV *End = RHS;
9228 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9229 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9231 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9233 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9234 : getUnsignedRange(Start).getUnsignedMax();
9236 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9237 : getUnsignedRange(Stride).getUnsignedMin();
9239 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9240 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9241 : APInt::getMinValue(BitWidth) + (MinStride - 1);
9243 // Although End can be a MIN expression we estimate MinEnd considering only
9244 // the case End = RHS. This is safe because in the other case (Start - End)
9245 // is zero, leading to a zero maximum backedge taken count.
9247 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9248 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9251 const SCEV *MaxBECount = getCouldNotCompute();
9252 if (isa<SCEVConstant>(BECount))
9253 MaxBECount = BECount;
9255 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9256 getConstant(MinStride), false);
9258 if (isa<SCEVCouldNotCompute>(MaxBECount))
9259 MaxBECount = BECount;
9261 return ExitLimit(BECount, MaxBECount, false, Predicates);
9264 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9265 ScalarEvolution &SE) const {
9266 if (Range.isFullSet()) // Infinite loop.
9267 return SE.getCouldNotCompute();
9269 // If the start is a non-zero constant, shift the range to simplify things.
9270 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9271 if (!SC->getValue()->isZero()) {
9272 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9273 Operands[0] = SE.getZero(SC->getType());
9274 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9275 getNoWrapFlags(FlagNW));
9276 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9277 return ShiftedAddRec->getNumIterationsInRange(
9278 Range.subtract(SC->getAPInt()), SE);
9279 // This is strange and shouldn't happen.
9280 return SE.getCouldNotCompute();
9283 // The only time we can solve this is when we have all constant indices.
9284 // Otherwise, we cannot determine the overflow conditions.
9285 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9286 return SE.getCouldNotCompute();
9288 // Okay at this point we know that all elements of the chrec are constants and
9289 // that the start element is zero.
9291 // First check to see if the range contains zero. If not, the first
9293 unsigned BitWidth = SE.getTypeSizeInBits(getType());
9294 if (!Range.contains(APInt(BitWidth, 0)))
9295 return SE.getZero(getType());
9298 // If this is an affine expression then we have this situation:
9299 // Solve {0,+,A} in Range === Ax in Range
9301 // We know that zero is in the range. If A is positive then we know that
9302 // the upper value of the range must be the first possible exit value.
9303 // If A is negative then the lower of the range is the last possible loop
9304 // value. Also note that we already checked for a full range.
9305 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9306 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9308 // The exit value should be (End+A)/A.
9309 APInt ExitVal = (End + A).udiv(A);
9310 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9312 // Evaluate at the exit value. If we really did fall out of the valid
9313 // range, then we computed our trip count, otherwise wrap around or other
9314 // things must have happened.
9315 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9316 if (Range.contains(Val->getValue()))
9317 return SE.getCouldNotCompute(); // Something strange happened
9319 // Ensure that the previous value is in the range. This is a sanity check.
9320 assert(Range.contains(
9321 EvaluateConstantChrecAtConstant(this,
9322 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9323 "Linear scev computation is off in a bad way!");
9324 return SE.getConstant(ExitValue);
9325 } else if (isQuadratic()) {
9326 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9327 // quadratic equation to solve it. To do this, we must frame our problem in
9328 // terms of figuring out when zero is crossed, instead of when
9329 // Range.getUpper() is crossed.
9330 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9331 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9332 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9334 // Next, solve the constructed addrec
9336 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9337 const SCEVConstant *R1 = Roots->first;
9338 const SCEVConstant *R2 = Roots->second;
9339 // Pick the smallest positive root value.
9340 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9341 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9342 if (!CB->getZExtValue())
9343 std::swap(R1, R2); // R1 is the minimum root now.
9345 // Make sure the root is not off by one. The returned iteration should
9346 // not be in the range, but the previous one should be. When solving
9347 // for "X*X < 5", for example, we should not return a root of 2.
9348 ConstantInt *R1Val =
9349 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9350 if (Range.contains(R1Val->getValue())) {
9351 // The next iteration must be out of the range...
9352 ConstantInt *NextVal =
9353 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9355 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9356 if (!Range.contains(R1Val->getValue()))
9357 return SE.getConstant(NextVal);
9358 return SE.getCouldNotCompute(); // Something strange happened
9361 // If R1 was not in the range, then it is a good return value. Make
9362 // sure that R1-1 WAS in the range though, just in case.
9363 ConstantInt *NextVal =
9364 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9365 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9366 if (Range.contains(R1Val->getValue()))
9368 return SE.getCouldNotCompute(); // Something strange happened
9373 return SE.getCouldNotCompute();
9376 // Return true when S contains at least an undef value.
9377 static inline bool containsUndefs(const SCEV *S) {
9378 return SCEVExprContains(S, [](const SCEV *S) {
9379 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9380 return isa<UndefValue>(SU->getValue());
9381 else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9382 return isa<UndefValue>(SC->getValue());
9388 // Collect all steps of SCEV expressions.
9389 struct SCEVCollectStrides {
9390 ScalarEvolution &SE;
9391 SmallVectorImpl<const SCEV *> &Strides;
9393 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9394 : SE(SE), Strides(S) {}
9396 bool follow(const SCEV *S) {
9397 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9398 Strides.push_back(AR->getStepRecurrence(SE));
9401 bool isDone() const { return false; }
9404 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9405 struct SCEVCollectTerms {
9406 SmallVectorImpl<const SCEV *> &Terms;
9408 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9411 bool follow(const SCEV *S) {
9412 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9413 isa<SCEVSignExtendExpr>(S)) {
9414 if (!containsUndefs(S))
9417 // Stop recursion: once we collected a term, do not walk its operands.
9424 bool isDone() const { return false; }
9427 // Check if a SCEV contains an AddRecExpr.
9428 struct SCEVHasAddRec {
9429 bool &ContainsAddRec;
9431 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9432 ContainsAddRec = false;
9435 bool follow(const SCEV *S) {
9436 if (isa<SCEVAddRecExpr>(S)) {
9437 ContainsAddRec = true;
9439 // Stop recursion: once we collected a term, do not walk its operands.
9446 bool isDone() const { return false; }
9449 // Find factors that are multiplied with an expression that (possibly as a
9450 // subexpression) contains an AddRecExpr. In the expression:
9452 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9454 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9455 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9456 // parameters as they form a product with an induction variable.
9458 // This collector expects all array size parameters to be in the same MulExpr.
9459 // It might be necessary to later add support for collecting parameters that are
9460 // spread over different nested MulExpr.
9461 struct SCEVCollectAddRecMultiplies {
9462 SmallVectorImpl<const SCEV *> &Terms;
9463 ScalarEvolution &SE;
9465 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9466 : Terms(T), SE(SE) {}
9468 bool follow(const SCEV *S) {
9469 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9470 bool HasAddRec = false;
9471 SmallVector<const SCEV *, 0> Operands;
9472 for (auto Op : Mul->operands()) {
9473 if (isa<SCEVUnknown>(Op)) {
9474 Operands.push_back(Op);
9476 bool ContainsAddRec;
9477 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9478 visitAll(Op, ContiansAddRec);
9479 HasAddRec |= ContainsAddRec;
9482 if (Operands.size() == 0)
9488 Terms.push_back(SE.getMulExpr(Operands));
9489 // Stop recursion: once we collected a term, do not walk its operands.
9496 bool isDone() const { return false; }
9500 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9502 /// 1) The strides of AddRec expressions.
9503 /// 2) Unknowns that are multiplied with AddRec expressions.
9504 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9505 SmallVectorImpl<const SCEV *> &Terms) {
9506 SmallVector<const SCEV *, 4> Strides;
9507 SCEVCollectStrides StrideCollector(*this, Strides);
9508 visitAll(Expr, StrideCollector);
9511 dbgs() << "Strides:\n";
9512 for (const SCEV *S : Strides)
9513 dbgs() << *S << "\n";
9516 for (const SCEV *S : Strides) {
9517 SCEVCollectTerms TermCollector(Terms);
9518 visitAll(S, TermCollector);
9522 dbgs() << "Terms:\n";
9523 for (const SCEV *T : Terms)
9524 dbgs() << *T << "\n";
9527 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9528 visitAll(Expr, MulCollector);
9531 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9532 SmallVectorImpl<const SCEV *> &Terms,
9533 SmallVectorImpl<const SCEV *> &Sizes) {
9534 int Last = Terms.size() - 1;
9535 const SCEV *Step = Terms[Last];
9537 // End of recursion.
9539 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9540 SmallVector<const SCEV *, 2> Qs;
9541 for (const SCEV *Op : M->operands())
9542 if (!isa<SCEVConstant>(Op))
9545 Step = SE.getMulExpr(Qs);
9548 Sizes.push_back(Step);
9552 for (const SCEV *&Term : Terms) {
9553 // Normalize the terms before the next call to findArrayDimensionsRec.
9555 SCEVDivision::divide(SE, Term, Step, &Q, &R);
9557 // Bail out when GCD does not evenly divide one of the terms.
9564 // Remove all SCEVConstants.
9566 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9569 if (Terms.size() > 0)
9570 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9573 Sizes.push_back(Step);
9578 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9579 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9580 for (const SCEV *T : Terms)
9581 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9586 // Return the number of product terms in S.
9587 static inline int numberOfTerms(const SCEV *S) {
9588 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9589 return Expr->getNumOperands();
9593 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9594 if (isa<SCEVConstant>(T))
9597 if (isa<SCEVUnknown>(T))
9600 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9601 SmallVector<const SCEV *, 2> Factors;
9602 for (const SCEV *Op : M->operands())
9603 if (!isa<SCEVConstant>(Op))
9604 Factors.push_back(Op);
9606 return SE.getMulExpr(Factors);
9612 /// Return the size of an element read or written by Inst.
9613 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9615 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9616 Ty = Store->getValueOperand()->getType();
9617 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9618 Ty = Load->getType();
9622 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9623 return getSizeOfExpr(ETy, Ty);
9626 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9627 SmallVectorImpl<const SCEV *> &Sizes,
9628 const SCEV *ElementSize) {
9629 if (Terms.size() < 1 || !ElementSize)
9632 // Early return when Terms do not contain parameters: we do not delinearize
9633 // non parametric SCEVs.
9634 if (!containsParameters(Terms))
9638 dbgs() << "Terms:\n";
9639 for (const SCEV *T : Terms)
9640 dbgs() << *T << "\n";
9643 // Remove duplicates.
9644 array_pod_sort(Terms.begin(), Terms.end());
9645 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9647 // Put larger terms first.
9648 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9649 return numberOfTerms(LHS) > numberOfTerms(RHS);
9652 // Try to divide all terms by the element size. If term is not divisible by
9653 // element size, proceed with the original term.
9654 for (const SCEV *&Term : Terms) {
9656 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
9661 SmallVector<const SCEV *, 4> NewTerms;
9663 // Remove constant factors.
9664 for (const SCEV *T : Terms)
9665 if (const SCEV *NewT = removeConstantFactors(*this, T))
9666 NewTerms.push_back(NewT);
9669 dbgs() << "Terms after sorting:\n";
9670 for (const SCEV *T : NewTerms)
9671 dbgs() << *T << "\n";
9674 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
9679 // The last element to be pushed into Sizes is the size of an element.
9680 Sizes.push_back(ElementSize);
9683 dbgs() << "Sizes:\n";
9684 for (const SCEV *S : Sizes)
9685 dbgs() << *S << "\n";
9689 void ScalarEvolution::computeAccessFunctions(
9690 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9691 SmallVectorImpl<const SCEV *> &Sizes) {
9693 // Early exit in case this SCEV is not an affine multivariate function.
9697 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9698 if (!AR->isAffine())
9701 const SCEV *Res = Expr;
9702 int Last = Sizes.size() - 1;
9703 for (int i = Last; i >= 0; i--) {
9705 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9708 dbgs() << "Res: " << *Res << "\n";
9709 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9710 dbgs() << "Res divided by Sizes[i]:\n";
9711 dbgs() << "Quotient: " << *Q << "\n";
9712 dbgs() << "Remainder: " << *R << "\n";
9717 // Do not record the last subscript corresponding to the size of elements in
9721 // Bail out if the remainder is too complex.
9722 if (isa<SCEVAddRecExpr>(R)) {
9731 // Record the access function for the current subscript.
9732 Subscripts.push_back(R);
9735 // Also push in last position the remainder of the last division: it will be
9736 // the access function of the innermost dimension.
9737 Subscripts.push_back(Res);
9739 std::reverse(Subscripts.begin(), Subscripts.end());
9742 dbgs() << "Subscripts:\n";
9743 for (const SCEV *S : Subscripts)
9744 dbgs() << *S << "\n";
9748 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9749 /// sizes of an array access. Returns the remainder of the delinearization that
9750 /// is the offset start of the array. The SCEV->delinearize algorithm computes
9751 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9752 /// expressions in the stride and base of a SCEV corresponding to the
9753 /// computation of a GCD (greatest common divisor) of base and stride. When
9754 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9756 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9758 /// void foo(long n, long m, long o, double A[n][m][o]) {
9760 /// for (long i = 0; i < n; i++)
9761 /// for (long j = 0; j < m; j++)
9762 /// for (long k = 0; k < o; k++)
9763 /// A[i][j][k] = 1.0;
9766 /// the delinearization input is the following AddRec SCEV:
9768 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9770 /// From this SCEV, we are able to say that the base offset of the access is %A
9771 /// because it appears as an offset that does not divide any of the strides in
9774 /// CHECK: Base offset: %A
9776 /// and then SCEV->delinearize determines the size of some of the dimensions of
9777 /// the array as these are the multiples by which the strides are happening:
9779 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9781 /// Note that the outermost dimension remains of UnknownSize because there are
9782 /// no strides that would help identifying the size of the last dimension: when
9783 /// the array has been statically allocated, one could compute the size of that
9784 /// dimension by dividing the overall size of the array by the size of the known
9785 /// dimensions: %m * %o * 8.
9787 /// Finally delinearize provides the access functions for the array reference
9788 /// that does correspond to A[i][j][k] of the above C testcase:
9790 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9792 /// The testcases are checking the output of a function pass:
9793 /// DelinearizationPass that walks through all loads and stores of a function
9794 /// asking for the SCEV of the memory access with respect to all enclosing
9795 /// loops, calling SCEV->delinearize on that and printing the results.
9797 void ScalarEvolution::delinearize(const SCEV *Expr,
9798 SmallVectorImpl<const SCEV *> &Subscripts,
9799 SmallVectorImpl<const SCEV *> &Sizes,
9800 const SCEV *ElementSize) {
9801 // First step: collect parametric terms.
9802 SmallVector<const SCEV *, 4> Terms;
9803 collectParametricTerms(Expr, Terms);
9808 // Second step: find subscript sizes.
9809 findArrayDimensions(Terms, Sizes, ElementSize);
9814 // Third step: compute the access functions for each subscript.
9815 computeAccessFunctions(Expr, Subscripts, Sizes);
9817 if (Subscripts.empty())
9821 dbgs() << "succeeded to delinearize " << *Expr << "\n";
9822 dbgs() << "ArrayDecl[UnknownSize]";
9823 for (const SCEV *S : Sizes)
9824 dbgs() << "[" << *S << "]";
9826 dbgs() << "\nArrayRef";
9827 for (const SCEV *S : Subscripts)
9828 dbgs() << "[" << *S << "]";
9833 //===----------------------------------------------------------------------===//
9834 // SCEVCallbackVH Class Implementation
9835 //===----------------------------------------------------------------------===//
9837 void ScalarEvolution::SCEVCallbackVH::deleted() {
9838 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9839 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9840 SE->ConstantEvolutionLoopExitValue.erase(PN);
9841 SE->eraseValueFromMap(getValPtr());
9842 // this now dangles!
9845 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9846 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9848 // Forget all the expressions associated with users of the old value,
9849 // so that future queries will recompute the expressions using the new
9851 Value *Old = getValPtr();
9852 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9853 SmallPtrSet<User *, 8> Visited;
9854 while (!Worklist.empty()) {
9855 User *U = Worklist.pop_back_val();
9856 // Deleting the Old value will cause this to dangle. Postpone
9857 // that until everything else is done.
9860 if (!Visited.insert(U).second)
9862 if (PHINode *PN = dyn_cast<PHINode>(U))
9863 SE->ConstantEvolutionLoopExitValue.erase(PN);
9864 SE->eraseValueFromMap(U);
9865 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9867 // Delete the Old value.
9868 if (PHINode *PN = dyn_cast<PHINode>(Old))
9869 SE->ConstantEvolutionLoopExitValue.erase(PN);
9870 SE->eraseValueFromMap(Old);
9871 // this now dangles!
9874 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9875 : CallbackVH(V), SE(se) {}
9877 //===----------------------------------------------------------------------===//
9878 // ScalarEvolution Class Implementation
9879 //===----------------------------------------------------------------------===//
9881 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9882 AssumptionCache &AC, DominatorTree &DT,
9884 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9885 CouldNotCompute(new SCEVCouldNotCompute()),
9886 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9887 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9888 FirstUnknown(nullptr) {
9890 // To use guards for proving predicates, we need to scan every instruction in
9891 // relevant basic blocks, and not just terminators. Doing this is a waste of
9892 // time if the IR does not actually contain any calls to
9893 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9895 // This pessimizes the case where a pass that preserves ScalarEvolution wants
9896 // to _add_ guards to the module when there weren't any before, and wants
9897 // ScalarEvolution to optimize based on those guards. For now we prefer to be
9898 // efficient in lieu of being smart in that rather obscure case.
9900 auto *GuardDecl = F.getParent()->getFunction(
9901 Intrinsic::getName(Intrinsic::experimental_guard));
9902 HasGuards = GuardDecl && !GuardDecl->use_empty();
9905 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9906 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9907 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9908 ValueExprMap(std::move(Arg.ValueExprMap)),
9909 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9910 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9911 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9912 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9913 PredicatedBackedgeTakenCounts(
9914 std::move(Arg.PredicatedBackedgeTakenCounts)),
9915 ConstantEvolutionLoopExitValue(
9916 std::move(Arg.ConstantEvolutionLoopExitValue)),
9917 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9918 LoopDispositions(std::move(Arg.LoopDispositions)),
9919 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9920 BlockDispositions(std::move(Arg.BlockDispositions)),
9921 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9922 SignedRanges(std::move(Arg.SignedRanges)),
9923 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9924 UniquePreds(std::move(Arg.UniquePreds)),
9925 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9926 FirstUnknown(Arg.FirstUnknown) {
9927 Arg.FirstUnknown = nullptr;
9930 ScalarEvolution::~ScalarEvolution() {
9931 // Iterate through all the SCEVUnknown instances and call their
9932 // destructors, so that they release their references to their values.
9933 for (SCEVUnknown *U = FirstUnknown; U;) {
9934 SCEVUnknown *Tmp = U;
9936 Tmp->~SCEVUnknown();
9938 FirstUnknown = nullptr;
9940 ExprValueMap.clear();
9941 ValueExprMap.clear();
9944 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9945 // that a loop had multiple computable exits.
9946 for (auto &BTCI : BackedgeTakenCounts)
9947 BTCI.second.clear();
9948 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9949 BTCI.second.clear();
9951 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9952 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9953 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9956 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9957 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9960 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9962 // Print all inner loops first
9964 PrintLoopInfo(OS, SE, I);
9967 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9970 SmallVector<BasicBlock *, 8> ExitBlocks;
9971 L->getExitBlocks(ExitBlocks);
9972 if (ExitBlocks.size() != 1)
9973 OS << "<multiple exits> ";
9975 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9976 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9978 OS << "Unpredictable backedge-taken count. ";
9983 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9986 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9987 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9988 if (SE->isBackedgeTakenCountMaxOrZero(L))
9989 OS << ", actual taken count either this or zero.";
9991 OS << "Unpredictable max backedge-taken count. ";
9996 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9999 SCEVUnionPredicate Pred;
10000 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10001 if (!isa<SCEVCouldNotCompute>(PBT)) {
10002 OS << "Predicated backedge-taken count is " << *PBT << "\n";
10003 OS << " Predicates:\n";
10006 OS << "Unpredictable predicated backedge-taken count. ";
10010 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10012 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10014 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10018 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10020 case ScalarEvolution::LoopVariant:
10022 case ScalarEvolution::LoopInvariant:
10023 return "Invariant";
10024 case ScalarEvolution::LoopComputable:
10025 return "Computable";
10027 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10030 void ScalarEvolution::print(raw_ostream &OS) const {
10031 // ScalarEvolution's implementation of the print method is to print
10032 // out SCEV values of all instructions that are interesting. Doing
10033 // this potentially causes it to create new SCEV objects though,
10034 // which technically conflicts with the const qualifier. This isn't
10035 // observable from outside the class though, so casting away the
10036 // const isn't dangerous.
10037 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10039 OS << "Classifying expressions for: ";
10040 F.printAsOperand(OS, /*PrintType=*/false);
10042 for (Instruction &I : instructions(F))
10043 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10046 const SCEV *SV = SE.getSCEV(&I);
10048 if (!isa<SCEVCouldNotCompute>(SV)) {
10050 SE.getUnsignedRange(SV).print(OS);
10052 SE.getSignedRange(SV).print(OS);
10055 const Loop *L = LI.getLoopFor(I.getParent());
10057 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10061 if (!isa<SCEVCouldNotCompute>(AtUse)) {
10063 SE.getUnsignedRange(AtUse).print(OS);
10065 SE.getSignedRange(AtUse).print(OS);
10070 OS << "\t\t" "Exits: ";
10071 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10072 if (!SE.isLoopInvariant(ExitValue, L)) {
10073 OS << "<<Unknown>>";
10079 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10081 OS << "\t\t" "LoopDispositions: { ";
10087 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10088 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10091 for (auto *InnerL : depth_first(L)) {
10095 OS << "\t\t" "LoopDispositions: { ";
10101 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10102 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10111 OS << "Determining loop execution counts for: ";
10112 F.printAsOperand(OS, /*PrintType=*/false);
10115 PrintLoopInfo(OS, &SE, I);
10118 ScalarEvolution::LoopDisposition
10119 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10120 auto &Values = LoopDispositions[S];
10121 for (auto &V : Values) {
10122 if (V.getPointer() == L)
10125 Values.emplace_back(L, LoopVariant);
10126 LoopDisposition D = computeLoopDisposition(S, L);
10127 auto &Values2 = LoopDispositions[S];
10128 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10129 if (V.getPointer() == L) {
10137 ScalarEvolution::LoopDisposition
10138 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10139 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10141 return LoopInvariant;
10145 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10146 case scAddRecExpr: {
10147 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10149 // If L is the addrec's loop, it's computable.
10150 if (AR->getLoop() == L)
10151 return LoopComputable;
10153 // Add recurrences are never invariant in the function-body (null loop).
10155 return LoopVariant;
10157 // This recurrence is variant w.r.t. L if L contains AR's loop.
10158 if (L->contains(AR->getLoop()))
10159 return LoopVariant;
10161 // This recurrence is invariant w.r.t. L if AR's loop contains L.
10162 if (AR->getLoop()->contains(L))
10163 return LoopInvariant;
10165 // This recurrence is variant w.r.t. L if any of its operands
10167 for (auto *Op : AR->operands())
10168 if (!isLoopInvariant(Op, L))
10169 return LoopVariant;
10171 // Otherwise it's loop-invariant.
10172 return LoopInvariant;
10178 bool HasVarying = false;
10179 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10180 LoopDisposition D = getLoopDisposition(Op, L);
10181 if (D == LoopVariant)
10182 return LoopVariant;
10183 if (D == LoopComputable)
10186 return HasVarying ? LoopComputable : LoopInvariant;
10189 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10190 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10191 if (LD == LoopVariant)
10192 return LoopVariant;
10193 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10194 if (RD == LoopVariant)
10195 return LoopVariant;
10196 return (LD == LoopInvariant && RD == LoopInvariant) ?
10197 LoopInvariant : LoopComputable;
10200 // All non-instruction values are loop invariant. All instructions are loop
10201 // invariant if they are not contained in the specified loop.
10202 // Instructions are never considered invariant in the function body
10203 // (null loop) because they are defined within the "loop".
10204 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10205 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10206 return LoopInvariant;
10207 case scCouldNotCompute:
10208 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10210 llvm_unreachable("Unknown SCEV kind!");
10213 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10214 return getLoopDisposition(S, L) == LoopInvariant;
10217 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10218 return getLoopDisposition(S, L) == LoopComputable;
10221 ScalarEvolution::BlockDisposition
10222 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10223 auto &Values = BlockDispositions[S];
10224 for (auto &V : Values) {
10225 if (V.getPointer() == BB)
10228 Values.emplace_back(BB, DoesNotDominateBlock);
10229 BlockDisposition D = computeBlockDisposition(S, BB);
10230 auto &Values2 = BlockDispositions[S];
10231 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10232 if (V.getPointer() == BB) {
10240 ScalarEvolution::BlockDisposition
10241 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10242 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10244 return ProperlyDominatesBlock;
10248 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10249 case scAddRecExpr: {
10250 // This uses a "dominates" query instead of "properly dominates" query
10251 // to test for proper dominance too, because the instruction which
10252 // produces the addrec's value is a PHI, and a PHI effectively properly
10253 // dominates its entire containing block.
10254 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10255 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10256 return DoesNotDominateBlock;
10258 // Fall through into SCEVNAryExpr handling.
10265 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10266 bool Proper = true;
10267 for (const SCEV *NAryOp : NAry->operands()) {
10268 BlockDisposition D = getBlockDisposition(NAryOp, BB);
10269 if (D == DoesNotDominateBlock)
10270 return DoesNotDominateBlock;
10271 if (D == DominatesBlock)
10274 return Proper ? ProperlyDominatesBlock : DominatesBlock;
10277 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10278 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10279 BlockDisposition LD = getBlockDisposition(LHS, BB);
10280 if (LD == DoesNotDominateBlock)
10281 return DoesNotDominateBlock;
10282 BlockDisposition RD = getBlockDisposition(RHS, BB);
10283 if (RD == DoesNotDominateBlock)
10284 return DoesNotDominateBlock;
10285 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10286 ProperlyDominatesBlock : DominatesBlock;
10289 if (Instruction *I =
10290 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10291 if (I->getParent() == BB)
10292 return DominatesBlock;
10293 if (DT.properlyDominates(I->getParent(), BB))
10294 return ProperlyDominatesBlock;
10295 return DoesNotDominateBlock;
10297 return ProperlyDominatesBlock;
10298 case scCouldNotCompute:
10299 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10301 llvm_unreachable("Unknown SCEV kind!");
10304 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10305 return getBlockDisposition(S, BB) >= DominatesBlock;
10308 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10309 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10312 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10313 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10316 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10317 ValuesAtScopes.erase(S);
10318 LoopDispositions.erase(S);
10319 BlockDispositions.erase(S);
10320 UnsignedRanges.erase(S);
10321 SignedRanges.erase(S);
10322 ExprValueMap.erase(S);
10323 HasRecMap.erase(S);
10324 MinTrailingZerosCache.erase(S);
10326 auto RemoveSCEVFromBackedgeMap =
10327 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10328 for (auto I = Map.begin(), E = Map.end(); I != E;) {
10329 BackedgeTakenInfo &BEInfo = I->second;
10330 if (BEInfo.hasOperand(S, this)) {
10338 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10339 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10342 void ScalarEvolution::verify() const {
10343 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10344 ScalarEvolution SE2(F, TLI, AC, DT, LI);
10346 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
10348 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10349 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10350 const SCEV *visitConstant(const SCEVConstant *Constant) {
10351 return SE.getConstant(Constant->getAPInt());
10353 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10354 return SE.getUnknown(Expr->getValue());
10357 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10358 return SE.getCouldNotCompute();
10360 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10363 SCEVMapper SCM(SE2);
10365 while (!LoopStack.empty()) {
10366 auto *L = LoopStack.pop_back_val();
10367 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10369 auto *CurBECount = SCM.visit(
10370 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10371 auto *NewBECount = SE2.getBackedgeTakenCount(L);
10373 if (CurBECount == SE2.getCouldNotCompute() ||
10374 NewBECount == SE2.getCouldNotCompute()) {
10375 // NB! This situation is legal, but is very suspicious -- whatever pass
10376 // change the loop to make a trip count go from could not compute to
10377 // computable or vice-versa *should have* invalidated SCEV. However, we
10378 // choose not to assert here (for now) since we don't want false
10383 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10384 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10385 // not propagate undef aggressively). This means we can (and do) fail
10386 // verification in cases where a transform makes the trip count of a loop
10387 // go from "undef" to "undef+1" (say). The transform is fine, since in
10388 // both cases the loop iterates "undef" times, but SCEV thinks we
10389 // increased the trip count of the loop by 1 incorrectly.
10393 if (SE.getTypeSizeInBits(CurBECount->getType()) >
10394 SE.getTypeSizeInBits(NewBECount->getType()))
10395 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10396 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10397 SE.getTypeSizeInBits(NewBECount->getType()))
10398 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10400 auto *ConstantDelta =
10401 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10403 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10404 dbgs() << "Trip Count Changed!\n";
10405 dbgs() << "Old: " << *CurBECount << "\n";
10406 dbgs() << "New: " << *NewBECount << "\n";
10407 dbgs() << "Delta: " << *ConstantDelta << "\n";
10413 bool ScalarEvolution::invalidate(
10414 Function &F, const PreservedAnalyses &PA,
10415 FunctionAnalysisManager::Invalidator &Inv) {
10416 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10417 // of its dependencies is invalidated.
10418 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10419 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10420 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10421 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10422 Inv.invalidate<LoopAnalysis>(F, PA);
10425 AnalysisKey ScalarEvolutionAnalysis::Key;
10427 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10428 FunctionAnalysisManager &AM) {
10429 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10430 AM.getResult<AssumptionAnalysis>(F),
10431 AM.getResult<DominatorTreeAnalysis>(F),
10432 AM.getResult<LoopAnalysis>(F));
10436 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10437 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10438 return PreservedAnalyses::all();
10441 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10442 "Scalar Evolution Analysis", false, true)
10443 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10444 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10445 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10446 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10447 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10448 "Scalar Evolution Analysis", false, true)
10449 char ScalarEvolutionWrapperPass::ID = 0;
10451 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10452 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10455 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10456 SE.reset(new ScalarEvolution(
10457 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10458 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10459 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10460 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10464 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10466 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10470 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10477 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10478 AU.setPreservesAll();
10479 AU.addRequiredTransitive<AssumptionCacheTracker>();
10480 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10481 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10482 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10485 const SCEVPredicate *
10486 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10487 const SCEVConstant *RHS) {
10488 FoldingSetNodeID ID;
10489 // Unique this node based on the arguments
10490 ID.AddInteger(SCEVPredicate::P_Equal);
10491 ID.AddPointer(LHS);
10492 ID.AddPointer(RHS);
10493 void *IP = nullptr;
10494 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10496 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10497 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10498 UniquePreds.InsertNode(Eq, IP);
10502 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10503 const SCEVAddRecExpr *AR,
10504 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10505 FoldingSetNodeID ID;
10506 // Unique this node based on the arguments
10507 ID.AddInteger(SCEVPredicate::P_Wrap);
10509 ID.AddInteger(AddedFlags);
10510 void *IP = nullptr;
10511 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10513 auto *OF = new (SCEVAllocator)
10514 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10515 UniquePreds.InsertNode(OF, IP);
10521 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10523 /// Rewrites \p S in the context of a loop L and the SCEV predication
10524 /// infrastructure.
10526 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10527 /// equivalences present in \p Pred.
10529 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10530 /// \p NewPreds such that the result will be an AddRecExpr.
10531 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10532 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10533 SCEVUnionPredicate *Pred) {
10534 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10535 return Rewriter.visit(S);
10538 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10539 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10540 SCEVUnionPredicate *Pred)
10541 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10543 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10545 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10546 for (auto *Pred : ExprPreds)
10547 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10548 if (IPred->getLHS() == Expr)
10549 return IPred->getRHS();
10555 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10556 const SCEV *Operand = visit(Expr->getOperand());
10557 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10558 if (AR && AR->getLoop() == L && AR->isAffine()) {
10559 // This couldn't be folded because the operand didn't have the nuw
10560 // flag. Add the nusw flag as an assumption that we could make.
10561 const SCEV *Step = AR->getStepRecurrence(SE);
10562 Type *Ty = Expr->getType();
10563 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10564 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10565 SE.getSignExtendExpr(Step, Ty), L,
10566 AR->getNoWrapFlags());
10568 return SE.getZeroExtendExpr(Operand, Expr->getType());
10571 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10572 const SCEV *Operand = visit(Expr->getOperand());
10573 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10574 if (AR && AR->getLoop() == L && AR->isAffine()) {
10575 // This couldn't be folded because the operand didn't have the nsw
10576 // flag. Add the nssw flag as an assumption that we could make.
10577 const SCEV *Step = AR->getStepRecurrence(SE);
10578 Type *Ty = Expr->getType();
10579 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10580 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10581 SE.getSignExtendExpr(Step, Ty), L,
10582 AR->getNoWrapFlags());
10584 return SE.getSignExtendExpr(Operand, Expr->getType());
10588 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10589 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10590 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10592 // Check if we've already made this assumption.
10593 return Pred && Pred->implies(A);
10595 NewPreds->insert(A);
10599 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10600 SCEVUnionPredicate *Pred;
10603 } // end anonymous namespace
10605 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10606 SCEVUnionPredicate &Preds) {
10607 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10610 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10611 const SCEV *S, const Loop *L,
10612 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10614 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10615 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10616 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10621 // Since the transformation was successful, we can now transfer the SCEV
10623 for (auto *P : TransformPreds)
10629 /// SCEV predicates
10630 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10631 SCEVPredicateKind Kind)
10632 : FastID(ID), Kind(Kind) {}
10634 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10635 const SCEVUnknown *LHS,
10636 const SCEVConstant *RHS)
10637 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10639 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10640 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10645 return Op->LHS == LHS && Op->RHS == RHS;
10648 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10650 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10652 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10653 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10656 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10657 const SCEVAddRecExpr *AR,
10658 IncrementWrapFlags Flags)
10659 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10661 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10663 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10664 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10666 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10669 bool SCEVWrapPredicate::isAlwaysTrue() const {
10670 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10671 IncrementWrapFlags IFlags = Flags;
10673 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10674 IFlags = clearFlags(IFlags, IncrementNSSW);
10676 return IFlags == IncrementAnyWrap;
10679 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10680 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10681 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10683 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10688 SCEVWrapPredicate::IncrementWrapFlags
10689 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10690 ScalarEvolution &SE) {
10691 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10692 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10694 // We can safely transfer the NSW flag as NSSW.
10695 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10696 ImpliedFlags = IncrementNSSW;
10698 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10699 // If the increment is positive, the SCEV NUW flag will also imply the
10700 // WrapPredicate NUSW flag.
10701 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10702 if (Step->getValue()->getValue().isNonNegative())
10703 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10706 return ImpliedFlags;
10709 /// Union predicates don't get cached so create a dummy set ID for it.
10710 SCEVUnionPredicate::SCEVUnionPredicate()
10711 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10713 bool SCEVUnionPredicate::isAlwaysTrue() const {
10714 return all_of(Preds,
10715 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10718 ArrayRef<const SCEVPredicate *>
10719 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10720 auto I = SCEVToPreds.find(Expr);
10721 if (I == SCEVToPreds.end())
10722 return ArrayRef<const SCEVPredicate *>();
10726 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10727 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10728 return all_of(Set->Preds,
10729 [this](const SCEVPredicate *I) { return this->implies(I); });
10731 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10732 if (ScevPredsIt == SCEVToPreds.end())
10734 auto &SCEVPreds = ScevPredsIt->second;
10736 return any_of(SCEVPreds,
10737 [N](const SCEVPredicate *I) { return I->implies(N); });
10740 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10742 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10743 for (auto Pred : Preds)
10744 Pred->print(OS, Depth);
10747 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10748 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10749 for (auto Pred : Set->Preds)
10757 const SCEV *Key = N->getExpr();
10758 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10759 " associated expression!");
10761 SCEVToPreds[Key].push_back(N);
10762 Preds.push_back(N);
10765 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10767 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10769 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10770 const SCEV *Expr = SE.getSCEV(V);
10771 RewriteEntry &Entry = RewriteMap[Expr];
10773 // If we already have an entry and the version matches, return it.
10774 if (Entry.second && Generation == Entry.first)
10775 return Entry.second;
10777 // We found an entry but it's stale. Rewrite the stale entry
10778 // according to the current predicate.
10780 Expr = Entry.second;
10782 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10783 Entry = {Generation, NewSCEV};
10788 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10789 if (!BackedgeCount) {
10790 SCEVUnionPredicate BackedgePred;
10791 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10792 addPredicate(BackedgePred);
10794 return BackedgeCount;
10797 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10798 if (Preds.implies(&Pred))
10801 updateGeneration();
10804 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10808 void PredicatedScalarEvolution::updateGeneration() {
10809 // If the generation number wrapped recompute everything.
10810 if (++Generation == 0) {
10811 for (auto &II : RewriteMap) {
10812 const SCEV *Rewritten = II.second.second;
10813 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10818 void PredicatedScalarEvolution::setNoOverflow(
10819 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10820 const SCEV *Expr = getSCEV(V);
10821 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10823 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10825 // Clear the statically implied flags.
10826 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10827 addPredicate(*SE.getWrapPredicate(AR, Flags));
10829 auto II = FlagsMap.insert({V, Flags});
10831 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10834 bool PredicatedScalarEvolution::hasNoOverflow(
10835 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10836 const SCEV *Expr = getSCEV(V);
10837 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10839 Flags = SCEVWrapPredicate::clearFlags(
10840 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10842 auto II = FlagsMap.find(V);
10844 if (II != FlagsMap.end())
10845 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10847 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10850 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10851 const SCEV *Expr = this->getSCEV(V);
10852 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10853 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10858 for (auto *P : NewPreds)
10861 updateGeneration();
10862 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10866 PredicatedScalarEvolution::PredicatedScalarEvolution(
10867 const PredicatedScalarEvolution &Init)
10868 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10869 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10870 for (const auto &I : Init.FlagsMap)
10871 FlagsMap.insert(I);
10874 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10876 for (auto *BB : L.getBlocks())
10877 for (auto &I : *BB) {
10878 if (!SE.isSCEVable(I.getType()))
10881 auto *Expr = SE.getSCEV(&I);
10882 auto II = RewriteMap.find(Expr);
10884 if (II == RewriteMap.end())
10887 // Don't print things that are not interesting.
10888 if (II->second.second == Expr)
10891 OS.indent(Depth) << "[PSE]" << I << ":\n";
10892 OS.indent(Depth + 2) << *Expr << "\n";
10893 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";