85#include "llvm/Config/llvm-config.h"
136using namespace PatternMatch;
137using namespace SCEVPatternMatch;
139#define DEBUG_TYPE "scalar-evolution"
142 "Number of loop exits with predictable exit counts");
144 "Number of loop exits without predictable exit counts");
146 "Number of loops with trip counts computed by force");
148#ifdef EXPENSIVE_CHECKS
156 cl::desc(
"Maximum number of iterations SCEV will "
157 "symbolically execute a constant "
163 cl::desc(
"Verify ScalarEvolution's backedge taken counts (slow)"));
166 cl::desc(
"Enable stricter verification with -verify-scev is passed"));
170 cl::desc(
"Verify IR correctness when making sensitive SCEV queries (slow)"),
175 cl::desc(
"Threshold for inlining multiplication operands into a SCEV"),
180 cl::desc(
"Threshold for inlining addition operands into a SCEV"),
184 "scalar-evolution-max-scev-compare-depth",
cl::Hidden,
185 cl::desc(
"Maximum depth of recursive SCEV complexity comparisons"),
189 "scalar-evolution-max-scev-operations-implication-depth",
cl::Hidden,
190 cl::desc(
"Maximum depth of recursive SCEV operations implication analysis"),
194 "scalar-evolution-max-value-compare-depth",
cl::Hidden,
195 cl::desc(
"Maximum depth of recursive value complexity comparisons"),
200 cl::desc(
"Maximum depth of recursive arithmetics"),
204 "scalar-evolution-max-constant-evolving-depth",
cl::Hidden,
209 cl::desc(
"Maximum depth of recursive SExt/ZExt/Trunc"),
214 cl::desc(
"Max coefficients in AddRec during evolving"),
219 cl::desc(
"Size of the expression which is considered huge"),
224 cl::desc(
"Threshold for switching to iteratively computing SCEV ranges"),
228 "scalar-evolution-max-loop-guard-collection-depth",
cl::Hidden,
229 cl::desc(
"Maximum depth for recursive loop guard collection"),
cl::init(1));
234 cl::desc(
"When printing analysis, include information on every instruction"));
237 "scalar-evolution-use-expensive-range-sharpening",
cl::Hidden,
239 cl::desc(
"Use more powerful methods of sharpening expression ranges. May "
240 "be costly in terms of compile time"));
243 "scalar-evolution-max-scc-analysis-depth",
cl::Hidden,
244 cl::desc(
"Maximum amount of nodes to process while searching SCEVUnknown "
245 "Phi strongly connected components"),
250 cl::desc(
"Handle <= and >= in finite loops"),
254 "scalar-evolution-use-context-for-no-wrap-flag-strenghening",
cl::Hidden,
255 cl::desc(
"Infer nuw/nsw flags using context where suitable"),
266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
276 cast<SCEVConstant>(
this)->getValue()->printAsOperand(
OS,
false);
284 OS <<
"(ptrtoint " << *
Op->getType() <<
" " << *
Op <<
" to "
285 << *PtrToInt->
getType() <<
")";
291 OS <<
"(trunc " << *
Op->getType() <<
" " << *
Op <<
" to "
298 OS <<
"(zext " << *
Op->getType() <<
" " << *
Op <<
" to "
305 OS <<
"(sext " << *
Op->getType() <<
" " << *
Op <<
" to "
334 const char *OpStr =
nullptr;
347 OpStr =
" umin_seq ";
353 ListSeparator LS(OpStr);
377 cast<SCEVUnknown>(
this)->getValue()->printAsOperand(
OS,
false);
380 OS <<
"***COULDNOTCOMPUTE***";
389 return cast<SCEVConstant>(
this)->getType();
391 return cast<SCEVVScale>(
this)->getType();
396 return cast<SCEVCastExpr>(
this)->getType();
398 return cast<SCEVAddRecExpr>(
this)->getType();
400 return cast<SCEVMulExpr>(
this)->getType();
405 return cast<SCEVMinMaxExpr>(
this)->getType();
407 return cast<SCEVSequentialMinMaxExpr>(
this)->getType();
409 return cast<SCEVAddExpr>(
this)->getType();
411 return cast<SCEVUDivExpr>(
this)->getType();
413 return cast<SCEVUnknown>(
this)->getType();
430 return cast<SCEVCastExpr>(
this)->operands();
439 return cast<SCEVNAryExpr>(
this)->operands();
441 return cast<SCEVUDivExpr>(
this)->operands();
456 if (!
Mul)
return false;
460 if (!SC)
return false;
463 return SC->getAPInt().isNegative();
478 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
480 UniqueSCEVs.InsertNode(S, IP);
499 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
502 UniqueSCEVs.InsertNode(S, IP);
521 "Must be a non-bit-width-changing pointer-to-integer cast!");
533 "Cannot truncate non-integer value!");
540 "Cannot zero extend non-integer value!");
547 "Cannot sign extend non-integer value!");
550void SCEVUnknown::deleted() {
552 SE->forgetMemoizedResults(
this);
555 SE->UniqueSCEVs.RemoveNode(
this);
561void SCEVUnknown::allUsesReplacedWith(
Value *New) {
563 SE->forgetMemoizedResults(
this);
566 SE->UniqueSCEVs.RemoveNode(
this);
588 if (LIsPointer != RIsPointer)
589 return (
int)LIsPointer - (int)RIsPointer;
594 return (
int)LID - (int)RID;
597 if (
const auto *LA = dyn_cast<Argument>(LV)) {
598 const auto *
RA = cast<Argument>(RV);
599 unsigned LArgNo = LA->getArgNo(), RArgNo =
RA->getArgNo();
600 return (
int)LArgNo - (int)RArgNo;
603 if (
const auto *LGV = dyn_cast<GlobalValue>(LV)) {
604 const auto *RGV = cast<GlobalValue>(RV);
606 const auto IsGVNameSemantic = [&](
const GlobalValue *GV) {
607 auto LT = GV->getLinkage();
614 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
615 return LGV->getName().compare(RGV->getName());
620 if (
const auto *LInst = dyn_cast<Instruction>(LV)) {
621 const auto *RInst = cast<Instruction>(RV);
626 if (LParent != RParent) {
629 if (LDepth != RDepth)
630 return (
int)LDepth - (int)RDepth;
634 unsigned LNumOps = LInst->getNumOperands(),
635 RNumOps = RInst->getNumOperands();
636 if (LNumOps != RNumOps)
637 return (
int)LNumOps - (int)RNumOps;
639 for (
unsigned Idx :
seq(LNumOps)) {
655static std::optional<int>
666 return (
int)LType - (int)RType;
696 unsigned LBitWidth = LA.
getBitWidth(), RBitWidth =
RA.getBitWidth();
697 if (LBitWidth != RBitWidth)
698 return (
int)LBitWidth - (int)RBitWidth;
699 return LA.
ult(
RA) ? -1 : 1;
703 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(
LHS)->
getType());
704 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(
RHS)->
getType());
705 return LTy->getBitWidth() - RTy->getBitWidth();
716 if (LLoop != RLoop) {
718 assert(LHead != RHead &&
"Two loops share the same header?");
722 "No dominance between recurrences used by one SCEV?");
745 unsigned LNumOps = LOps.
size(), RNumOps = ROps.
size();
746 if (LNumOps != RNumOps)
747 return (
int)LNumOps - (int)RNumOps;
749 for (
unsigned i = 0; i != LNumOps; ++i) {
776 if (Ops.
size() < 2)
return;
783 return Complexity && *Complexity < 0;
785 if (Ops.
size() == 2) {
789 if (IsLessComplex(
RHS,
LHS))
796 return IsLessComplex(
LHS,
RHS);
803 for (
unsigned i = 0, e = Ops.
size(); i != e-2; ++i) {
804 const SCEV *S = Ops[i];
809 for (
unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
814 if (i == e-2)
return;
836template <
typename FoldT,
typename IsIdentityT,
typename IsAbsorberT>
840 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
844 if (
const auto *
C = dyn_cast<SCEVConstant>(
Op)) {
848 Folded = cast<SCEVConstant>(
857 assert(Folded &&
"Must have folded value");
861 if (Folded && IsAbsorber(Folded->
getAPInt()))
865 if (Folded && !IsIdentity(Folded->
getAPInt()))
868 return Ops.
size() == 1 ? Ops[0] :
nullptr;
943 APInt OddFactorial(W, 1);
945 for (
unsigned i = 3; i <= K; ++i) {
948 OddFactorial *= (i >> TwoFactors);
952 unsigned CalculationBits = W +
T;
966 for (
unsigned i = 1; i != K; ++i) {
999 for (
unsigned i = 1, e =
Operands.size(); i != e; ++i) {
1004 if (isa<SCEVCouldNotCompute>(Coeff))
1019 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1023 if (!
Op->getType()->isPointerTy())
1034 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
1053 if (
auto *U = dyn_cast<SCEVUnknown>(
Op)) {
1058 if (isa<ConstantPointerNull>(U->getValue()))
1064 SCEV *S =
new (SCEVAllocator)
1066 UniqueSCEVs.InsertNode(S, IP);
1071 assert(
Depth == 0 &&
"getLosslessPtrToIntExpr() should not self-recurse for "
1072 "non-SCEVUnknown's.");
1084 class SCEVPtrToIntSinkingRewriter
1092 SCEVPtrToIntSinkingRewriter
Rewriter(SE);
1102 return Base::visit(S);
1107 bool Changed =
false;
1117 bool Changed =
false;
1127 "Should only reach pointer-typed SCEVUnknown's.");
1133 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(
Op, *
this);
1135 "We must have succeeded in sinking the cast, "
1136 "and ending up with an integer-typed expression!");
1144 if (isa<SCEVCouldNotCompute>(IntOp))
1153 "This is not a truncating conversion!");
1155 "This is not a conversion to a SCEVable type!");
1156 assert(!
Op->getType()->isPointerTy() &&
"Can't truncate pointer!");
1164 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
1186 UniqueSCEVs.InsertNode(S, IP);
1195 if (isa<SCEVAddExpr>(
Op) || isa<SCEVMulExpr>(
Op)) {
1196 auto *CommOp = cast<SCEVCommutativeExpr>(
Op);
1198 unsigned numTruncs = 0;
1199 for (
unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1202 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1203 isa<SCEVTruncateExpr>(S))
1207 if (numTruncs < 2) {
1208 if (isa<SCEVAddExpr>(
Op))
1210 if (isa<SCEVMulExpr>(
Op))
1217 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
1224 for (
const SCEV *
Op : AddRec->operands())
1239 UniqueSCEVs.InsertNode(S, IP);
1279struct ExtendOpTraitsBase {
1285template <
typename ExtendOp>
struct ExtendOpTraits {
1301 static const GetExtendExprTy GetExtendExpr;
1303 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1310const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1317 static const GetExtendExprTy GetExtendExpr;
1319 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1326const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1338template <
typename ExtendOpTy>
1341 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1342 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1349 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1358 for (
auto It = DiffOps.
begin(); It != DiffOps.
end(); ++It)
1371 auto PreStartFlags =
1389 const SCEV *OperandExtendedStart =
1391 (SE->*GetExtendExpr)(Step, WideTy,
Depth));
1392 if ((SE->*GetExtendExpr)(Start, WideTy,
Depth) == OperandExtendedStart) {
1404 const SCEV *OverflowLimit =
1405 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1407 if (OverflowLimit &&
1415template <
typename ExtendOpTy>
1419 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1421 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE,
Depth);
1427 (SE->*GetExtendExpr)(PreStart, Ty,
Depth));
1462template <
typename ExtendOpTy>
1463bool ScalarEvolution::proveNoWrapByVaryingStart(
const SCEV *Start,
1466 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1472 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1478 for (
unsigned Delta : {-2, -1, 1, 2}) {
1483 ID.AddPointer(PreStart);
1484 ID.AddPointer(Step);
1492 if (PreAR && PreAR->getNoWrapFlags(WrapType)) {
1495 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1496 DeltaS, &Pred,
this);
1514 const unsigned BitWidth =
C.getBitWidth();
1532 const APInt &ConstantStart,
1551 auto &UserIDs = FoldCacheUser[
I.first->second];
1552 assert(
count(UserIDs,
ID) == 1 &&
"unexpected duplicates in UserIDs");
1553 for (
unsigned I = 0;
I != UserIDs.size(); ++
I)
1554 if (UserIDs[
I] ==
ID) {
1559 I.first->second = S;
1561 FoldCacheUser[S].push_back(
ID);
1567 "This is not an extending conversion!");
1569 "This is not a conversion to a SCEVable type!");
1570 assert(!
Op->getType()->isPointerTy() &&
"Can't extend pointer!");
1574 auto Iter = FoldCache.find(
ID);
1575 if (Iter != FoldCache.end())
1576 return Iter->second;
1579 if (!isa<SCEVZeroExtendExpr>(S))
1587 "This is not an extending conversion!");
1589 assert(!
Op->getType()->isPointerTy() &&
"Can't extend pointer!");
1606 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
1610 UniqueSCEVs.InsertNode(S, IP);
1619 const SCEV *
X = ST->getOperand();
1633 if (AR->isAffine()) {
1634 const SCEV *Start = AR->getStart();
1635 const SCEV *Step = AR->getStepRecurrence(*
this);
1637 const Loop *L = AR->getLoop();
1641 if (AR->hasNoUnsignedWrap()) {
1643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
Depth + 1);
1657 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1662 const SCEV *CastedMaxBECount =
1666 if (MaxBECount == RecastedMaxBECount) {
1676 const SCEV *WideMaxBECount =
1678 const SCEV *OperandExtendedAdd =
1684 if (ZAdd == OperandExtendedAdd) {
1688 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1695 OperandExtendedAdd =
1701 if (ZAdd == OperandExtendedAdd) {
1706 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1721 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1724 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1726 if (AR->hasNoUnsignedWrap()) {
1732 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
Depth + 1);
1749 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1760 if (
const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1761 const APInt &
C = SC->getAPInt();
1765 const SCEV *SResidual =
1774 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1777 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
Depth + 1);
1793 if (
auto *Div = dyn_cast<SCEVUDivExpr>(
Op))
1797 if (
auto *SA = dyn_cast<SCEVAddExpr>(
Op)) {
1799 if (SA->hasNoUnsignedWrap()) {
1803 for (
const auto *
Op : SA->operands())
1816 if (
const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1820 const SCEV *SResidual =
1830 if (
auto *SM = dyn_cast<SCEVMulExpr>(
Op)) {
1832 if (SM->hasNoUnsignedWrap()) {
1836 for (
const auto *
Op : SM->operands())
1853 if (SM->getNumOperands() == 2)
1854 if (
auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1855 if (MulLHS->getAPInt().isPowerOf2())
1856 if (
auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1858 MulLHS->getAPInt().logBase2();
1870 if (isa<SCEVUMinExpr>(
Op) || isa<SCEVUMaxExpr>(
Op)) {
1871 auto *
MinMax = cast<SCEVMinMaxExpr>(
Op);
1873 for (
auto *Operand :
MinMax->operands())
1875 if (isa<SCEVUMinExpr>(
MinMax))
1881 if (
auto *
MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(
Op)) {
1882 assert(isa<SCEVSequentialUMinExpr>(
MinMax) &&
"Not supported!");
1884 for (
auto *Operand :
MinMax->operands())
1891 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
1894 UniqueSCEVs.InsertNode(S, IP);
1902 "This is not an extending conversion!");
1904 "This is not a conversion to a SCEVable type!");
1905 assert(!
Op->getType()->isPointerTy() &&
"Can't extend pointer!");
1909 auto Iter = FoldCache.find(
ID);
1910 if (Iter != FoldCache.end())
1911 return Iter->second;
1914 if (!isa<SCEVSignExtendExpr>(S))
1922 "This is not an extending conversion!");
1924 assert(!
Op->getType()->isPointerTy() &&
"Can't extend pointer!");
1946 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
1951 UniqueSCEVs.InsertNode(S, IP);
1960 const SCEV *
X = ST->getOperand();
1969 if (
auto *SA = dyn_cast<SCEVAddExpr>(
Op)) {
1971 if (SA->hasNoSignedWrap()) {
1975 for (
const auto *
Op : SA->operands())
1989 if (
const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1993 const SCEV *SResidual =
2007 if (AR->isAffine()) {
2008 const SCEV *Start = AR->getStart();
2009 const SCEV *Step = AR->getStepRecurrence(*
this);
2011 const Loop *L = AR->getLoop();
2015 if (AR->hasNoSignedWrap()) {
2017 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
Depth + 1);
2031 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2037 const SCEV *CastedMaxBECount =
2041 if (MaxBECount == RecastedMaxBECount) {
2051 const SCEV *WideMaxBECount =
2053 const SCEV *OperandExtendedAdd =
2059 if (SAdd == OperandExtendedAdd) {
2063 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2070 OperandExtendedAdd =
2076 if (SAdd == OperandExtendedAdd) {
2088 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2096 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2098 if (AR->hasNoSignedWrap()) {
2104 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
Depth + 1);
2112 if (
const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2113 const APInt &
C = SC->getAPInt();
2117 const SCEV *SResidual =
2126 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2129 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
Depth + 1);
2142 if (isa<SCEVSMinExpr>(
Op) || isa<SCEVSMaxExpr>(
Op)) {
2143 auto *
MinMax = cast<SCEVMinMaxExpr>(
Op);
2145 for (
auto *Operand :
MinMax->operands())
2147 if (isa<SCEVSMinExpr>(
MinMax))
2154 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
2157 UniqueSCEVs.InsertNode(S, IP);
2183 "This is not an extending conversion!");
2185 "This is not a conversion to a SCEVable type!");
2190 if (SC->getAPInt().isNegative())
2195 const SCEV *NewOp =
T->getOperand();
2203 if (!isa<SCEVZeroExtendExpr>(ZExt))
2208 if (!isa<SCEVSignExtendExpr>(SExt))
2214 for (
const SCEV *
Op : AR->operands())
2220 if (isa<SCEVSMaxExpr>(
Op))
2253 APInt &AccumulatedConstant,
2256 bool Interesting =
false;
2260 while (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2263 if (Scale != 1 || AccumulatedConstant != 0 ||
C->getValue()->isZero())
2265 AccumulatedConstant += Scale *
C->getAPInt();
2270 for (; i != Ops.
size(); ++i) {
2272 if (
Mul && isa<SCEVConstant>(
Mul->getOperand(0))) {
2274 Scale * cast<SCEVConstant>(
Mul->getOperand(0))->getAPInt();
2275 if (
Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(
Mul->getOperand(1))) {
2280 Add->operands(), NewScale, SE);
2286 auto Pair = M.insert({Key, NewScale});
2290 Pair.first->second += NewScale;
2298 std::pair<DenseMap<const SCEV *, APInt>::iterator,
bool> Pair =
2299 M.insert({Ops[i], Scale});
2303 Pair.first->second += Scale;
2322 case Instruction::Add:
2325 case Instruction::Sub:
2328 case Instruction::Mul:
2338 auto *NarrowTy = cast<IntegerType>(
LHS->
getType());
2342 const SCEV *
A = (this->*Extension)(
2344 const SCEV *LHSB = (this->*Extension)(
LHS, WideTy, 0);
2345 const SCEV *RHSB = (this->*Extension)(
RHS, WideTy, 0);
2353 if (BinOp == Instruction::Mul)
2355 auto *RHSC = dyn_cast<SCEVConstant>(
RHS);
2359 APInt C = RHSC->getAPInt();
2360 unsigned NumBits =
C.getBitWidth();
2361 bool IsSub = (BinOp == Instruction::Sub);
2362 bool IsNegativeConst = (
Signed &&
C.isNegative());
2364 bool OverflowDown = IsSub ^ IsNegativeConst;
2366 if (IsNegativeConst) {
2379 APInt Limit = Min + Magnitude;
2385 APInt Limit = Max - Magnitude;
2390std::optional<SCEV::NoWrapFlags>
2395 return std::nullopt;
2404 bool Deduced =
false;
2406 if (OBO->
getOpcode() != Instruction::Add &&
2409 return std::nullopt;
2418 false,
LHS,
RHS, CtxI)) {
2432 return std::nullopt;
2442 using namespace std::placeholders;
2449 assert(CanAnalyze &&
"don't call from other places!");
2456 auto IsKnownNonNegative = [&](
const SCEV *S) {
2466 if (SignOrUnsignWrap != SignOrUnsignMask &&
2468 isa<SCEVConstant>(Ops[0])) {
2473 return Instruction::Add;
2475 return Instruction::Mul;
2481 const APInt &
C = cast<SCEVConstant>(Ops[0])->getAPInt();
2486 Opcode,
C, OBO::NoSignedWrap);
2494 Opcode,
C, OBO::NoUnsignedWrap);
2504 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2510 if (
auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2511 if (UDiv->getOperand(1) == Ops[1])
2513 if (
auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2514 if (UDiv->getOperand(1) == Ops[0])
2530 "only nuw or nsw allowed");
2532 if (Ops.
size() == 1)
return Ops[0];
2535 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
2537 "SCEVAddExpr operand types don't match!");
2540 assert(NumPtrs <= 1 &&
"add has at most one pointer operand");
2545 [](
const APInt &C1,
const APInt &C2) {
return C1 + C2; },
2546 [](
const APInt &
C) {
return C.isZero(); },
2547 [](
const APInt &
C) {
return false; });
2551 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2560 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2565 if (
Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2566 Add->setNoWrapFlags(ComputeFlags(Ops));
2573 Type *Ty = Ops[0]->getType();
2574 bool FoundMatch =
false;
2575 for (
unsigned i = 0, e = Ops.
size(); i != e-1; ++i)
2576 if (Ops[i] == Ops[i+1]) {
2579 while (i+Count != e && Ops[i+Count] == Ops[i])
2584 if (Ops.
size() == Count)
2588 --i; e -= Count - 1;
2598 auto FindTruncSrcType = [&]() ->
Type * {
2603 if (
auto *
T = dyn_cast<SCEVTruncateExpr>(Ops[
Idx]))
2604 return T->getOperand()->getType();
2605 if (
const auto *
Mul = dyn_cast<SCEVMulExpr>(Ops[
Idx])) {
2606 const auto *LastOp =
Mul->getOperand(
Mul->getNumOperands() - 1);
2607 if (
const auto *
T = dyn_cast<SCEVTruncateExpr>(LastOp))
2608 return T->getOperand()->getType();
2612 if (
auto *SrcType = FindTruncSrcType()) {
2617 for (
const SCEV *
Op : Ops) {
2619 if (
T->getOperand()->getType() != SrcType) {
2626 }
else if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(
Op)) {
2628 for (
unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2630 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2631 if (
T->getOperand()->getType() != SrcType) {
2636 }
else if (
const auto *
C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2654 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2659 if (Ops.
size() == 2) {
2663 const SCEV *
A = Ops[0];
2664 const SCEV *
B = Ops[1];
2665 auto *AddExpr = dyn_cast<SCEVAddExpr>(
B);
2666 auto *
C = dyn_cast<SCEVConstant>(
A);
2667 if (AddExpr &&
C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2668 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2669 auto C2 =
C->getAPInt();
2672 APInt ConstAdd = C1 + C2;
2673 auto AddFlags = AddExpr->getNoWrapFlags();
2699 if (Ops.
size() == 2) {
2701 if (
Mul &&
Mul->getNumOperands() == 2 &&
2702 Mul->getOperand(0)->isAllOnesValue()) {
2705 if (matchURem(
Mul->getOperand(1),
X,
Y) &&
X == Ops[1]) {
2717 bool DeletedAdd =
false;
2731 CommonFlags =
maskFlags(CommonFlags,
Add->getNoWrapFlags());
2747 if (
Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[
Idx])) {
2754 struct APIntCompare {
2763 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2764 for (
const SCEV *NewOp : NewOps)
2765 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2768 if (AccumulatedConstant != 0)
2770 for (
auto &MulOp : MulOpLists) {
2771 if (MulOp.first == 1) {
2773 }
else if (MulOp.first != 0) {
2782 if (Ops.
size() == 1)
2791 for (;
Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[
Idx]); ++
Idx) {
2793 for (
unsigned MulOp = 0, e =
Mul->getNumOperands(); MulOp != e; ++MulOp) {
2794 const SCEV *MulOpSCEV =
Mul->getOperand(MulOp);
2795 if (isa<SCEVConstant>(MulOpSCEV))
2797 for (
unsigned AddOp = 0, e = Ops.
size(); AddOp != e; ++AddOp)
2798 if (MulOpSCEV == Ops[AddOp]) {
2800 const SCEV *InnerMul =
Mul->getOperand(MulOp == 0);
2801 if (
Mul->getNumOperands() != 2) {
2805 Mul->operands().take_front(MulOp));
2813 if (Ops.
size() == 2)
return OuterMul;
2826 for (
unsigned OtherMulIdx =
Idx+1;
2827 OtherMulIdx < Ops.
size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2829 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2833 OMulOp != e; ++OMulOp)
2834 if (OtherMul->
getOperand(OMulOp) == MulOpSCEV) {
2836 const SCEV *InnerMul1 =
Mul->getOperand(MulOp == 0);
2837 if (
Mul->getNumOperands() != 2) {
2839 Mul->operands().take_front(MulOp));
2846 OtherMul->
operands().take_front(OMulOp));
2851 const SCEV *InnerMulSum =
2855 if (Ops.
size() == 2)
return OuterMul;
2872 for (;
Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[
Idx]); ++
Idx) {
2878 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2886 if (!LIOps.
empty()) {
2911 auto *DefI = getDefiningScopeBound(LIOps);
2913 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2925 if (Ops.
size() == 1)
return NewRec;
2928 for (
unsigned i = 0;; ++i)
2929 if (Ops[i] == AddRec) {
2939 for (
unsigned OtherIdx =
Idx+1;
2940 OtherIdx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2945 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2947 "AddRecExprs are not sorted in reverse dominance order?");
2948 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2951 for (; OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2953 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2954 if (OtherAddRec->getLoop() == AddRecLoop) {
2955 for (
unsigned i = 0, e = OtherAddRec->getNumOperands();
2957 if (i >= AddRecOps.
size()) {
2958 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2962 AddRecOps[i], OtherAddRec->getOperand(i)};
2965 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
2980 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2988 for (
const SCEV *
Op : Ops)
2992 static_cast<SCEVAddExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(
ID, IP));
2995 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2996 S =
new (SCEVAllocator)
2998 UniqueSCEVs.InsertNode(S, IP);
3010 for (
const SCEV *
Op : Ops)
3018 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3019 S =
new (SCEVAllocator)
3021 UniqueSCEVs.InsertNode(S, IP);
3022 LoopUsers[
L].push_back(S);
3034 for (
const SCEV *
Op : Ops)
3038 static_cast<SCEVMulExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(
ID, IP));
3041 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3042 S =
new (SCEVAllocator)
SCEVMulExpr(
ID.Intern(SCEVAllocator),
3044 UniqueSCEVs.InsertNode(S, IP);
3053 if (j > 1 && k / j != i) Overflow =
true;
3069 if (n == 0 || n == k)
return 1;
3070 if (k > n)
return 0;
3076 for (
uint64_t i = 1; i <= k; ++i) {
3077 r =
umul_ov(r, n-(i-1), Overflow);
3086 struct FindConstantInAddMulChain {
3087 bool FoundConstant =
false;
3089 bool follow(
const SCEV *S) {
3090 FoundConstant |= isa<SCEVConstant>(S);
3091 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3094 bool isDone()
const {
3095 return FoundConstant;
3099 FindConstantInAddMulChain
F;
3101 ST.visitAll(StartExpr);
3102 return F.FoundConstant;
3110 "only nuw or nsw allowed");
3112 if (Ops.
size() == 1)
return Ops[0];
3114 Type *ETy = Ops[0]->getType();
3116 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
3118 "SCEVMulExpr operand types don't match!");
3123 [](
const APInt &C1,
const APInt &C2) {
return C1 * C2; },
3124 [](
const APInt &
C) {
return C.isOne(); },
3125 [](
const APInt &
C) {
return C.isZero(); });
3136 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3141 if (
Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3142 Mul->setNoWrapFlags(ComputeFlags(Ops));
3146 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3147 if (Ops.
size() == 2) {
3164 if (Ops[0]->isAllOnesValue()) {
3169 bool AnyFolded =
false;
3170 for (
const SCEV *AddOp :
Add->operands()) {
3173 if (!isa<SCEVMulExpr>(
Mul)) AnyFolded =
true;
3178 }
else if (
const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3197 AddRec->getNoWrapFlags(FlagsMask));
3210 bool DeletedMul =
false;
3235 for (;
Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[
Idx]); ++
Idx) {
3240 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
3248 if (!LIOps.
empty()) {
3261 for (
unsigned i = 0, e = AddRec->
getNumOperands(); i != e; ++i) {
3277 if (Ops.
size() == 1)
return NewRec;
3280 for (
unsigned i = 0;; ++i)
3281 if (Ops[i] == AddRec) {
3302 bool OpsModified =
false;
3303 for (
unsigned OtherIdx =
Idx+1;
3304 OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3307 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3317 bool Overflow =
false;
3323 SmallVector <const SCEV *, 7> SumOps;
3324 for (
int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3328 z < ze && !Overflow; ++z) {
3331 if (LargerThan64Bits)
3332 Coeff =
umul_ov(Coeff1, Coeff2, Overflow);
3334 Coeff = Coeff1*Coeff2;
3349 if (Ops.
size() == 2)
return NewAddRec;
3350 Ops[
Idx] = NewAddRec;
3351 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
3353 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3367 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3375 "SCEVURemExpr operand types don't match!");
3380 if (RHSC->getValue()->isOne())
3384 if (RHSC->getAPInt().isPowerOf2()) {
3403 "SCEVUDivExpr operand can't be pointer!");
3405 "SCEVUDivExpr operand types don't match!");
3412 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
3420 if (RHSC->getValue()->isOne())
3425 if (!RHSC->getValue()->isZero()) {
3430 unsigned LZ = RHSC->getAPInt().countl_zero();
3434 if (!RHSC->getAPInt().isPowerOf2())
3440 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*
this))) {
3442 const APInt &StepInt = Step->getAPInt();
3443 const APInt &DivInt = RHSC->getAPInt();
3444 if (!StepInt.
urem(DivInt) &&
3450 for (
const SCEV *
Op : AR->operands())
3457 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3458 if (StartC && !DivInt.
urem(StepInt) &&
3464 const APInt &StartRem = StartInt.
urem(StepInt);
3465 if (StartRem != 0) {
3466 const SCEV *NewLHS =
3469 if (
LHS != NewLHS) {
3479 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
3488 for (
const SCEV *
Op : M->operands())
3492 for (
unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3493 const SCEV *
Op = M->getOperand(i);
3495 if (!isa<SCEVUDivExpr>(Div) &&
getMulExpr(Div, RHSC) ==
Op) {
3505 if (
auto *DivisorConstant =
3506 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3507 bool Overflow =
false;
3509 DivisorConstant->getAPInt().
umul_ov(RHSC->getAPInt(), Overflow);
3520 for (
const SCEV *
Op :
A->operands())
3524 for (
unsigned i = 0, e =
A->getNumOperands(); i != e; ++i) {
3526 if (isa<SCEVUDivExpr>(
Op) ||
3531 if (
Operands.size() ==
A->getNumOperands())
3538 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3543 if (
const auto *AE = dyn_cast<SCEVAddExpr>(
LHS);
3544 AE && AE->getNumOperands() == 2) {
3545 if (
const auto *VC = dyn_cast<SCEVConstant>(AE->getOperand(0))) {
3546 const APInt &NegC = VC->getAPInt();
3548 const auto *MME = dyn_cast<SCEVSMaxExpr>(AE->getOperand(1));
3549 if (MME && MME->getNumOperands() == 2 &&
3550 isa<SCEVConstant>(MME->getOperand(0)) &&
3551 cast<SCEVConstant>(MME->getOperand(0))->getAPInt() == -NegC &&
3552 MME->getOperand(1) ==
RHS)
3561 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP))
return S;
3564 UniqueSCEVs.InsertNode(S, IP);
3594 if (!
Mul || !
Mul->hasNoUnsignedWrap())
3600 if (
const auto *LHSCst = dyn_cast<SCEVConstant>(
Mul->getOperand(0))) {
3601 if (LHSCst == RHSCst) {
3609 APInt Factor =
gcd(LHSCst, RHSCst);
3612 cast<SCEVConstant>(
getConstant(LHSCst->getAPInt().udiv(Factor)));
3614 cast<SCEVConstant>(
getConstant(RHSCst->getAPInt().udiv(Factor)));
3620 Mul = dyn_cast<SCEVMulExpr>(
LHS);
3627 for (
int i = 0, e =
Mul->getNumOperands(); i != e; ++i) {
3628 if (
Mul->getOperand(i) ==
RHS) {
3646 if (
const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3647 if (StepChrec->getLoop() == L) {
3666 "SCEVAddRecExpr operand types don't match!");
3667 assert(!
Op->getType()->isPointerTy() &&
"Step must be integer");
3671 "SCEVAddRecExpr operand is not available at loop entry!");
3689 const Loop *NestedLoop = NestedAR->getLoop();
3690 if (L->contains(NestedLoop)
3695 Operands[0] = NestedAR->getStart();
3699 bool AllInvariant =
all_of(
3711 AllInvariant =
all_of(NestedOperands, [&](
const SCEV *
Op) {
3722 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3732 return getOrCreateAddRecExpr(
Operands, L, Flags);
3749 auto *GEPI = dyn_cast<Instruction>(
GEP);
3750 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3761 bool FirstIter =
true;
3763 for (
const SCEV *IndexExpr : IndexExprs) {
3765 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
3767 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3768 unsigned FieldNo = Index->getZExtValue();
3770 Offsets.push_back(FieldOffset);
3773 CurTy = STy->getTypeAtIndex(Index);
3777 assert(isa<PointerType>(CurTy) &&
3778 "The first index of a GEP indexes a pointer");
3779 CurTy =
GEP->getSourceElementType();
3790 const SCEV *LocalOffset =
getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3791 Offsets.push_back(LocalOffset);
3796 if (Offsets.empty())
3809 "GEP should not change type mid-flight.");
3813SCEV *ScalarEvolution::findExistingSCEVInCache(
SCEVTypes SCEVType,
3816 ID.AddInteger(SCEVType);
3817 for (
const SCEV *
Op : Ops)
3820 return UniqueSCEVs.FindNodeOrInsertPos(
ID, IP);
3830 assert(SCEVMinMaxExpr::isMinMaxType(Kind) &&
"Not a SCEVMinMaxExpr!");
3831 assert(!Ops.
empty() &&
"Cannot get empty (u|s)(min|max)!");
3832 if (Ops.
size() == 1)
return Ops[0];
3835 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i) {
3837 "Operand types don't match!");
3840 "min/max should be consistently pointerish");
3866 return IsSigned ?
C.isMinSignedValue() :
C.isMinValue();
3868 return IsSigned ?
C.isMaxSignedValue() :
C.isMaxValue();
3873 return IsSigned ?
C.isMaxSignedValue() :
C.isMaxValue();
3875 return IsSigned ?
C.isMinSignedValue() :
C.isMinValue();
3881 if (
const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3887 while (
Idx < Ops.
size() && Ops[
Idx]->getSCEVType() < Kind)
3893 bool DeletedAny =
false;
3894 while (Ops[
Idx]->getSCEVType() == Kind) {
3914 for (
unsigned i = 0, e = Ops.
size() - 1; i != e; ++i) {
3915 if (Ops[i] == Ops[i + 1] ||
3916 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3922 }
else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3931 if (Ops.
size() == 1)
return Ops[0];
3933 assert(!Ops.
empty() &&
"Reduced smax down to nothing!");
3938 ID.AddInteger(Kind);
3939 for (
const SCEV *
Op : Ops)
3942 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP);
3944 return ExistingSCEV;
3946 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
3947 SCEV *S =
new (SCEVAllocator)
3950 UniqueSCEVs.InsertNode(S, IP);
3957class SCEVSequentialMinMaxDeduplicatingVisitor final
3958 :
public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3959 std::optional<const SCEV *>> {
3960 using RetVal = std::optional<const SCEV *>;
3968 bool canRecurseInto(
SCEVTypes Kind)
const {
3971 return RootKind == Kind || NonSequentialRootKind == Kind;
3974 RetVal visitAnyMinMaxExpr(
const SCEV *S) {
3975 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3976 "Only for min/max expressions.");
3979 if (!canRecurseInto(Kind))
3982 auto *NAry = cast<SCEVNAryExpr>(S);
3984 bool Changed =
visit(Kind, NAry->operands(), NewOps);
3989 return std::nullopt;
3991 return isa<SCEVSequentialMinMaxExpr>(S)
3998 if (!SeenOps.
insert(S).second)
3999 return std::nullopt;
4000 return Base::visit(S);
4006 : SE(SE), RootKind(RootKind),
4007 NonSequentialRootKind(
4013 bool Changed =
false;
4017 for (
const SCEV *
Op : OrigOps) {
4026 NewOps = std::move(Ops);
4032 RetVal visitVScale(
const SCEVVScale *VScale) {
return VScale; }
4042 RetVal visitAddExpr(
const SCEVAddExpr *Expr) {
return Expr; }
4044 RetVal visitMulExpr(
const SCEVMulExpr *Expr) {
return Expr; }
4046 RetVal visitUDivExpr(
const SCEVUDivExpr *Expr) {
return Expr; }
4048 RetVal visitAddRecExpr(
const SCEVAddRecExpr *Expr) {
return Expr; }
4051 return visitAnyMinMaxExpr(Expr);
4055 return visitAnyMinMaxExpr(Expr);
4059 return visitAnyMinMaxExpr(Expr);
4063 return visitAnyMinMaxExpr(Expr);
4067 return visitAnyMinMaxExpr(Expr);
4070 RetVal visitUnknown(
const SCEVUnknown *Expr) {
return Expr; }
4114struct SCEVPoisonCollector {
4115 bool LookThroughMaybePoisonBlocking;
4117 SCEVPoisonCollector(
bool LookThroughMaybePoisonBlocking)
4118 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4120 bool follow(
const SCEV *S) {
4121 if (!LookThroughMaybePoisonBlocking &&
4125 if (
auto *SU = dyn_cast<SCEVUnknown>(S)) {
4131 bool isDone()
const {
return false; }
4141 SCEVPoisonCollector PC1(
true);
4146 if (PC1.MaybePoison.empty())
4152 SCEVPoisonCollector PC2(
false);
4162 SCEVPoisonCollector PC(
false);
4185 while (!Worklist.
empty()) {
4187 if (!Visited.
insert(V).second)
4191 if (Visited.
size() > 16)
4196 if (PoisonVals.
contains(V) || ::isGuaranteedNotToBePoison(V))
4199 auto *
I = dyn_cast<Instruction>(V);
4206 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
4207 if (PDI->isDisjoint())
4213 if (
auto *
II = dyn_cast<IntrinsicInst>(
I);
4214 II &&
II->getIntrinsicID() == Intrinsic::vscale)
4221 if (
I->hasPoisonGeneratingAnnotations())
4233 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4234 "Not a SCEVSequentialMinMaxExpr!");
4235 assert(!Ops.
empty() &&
"Cannot get empty (u|s)(min|max)!");
4236 if (Ops.
size() == 1)
4240 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i) {
4242 "Operand types don't match!");
4245 "min/max should be consistently pointerish");
4253 if (
const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4260 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*
this, Kind);
4261 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4270 bool DeletedAny =
false;
4272 if (Ops[
Idx]->getSCEVType() != Kind) {
4276 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[
Idx]);
4279 SMME->operands().end());
4287 const SCEV *SaturationPoint;
4298 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i) {
4299 if (!isGuaranteedNotToCauseUB(Ops[i]))
4316 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4325 ID.AddInteger(Kind);
4326 for (
const SCEV *
Op : Ops)
4329 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP);
4331 return ExistingSCEV;
4334 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
4335 SCEV *S =
new (SCEVAllocator)
4338 UniqueSCEVs.InsertNode(S, IP);
4386 if (
Size.isScalable())
4407 "Cannot get offset for structure containing scalable vector types");
4421 if (
SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(
ID, IP)) {
4422 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4423 "Stale SCEVUnknown in uniquing map!");
4428 FirstUnknown = cast<SCEVUnknown>(S);
4429 UniqueSCEVs.InsertNode(S, IP);
4477 bool PreciseA, PreciseB;
4478 auto *ScopeA = getDefiningScopeBound({
A}, PreciseA);
4479 auto *ScopeB = getDefiningScopeBound({
B}, PreciseB);
4480 if (!PreciseA || !PreciseB)
4483 return (ScopeA == ScopeB) || DT.
dominates(ScopeA, ScopeB) ||
4488 return CouldNotCompute.get();
4491bool ScalarEvolution::checkValidity(
const SCEV *S)
const {
4493 auto *SU = dyn_cast<SCEVUnknown>(S);
4494 return SU && SU->getValue() ==
nullptr;
4497 return !ContainsNulls;
4502 if (
I != HasRecMap.
end())
4507 HasRecMap.
insert({S, FoundAddRec});
4515 if (SI == ExprValueMap.
end())
4517 return SI->second.getArrayRef();
4523void ScalarEvolution::eraseValueFromMap(
Value *V) {
4525 if (
I != ValueExprMap.
end()) {
4526 auto EVIt = ExprValueMap.
find(
I->second);
4527 bool Removed = EVIt->second.remove(V);
4529 assert(Removed &&
"Value not in ExprValueMap?");
4534void ScalarEvolution::insertValueToMap(
Value *V,
const SCEV *S) {
4538 auto It = ValueExprMap.
find_as(V);
4539 if (It == ValueExprMap.
end()) {
4541 ExprValueMap[S].
insert(V);
4552 return createSCEVIter(V);
4559 if (
I != ValueExprMap.
end()) {
4560 const SCEV *S =
I->second;
4561 assert(checkValidity(S) &&
4562 "existing SCEV has not been properly invalidated");
4571 if (
const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4575 Type *Ty = V->getType();
4583 if (!
Add ||
Add->getNumOperands() != 2 ||
4584 !
Add->getOperand(0)->isAllOnesValue())
4587 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(
Add->getOperand(1));
4597 assert(!V->getType()->isPointerTy() &&
"Can't negate pointer");
4599 if (
const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4610 return (
const SCEV *)
nullptr;
4616 if (
const SCEV *Replaced = MatchMinMaxNegation(MME))
4620 Type *Ty = V->getType();
4626 assert(
P->getType()->isPointerTy());
4628 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(
P)) {
4636 if (
auto *
Add = dyn_cast<SCEVAddExpr>(
P)) {
4639 const SCEV **PtrOp =
nullptr;
4640 for (
const SCEV *&AddOp : Ops) {
4641 if (AddOp->getType()->isPointerTy()) {
4642 assert(!PtrOp &&
"Cannot have multiple pointer ops");
4676 const bool RHSIsNotMinSigned =
4707 Type *SrcTy = V->getType();
4709 "Cannot truncate or zero extend with non-integer arguments!");
4719 Type *SrcTy = V->getType();
4721 "Cannot truncate or zero extend with non-integer arguments!");
4731 Type *SrcTy = V->getType();
4733 "Cannot noop or zero extend with non-integer arguments!");
4735 "getNoopOrZeroExtend cannot truncate!");
4743 Type *SrcTy = V->getType();
4745 "Cannot noop or sign extend with non-integer arguments!");
4747 "getNoopOrSignExtend cannot truncate!");
4755 Type *SrcTy = V->getType();
4757 "Cannot noop or any extend with non-integer arguments!");
4759 "getNoopOrAnyExtend cannot truncate!");
4767 Type *SrcTy = V->getType();
4769 "Cannot truncate or noop with non-integer arguments!");
4771 "getTruncateOrNoop cannot extend!");
4779 const SCEV *PromotedLHS =
LHS;
4780 const SCEV *PromotedRHS =
RHS;
4800 assert(!Ops.
empty() &&
"At least one operand must be!");
4802 if (Ops.
size() == 1)
4806 Type *MaxType =
nullptr;
4807 for (
const auto *S : Ops)
4812 assert(MaxType &&
"Failed to find maximum type!");
4816 for (
const auto *S : Ops)
4825 if (!V->getType()->isPointerTy())
4829 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4830 V = AddRec->getStart();
4831 }
else if (
auto *
Add = dyn_cast<SCEVAddExpr>(V)) {
4832 const SCEV *PtrOp =
nullptr;
4833 for (
const SCEV *AddOp :
Add->operands()) {
4834 if (AddOp->getType()->isPointerTy()) {
4835 assert(!PtrOp &&
"Cannot have multiple pointer ops");
4839 assert(PtrOp &&
"Must have pointer op");
4851 for (
User *U :
I->users()) {
4852 auto *UserInsn = cast<Instruction>(U);
4853 if (Visited.
insert(UserInsn).second)
4868 bool IgnoreOtherLoops =
true) {
4871 if (
Rewriter.hasSeenLoopVariantSCEVUnknown())
4873 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4880 SeenLoopVariantSCEVUnknown =
true;
4888 SeenOtherLoops =
true;
4892 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4894 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4901 bool SeenLoopVariantSCEVUnknown =
false;
4902 bool SeenOtherLoops =
false;
4912 SCEVPostIncRewriter
Rewriter(L, SE);
4914 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4921 SeenLoopVariantSCEVUnknown =
true;
4929 SeenOtherLoops =
true;
4933 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4935 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4942 bool SeenLoopVariantSCEVUnknown =
false;
4943 bool SeenOtherLoops =
false;
4949class SCEVBackedgeConditionFolder
4952 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
4954 bool IsPosBECond =
false;
4955 Value *BECond =
nullptr;
4957 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4960 "Both outgoing branches should not target same header!");
4967 SCEVBackedgeConditionFolder
Rewriter(L, BECond, IsPosBECond, SE);
4977 switch (
I->getOpcode()) {
4978 case Instruction::Select: {
4980 std::optional<const SCEV *> Res =
4981 compareWithBackedgeCondition(
SI->getCondition());
4983 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4989 std::optional<const SCEV *> Res = compareWithBackedgeCondition(
I);
5000 explicit SCEVBackedgeConditionFolder(
const Loop *L,
Value *BECond,
5003 IsPositiveBECond(IsPosBECond) {}
5005 std::optional<const SCEV *> compareWithBackedgeCondition(
Value *IC);
5009 Value *BackedgeCond =
nullptr;
5011 bool IsPositiveBECond;
5014std::optional<const SCEV *>
5015SCEVBackedgeConditionFolder::compareWithBackedgeCondition(
Value *IC) {
5020 if (BackedgeCond == IC)
5023 return std::nullopt;
5028 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
5049 bool isValid() {
return Valid; }
5062ScalarEvolution::proveNoWrapViaConstantRanges(
const SCEVAddRecExpr *AR) {
5072 if (
const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5074 const APInt &BECountAP = BECountMax->getAPInt();
5075 unsigned NoOverflowBitWidth =
5087 Instruction::Add, IncRange, OBO::NoSignedWrap);
5088 if (NSWRegion.contains(AddRecRange))
5097 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5098 if (NUWRegion.contains(AddRecRange))
5106ScalarEvolution::proveNoSignedWrapViaInduction(
const SCEVAddRecExpr *AR) {
5116 if (!SignedWrapViaInductionTried.insert(AR).second)
5140 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5149 const SCEV *OverflowLimit =
5151 if (OverflowLimit &&
5159ScalarEvolution::proveNoUnsignedWrapViaInduction(
const SCEVAddRecExpr *AR) {
5169 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5194 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5233 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
Op)) {
5234 IsNSW = OBO->hasNoSignedWrap();
5235 IsNUW = OBO->hasNoUnsignedWrap();
5239 explicit BinaryOp(
unsigned Opcode,
Value *
LHS,
Value *
RHS,
bool IsNSW =
false,
5241 : Opcode(Opcode),
LHS(
LHS),
RHS(
RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5251 auto *
Op = dyn_cast<Operator>(V);
5253 return std::nullopt;
5259 switch (
Op->getOpcode()) {
5260 case Instruction::Add:
5261 case Instruction::Sub:
5262 case Instruction::Mul:
5263 case Instruction::UDiv:
5264 case Instruction::URem:
5265 case Instruction::And:
5266 case Instruction::AShr:
5267 case Instruction::Shl:
5268 return BinaryOp(
Op);
5270 case Instruction::Or: {
5272 if (cast<PossiblyDisjointInst>(
Op)->isDisjoint())
5273 return BinaryOp(Instruction::Add,
Op->getOperand(0),
Op->getOperand(1),
5275 return BinaryOp(
Op);
5278 case Instruction::Xor:
5279 if (
auto *RHSC = dyn_cast<ConstantInt>(
Op->getOperand(1)))
5282 if (RHSC->getValue().isSignMask())
5283 return BinaryOp(Instruction::Add,
Op->getOperand(0),
Op->getOperand(1));
5285 if (V->getType()->isIntegerTy(1))
5286 return BinaryOp(Instruction::Add,
Op->getOperand(0),
Op->getOperand(1));
5287 return BinaryOp(
Op);
5289 case Instruction::LShr:
5291 if (
ConstantInt *SA = dyn_cast<ConstantInt>(
Op->getOperand(1))) {
5298 if (SA->getValue().ult(
BitWidth)) {
5300 ConstantInt::get(SA->getContext(),
5302 return BinaryOp(Instruction::UDiv,
Op->getOperand(0),
X);
5305 return BinaryOp(
Op);
5307 case Instruction::ExtractValue: {
5308 auto *EVI = cast<ExtractValueInst>(
Op);
5309 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5312 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5317 bool Signed = WO->isSigned();
5320 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5325 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5335 if (
auto *
II = dyn_cast<IntrinsicInst>(V))
5336 if (
II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5337 return BinaryOp(Instruction::Sub,
II->getOperand(0),
II->getOperand(1));
5339 return std::nullopt;
5365 if (
Op == SymbolicPHI)
5370 if (SourceBits != NewBits)
5378 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->
getOperand())
5379 : dyn_cast<SCEVTruncateExpr>(ZExt->
getOperand());
5383 if (
X != SymbolicPHI)
5385 Signed = SExt !=
nullptr;
5393 if (!L || L->getHeader() != PN->
getParent())
5451std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5452ScalarEvolution::createAddRecFromPHIWithCastsImpl(
const SCEVUnknown *SymbolicPHI) {
5458 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
5460 assert(L &&
"Expecting an integer loop header phi");
5465 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
5466 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5467 Value *
V = PN->getIncomingValue(i);
5468 if (
L->contains(PN->getIncomingBlock(i))) {
5471 }
else if (BEValueV != V) {
5475 }
else if (!StartValueV) {
5477 }
else if (StartValueV != V) {
5478 StartValueV =
nullptr;
5482 if (!BEValueV || !StartValueV)
5483 return std::nullopt;
5490 const auto *
Add = dyn_cast<SCEVAddExpr>(BEValue);
5492 return std::nullopt;
5496 unsigned FoundIndex =
Add->getNumOperands();
5497 Type *TruncTy =
nullptr;
5499 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5502 if (FoundIndex == e) {
5507 if (FoundIndex ==
Add->getNumOperands())
5508 return std::nullopt;
5512 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5513 if (i != FoundIndex)
5520 return std::nullopt;
5574 const SCEV *PHISCEV =
5584 if (
const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5601 auto getExtendedExpr = [&](
const SCEV *Expr,
5602 bool CreateSignExtend) ->
const SCEV * {
5605 const SCEV *ExtendedExpr =
5608 return ExtendedExpr;
5616 auto PredIsKnownFalse = [&](
const SCEV *Expr,
5617 const SCEV *ExtendedExpr) ->
bool {
5618 return Expr != ExtendedExpr &&
5622 const SCEV *StartExtended = getExtendedExpr(StartVal,
Signed);
5623 if (PredIsKnownFalse(StartVal, StartExtended)) {
5625 return std::nullopt;
5630 const SCEV *AccumExtended = getExtendedExpr(Accum,
true);
5631 if (PredIsKnownFalse(Accum, AccumExtended)) {
5633 return std::nullopt;
5636 auto AppendPredicate = [&](
const SCEV *Expr,
5637 const SCEV *ExtendedExpr) ->
void {
5638 if (Expr != ExtendedExpr &&
5646 AppendPredicate(StartVal, StartExtended);
5647 AppendPredicate(Accum, AccumExtended);
5655 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5656 std::make_pair(NewAR, Predicates);
5658 PredicatedSCEVRewrites[{SymbolicPHI,
L}] = PredRewrite;
5662std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5664 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
5667 return std::nullopt;
5670 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5671 if (
I != PredicatedSCEVRewrites.end()) {
5672 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5675 if (Rewrite.first == SymbolicPHI)
5676 return std::nullopt;
5679 assert(isa<SCEVAddRecExpr>(Rewrite.first) &&
"Expected an AddRec");
5680 assert(!(Rewrite.second).empty() &&
"Expected to find Predicates");
5684 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5685 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5690 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5691 return std::nullopt;
5708 auto areExprsEqual = [&](
const SCEV *Expr1,
const SCEV *Expr2) ->
bool {
5709 if (Expr1 != Expr2 &&
5728const SCEV *ScalarEvolution::createSimpleAffineAddRec(
PHINode *PN,
5730 Value *StartValueV) {
5733 assert(BEValueV && StartValueV);
5739 if (BO->Opcode != Instruction::Add)
5742 const SCEV *Accum =
nullptr;
5743 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5745 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5759 insertValueToMap(PN, PHISCEV);
5761 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5764 proveNoWrapViaConstantRanges(AR)));
5770 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5772 "Accum is defined outside L, but is not invariant?");
5773 if (isAddRecNeverPoison(BEInst, L))
5780const SCEV *ScalarEvolution::createAddRecFromPHI(
PHINode *PN) {
5788 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
5794 }
else if (BEValueV != V) {
5798 }
else if (!StartValueV) {
5800 }
else if (StartValueV != V) {
5801 StartValueV =
nullptr;
5805 if (!BEValueV || !StartValueV)
5809 "PHI node already processed?");
5813 if (
auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5818 insertValueToMap(PN, SymbolicName);
5832 unsigned FoundIndex =
Add->getNumOperands();
5833 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5834 if (
Add->getOperand(i) == SymbolicName)
5835 if (FoundIndex == e) {
5840 if (FoundIndex !=
Add->getNumOperands()) {
5843 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5844 if (i != FoundIndex)
5845 Ops.
push_back(SCEVBackedgeConditionFolder::rewrite(
Add->getOperand(i),
5852 (isa<SCEVAddRecExpr>(Accum) &&
5853 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5857 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5864 if (
GEP->getOperand(0) == PN) {
5889 forgetMemoizedResults(SymbolicName);
5890 insertValueToMap(PN, PHISCEV);
5892 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5895 proveNoWrapViaConstantRanges(AR)));
5901 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
5920 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *
this);
5921 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *
this,
false);
5923 isGuaranteedNotToCauseUB(Shifted) &&
::impliesPoison(Shifted, Start)) {
5925 if (Start == StartVal) {
5929 forgetMemoizedResults(SymbolicName);
5930 insertValueToMap(PN, Shifted);
5940 eraseValueFromMap(PN);
5960 Use &LeftUse =
Merge->getOperandUse(0);
5961 Use &RightUse =
Merge->getOperandUse(1);
5978const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(
PHINode *PN) {
5995 assert(IDom &&
"At least the entry block should dominate PN");
6004 return createNodeForSelectOrPHI(PN,
Cond, LHS, RHS);
6020ScalarEvolution::createNodeForPHIWithIdenticalOperands(
PHINode *PN) {
6024 auto *IncomingInst = dyn_cast<BinaryOperator>(
Incoming);
6032 CommonInst = IncomingInst;
6040 bool SCEVExprsIdentical =
6042 [
this, CommonSCEV](
Value *V) { return CommonSCEV == getSCEV(V); });
6043 return SCEVExprsIdentical ? CommonSCEV :
nullptr;
6046const SCEV *ScalarEvolution::createNodeForPHI(
PHINode *PN) {
6047 if (
const SCEV *S = createAddRecFromPHI(PN))
6057 if (
const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6060 if (
const SCEV *S = createNodeFromSelectLikePHI(PN))
6069 struct FindClosure {
6070 const SCEV *OperandToFind;
6076 bool canRecurseInto(
SCEVTypes Kind)
const {
6079 return RootKind == Kind || NonSequentialRootKind == Kind ||
6084 : OperandToFind(OperandToFind), RootKind(RootKind),
6085 NonSequentialRootKind(
6089 bool follow(
const SCEV *S) {
6090 Found = S == OperandToFind;
6092 return !isDone() && canRecurseInto(S->
getSCEVType());
6095 bool isDone()
const {
return Found; }
6098 FindClosure FC(OperandToFind, RootKind);
6103std::optional<const SCEV *>
6104ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
Type *Ty,
6114 switch (ICI->getPredicate()) {
6128 bool Signed = ICI->isSigned();
6137 if (LA == LS &&
RA == RS)
6139 if (LA == RS &&
RA == LS)
6142 auto CoerceOperand = [&](
const SCEV *
Op) ->
const SCEV * {
6143 if (
Op->getType()->isPointerTy()) {
6145 if (isa<SCEVCouldNotCompute>(
Op))
6154 LS = CoerceOperand(LS);
6155 RS = CoerceOperand(RS);
6156 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6177 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
6183 if (isa<SCEVConstant>(
C) && cast<SCEVConstant>(
C)->getAPInt().ule(1))
6190 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero() &&
6191 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->
isZero()) {
6193 while (
auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(
X))
6194 X = ZExt->getOperand();
6207 return std::nullopt;
6210static std::optional<const SCEV *>
6212 const SCEV *TrueExpr,
const SCEV *FalseExpr) {
6216 "Unexpected operands of a select.");
6227 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6228 return std::nullopt;
6231 if (isa<SCEVConstant>(TrueExpr)) {
6243static std::optional<const SCEV *>
6246 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6247 return std::nullopt;
6250 const auto *SETrue = SE->
getSCEV(TrueVal);
6251 const auto *SEFalse = SE->
getSCEV(FalseVal);
6255const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6257 assert(
Cond->getType()->isIntegerTy(1) &&
"Select condition is not an i1?");
6259 V->getType() ==
TrueVal->getType() &&
6260 "Types of select hands and of the result must match.");
6263 if (!
V->getType()->isIntegerTy(1))
6266 if (std::optional<const SCEV *> S =
6278 if (
auto *CI = dyn_cast<ConstantInt>(
Cond))
6279 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6281 if (
auto *
I = dyn_cast<Instruction>(V)) {
6282 if (
auto *ICI = dyn_cast<ICmpInst>(
Cond)) {
6283 if (std::optional<const SCEV *> S =
6284 createNodeForSelectOrPHIInstWithICmpInstCond(
I->getType(), ICI,
6290 return createNodeForSelectOrPHIViaUMinSeq(V,
Cond, TrueVal, FalseVal);
6296 assert(
GEP->getSourceElementType()->isSized() &&
6297 "GEP source element type must be sized");
6300 for (
Value *Index :
GEP->indices())
6305APInt ScalarEvolution::getConstantMultipleImpl(
const SCEV *S) {
6315 for (
unsigned I = 1, E =
N->getNumOperands();
I < E && Res != 1; ++
I)
6323 return cast<SCEVConstant>(S)->getAPInt();
6333 return GetShiftedByZeros(TZ);
6343 return GetShiftedByZeros(TZ);
6347 if (
M->hasNoUnsignedWrap()) {
6350 for (
const SCEV *Operand :
M->operands().drop_front())
6358 for (
const SCEV *Operand :
M->operands())
6360 return GetShiftedByZeros(TZ);
6365 if (
N->hasNoUnsignedWrap())
6366 return GetGCDMultiple(
N);
6369 for (
const SCEV *Operand :
N->operands().drop_front())
6371 return GetShiftedByZeros(TZ);
6378 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6384 .countMinTrailingZeros();
6385 return GetShiftedByZeros(Known);
6394 auto I = ConstantMultipleCache.find(S);
6395 if (
I != ConstantMultipleCache.end())
6398 APInt Result = getConstantMultipleImpl(S);
6399 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6400 assert(InsertPair.second &&
"Should insert a new key");
6401 return InsertPair.first->second;
6417 if (
MDNode *MD =
I->getMetadata(LLVMContext::MD_range))
6419 if (
const auto *CB = dyn_cast<CallBase>(V))
6420 if (std::optional<ConstantRange>
Range = CB->getRange())
6423 if (
auto *
A = dyn_cast<Argument>(V))
6424 if (std::optional<ConstantRange>
Range =
A->getRange())
6427 return std::nullopt;
6434 UnsignedRanges.erase(AddRec);
6435 SignedRanges.erase(AddRec);
6436 ConstantMultipleCache.erase(AddRec);
6441getRangeForUnknownRecurrence(
const SCEVUnknown *U) {
6455 auto *
P = dyn_cast<PHINode>(U->getValue());
6467 Value *Start, *Step;
6474 assert(L && L->getHeader() ==
P->getParent());
6487 case Instruction::AShr:
6488 case Instruction::LShr:
6489 case Instruction::Shl:
6504 KnownStep.getBitWidth() ==
BitWidth);
6507 auto MaxShiftAmt = KnownStep.getMaxValue();
6509 bool Overflow =
false;
6510 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6517 case Instruction::AShr: {
6525 if (KnownStart.isNonNegative())
6528 KnownStart.getMaxValue() + 1);
6529 if (KnownStart.isNegative())
6532 KnownEnd.getMaxValue() + 1);
6535 case Instruction::LShr: {
6544 KnownStart.getMaxValue() + 1);
6546 case Instruction::Shl: {
6550 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6552 KnownEnd.getMaxValue() + 1);
6560ScalarEvolution::getRangeRefIter(
const SCEV *S,
6561 ScalarEvolution::RangeSignHint SignHint) {
6563 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6570 auto AddToWorklist = [&WorkList, &Seen, &Cache](
const SCEV *Expr) {
6571 if (!Seen.
insert(Expr).second)
6577 if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6604 for (
unsigned I = 0;
I != WorkList.
size(); ++
I) {
6605 const SCEV *
P = WorkList[
I];
6606 auto *UnknownS = dyn_cast<SCEVUnknown>(
P);
6609 for (
const SCEV *
Op :
P->operands())
6614 if (
const PHINode *
P = dyn_cast<PHINode>(UnknownS->getValue())) {
6615 if (!PendingPhiRangesIter.insert(
P).second)
6622 if (!WorkList.
empty()) {
6627 getRangeRef(
P, SignHint);
6629 if (
auto *UnknownS = dyn_cast<SCEVUnknown>(
P))
6630 if (
const PHINode *
P = dyn_cast<PHINode>(UnknownS->getValue()))
6631 PendingPhiRangesIter.erase(
P);
6635 return getRangeRef(S, SignHint, 0);
6642 const SCEV *S, ScalarEvolution::RangeSignHint SignHint,
unsigned Depth) {
6644 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6652 if (
I != Cache.
end())
6661 return getRangeRefIter(S, SignHint);
6669 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6673 ConservativeResult =
6696 ConservativeResult.intersectWith(
X.truncate(
BitWidth), RangeType));
6703 ConservativeResult.intersectWith(
X.zeroExtend(
BitWidth), RangeType));
6710 ConservativeResult.intersectWith(
X.signExtend(
BitWidth), RangeType));
6715 return setRange(PtrToInt, SignHint,
X);
6720 unsigned WrapType = OBO::AnyWrap;
6721 if (
Add->hasNoSignedWrap())
6722 WrapType |= OBO::NoSignedWrap;
6723 if (
Add->hasNoUnsignedWrap())
6724 WrapType |= OBO::NoUnsignedWrap;
6726 X =
X.addWithNoWrap(getRangeRef(
Op, SignHint,
Depth + 1), WrapType,
6728 return setRange(
Add, SignHint,
6729 ConservativeResult.intersectWith(
X, RangeType));
6735 X =
X.multiply(getRangeRef(
Op, SignHint,
Depth + 1));
6736 return setRange(
Mul, SignHint,
6737 ConservativeResult.intersectWith(
X, RangeType));
6743 return setRange(UDiv, SignHint,
6744 ConservativeResult.intersectWith(
X.udiv(
Y), RangeType));
6752 if (!UnsignedMinValue.
isZero())
6753 ConservativeResult = ConservativeResult.intersectWith(
6763 bool AllNonNeg =
true;
6764 bool AllNonPos =
true;
6765 for (
unsigned i = 1, e = AddRec->
getNumOperands(); i != e; ++i) {
6772 ConservativeResult = ConservativeResult.intersectWith(
6777 ConservativeResult = ConservativeResult.intersectWith(
6786 const SCEV *MaxBEScev =
6788 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6789 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6800 auto RangeFromAffine = getRangeForAffineAR(
6802 ConservativeResult =
6803 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6805 auto RangeFromFactoring = getRangeViaFactoring(
6807 ConservativeResult =
6808 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6814 const SCEV *SymbolicMaxBECount =
6816 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6819 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6820 AddRec, SymbolicMaxBECount,
BitWidth, SignHint);
6821 ConservativeResult =
6822 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6827 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6837 ID = Intrinsic::umax;
6840 ID = Intrinsic::smax;
6844 ID = Intrinsic::umin;
6847 ID = Intrinsic::smin;
6853 const auto *NAry = cast<SCEVNAryExpr>(S);
6855 for (
unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6857 ID, {
X, getRangeRef(NAry->getOperand(i), SignHint,
Depth + 1)});
6858 return setRange(S, SignHint,
6859 ConservativeResult.intersectWith(
X, RangeType));
6868 ConservativeResult =
6869 ConservativeResult.intersectWith(*MDRange, RangeType);
6874 auto CR = getRangeForUnknownRecurrence(U);
6875 ConservativeResult = ConservativeResult.intersectWith(CR);
6886 if (
U->getType()->isPointerTy()) {
6889 unsigned ptrSize =
DL.getPointerTypeSizeInBits(
U->getType());
6890 int ptrIdxDiff = ptrSize -
BitWidth;
6891 if (ptrIdxDiff > 0 && ptrSize >
BitWidth && NS > (
unsigned)ptrIdxDiff)
6904 ConservativeResult = ConservativeResult.intersectWith(
6908 ConservativeResult = ConservativeResult.intersectWith(
6913 if (
U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6916 bool CanBeNull, CanBeFreed;
6918 V->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
6934 ConservativeResult = ConservativeResult.intersectWith(
6940 if (
PHINode *Phi = dyn_cast<PHINode>(V)) {
6942 if (PendingPhiRanges.insert(Phi).second) {
6945 for (
const auto &
Op :
Phi->operands()) {
6947 RangeFromOps = RangeFromOps.unionWith(OpRange);
6949 if (RangeFromOps.isFullSet())
6952 ConservativeResult =
6953 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6954 bool Erased = PendingPhiRanges.erase(Phi);
6955 assert(Erased &&
"Failed to erase Phi properly?");
6961 if (
const auto *
II = dyn_cast<IntrinsicInst>(V))
6962 if (
II->getIntrinsicID() == Intrinsic::vscale) {
6964 ConservativeResult = ConservativeResult.difference(Disallowed);
6967 return setRange(U, SignHint, std::move(ConservativeResult));
6973 return setRange(S, SignHint, std::move(ConservativeResult));
6982 const APInt &MaxBECount,
6989 if (Step == 0 || MaxBECount == 0)
6996 return ConstantRange::getFull(
BitWidth);
7012 return ConstantRange::getFull(
BitWidth);
7024 APInt MovedBoundary = Descending ? (StartLower - std::move(
Offset))
7025 : (StartUpper + std::move(
Offset));
7030 if (StartRange.
contains(MovedBoundary))
7031 return ConstantRange::getFull(
BitWidth);
7034 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7036 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7045 const APInt &MaxBECount) {
7049 "mismatched bit widths");
7058 StepSRange.
getSignedMin(), StartSRange, MaxBECount,
true);
7060 StartSRange, MaxBECount,
7072ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7074 ScalarEvolution::RangeSignHint SignHint) {
7075 assert(AddRec->
isAffine() &&
"Non-affine AddRecs are not suppored!\n");
7077 "This only works for non-self-wrapping AddRecs!");
7078 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7081 if (!isa<SCEVConstant>(Step))
7082 return ConstantRange::getFull(
BitWidth);
7090 return ConstantRange::getFull(
BitWidth);
7096 MaxItersWithoutWrap))
7097 return ConstantRange::getFull(
BitWidth);
7124 return RangeBetween;
7129 return ConstantRange::getFull(
BitWidth);
7132 isKnownPredicateViaConstantRanges(LEPred, Start,
End))
7133 return RangeBetween;
7135 isKnownPredicateViaConstantRanges(GEPred, Start,
End))
7136 return RangeBetween;
7137 return ConstantRange::getFull(
BitWidth);
7142 const APInt &MaxBECount) {
7149 "mismatched bit widths");
7151 struct SelectPattern {
7152 Value *Condition =
nullptr;
7158 std::optional<unsigned> CastOp;
7165 if (
auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7168 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7171 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7172 S = SA->getOperand(1);
7176 if (
auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7178 S = SCast->getOperand();
7183 auto *SU = dyn_cast<SCEVUnknown>(S);
7188 Condition =
nullptr;
7220 bool isRecognized() {
return Condition !=
nullptr; }
7223 SelectPattern StartPattern(*
this,
BitWidth, Start);
7224 if (!StartPattern.isRecognized())
7225 return ConstantRange::getFull(
BitWidth);
7227 SelectPattern StepPattern(*
this,
BitWidth, Step);
7228 if (!StepPattern.isRecognized())
7229 return ConstantRange::getFull(
BitWidth);
7231 if (StartPattern.Condition != StepPattern.Condition) {
7235 return ConstantRange::getFull(
BitWidth);
7252 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount);
7254 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount);
7276ScalarEvolution::getNonTrivialDefiningScopeBound(
const SCEV *S) {
7277 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7279 if (
auto *U = dyn_cast<SCEVUnknown>(S))
7280 if (
auto *
I = dyn_cast<Instruction>(
U->getValue()))
7292 auto pushOp = [&](
const SCEV *S) {
7293 if (!Visited.
insert(S).second)
7296 if (Visited.
size() > 30) {
7303 for (
const auto *S : Ops)
7307 while (!Worklist.
empty()) {
7309 if (
auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7310 if (!Bound || DT.
dominates(Bound, DefI))
7323 return getDefiningScopeBound(Ops, Discard);
7326bool ScalarEvolution::isGuaranteedToTransferExecutionTo(
const Instruction *
A,
7328 if (
A->getParent() ==
B->getParent() &&
7334 if (BLoop && BLoop->getHeader() ==
B->getParent() &&
7335 BLoop->getLoopPreheader() ==
A->getParent() &&
7337 A->getParent()->end()) &&
7344bool ScalarEvolution::isGuaranteedNotToBePoison(
const SCEV *
Op) {
7345 SCEVPoisonCollector PC(
true);
7347 return PC.MaybePoison.empty();
7350bool ScalarEvolution::isGuaranteedNotToCauseUB(
const SCEV *
Op) {
7352 auto *UDiv = dyn_cast<SCEVUDivExpr>(S);
7356 !isGuaranteedNotToBePoison(UDiv->getOperand(1)));
7360bool ScalarEvolution::isSCEVExprNeverPoison(
const Instruction *
I) {
7377 for (
const Use &
Op :
I->operands()) {
7383 auto *DefI = getDefiningScopeBound(SCEVOps);
7384 return isGuaranteedToTransferExecutionTo(DefI,
I);
7387bool ScalarEvolution::isAddRecNeverPoison(
const Instruction *
I,
const Loop *L) {
7389 if (isSCEVExprNeverPoison(
I))
7400 auto *ExitingBB =
L->getExitingBlock();
7413 while (!Worklist.
empty()) {
7417 const Instruction *PoisonUser = cast<Instruction>(
U.getUser());
7423 if (KnownPoison.
insert(PoisonUser).second)
7431ScalarEvolution::LoopProperties
7432ScalarEvolution::getLoopProperties(
const Loop *L) {
7433 using LoopProperties = ScalarEvolution::LoopProperties;
7435 auto Itr = LoopPropertiesCache.find(L);
7436 if (Itr == LoopPropertiesCache.end()) {
7438 if (
auto *SI = dyn_cast<StoreInst>(
I))
7439 return !
SI->isSimple();
7441 return I->mayThrow() ||
I->mayWriteToMemory();
7444 LoopProperties LP = {
true,
7447 for (
auto *BB :
L->getBlocks())
7448 for (
auto &
I : *BB) {
7450 LP.HasNoAbnormalExits =
false;
7451 if (HasSideEffects(&
I))
7452 LP.HasNoSideEffects =
false;
7453 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7457 auto InsertPair = LoopPropertiesCache.insert({
L, LP});
7458 assert(InsertPair.second &&
"We just checked!");
7459 Itr = InsertPair.first;
7472const SCEV *ScalarEvolution::createSCEVIter(
Value *V) {
7478 Stack.emplace_back(V,
true);
7479 Stack.emplace_back(V,
false);
7480 while (!Stack.empty()) {
7481 auto E = Stack.pop_back_val();
7482 Value *CurV = E.getPointer();
7488 const SCEV *CreatedSCEV =
nullptr;
7491 CreatedSCEV = createSCEV(CurV);
7496 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7500 insertValueToMap(CurV, CreatedSCEV);
7504 Stack.emplace_back(CurV,
true);
7506 Stack.emplace_back(
Op,
false);
7525 }
else if (
ConstantInt *CI = dyn_cast<ConstantInt>(V))
7527 else if (isa<GlobalAlias>(V))
7529 else if (!isa<ConstantExpr>(V))
7535 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7536 switch (BO->Opcode) {
7537 case Instruction::Add:
7538 case Instruction::Mul: {
7551 dyn_cast<Instruction>(V));
7553 (BO->Opcode == Instruction::Add &&
7554 (NewBO->Opcode != Instruction::Add &&
7555 NewBO->Opcode != Instruction::Sub)) ||
7556 (BO->Opcode == Instruction::Mul &&
7557 NewBO->Opcode != Instruction::Mul)) {
7563 if (BO->
Op && (BO->IsNSW || BO->IsNUW)) {
7564 auto *
I = dyn_cast<Instruction>(BO->
Op);
7574 case Instruction::Sub:
7575 case Instruction::UDiv:
7576 case Instruction::URem:
7578 case Instruction::AShr:
7579 case Instruction::Shl:
7580 case Instruction::Xor:
7584 case Instruction::And:
7585 case Instruction::Or:
7589 case Instruction::LShr:
7601 switch (
U->getOpcode()) {
7602 case Instruction::Trunc:
7603 case Instruction::ZExt:
7604 case Instruction::SExt:
7605 case Instruction::PtrToInt:
7609 case Instruction::BitCast:
7616 case Instruction::SDiv:
7617 case Instruction::SRem:
7622 case Instruction::GetElementPtr:
7623 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7624 "GEP source element type must be sized");
7625 for (
Value *Index :
U->operands())
7629 case Instruction::IntToPtr:
7632 case Instruction::PHI:
7636 case Instruction::Select: {
7638 auto CanSimplifyToUnknown = [
this,
U]() {
7639 if (
U->getType()->isIntegerTy(1) || isa<ConstantInt>(
U->getOperand(0)))
7642 auto *ICI = dyn_cast<ICmpInst>(
U->getOperand(0));
7649 if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()))
7656 if (CanSimplifyToUnknown())
7659 for (
Value *Inc :
U->operands())
7664 case Instruction::Call:
7665 case Instruction::Invoke:
7666 if (
Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7671 if (
auto *
II = dyn_cast<IntrinsicInst>(U)) {
7672 switch (
II->getIntrinsicID()) {
7673 case Intrinsic::abs:
7676 case Intrinsic::umax:
7677 case Intrinsic::umin:
7678 case Intrinsic::smax:
7679 case Intrinsic::smin:
7680 case Intrinsic::usub_sat:
7681 case Intrinsic::uadd_sat:
7685 case Intrinsic::start_loop_iterations:
7686 case Intrinsic::annotation:
7687 case Intrinsic::ptr_annotation:
7700const SCEV *ScalarEvolution::createSCEV(
Value *V) {
7711 }
else if (
ConstantInt *CI = dyn_cast<ConstantInt>(V))
7713 else if (isa<GlobalAlias>(V))
7715 else if (!isa<ConstantExpr>(V))
7724 switch (BO->Opcode) {
7725 case Instruction::Add: {
7751 if (BO->Opcode == Instruction::Sub)
7759 if (BO->Opcode == Instruction::Sub)
7765 dyn_cast<Instruction>(V));
7766 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7767 NewBO->Opcode != Instruction::Sub)) {
7777 case Instruction::Mul: {
7797 dyn_cast<Instruction>(V));
7798 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7807 case Instruction::UDiv:
7811 case Instruction::URem:
7815 case Instruction::Sub: {
7818 Flags = getNoWrapFlagsFromUB(BO->
Op);
7823 case Instruction::And:
7826 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7829 if (CI->isMinusOne())
7831 const APInt &
A = CI->getValue();
7837 unsigned LZ =
A.countl_zero();
7838 unsigned TZ =
A.countr_zero();
7842 0, &AC,
nullptr, &DT);
7844 APInt EffectiveMask =
7846 if ((LZ != 0 || TZ != 0) && !((~
A & ~Known.
Zero) & EffectiveMask)) {
7849 const SCEV *ShiftedLHS =
nullptr;
7850 if (
auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7851 if (
auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7853 unsigned MulZeros = OpC->getAPInt().countr_zero();
7854 unsigned GCD = std::min(MulZeros, TZ);
7859 auto *NewMul =
getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7881 case Instruction::Or:
7890 case Instruction::Xor:
7891 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7893 if (CI->isMinusOne())
7900 if (
auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7901 if (
ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7902 if (LBO->getOpcode() == Instruction::And &&
7903 LCI->getValue() == CI->getValue())
7905 dyn_cast<SCEVZeroExtendExpr>(
getSCEV(BO->LHS))) {
7907 const SCEV *Z0 =
Z->getOperand();
7914 if (CI->getValue().isMask(Z0TySize))
7920 APInt Trunc = CI->getValue().
trunc(Z0TySize);
7929 case Instruction::Shl:
7931 if (
ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7947 auto MulFlags = getNoWrapFlagsFromUB(BO->
Op);
7961 case Instruction::AShr:
7982 Operator *
L = dyn_cast<Operator>(BO->LHS);
7983 const SCEV *AddTruncateExpr =
nullptr;
7985 const SCEV *AddConstant =
nullptr;
7987 if (L &&
L->getOpcode() == Instruction::Add) {
7993 Operator *LShift = dyn_cast<Operator>(
L->getOperand(0));
7994 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(
L->getOperand(1));
7995 if (LShift && LShift->
getOpcode() == Instruction::Shl) {
7998 ShlAmtCI = dyn_cast<ConstantInt>(LShift->
getOperand(1));
8010 }
else if (L &&
L->getOpcode() == Instruction::Shl) {
8016 ShlAmtCI = dyn_cast<ConstantInt>(
L->getOperand(1));
8020 if (AddTruncateExpr && ShlAmtCI) {
8036 const SCEV *CompositeExpr =
8038 if (
L->getOpcode() != Instruction::Shl)
8039 CompositeExpr =
getAddExpr(CompositeExpr, AddConstant);
8048 switch (
U->getOpcode()) {
8049 case Instruction::Trunc:
8052 case Instruction::ZExt:
8055 case Instruction::SExt:
8057 dyn_cast<Instruction>(V))) {
8065 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8066 Type *Ty =
U->getType();
8074 case Instruction::BitCast:
8080 case Instruction::PtrToInt: {
8083 Type *DstIntTy =
U->getType();
8087 if (isa<SCEVCouldNotCompute>(IntOp))
8091 case Instruction::IntToPtr:
8095 case Instruction::SDiv:
8102 case Instruction::SRem:
8109 case Instruction::GetElementPtr:
8110 return createNodeForGEP(cast<GEPOperator>(U));
8112 case Instruction::PHI:
8113 return createNodeForPHI(cast<PHINode>(U));
8115 case Instruction::Select:
8116 return createNodeForSelectOrPHI(U,
U->getOperand(0),
U->getOperand(1),
8119 case Instruction::Call:
8120 case Instruction::Invoke:
8121 if (
Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8124 if (
auto *
II = dyn_cast<IntrinsicInst>(U)) {
8125 switch (
II->getIntrinsicID()) {
8126 case Intrinsic::abs:
8129 cast<ConstantInt>(
II->getArgOperand(1))->
isOne());
8130 case Intrinsic::umax:
8134 case Intrinsic::umin:
8138 case Intrinsic::smax:
8142 case Intrinsic::smin:
8146 case Intrinsic::usub_sat: {
8152 case Intrinsic::uadd_sat: {
8158 case Intrinsic::start_loop_iterations:
8159 case Intrinsic::annotation:
8160 case Intrinsic::ptr_annotation:
8164 case Intrinsic::vscale:
8181 if (isa<SCEVCouldNotCompute>(ExitCount))
8184 auto *ExitCountType = ExitCount->
getType();
8185 assert(ExitCountType->isIntegerTy());
8187 1 + ExitCountType->getScalarSizeInBits());
8194 if (isa<SCEVCouldNotCompute>(ExitCount))
8200 auto CanAddOneWithoutOverflow = [&]() {
8202 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8213 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8243 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
8244 assert(L->isLoopExiting(ExitingBlock) &&
8245 "Exiting block must actually branch out of the loop!");
8254 const auto *MaxExitCount =
8262 L->getExitingBlocks(ExitingBlocks);
8264 std::optional<unsigned> Res;
8265 for (
auto *ExitingBB : ExitingBlocks) {
8269 Res = (
unsigned)std::gcd(*Res, Multiple);
8271 return Res.value_or(1);
8275 const SCEV *ExitCount) {
8305 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
8306 assert(L->isLoopExiting(ExitingBlock) &&
8307 "Exiting block must actually branch out of the loop!");
8317 return getBackedgeTakenInfo(L).getExact(ExitingBlock,
this);
8319 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock,
this);
8321 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock,
this);
8331 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock,
this,
8334 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock,
this,
8337 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock,
this,
8345 return getPredicatedBackedgeTakenInfo(L).getExact(L,
this, &Preds);
8352 return getBackedgeTakenInfo(L).getExact(L,
this);
8354 return getBackedgeTakenInfo(L).getConstantMax(
this);
8356 return getBackedgeTakenInfo(L).getSymbolicMax(L,
this);
8363 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L,
this, &Preds);
8368 return getPredicatedBackedgeTakenInfo(L).getConstantMax(
this, &Preds);
8372 return getBackedgeTakenInfo(L).isConstantMaxOrZero(
this);
8382 for (
PHINode &PN : Header->phis())
8383 if (Visited.
insert(&PN).second)
8387ScalarEvolution::BackedgeTakenInfo &
8388ScalarEvolution::getPredicatedBackedgeTakenInfo(
const Loop *L) {
8389 auto &BTI = getBackedgeTakenInfo(L);
8390 if (BTI.hasFullInfo())
8393 auto Pair = PredicatedBackedgeTakenCounts.insert({
L, BackedgeTakenInfo()});
8396 return Pair.first->second;
8398 BackedgeTakenInfo
Result =
8399 computeBackedgeTakenCount(L,
true);
8401 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8404ScalarEvolution::BackedgeTakenInfo &
8405ScalarEvolution::getBackedgeTakenInfo(
const Loop *L) {
8411 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator,
bool> Pair =
8412 BackedgeTakenCounts.insert({
L, BackedgeTakenInfo()});
8414 return Pair.first->second;
8419 BackedgeTakenInfo
Result = computeBackedgeTakenCount(L);
8426 if (
Result.hasAnyInfo()) {
8429 auto LoopUsersIt = LoopUsers.find(L);
8430 if (LoopUsersIt != LoopUsers.end())
8432 forgetMemoizedResults(ToForget);
8435 for (
PHINode &PN :
L->getHeader()->phis())
8436 ConstantEvolutionLoopExitValue.erase(&PN);
8444 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8453 BackedgeTakenCounts.clear();
8454 PredicatedBackedgeTakenCounts.clear();
8455 BECountUsers.clear();
8456 LoopPropertiesCache.clear();
8457 ConstantEvolutionLoopExitValue.clear();
8458 ValueExprMap.
clear();
8459 ValuesAtScopes.clear();
8460 ValuesAtScopesUsers.clear();
8461 LoopDispositions.clear();
8462 BlockDispositions.clear();
8463 UnsignedRanges.clear();
8464 SignedRanges.clear();
8465 ExprValueMap.
clear();
8467 ConstantMultipleCache.clear();
8468 PredicatedSCEVRewrites.clear();
8470 FoldCacheUser.clear();
8472void ScalarEvolution::visitAndClearUsers(
8476 while (!Worklist.
empty()) {
8478 if (!
isSCEVable(
I->getType()) && !isa<WithOverflowInst>(
I))
8483 if (It != ValueExprMap.
end()) {
8484 eraseValueFromMap(It->first);
8486 if (
PHINode *PN = dyn_cast<PHINode>(
I))
8487 ConstantEvolutionLoopExitValue.erase(PN);
8501 while (!LoopWorklist.
empty()) {
8505 forgetBackedgeTakenCounts(CurrL,
false);
8506 forgetBackedgeTakenCounts(CurrL,
true);
8509 for (
auto I = PredicatedSCEVRewrites.begin();
8510 I != PredicatedSCEVRewrites.end();) {
8511 std::pair<const SCEV *, const Loop *> Entry =
I->first;
8512 if (Entry.second == CurrL)
8513 PredicatedSCEVRewrites.erase(
I++);
8518 auto LoopUsersItr = LoopUsers.find(CurrL);
8519 if (LoopUsersItr != LoopUsers.end()) {
8520 ToForget.
insert(ToForget.
end(), LoopUsersItr->second.begin(),
8521 LoopUsersItr->second.end());
8526 visitAndClearUsers(Worklist, Visited, ToForget);
8528 LoopPropertiesCache.erase(CurrL);
8531 LoopWorklist.
append(CurrL->begin(), CurrL->end());
8533 forgetMemoizedResults(ToForget);
8550 visitAndClearUsers(Worklist, Visited, ToForget);
8552 forgetMemoizedResults(ToForget);
8564 struct InvalidationRootCollector {
8568 InvalidationRootCollector(
Loop *L) : L(L) {}
8570 bool follow(
const SCEV *S) {
8571 if (
auto *SU = dyn_cast<SCEVUnknown>(S)) {
8572 if (
auto *
I = dyn_cast<Instruction>(SU->getValue()))
8575 }
else if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8576 if (L->contains(AddRec->
getLoop()))
8581 bool isDone()
const {
return false; }
8584 InvalidationRootCollector
C(L);
8586 forgetMemoizedResults(
C.Roots);
8599 BlockDispositions.clear();
8600 LoopDispositions.clear();
8617 while (!Worklist.
empty()) {
8619 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8620 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8621 if (!LoopDispoRemoved && !BlockDispoRemoved)
8623 auto Users = SCEVUsers.find(Curr);
8624 if (
Users != SCEVUsers.end())
8637const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8641 if (!isComplete() || ExitNotTaken.empty())
8652 for (
const auto &ENT : ExitNotTaken) {
8653 const SCEV *BECount = ENT.ExactNotTaken;
8656 "We should only have known counts for exiting blocks that dominate "
8664 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8665 "Predicate should be always true!");
8674const ScalarEvolution::ExitNotTakenInfo *
8675ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8678 for (
const auto &ENT : ExitNotTaken)
8679 if (ENT.ExitingBlock == ExitingBlock) {
8680 if (ENT.hasAlwaysTruePredicate())
8682 else if (Predicates) {
8692const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8695 if (!getConstantMax())
8698 for (
const auto &ENT : ExitNotTaken)
8699 if (!ENT.hasAlwaysTruePredicate()) {
8705 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8706 isa<SCEVConstant>(getConstantMax())) &&
8707 "No point in having a non-constant max backedge taken count!");
8708 return getConstantMax();
8711const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8721 for (
const auto &ENT : ExitNotTaken) {
8722 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8723 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8725 "We should only have known counts for exiting blocks that "
8731 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8732 "Predicate should be always true!");
8735 if (ExitCounts.
empty())
8744bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8746 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
8747 return !ENT.hasAlwaysTruePredicate();
8749 return MaxOrZero && !
any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8756 const SCEV *E,
const SCEV *ConstantMaxNotTaken,
8757 const SCEV *SymbolicMaxNotTaken,
bool MaxOrZero,
8759 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8760 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8771 "Exact is not allowed to be less precise than Constant Max");
8774 "Exact is not allowed to be less precise than Symbolic Max");
8777 "Symbolic Max is not allowed to be less precise than Constant Max");
8780 "No point in having a non-constant max backedge taken count!");
8782 for (
const auto PredList : PredLists)
8783 for (
const auto *
P : PredList) {
8786 assert(!isa<SCEVUnionPredicate>(
P) &&
"Only add leaf predicates here!");
8791 "Backedge count should be int");
8794 "Max backedge count should be int");
8798 const SCEV *ConstantMaxNotTaken,
8799 const SCEV *SymbolicMaxNotTaken,
8802 :
ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8807ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8809 bool IsComplete,
const SCEV *ConstantMax,
bool MaxOrZero)
8810 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8811 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8813 ExitNotTaken.reserve(ExitCounts.
size());
8814 std::transform(ExitCounts.
begin(), ExitCounts.
end(),
8815 std::back_inserter(ExitNotTaken),
8816 [&](
const EdgeExitInfo &EEI) {
8817 BasicBlock *ExitBB = EEI.first;
8818 const ExitLimit &EL = EEI.second;
8819 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8820 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8823 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8824 isa<SCEVConstant>(ConstantMax)) &&
8825 "No point in having a non-constant max backedge taken count!");
8829ScalarEvolution::BackedgeTakenInfo
8830ScalarEvolution::computeBackedgeTakenCount(
const Loop *L,
8831 bool AllowPredicates) {
8833 L->getExitingBlocks(ExitingBlocks);
8835 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8838 bool CouldComputeBECount =
true;
8840 const SCEV *MustExitMaxBECount =
nullptr;
8841 const SCEV *MayExitMaxBECount =
nullptr;
8842 bool MustExitMaxOrZero =
false;
8843 bool IsOnlyExit = ExitingBlocks.
size() == 1;
8852 if (
auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8853 if (
auto *CI = dyn_cast<ConstantInt>(BI->
getCondition())) {
8855 if (ExitIfTrue == CI->
isZero())
8859 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8861 assert((AllowPredicates || EL.Predicates.empty()) &&
8862 "Predicated exit limit when predicates are not allowed!");
8867 ++NumExitCountsComputed;
8871 CouldComputeBECount =
false;
8878 "Exact is known but symbolic isn't?");
8879 ++NumExitCountsNotComputed;
8895 if (!MustExitMaxBECount) {
8896 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8897 MustExitMaxOrZero = EL.MaxOrZero;
8900 EL.ConstantMaxNotTaken);
8904 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8907 EL.ConstantMaxNotTaken);
8911 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8915 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8921 for (
const auto &Pair : ExitCounts) {
8922 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8923 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8924 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8925 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8926 {L, AllowPredicates});
8928 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8929 MaxBECount, MaxOrZero);
8933ScalarEvolution::computeExitLimit(
const Loop *L,
BasicBlock *ExitingBlock,
8934 bool IsOnlyExit,
bool AllowPredicates) {
8935 assert(
L->contains(ExitingBlock) &&
"Exit count for non-loop block?");
8939 if (!Latch || !DT.
dominates(ExitingBlock, Latch))
8943 if (
BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8947 "It should have one successor in loop and one exit block!");
8954 if (
SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8958 if (!
L->contains(SBB)) {
8963 assert(Exit &&
"Exiting block must have at least one exit");
8964 return computeExitLimitFromSingleExitSwitch(
8965 L, SI, Exit, IsOnlyExit);
8972 const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
bool ControlsOnlyExit,
8973 bool AllowPredicates) {
8974 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8975 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8976 ControlsOnlyExit, AllowPredicates);
8979std::optional<ScalarEvolution::ExitLimit>
8980ScalarEvolution::ExitLimitCache::find(
const Loop *L,
Value *ExitCond,
8981 bool ExitIfTrue,
bool ControlsOnlyExit,
8982 bool AllowPredicates) {
8984 (void)this->ExitIfTrue;
8985 (void)this->AllowPredicates;
8987 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8988 this->AllowPredicates == AllowPredicates &&
8989 "Variance in assumed invariant key components!");
8990 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8991 if (Itr == TripCountMap.end())
8992 return std::nullopt;
8996void ScalarEvolution::ExitLimitCache::insert(
const Loop *L,
Value *ExitCond,
8998 bool ControlsOnlyExit,
8999 bool AllowPredicates,
9000 const ExitLimit &EL) {
9001 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9002 this->AllowPredicates == AllowPredicates &&
9003 "Variance in assumed invariant key components!");
9005 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9006 assert(InsertResult.second &&
"Expected successful insertion!");
9012 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
9013 bool ControlsOnlyExit,
bool AllowPredicates) {
9015 if (
auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9019 ExitLimit EL = computeExitLimitFromCondImpl(
9020 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9021 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9026 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
9027 bool ControlsOnlyExit,
bool AllowPredicates) {
9029 if (
auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9030 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
9031 return *LimitFromBinOp;
9035 if (
ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9037 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9038 if (EL.hasFullInfo() || !AllowPredicates)
9042 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9051 if (
ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9077 auto EL = computeExitLimitFromICmp(L, Pred, LHS,
getConstant(NewRHSC),
9078 ControlsOnlyExit, AllowPredicates);
9079 if (EL.hasAnyInfo())
9084 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9087std::optional<ScalarEvolution::ExitLimit>
9088ScalarEvolution::computeExitLimitFromCondFromBinOp(
9089 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
9090 bool ControlsOnlyExit,
bool AllowPredicates) {
9099 return std::nullopt;
9104 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9105 ExitLimit EL0 = computeExitLimitFromCondCached(
9106 Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9108 ExitLimit EL1 = computeExitLimitFromCondCached(
9109 Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9113 const Constant *NeutralElement = ConstantInt::get(ExitCond->
getType(), IsAnd);
9114 if (isa<ConstantInt>(Op1))
9115 return Op1 == NeutralElement ? EL0 : EL1;
9116 if (isa<ConstantInt>(Op0))
9117 return Op0 == NeutralElement ? EL1 : EL0;
9122 if (EitherMayExit) {
9123 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9132 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9134 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9137 EL1.ConstantMaxNotTaken);
9139 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9141 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9144 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9148 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9149 BECount = EL0.ExactNotTaken;
9158 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9159 !isa<SCEVCouldNotCompute>(BECount))
9161 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9162 SymbolicMaxBECount =
9163 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9164 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount,
false,
9169 const Loop *L,
ICmpInst *ExitCond,
bool ExitIfTrue,
bool ControlsOnlyExit,
9170 bool AllowPredicates) {
9182 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9184 if (EL.hasAnyInfo())
9187 auto *ExhaustiveCount =
9188 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9190 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9191 return ExhaustiveCount;
9193 return computeShiftCompareExitLimit(ExitCond->
getOperand(0),
9198 bool ControlsOnlyExit,
bool AllowPredicates) {
9219 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9220 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9227 if (!isa<SCEVCouldNotCompute>(Ret))
return Ret;
9239 auto *InnerLHS =
LHS;
9240 if (
auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9241 InnerLHS = ZExt->getOperand();
9242 if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9278 if (isa<SCEVCouldNotCompute>(LHS))
9283 if (isa<SCEVCouldNotCompute>(RHS))
9286 ExitLimit EL = howFarToZero(
getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9288 if (EL.hasAnyInfo())
9296 if (isa<SCEVCouldNotCompute>(LHS))
9301 if (isa<SCEVCouldNotCompute>(RHS))
9304 ExitLimit EL = howFarToNonZero(
getMinusSCEV(LHS, RHS), L);
9305 if (EL.hasAnyInfo())
return EL;
9317 auto *OldType = dyn_cast<IntegerType>(
LHS->
getType());
9337 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9339 if (EL.hasAnyInfo())
9355 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9357 if (EL.hasAnyInfo())
9369ScalarEvolution::computeExitLimitFromSingleExitSwitch(
const Loop *L,
9372 bool ControlsOnlyExit) {
9373 assert(!
L->contains(ExitingBlock) &&
"Not an exiting block!");
9376 if (
Switch->getDefaultDest() == ExitingBlock)
9380 "Default case must not exit the loop!");
9385 ExitLimit EL = howFarToZero(
getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9386 if (EL.hasAnyInfo())
9397 assert(isa<SCEVConstant>(Val) &&
9398 "Evaluation of SCEV at constant didn't fold correctly?");
9399 return cast<SCEVConstant>(Val)->getValue();
9412 const BasicBlock *Predecessor =
L->getLoopPredecessor();
9418 auto MatchPositiveShift =
9421 using namespace PatternMatch;
9425 OutOpCode = Instruction::LShr;
9427 OutOpCode = Instruction::AShr;
9429 OutOpCode = Instruction::Shl;
9444 auto MatchShiftRecurrence =
9446 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9461 if (MatchPositiveShift(LHS, V, OpC)) {
9462 PostShiftOpCode = OpC;
9467 PNOut = dyn_cast<PHINode>(LHS);
9468 if (!PNOut || PNOut->getParent() !=
L->getHeader())
9471 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9477 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9484 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9489 if (!MatchShiftRecurrence(LHS, PN, OpCode))
9506 case Instruction::AShr: {
9512 auto *Ty = cast<IntegerType>(
RHS->
getType());
9514 StableValue = ConstantInt::get(Ty, 0);
9516 StableValue = ConstantInt::get(Ty, -1,
true);
9522 case Instruction::LShr:
9523 case Instruction::Shl:
9526 StableValue = ConstantInt::get(cast<IntegerType>(
RHS->
getType()), 0);
9533 "Otherwise cannot be an operand to a branch instruction");
9535 if (
Result->isZeroValue()) {
9537 const SCEV *UpperBound =
9548 if (isa<BinaryOperator>(
I) || isa<CmpInst>(
I) ||
9549 isa<SelectInst>(
I) || isa<CastInst>(
I) || isa<GetElementPtrInst>(
I) ||
9550 isa<LoadInst>(
I) || isa<ExtractValueInst>(
I))
9553 if (
const CallInst *CI = dyn_cast<CallInst>(
I))
9554 if (
const Function *F = CI->getCalledFunction())
9563 if (!L->contains(
I))
return false;
9565 if (isa<PHINode>(
I)) {
9568 return L->getHeader() ==
I->getParent();
9589 if (isa<Constant>(
Op))
continue;
9594 PHINode *
P = dyn_cast<PHINode>(OpInst);
9625 if (
PHINode *PN = dyn_cast<PHINode>(
I))
9642 if (
Constant *
C = dyn_cast<Constant>(V))
return C;
9644 if (!
I)
return nullptr;
9655 if (isa<PHINode>(
I))
return nullptr;
9657 std::vector<Constant*>
Operands(
I->getNumOperands());
9659 for (
unsigned i = 0, e =
I->getNumOperands(); i != e; ++i) {
9660 Instruction *Operand = dyn_cast<Instruction>(
I->getOperand(i));
9662 Operands[i] = dyn_cast<Constant>(
I->getOperand(i));
9668 if (!
C)
return nullptr;
9690 if (IncomingVal != CurrentVal) {
9693 IncomingVal = CurrentVal;
9705ScalarEvolution::getConstantEvolutionLoopExitValue(
PHINode *PN,
9708 auto [
I,
Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9719 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
9727 CurrentIterVals[&
PHI] = StartCST;
9729 if (!CurrentIterVals.
count(PN))
9730 return RetVal =
nullptr;
9736 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9739 unsigned IterationNum = 0;
9741 for (; ; ++IterationNum) {
9742 if (IterationNum == NumIterations)
9743 return RetVal = CurrentIterVals[PN];
9752 NextIterVals[PN] = NextPHI;
9754 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9760 for (
const auto &
I : CurrentIterVals) {
9762 if (!
PHI ||
PHI == PN ||
PHI->getParent() != Header)
continue;
9767 for (
const auto &
I : PHIsToCompute) {
9771 Value *BEValue =
PHI->getIncomingValueForBlock(Latch);
9774 if (NextPHI !=
I.second)
9775 StoppedEvolving =
false;
9780 if (StoppedEvolving)
9781 return RetVal = CurrentIterVals[PN];
9783 CurrentIterVals.swap(NextIterVals);
9787const SCEV *ScalarEvolution::computeExitCountExhaustively(
const Loop *L,
9799 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
9802 assert(Latch &&
"Should follow from NumIncomingValues == 2!");
9806 CurrentIterVals[&
PHI] = StartCST;
9808 if (!CurrentIterVals.
count(PN))
9816 for (
unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9817 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9823 if (CondVal->getValue() ==
uint64_t(ExitWhen)) {
9824 ++NumBruteForceTripCountsComputed;
9835 for (
const auto &
I : CurrentIterVals) {
9837 if (!
PHI ||
PHI->getParent() != Header)
continue;
9842 if (NextPHI)
continue;
9844 Value *BEValue =
PHI->getIncomingValueForBlock(Latch);
9847 CurrentIterVals.swap(NextIterVals);
9858 for (
auto &LS : Values)
9860 return LS.second ? LS.second : V;
9865 const SCEV *
C = computeSCEVAtScope(V, L);
9866 for (
auto &LS :
reverse(ValuesAtScopes[V]))
9867 if (LS.first == L) {
9869 if (!isa<SCEVConstant>(
C))
9870 ValuesAtScopesUsers[
C].push_back({L, V});
9881 switch (V->getSCEVType()) {
9887 return cast<SCEVConstant>(V)->getValue();
9889 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9914 assert(!
C->getType()->isPointerTy() &&
9915 "Can only have one pointer, and it must be last");
9942ScalarEvolution::getWithOperands(
const SCEV *S,
9951 auto *AddRec = cast<SCEVAddRecExpr>(S);
9955 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9957 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9977const SCEV *ScalarEvolution::computeSCEVAtScope(
const SCEV *V,
const Loop *L) {
9978 switch (
V->getSCEVType()) {
9989 for (
unsigned i = 0, e = AddRec->
getNumOperands(); i != e; ++i) {
10000 for (++i; i !=
e; ++i)
10005 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10044 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
10046 if (OpAtScope != Ops[i]) {
10054 for (++i; i !=
e; ++i) {
10059 return getWithOperands(V, NewOps);
10073 if (
PHINode *PN = dyn_cast<PHINode>(
I)) {
10074 const Loop *CurrLoop = this->LI[
I->getParent()];
10085 if (BackedgeTakenCount->
isZero()) {
10086 Value *InitValue =
nullptr;
10087 bool MultipleInitValues =
false;
10093 MultipleInitValues =
true;
10098 if (!MultipleInitValues && InitValue)
10103 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10107 unsigned InLoopPred =
10113 if (
auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10118 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10134 bool MadeImprovement =
false;
10149 MadeImprovement |= OrigV != OpV;
10154 assert(
C->getType() ==
Op->getType() &&
"Type mismatch");
10159 if (!MadeImprovement)
10180const SCEV *ScalarEvolution::stripInjectiveFunctions(
const SCEV *S)
const {
10182 return stripInjectiveFunctions(ZExt->getOperand());
10184 return stripInjectiveFunctions(SExt->getOperand());
10203 assert(
A != 0 &&
"A must be non-zero.");
10239 APInt AD =
A.lshr(Mult2).trunc(BW - Mult2);
10259static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10265 LLVM_DEBUG(
dbgs() << __func__ <<
": analyzing quadratic addrec: "
10266 << *AddRec <<
'\n');
10269 if (!LC || !MC || !
NC) {
10270 LLVM_DEBUG(
dbgs() << __func__ <<
": coefficients are not constant\n");
10271 return std::nullopt;
10277 assert(!
N.isZero() &&
"This is not a quadratic addrec");
10285 N =
N.sext(NewWidth);
10286 M = M.sext(NewWidth);
10287 L = L.sext(NewWidth);
10304 <<
"x + " <<
C <<
", coeff bw: " << NewWidth
10305 <<
", multiplied by " <<
T <<
'\n');
10314 std::optional<APInt>
Y) {
10316 unsigned W = std::max(
X->getBitWidth(),
Y->getBitWidth());
10319 return XW.
slt(YW) ? *
X : *
Y;
10322 return std::nullopt;
10323 return X ? *
X : *
Y;
10340 return std::nullopt;
10341 unsigned W =
X->getBitWidth();
10361static std::optional<APInt>
10367 return std::nullopt;
10370 LLVM_DEBUG(
dbgs() << __func__ <<
": solving for unsigned overflow\n");
10371 std::optional<APInt>
X =
10374 return std::nullopt;
10379 return std::nullopt;
10394static std::optional<APInt>
10398 "Starting value of addrec should be 0");
10399 LLVM_DEBUG(
dbgs() << __func__ <<
": solving boundary crossing for range "
10400 <<
Range <<
", addrec " << *AddRec <<
'\n');
10404 "Addrec's initial value should be in range");
10410 return std::nullopt;
10420 auto SolveForBoundary =
10421 [&](
APInt Bound) -> std::pair<std::optional<APInt>,
bool> {
10424 LLVM_DEBUG(
dbgs() <<
"SolveQuadraticAddRecRange: checking boundary "
10425 << Bound <<
" (before multiplying by " << M <<
")\n");
10428 std::optional<APInt> SO;
10431 "signed overflow\n");
10435 "unsigned overflow\n");
10436 std::optional<APInt> UO =
10439 auto LeavesRange = [&] (
const APInt &
X) {
10456 return {std::nullopt,
false};
10461 if (LeavesRange(*Min))
10462 return { Min,
true };
10463 std::optional<APInt> Max = Min == SO ? UO : SO;
10464 if (LeavesRange(*Max))
10465 return { Max,
true };
10468 return {std::nullopt,
true};
10475 auto SL = SolveForBoundary(
Lower);
10476 auto SU = SolveForBoundary(
Upper);
10479 if (!SL.second || !SU.second)
10480 return std::nullopt;
10525 bool ControlsOnlyExit,
10526 bool AllowPredicates) {
10537 if (
C->getValue()->isZero())
return C;
10542 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10544 if (!AddRec && AllowPredicates)
10550 if (!AddRec || AddRec->
getLoop() != L)
10561 return ExitLimit(R, R, R,
false, Predicates);
10626 return ExitLimit(Distance,
getConstant(MaxBECount), Distance,
false,
10652 const SCEV *SymbolicMax =
10653 isa<SCEVCouldNotCompute>(
Exact) ? ConstantMax :
Exact;
10654 return ExitLimit(
Exact, ConstantMax, SymbolicMax,
false, Predicates);
10658 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10663 AllowPredicates ? &Predicates :
nullptr, *
this);
10670 auto *S = isa<SCEVCouldNotCompute>(E) ?
M : E;
10671 return ExitLimit(E, M, S,
false, Predicates);
10675ScalarEvolution::howFarToNonZero(
const SCEV *V,
const Loop *L) {
10683 if (!
C->getValue()->isZero())
10693std::pair<const BasicBlock *, const BasicBlock *>
10694ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(
const BasicBlock *BB)
10706 return {
L->getLoopPredecessor(),
L->getHeader()};
10708 return {
nullptr, BB};
10717 if (
A ==
B)
return true;
10723 return A->isIdenticalTo(
B) && (isa<BinaryOperator>(
A) || isa<GetElementPtrInst>(
A));
10730 if (
const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10731 if (
const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10732 if (ComputesEqualValues(AI, BI))
10741 if (!
Add ||
Add->getNumOperands() != 2)
10743 if (
auto *ME = dyn_cast<SCEVMulExpr>(
Add->getOperand(0));
10744 ME && ME->getNumOperands() == 2 && ME->getOperand(0)->isAllOnesValue()) {
10745 LHS =
Add->getOperand(1);
10746 RHS = ME->getOperand(1);
10749 if (
auto *ME = dyn_cast<SCEVMulExpr>(
Add->getOperand(1));
10750 ME && ME->getNumOperands() == 2 && ME->getOperand(0)->isAllOnesValue()) {
10751 LHS =
Add->getOperand(0);
10752 RHS = ME->getOperand(1);
10760 bool Changed =
false;
10763 auto TrivialCase = [&](
bool TriviallyTrue) {
10777 return TrivialCase(
false);
10778 return TrivialCase(
true);
10801 const APInt &
RA = RC->getAPInt();
10803 bool SimplifiedByConstantRange =
false;
10808 return TrivialCase(
true);
10810 return TrivialCase(
false);
10819 Changed = SimplifiedByConstantRange =
true;
10823 if (!SimplifiedByConstantRange) {
10840 assert(!
RA.isMinValue() &&
"Should have been caught earlier!");
10846 assert(!
RA.isMaxValue() &&
"Should have been caught earlier!");
10852 assert(!
RA.isMinSignedValue() &&
"Should have been caught earlier!");
10858 assert(!
RA.isMaxSignedValue() &&
"Should have been caught earlier!");
10870 return TrivialCase(
true);
10872 return TrivialCase(
false);
10961 if (
const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10968 auto NonRecursive = [
this, OrNegative](
const SCEV *S) {
10969 if (
auto *
C = dyn_cast<SCEVConstant>(S))
10970 return C->getAPInt().isPowerOf2() ||
10971 (OrNegative &&
C->getAPInt().isNegatedPowerOf2());
10974 return isa<SCEVVScale>(S) && F.
hasFnAttribute(Attribute::VScaleRange);
10977 if (NonRecursive(S))
10980 auto *
Mul = dyn_cast<SCEVMulExpr>(S);
10986std::pair<const SCEV *, const SCEV *>
10989 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *
this);
10991 return { Start, Start };
10993 const SCEV *
PostInc = SCEVPostIncRewriter::rewrite(S, L, *
this);
11002 getUsedLoops(
LHS, LoopsUsed);
11003 getUsedLoops(
RHS, LoopsUsed);
11005 if (LoopsUsed.
empty())
11010 for (
const auto *L1 : LoopsUsed)
11011 for (
const auto *L2 : LoopsUsed)
11013 DT.
dominates(L2->getHeader(), L1->getHeader())) &&
11014 "Domination relationship is not a linear order");
11044 SplitRHS.second) &&
11056 if (isKnownPredicateViaSplitting(Pred,
LHS,
RHS))
11060 return isKnownViaNonRecursiveReasoning(Pred,
LHS,
RHS);
11070 return std::nullopt;
11085 if (KnownWithoutContext)
11086 return KnownWithoutContext;
11093 return std::nullopt;
11099 const Loop *L =
LHS->getLoop();
11104std::optional<ScalarEvolution::MonotonicPredicateType>
11107 auto Result = getMonotonicPredicateTypeImpl(
LHS, Pred);
11113 auto ResultSwapped =
11116 assert(*ResultSwapped != *Result &&
11117 "monotonicity should flip as we flip the predicate");
11124std::optional<ScalarEvolution::MonotonicPredicateType>
11125ScalarEvolution::getMonotonicPredicateTypeImpl(
const SCEVAddRecExpr *LHS,
11139 return std::nullopt;
11143 "Should be greater or less!");
11147 if (!
LHS->hasNoUnsignedWrap())
11148 return std::nullopt;
11152 "Relational predicate is either signed or unsigned!");
11153 if (!
LHS->hasNoSignedWrap())
11154 return std::nullopt;
11156 const SCEV *Step =
LHS->getStepRecurrence(*
this);
11164 return std::nullopt;
11167std::optional<ScalarEvolution::LoopInvariantPredicate>
11174 return std::nullopt;
11181 if (!ArLHS || ArLHS->
getLoop() != L)
11182 return std::nullopt;
11186 return std::nullopt;
11212 return std::nullopt;
11249 return std::nullopt;
11252std::optional<ScalarEvolution::LoopInvariantPredicate>
11257 Pred,
LHS,
RHS, L, CtxI, MaxIter))
11259 if (
auto *
UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11265 for (
auto *
Op :
UMin->operands())
11269 return std::nullopt;
11272std::optional<ScalarEvolution::LoopInvariantPredicate>
11287 return std::nullopt;
11293 auto *AR = dyn_cast<SCEVAddRecExpr>(
LHS);
11294 if (!AR || AR->
getLoop() != L)
11295 return std::nullopt;
11299 return std::nullopt;
11305 if (Step != One && Step != MinusOne)
11306 return std::nullopt;
11312 return std::nullopt;
11318 return std::nullopt;
11326 if (Step == MinusOne)
11330 return std::nullopt;
11336bool ScalarEvolution::isKnownPredicateViaConstantRanges(
CmpPredicate Pred,
11347 return RangeLHS.
icmp(Pred, RangeRHS);
11358 if (CheckRanges(SL, SR))
11362 if (CheckRanges(UL, UR))
11371 return CheckRanges(SL, SR);
11376 return CheckRanges(UL, UR);
11379bool ScalarEvolution::isKnownPredicateViaNoOverflow(
CmpPredicate Pred,
11386 auto MatchBinaryAddToConst = [
this](
const SCEV *
X,
const SCEV *
Y,
11389 const SCEV *XNonConstOp, *XConstOp;
11390 const SCEV *YNonConstOp, *YConstOp;
11394 if (!splitBinaryAdd(
X, XConstOp, XNonConstOp, XFlagsPresent)) {
11397 XFlagsPresent = ExpectedFlags;
11399 if (!isa<SCEVConstant>(XConstOp) ||
11400 (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11403 if (!splitBinaryAdd(
Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11406 YFlagsPresent = ExpectedFlags;
11409 if (!isa<SCEVConstant>(YConstOp) ||
11410 (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11413 if (YNonConstOp != XNonConstOp)
11416 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11417 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11472bool ScalarEvolution::isKnownPredicateViaSplitting(
CmpPredicate Pred,
11495 const SCEV *LHS,
const SCEV *RHS) {
11504 return match(&
I, m_Intrinsic<Intrinsic::experimental_guard>(
11506 isImpliedCond(Pred, LHS, RHS, Condition,
false);
11525 "This cannot be done on broken IR!");
11528 if (isKnownViaNonRecursiveReasoning(Pred,
LHS,
RHS))
11537 if (LoopContinuePredicate && LoopContinuePredicate->
isConditional() &&
11538 isImpliedCond(Pred,
LHS,
RHS,
11540 LoopContinuePredicate->
getSuccessor(0) != L->getHeader()))
11545 if (WalkingBEDominatingConds)
11551 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11552 const SCEV *LatchBECount = BETakenInfo.getExact(Latch,
this);
11559 const SCEV *LoopCounter =
11570 auto *CI = cast<CallInst>(AssumeVH);
11574 if (isImpliedCond(Pred,
LHS,
RHS, CI->getArgOperand(0),
false))
11578 if (isImpliedViaGuard(Latch, Pred,
LHS,
RHS))
11581 for (
DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11582 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11583 assert(DTN &&
"should reach the loop header before reaching the root!");
11586 if (isImpliedViaGuard(BB, Pred,
LHS,
RHS))
11594 if (!ContinuePredicate || !ContinuePredicate->
isConditional())
11610 if (isImpliedCond(Pred,
LHS,
RHS, Condition,
11628 "This cannot be done on broken IR!");
11636 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11637 bool ProvedNonStrictComparison =
false;
11638 bool ProvedNonEquality =
false;
11641 if (!ProvedNonStrictComparison)
11642 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11643 if (!ProvedNonEquality)
11645 if (ProvedNonStrictComparison && ProvedNonEquality)
11650 if (ProvingStrictComparison) {
11652 return isKnownViaNonRecursiveReasoning(
P,
LHS,
RHS);
11654 if (SplitAndProve(ProofFn))
11659 auto ProveViaCond = [&](
const Value *Condition,
bool Inverse) {
11661 if (isImpliedCond(Pred,
LHS,
RHS, Condition,
Inverse, CtxI))
11663 if (ProvingStrictComparison) {
11667 if (SplitAndProve(ProofFn))
11678 if (ContainingLoop && ContainingLoop->
getHeader() == BB)
11682 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11683 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11685 dyn_cast<BranchInst>(Pair.first->getTerminator());
11698 auto *CI = cast<CallInst>(AssumeVH);
11702 if (ProveViaCond(CI->getArgOperand(0),
false))
11708 F.
getParent(), Intrinsic::experimental_guard);
11710 for (
const auto *GU : GuardDecl->users())
11711 if (
const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11713 if (ProveViaCond(Guard->getArgOperand(0),
false))
11728 "LHS is not available at Loop Entry");
11730 "RHS is not available at Loop Entry");
11732 if (isKnownViaNonRecursiveReasoning(Pred,
LHS,
RHS))
11743 if (FoundCondValue ==
11747 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11751 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11754 const Value *Op0, *Op1;
11757 return isImpliedCond(Pred, LHS, RHS, Op0,
Inverse, CtxI) ||
11758 isImpliedCond(Pred, LHS, RHS, Op1,
Inverse, CtxI);
11761 return isImpliedCond(Pred, LHS, RHS, Op0,
Inverse, CtxI) ||
11762 isImpliedCond(Pred, LHS, RHS, Op1,
Inverse, CtxI);
11765 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11766 if (!ICI)
return false;
11779 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11784 const SCEV *FoundLHS,
const SCEV *FoundRHS,
11795 auto *WideType = FoundLHS->
getType();
11805 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11806 TruncFoundRHS, CtxI))
11832 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11836bool ScalarEvolution::isImpliedCondBalancedTypes(
11841 "Types should be balanced!");
11848 if (FoundLHS == FoundRHS)
11852 if (LHS == FoundRHS || RHS == FoundLHS) {
11853 if (isa<SCEVConstant>(RHS)) {
11865 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11881 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11882 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11884 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11885 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11892 FoundLHS, FoundRHS, CtxI))
11897 isImpliedCondOperands(Pred, LHS, RHS,
getNotSCEV(FoundLHS),
11906 assert(P1 != P2 &&
"Handled earlier!");
11910 if (IsSignFlippedPredicate(Pred, FoundPred)) {
11915 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11918 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11919 const SCEV *CanonicalLHS =
LHS, *CanonicalRHS =
RHS,
11920 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11925 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11936 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11937 CanonicalRHS, CanonicalFoundLHS,
11938 CanonicalFoundRHS);
11943 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11944 CanonicalRHS, CanonicalFoundLHS,
11945 CanonicalFoundRHS);
11950 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11953 const SCEV *
V =
nullptr;
11955 if (isa<SCEVConstant>(FoundLHS)) {
11956 C = cast<SCEVConstant>(FoundLHS);
11959 C = cast<SCEVConstant>(FoundRHS);
11971 if (Min ==
C->getAPInt()) {
11976 APInt SharperMin = Min + 1;
11983 if (isImpliedCondOperands(Pred, LHS, RHS, V,
getConstant(SharperMin),
11999 if (isImpliedCondOperands(Pred, LHS, RHS, V,
getConstant(Min), CtxI))
12028 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12032 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12035 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12042bool ScalarEvolution::splitBinaryAdd(
const SCEV *Expr,
12045 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
12046 if (!AE || AE->getNumOperands() != 2)
12049 L = AE->getOperand(0);
12050 R = AE->getOperand(1);
12051 Flags = AE->getNoWrapFlags();
12055std::optional<APInt>
12062 APInt DiffMul(BW, 1);
12065 for (
unsigned I = 0;
I < 8; ++
I) {
12070 if (isa<SCEVAddRecExpr>(
Less) && isa<SCEVAddRecExpr>(More)) {
12071 const auto *LAR = cast<SCEVAddRecExpr>(
Less);
12072 const auto *MAR = cast<SCEVAddRecExpr>(More);
12074 if (LAR->getLoop() != MAR->getLoop())
12075 return std::nullopt;
12079 if (!LAR->isAffine() || !MAR->isAffine())
12080 return std::nullopt;
12082 if (LAR->getStepRecurrence(*
this) != MAR->getStepRecurrence(*
this))
12083 return std::nullopt;
12085 Less = LAR->getStart();
12086 More = MAR->getStart();
12091 auto MatchConstMul =
12092 [](
const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12093 auto *M = dyn_cast<SCEVMulExpr>(S);
12094 if (!M || M->getNumOperands() != 2 ||
12095 !isa<SCEVConstant>(M->getOperand(0)))
12096 return std::nullopt;
12098 {M->getOperand(1), cast<SCEVConstant>(M->getOperand(0))->getAPInt()}};
12100 if (
auto MatchedMore = MatchConstMul(More)) {
12101 if (
auto MatchedLess = MatchConstMul(
Less)) {
12102 if (MatchedMore->second == MatchedLess->second) {
12103 More = MatchedMore->first;
12104 Less = MatchedLess->first;
12105 DiffMul *= MatchedMore->second;
12114 if (
auto *
C = dyn_cast<SCEVConstant>(S)) {
12116 Diff +=
C->getAPInt() * DiffMul;
12119 Diff -=
C->getAPInt() * DiffMul;
12122 Multiplicity[S] +=
Mul;
12124 auto Decompose = [&](
const SCEV *S,
int Mul) {
12125 if (isa<SCEVAddExpr>(S)) {
12131 Decompose(More, 1);
12132 Decompose(
Less, -1);
12136 const SCEV *NewMore =
nullptr, *NewLess =
nullptr;
12137 for (
const auto &[S,
Mul] : Multiplicity) {
12142 return std::nullopt;
12144 }
else if (
Mul == -1) {
12146 return std::nullopt;
12149 return std::nullopt;
12153 if (NewMore == More || NewLess ==
Less)
12154 return std::nullopt;
12160 if (!More && !
Less)
12164 if (!More || !
Less)
12165 return std::nullopt;
12169 return std::nullopt;
12172bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12192 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12196 if (!L->contains(ContextBB) || !DT.
dominates(ContextBB, L->getLoopLatch()))
12200 return isImpliedCondOperands(Pred, LHS, RHS, AR->
getStart(), FoundRHS);
12203 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12207 if (!L->contains(ContextBB) || !DT.
dominates(ContextBB, L->getLoopLatch()))
12211 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->
getStart());
12217bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
CmpPredicate Pred,
12220 const SCEV *FoundLHS,
12221 const SCEV *FoundRHS) {
12225 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12229 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12230 if (!AddRecFoundLHS)
12237 const Loop *
L = AddRecFoundLHS->getLoop();
12238 if (L != AddRecLHS->getLoop())
12277 if (!RDiff || *LDiff != *RDiff)
12280 if (LDiff->isMinValue())
12283 APInt FoundRHSLimit;
12286 FoundRHSLimit = -(*RDiff);
12298bool ScalarEvolution::isImpliedViaMerge(
CmpPredicate Pred,
const SCEV *LHS,
12299 const SCEV *RHS,
const SCEV *FoundLHS,
12300 const SCEV *FoundRHS,
unsigned Depth) {
12301 const PHINode *LPhi =
nullptr, *RPhi =
nullptr;
12305 bool Erased = PendingMerges.erase(LPhi);
12306 assert(Erased &&
"Failed to erase LPhi!");
12310 bool Erased = PendingMerges.erase(RPhi);
12311 assert(Erased &&
"Failed to erase RPhi!");
12317 if (
const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12318 if (
auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12319 if (!PendingMerges.insert(Phi).second)
12323 if (
const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12324 if (
auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12333 if (!PendingMerges.insert(Phi).second)
12339 if (!LPhi && !RPhi)
12350 assert(LPhi &&
"LPhi should definitely be a SCEVUnknown Phi!");
12354 auto ProvedEasily = [&](
const SCEV *
S1,
const SCEV *S2) {
12355 return isKnownViaNonRecursiveReasoning(Pred,
S1, S2) ||
12356 isImpliedCondOperandsViaRanges(Pred,
S1, S2, Pred, FoundLHS, FoundRHS) ||
12357 isImpliedViaOperations(Pred,
S1, S2, FoundLHS, FoundRHS,
Depth);
12360 if (RPhi && RPhi->getParent() == LBB) {
12367 const SCEV *
R =
getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12368 if (!ProvedEasily(L, R))
12379 auto *RLoop = RAR->
getLoop();
12380 auto *Predecessor = RLoop->getLoopPredecessor();
12381 assert(Predecessor &&
"Loop with AddRec with no predecessor?");
12383 if (!ProvedEasily(L1, RAR->
getStart()))
12385 auto *Latch = RLoop->getLoopLatch();
12386 assert(Latch &&
"Loop with AddRec with no latch?");
12404 if (!ProvedEasily(L, RHS))
12411bool ScalarEvolution::isImpliedCondOperandsViaShift(
CmpPredicate Pred,
12414 const SCEV *FoundLHS,
12415 const SCEV *FoundRHS) {
12418 if (RHS == FoundRHS) {
12423 if (LHS != FoundLHS)
12426 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12430 Value *Shiftee, *ShiftValue;
12432 using namespace PatternMatch;
12433 if (
match(SUFoundRHS->getValue(),
12435 auto *ShifteeS =
getSCEV(Shiftee);
12453bool ScalarEvolution::isImpliedCondOperands(
CmpPredicate Pred,
const SCEV *LHS,
12455 const SCEV *FoundLHS,
12456 const SCEV *FoundRHS,
12458 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS, FoundRHS))
12461 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12464 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12467 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12471 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12472 FoundLHS, FoundRHS);
12476template <
typename MinMaxExprType>
12478 const SCEV *Candidate) {
12479 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12483 return is_contained(MinMaxExpr->operands(), Candidate);
12521 const SCEV *LHS,
const SCEV *RHS) {
12532 IsMinMaxConsistingOf<SCEVSMinExpr>(
LHS,
RHS) ||
12534 IsMinMaxConsistingOf<SCEVSMaxExpr>(
RHS,
LHS);
12543 IsMinMaxConsistingOf<SCEVUMinExpr>(
LHS,
RHS) ||
12545 IsMinMaxConsistingOf<SCEVUMaxExpr>(
RHS,
LHS);
12551bool ScalarEvolution::isImpliedViaOperations(
CmpPredicate Pred,
const SCEV *LHS,
12553 const SCEV *FoundLHS,
12554 const SCEV *FoundRHS,
12558 "LHS and RHS have different sizes?");
12561 "FoundLHS and FoundRHS have different sizes?");
12593 auto GetOpFromSExt = [&](
const SCEV *S) {
12594 if (
auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12595 return Ext->getOperand();
12602 auto *OrigLHS =
LHS;
12603 auto *OrigFoundLHS = FoundLHS;
12604 LHS = GetOpFromSExt(LHS);
12605 FoundLHS = GetOpFromSExt(FoundLHS);
12608 auto IsSGTViaContext = [&](
const SCEV *
S1,
const SCEV *S2) {
12611 FoundRHS,
Depth + 1);
12614 if (
auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12624 if (!LHSAddExpr->hasNoSignedWrap())
12627 auto *LL = LHSAddExpr->getOperand(0);
12628 auto *LR = LHSAddExpr->getOperand(1);
12632 auto IsSumGreaterThanRHS = [&](
const SCEV *
S1,
const SCEV *S2) {
12633 return IsSGTViaContext(
S1, MinusOne) && IsSGTViaContext(S2, RHS);
12638 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12640 }
else if (
auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12655 if (!isa<ConstantInt>(LR))
12658 auto *Denominator = cast<SCEVConstant>(
getSCEV(LR));
12663 if (!Numerator || Numerator->getType() != FoundLHS->
getType())
12671 auto *DTy = Denominator->getType();
12672 auto *FRHSTy = FoundRHS->
getType();
12673 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12692 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12703 auto *NegDenomMinusOne =
getMinusSCEV(MinusOne, DenominatorExt);
12705 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12713 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS,
Depth + 1))
12746bool ScalarEvolution::isKnownViaNonRecursiveReasoning(
CmpPredicate Pred,
12750 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12753 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12756bool ScalarEvolution::isImpliedCondOperandsHelper(
CmpPredicate Pred,
12759 const SCEV *FoundLHS,
12760 const SCEV *FoundRHS) {
12796 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12802bool ScalarEvolution::isImpliedCondOperandsViaRanges(
12804 const SCEV *FoundLHS,
const SCEV *FoundRHS) {
12805 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12814 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12826 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12829 return LHSRange.
icmp(Pred, ConstRHS);
12832bool ScalarEvolution::canIVOverflowOnLT(
const SCEV *RHS,
const SCEV *Stride,
12845 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12853 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12856bool ScalarEvolution::canIVOverflowOnGT(
const SCEV *RHS,
const SCEV *Stride,
12868 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12876 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12888const SCEV *ScalarEvolution::computeMaxBECountForLT(
const SCEV *Start,
12889 const SCEV *Stride,
12916 : APIntOps::umax(One, MinStride);
12920 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12931 : APIntOps::umax(MaxEnd, MinStart);
12938ScalarEvolution::howManyLessThans(
const SCEV *LHS,
const SCEV *RHS,
12939 const Loop *L,
bool IsSigned,
12940 bool ControlsOnlyExit,
bool AllowPredicates) {
12944 bool PredicatedIV =
false;
12946 if (
auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12947 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12949 auto canProveNUW = [&]() {
12952 if (!ControlsOnlyExit)
12973 Limit = Limit.
zext(OuterBitWidth);
12985 Type *Ty = ZExt->getType();
12987 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, 0),
12989 IV = dyn_cast<SCEVAddRecExpr>(S);
12996 if (!
IV && AllowPredicates) {
13001 PredicatedIV =
true;
13005 if (!
IV ||
IV->getLoop() != L || !
IV->isAffine())
13019 bool NoWrap = ControlsOnlyExit &&
IV->getNoWrapFlags(WrapType);
13022 const SCEV *Stride =
IV->getStepRecurrence(*
this);
13027 if (!PositiveStride) {
13079 auto wouldZeroStrideBeUB = [&]() {
13091 if (!wouldZeroStrideBeUB()) {
13095 }
else if (!NoWrap) {
13098 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13111 const SCEV *Start =
IV->getStart();
13117 const SCEV *OrigStart = Start;
13119 if (Start->getType()->isPointerTy()) {
13121 if (isa<SCEVCouldNotCompute>(Start))
13126 if (isa<SCEVCouldNotCompute>(RHS))
13130 const SCEV *
End =
nullptr, *BECount =
nullptr,
13131 *BECountIfBackedgeTaken =
nullptr;
13133 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13134 if (PositiveStride && RHSAddRec !=
nullptr && RHSAddRec->getLoop() == L &&
13135 RHSAddRec->getNoWrapFlags()) {
13148 const SCEV *RHSStart = RHSAddRec->getStart();
13149 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*
this);
13170 BECountIfBackedgeTaken =
13175 if (BECount ==
nullptr) {
13180 const SCEV *MaxBECount = computeMaxBECountForLT(
13183 MaxBECount,
false , Predicates);
13190 auto *OrigStartMinusStride =
getMinusSCEV(OrigStart, Stride);
13217 const SCEV *Numerator =
13223 auto canProveRHSGreaterThanEqualStart = [&]() {
13242 auto *StartMinusOne =
13249 if (canProveRHSGreaterThanEqualStart()) {
13264 BECountIfBackedgeTaken =
13280 bool MayAddOverflow = [&] {
13326 if (Start == Stride || Start ==
getMinusSCEV(Stride, One)) {
13340 if (!MayAddOverflow) {
13352 const SCEV *ConstantMaxBECount;
13353 bool MaxOrZero =
false;
13354 if (isa<SCEVConstant>(BECount)) {
13355 ConstantMaxBECount = BECount;
13356 }
else if (BECountIfBackedgeTaken &&
13357 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13361 ConstantMaxBECount = BECountIfBackedgeTaken;
13364 ConstantMaxBECount = computeMaxBECountForLT(
13368 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13369 !isa<SCEVCouldNotCompute>(BECount))
13372 const SCEV *SymbolicMaxBECount =
13373 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13374 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13379 const SCEV *LHS,
const SCEV *RHS,
const Loop *L,
bool IsSigned,
13380 bool ControlsOnlyExit,
bool AllowPredicates) {
13387 if (!
IV && AllowPredicates)
13394 if (!
IV ||
IV->getLoop() != L || !
IV->isAffine())
13398 bool NoWrap = ControlsOnlyExit &&
IV->getNoWrapFlags(WrapType);
13411 if (!Stride->
isOne() && !NoWrap)
13412 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13415 const SCEV *Start =
IV->getStart();
13427 if (Start->getType()->isPointerTy()) {
13429 if (isa<SCEVCouldNotCompute>(Start))
13432 if (
End->getType()->isPointerTy()) {
13434 if (isa<SCEVCouldNotCompute>(
End))
13462 const SCEV *ConstantMaxBECount =
13463 isa<SCEVConstant>(BECount)
13468 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13469 ConstantMaxBECount = BECount;
13470 const SCEV *SymbolicMaxBECount =
13471 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13473 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount,
false,
13483 if (
const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13484 if (!SC->getValue()->isZero()) {
13488 getNoWrapFlags(FlagNW));
13489 if (
const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13490 return ShiftedAddRec->getNumIterationsInRange(
13498 if (
any_of(operands(), [](
const SCEV *
Op) {
return !isa<SCEVConstant>(
Op); }))
13518 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13536 "Linear scev computation is off in a bad way!");
13540 if (isQuadratic()) {
13550 assert(getNumOperands() > 1 &&
"AddRec with zero step?");
13560 for (
unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13566 const SCEV *
Last = getOperand(getNumOperands() - 1);
13567 assert(!
Last->isZero() &&
"Recurrency with zero step?");
13569 return cast<SCEVAddRecExpr>(SE.
getAddRecExpr(Ops, getLoop(),
13576 if (
const auto *SU = dyn_cast<SCEVUnknown>(S))
13577 return isa<UndefValue>(SU->
getValue());
13585 if (
const auto *SU = dyn_cast<SCEVUnknown>(S))
13594 if (
StoreInst *Store = dyn_cast<StoreInst>(Inst))
13595 Ty = Store->getValueOperand()->getType();
13596 else if (
LoadInst *Load = dyn_cast<LoadInst>(Inst))
13597 Ty = Load->getType();
13609void ScalarEvolution::SCEVCallbackVH::deleted() {
13610 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
13611 if (
PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13612 SE->ConstantEvolutionLoopExitValue.erase(PN);
13613 SE->eraseValueFromMap(getValPtr());
13617void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(
Value *V) {
13618 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
13637 :
F(
F),
DL(
F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
13639 LoopDispositions(64), BlockDispositions(64) {
13651 F.getParent(), Intrinsic::experimental_guard);
13652 HasGuards = GuardDecl && !GuardDecl->use_empty();
13656 :
F(Arg.
F),
DL(Arg.
DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
13657 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(
std::
move(Arg.CouldNotCompute)),
13658 ValueExprMap(
std::
move(Arg.ValueExprMap)),
13659 PendingLoopPredicates(
std::
move(Arg.PendingLoopPredicates)),
13660 PendingPhiRanges(
std::
move(Arg.PendingPhiRanges)),
13661 PendingMerges(
std::
move(Arg.PendingMerges)),
13662 ConstantMultipleCache(
std::
move(Arg.ConstantMultipleCache)),
13663 BackedgeTakenCounts(
std::
move(Arg.BackedgeTakenCounts)),
13664 PredicatedBackedgeTakenCounts(
13665 std::
move(Arg.PredicatedBackedgeTakenCounts)),
13666 BECountUsers(
std::
move(Arg.BECountUsers)),
13667 ConstantEvolutionLoopExitValue(
13668 std::
move(Arg.ConstantEvolutionLoopExitValue)),
13669 ValuesAtScopes(
std::
move(Arg.ValuesAtScopes)),
13670 ValuesAtScopesUsers(
std::
move(Arg.ValuesAtScopesUsers)),
13671 LoopDispositions(
std::
move(Arg.LoopDispositions)),
13672 LoopPropertiesCache(
std::
move(Arg.LoopPropertiesCache)),
13673 BlockDispositions(
std::
move(Arg.BlockDispositions)),
13674 SCEVUsers(
std::
move(Arg.SCEVUsers)),
13675 UnsignedRanges(
std::
move(Arg.UnsignedRanges)),
13676 SignedRanges(
std::
move(Arg.SignedRanges)),
13677 UniqueSCEVs(
std::
move(Arg.UniqueSCEVs)),
13678 UniquePreds(
std::
move(Arg.UniquePreds)),
13679 SCEVAllocator(
std::
move(Arg.SCEVAllocator)),
13680 LoopUsers(
std::
move(Arg.LoopUsers)),
13681 PredicatedSCEVRewrites(
std::
move(Arg.PredicatedSCEVRewrites)),
13682 FirstUnknown(Arg.FirstUnknown) {
13683 Arg.FirstUnknown =
nullptr;
13692 Tmp->~SCEVUnknown();
13694 FirstUnknown =
nullptr;
13696 ExprValueMap.
clear();
13697 ValueExprMap.
clear();
13699 BackedgeTakenCounts.clear();
13700 PredicatedBackedgeTakenCounts.clear();
13702 assert(PendingLoopPredicates.empty() &&
"isImpliedCond garbage");
13703 assert(PendingPhiRanges.empty() &&
"getRangeRef garbage");
13704 assert(PendingMerges.empty() &&
"isImpliedViaMerge garbage");
13705 assert(!WalkingBEDominatingConds &&
"isLoopBackedgeGuardedByCond garbage!");
13706 assert(!ProvingSplitPredicate &&
"ProvingSplitPredicate garbage!");
13716 if (isa<SCEVConstant>(S))
13728 L->getHeader()->printAsOperand(
OS,
false);
13732 L->getExitingBlocks(ExitingBlocks);
13733 if (ExitingBlocks.
size() != 1)
13734 OS <<
"<multiple exits> ";
13737 if (!isa<SCEVCouldNotCompute>(BTC)) {
13738 OS <<
"backedge-taken count is ";
13741 OS <<
"Unpredictable backedge-taken count.";
13744 if (ExitingBlocks.
size() > 1)
13745 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
13746 OS <<
" exit count for " << ExitingBlock->
getName() <<
": ";
13749 if (isa<SCEVCouldNotCompute>(EC)) {
13753 if (!isa<SCEVCouldNotCompute>(EC)) {
13754 OS <<
"\n predicated exit count for " << ExitingBlock->
getName()
13757 OS <<
"\n Predicates:\n";
13758 for (
const auto *
P : Predicates)
13766 L->getHeader()->printAsOperand(
OS,
false);
13770 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13771 OS <<
"constant max backedge-taken count is ";
13774 OS <<
", actual taken count either this or zero.";
13776 OS <<
"Unpredictable constant max backedge-taken count. ";
13781 L->getHeader()->printAsOperand(
OS,
false);
13785 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13786 OS <<
"symbolic max backedge-taken count is ";
13789 OS <<
", actual taken count either this or zero.";
13791 OS <<
"Unpredictable symbolic max backedge-taken count. ";
13795 if (ExitingBlocks.
size() > 1)
13796 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
13797 OS <<
" symbolic max exit count for " << ExitingBlock->
getName() <<
": ";
13801 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
13806 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
13807 OS <<
"\n predicated symbolic max exit count for "
13808 << ExitingBlock->
getName() <<
": ";
13810 OS <<
"\n Predicates:\n";
13811 for (
const auto *
P : Predicates)
13821 assert(!Preds.
empty() &&
"Different predicated BTC, but no predicates");
13823 L->getHeader()->printAsOperand(
OS,
false);
13825 if (!isa<SCEVCouldNotCompute>(PBT)) {
13826 OS <<
"Predicated backedge-taken count is ";
13829 OS <<
"Unpredictable predicated backedge-taken count.";
13831 OS <<
" Predicates:\n";
13832 for (
const auto *
P : Preds)
13837 auto *PredConstantMax =
13839 if (PredConstantMax != ConstantBTC) {
13841 "different predicated constant max BTC but no predicates");
13843 L->getHeader()->printAsOperand(
OS,
false);
13845 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
13846 OS <<
"Predicated constant max backedge-taken count is ";
13849 OS <<
"Unpredictable predicated constant max backedge-taken count.";
13851 OS <<
" Predicates:\n";
13852 for (
const auto *
P : Preds)
13857 auto *PredSymbolicMax =
13859 if (SymbolicBTC != PredSymbolicMax) {
13861 "Different predicated symbolic max BTC, but no predicates");
13863 L->getHeader()->printAsOperand(
OS,
false);
13865 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
13866 OS <<
"Predicated symbolic max backedge-taken count is ";
13869 OS <<
"Unpredictable predicated symbolic max backedge-taken count.";
13871 OS <<
" Predicates:\n";
13872 for (
const auto *
P : Preds)
13878 L->getHeader()->printAsOperand(
OS,
false);
13894 OS <<
"Computable";
13903 OS <<
"DoesNotDominate";
13909 OS <<
"ProperlyDominates";
13926 OS <<
"Classifying expressions for: ";
13935 if (!isa<SCEVCouldNotCompute>(SV)) {
13948 if (!isa<SCEVCouldNotCompute>(AtUse)) {
13957 OS <<
"\t\t" "Exits: ";
13960 OS <<
"<<Unknown>>";
13966 for (
const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13968 OS <<
"\t\t" "LoopDispositions: { ";
13974 Iter->getHeader()->printAsOperand(
OS,
false);
13982 OS <<
"\t\t" "LoopDispositions: { ";
13988 InnerL->getHeader()->printAsOperand(
OS,
false);
13999 OS <<
"Determining loop execution counts for: ";
14008 auto &Values = LoopDispositions[S];
14009 for (
auto &V : Values) {
14010 if (V.getPointer() == L)
14015 auto &Values2 = LoopDispositions[S];
14017 if (V.getPointer() == L) {
14026ScalarEvolution::computeLoopDisposition(
const SCEV *S,
const Loop *L) {
14045 assert(!L->contains(AR->
getLoop()) &&
"Containing loop's header does not"
14046 " dominate the contained loop's header?");
14073 bool HasVarying =
false;
14088 if (
auto *
I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
14107 auto &Values = BlockDispositions[S];
14108 for (
auto &V : Values) {
14109 if (V.getPointer() == BB)
14114 auto &Values2 = BlockDispositions[S];
14116 if (V.getPointer() == BB) {
14125ScalarEvolution::computeBlockDisposition(
const SCEV *S,
const BasicBlock *BB) {
14154 bool Proper =
true;
14166 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
14167 if (
I->getParent() == BB)
14192void ScalarEvolution::forgetBackedgeTakenCounts(
const Loop *L,
14195 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14196 auto It = BECounts.find(L);
14197 if (It != BECounts.end()) {
14198 for (
const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14199 for (
const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14200 if (!isa<SCEVConstant>(S)) {
14201 auto UserIt = BECountUsers.find(S);
14202 assert(UserIt != BECountUsers.end());
14207 BECounts.erase(It);
14215 while (!Worklist.
empty()) {
14217 auto Users = SCEVUsers.find(Curr);
14218 if (
Users != SCEVUsers.end())
14224 for (
const auto *S : ToForget)
14225 forgetMemoizedResultsImpl(S);
14227 for (
auto I = PredicatedSCEVRewrites.begin();
14228 I != PredicatedSCEVRewrites.end();) {
14229 std::pair<const SCEV *, const Loop *>
Entry =
I->first;
14230 if (ToForget.count(
Entry.first))
14231 PredicatedSCEVRewrites.erase(
I++);
14237void ScalarEvolution::forgetMemoizedResultsImpl(
const SCEV *S) {
14238 LoopDispositions.erase(S);
14239 BlockDispositions.erase(S);
14240 UnsignedRanges.erase(S);
14241 SignedRanges.erase(S);
14242 HasRecMap.
erase(S);
14243 ConstantMultipleCache.erase(S);
14245 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14246 UnsignedWrapViaInductionTried.erase(AR);
14247 SignedWrapViaInductionTried.erase(AR);
14250 auto ExprIt = ExprValueMap.
find(S);
14251 if (ExprIt != ExprValueMap.
end()) {
14252 for (
Value *V : ExprIt->second) {
14253 auto ValueIt = ValueExprMap.
find_as(V);
14254 if (ValueIt != ValueExprMap.
end())
14255 ValueExprMap.
erase(ValueIt);
14257 ExprValueMap.
erase(ExprIt);
14260 auto ScopeIt = ValuesAtScopes.find(S);
14261 if (ScopeIt != ValuesAtScopes.end()) {
14262 for (
const auto &Pair : ScopeIt->second)
14263 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14265 std::make_pair(Pair.first, S));
14266 ValuesAtScopes.erase(ScopeIt);
14269 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14270 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14271 for (
const auto &Pair : ScopeUserIt->second)
14272 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14273 ValuesAtScopesUsers.erase(ScopeUserIt);
14276 auto BEUsersIt = BECountUsers.find(S);
14277 if (BEUsersIt != BECountUsers.end()) {
14279 auto Copy = BEUsersIt->second;
14280 for (
const auto &Pair : Copy)
14281 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14282 BECountUsers.erase(BEUsersIt);
14285 auto FoldUser = FoldCacheUser.find(S);
14286 if (FoldUser != FoldCacheUser.end())
14287 for (
auto &KV : FoldUser->second)
14288 FoldCache.erase(KV);
14289 FoldCacheUser.erase(S);
14293ScalarEvolution::getUsedLoops(
const SCEV *S,
14295 struct FindUsedLoops {
14297 : LoopsUsed(LoopsUsed) {}
14299 bool follow(
const SCEV *S) {
14300 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14305 bool isDone()
const {
return false; }
14308 FindUsedLoops F(LoopsUsed);
14312void ScalarEvolution::getReachableBlocks(
14316 while (!Worklist.
empty()) {
14318 if (!Reachable.
insert(BB).second)
14325 if (
auto *
C = dyn_cast<ConstantInt>(
Cond)) {
14326 Worklist.
push_back(
C->isOne() ? TrueBB : FalseBB);
14330 if (
auto *Cmp = dyn_cast<ICmpInst>(
Cond)) {
14333 if (isKnownPredicateViaConstantRanges(
Cmp->getCmpPredicate(), L, R)) {
14337 if (isKnownPredicateViaConstantRanges(
Cmp->getInverseCmpPredicate(), L,
14372 SCEVMapper SCM(SE2);
14374 SE2.getReachableBlocks(ReachableBlocks,
F);
14376 auto GetDelta = [&](
const SCEV *Old,
const SCEV *New) ->
const SCEV * {
14394 while (!LoopStack.
empty()) {
14400 if (!ReachableBlocks.
contains(L->getHeader()))
14405 auto It = BackedgeTakenCounts.find(L);
14406 if (It == BackedgeTakenCounts.end())
14410 SCM.visit(It->second.getExact(L,
const_cast<ScalarEvolution *
>(
this)));
14430 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14431 if (Delta && !Delta->
isZero()) {
14432 dbgs() <<
"Trip Count for " << *L <<
" Changed!\n";
14433 dbgs() <<
"Old: " << *CurBECount <<
"\n";
14434 dbgs() <<
"New: " << *NewBECount <<
"\n";
14435 dbgs() <<
"Delta: " << *Delta <<
"\n";
14443 while (!Worklist.
empty()) {
14445 if (ValidLoops.
insert(L).second)
14446 Worklist.
append(L->begin(), L->end());
14448 for (
const auto &KV : ValueExprMap) {
14451 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14453 "AddRec references invalid loop");
14458 auto It = ExprValueMap.
find(KV.second);
14459 if (It == ExprValueMap.
end() || !It->second.contains(KV.first)) {
14460 dbgs() <<
"Value " << *KV.first
14461 <<
" is in ValueExprMap but not in ExprValueMap\n";
14465 if (
auto *
I = dyn_cast<Instruction>(&*KV.first)) {
14466 if (!ReachableBlocks.
contains(
I->getParent()))
14468 const SCEV *OldSCEV = SCM.visit(KV.second);
14470 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14471 if (Delta && !Delta->
isZero()) {
14472 dbgs() <<
"SCEV for value " << *
I <<
" changed!\n"
14473 <<
"Old: " << *OldSCEV <<
"\n"
14474 <<
"New: " << *NewSCEV <<
"\n"
14475 <<
"Delta: " << *Delta <<
"\n";
14481 for (
const auto &KV : ExprValueMap) {
14482 for (
Value *V : KV.second) {
14483 auto It = ValueExprMap.find_as(V);
14484 if (It == ValueExprMap.end()) {
14485 dbgs() <<
"Value " << *V
14486 <<
" is in ExprValueMap but not in ValueExprMap\n";
14489 if (It->second != KV.first) {
14490 dbgs() <<
"Value " << *V <<
" mapped to " << *It->second
14491 <<
" rather than " << *KV.first <<
"\n";
14498 for (
const auto &S : UniqueSCEVs) {
14501 if (isa<SCEVConstant>(
Op))
14503 auto It = SCEVUsers.find(
Op);
14504 if (It != SCEVUsers.end() && It->second.count(&S))
14506 dbgs() <<
"Use of operand " << *
Op <<
" by user " << S
14507 <<
" is not being tracked!\n";
14513 for (
const auto &ValueAndVec : ValuesAtScopes) {
14515 for (
const auto &LoopAndValueAtScope : ValueAndVec.second) {
14516 const Loop *L = LoopAndValueAtScope.first;
14517 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14518 if (!isa<SCEVConstant>(ValueAtScope)) {
14519 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14520 if (It != ValuesAtScopesUsers.end() &&
14523 dbgs() <<
"Value: " << *
Value <<
", Loop: " << *L <<
", ValueAtScope: "
14524 << *ValueAtScope <<
" missing in ValuesAtScopesUsers\n";
14530 for (
const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14531 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14532 for (
const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14533 const Loop *L = LoopAndValue.first;
14534 const SCEV *
Value = LoopAndValue.second;
14536 auto It = ValuesAtScopes.find(
Value);
14537 if (It != ValuesAtScopes.end() &&
14538 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14540 dbgs() <<
"Value: " << *
Value <<
", Loop: " << *L <<
", ValueAtScope: "
14541 << *ValueAtScope <<
" missing in ValuesAtScopes\n";
14547 auto VerifyBECountUsers = [&](
bool Predicated) {
14549 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14550 for (
const auto &LoopAndBEInfo : BECounts) {
14551 for (
const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14552 for (
const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14553 if (!isa<SCEVConstant>(S)) {
14554 auto UserIt = BECountUsers.find(S);
14555 if (UserIt != BECountUsers.end() &&
14556 UserIt->second.contains({ LoopAndBEInfo.first,
Predicated }))
14558 dbgs() <<
"Value " << *S <<
" for loop " << *LoopAndBEInfo.first
14559 <<
" missing from BECountUsers\n";
14566 VerifyBECountUsers(
false);
14567 VerifyBECountUsers(
true);
14570 for (
auto &[S, Values] : LoopDispositions) {
14571 for (
auto [
Loop, CachedDisposition] : Values) {
14573 if (CachedDisposition != RecomputedDisposition) {
14574 dbgs() <<
"Cached disposition of " << *S <<
" for loop " << *
Loop
14575 <<
" is incorrect: cached " << CachedDisposition <<
", actual "
14576 << RecomputedDisposition <<
"\n";
14583 for (
auto &[S, Values] : BlockDispositions) {
14584 for (
auto [BB, CachedDisposition] : Values) {
14586 if (CachedDisposition != RecomputedDisposition) {
14587 dbgs() <<
"Cached disposition of " << *S <<
" for block %"
14588 << BB->
getName() <<
" is incorrect: cached " << CachedDisposition
14589 <<
", actual " << RecomputedDisposition <<
"\n";
14596 for (
auto [
FoldID, Expr] : FoldCache) {
14597 auto I = FoldCacheUser.find(Expr);
14598 if (
I == FoldCacheUser.end()) {
14599 dbgs() <<
"Missing entry in FoldCacheUser for cached expression " << *Expr
14604 dbgs() <<
"Missing FoldID in cached users of " << *Expr <<
"!\n";
14608 for (
auto [Expr, IDs] : FoldCacheUser) {
14609 for (
auto &
FoldID : IDs) {
14610 auto I = FoldCache.find(
FoldID);
14611 if (
I == FoldCache.end()) {
14612 dbgs() <<
"Missing entry in FoldCache for expression " << *Expr
14616 if (
I->second != Expr) {
14617 dbgs() <<
"Entry in FoldCache doesn't match FoldCacheUser: "
14618 << *
I->second <<
" != " << *Expr <<
"!\n";
14629 for (
auto [S, Multiple] : ConstantMultipleCache) {
14631 if ((Multiple != 0 && RecomputedMultiple != 0 &&
14632 Multiple.
urem(RecomputedMultiple) != 0 &&
14633 RecomputedMultiple.
urem(Multiple) != 0)) {
14634 dbgs() <<
"Incorrect cached computation in ConstantMultipleCache for "
14635 << *S <<
" : Computed " << RecomputedMultiple
14636 <<
" but cache contains " << Multiple <<
"!\n";
14676 OS <<
"Printing analysis 'Scalar Evolution Analysis' for function '"
14677 <<
F.getName() <<
"':\n";
14683 "Scalar Evolution Analysis",
false,
true)
14699 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F),
14700 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F),
14701 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14702 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14734 const SCEV *LHS,
const SCEV *RHS) {
14737 "Type mismatch between LHS and RHS");
14740 ID.AddInteger(Pred);
14741 ID.AddPointer(
LHS);
14742 ID.AddPointer(
RHS);
14743 void *IP =
nullptr;
14744 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(
ID, IP))
14748 UniquePreds.InsertNode(Eq, IP);
14759 ID.AddInteger(AddedFlags);
14760 void *IP =
nullptr;
14761 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(
ID, IP))
14763 auto *OF =
new (SCEVAllocator)
14765 UniquePreds.InsertNode(OF, IP);
14785 SCEVPredicateRewriter
Rewriter(L, SE, NewPreds, Pred);
14791 if (
auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14792 for (
const auto *Pred : U->getPredicates())
14793 if (
const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14794 if (IPred->getLHS() == Expr &&
14795 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14796 return IPred->getRHS();
14797 }
else if (
const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14798 if (IPred->getLHS() == Expr &&
14799 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14800 return IPred->getRHS();
14803 return convertToAddRecWithPreds(Expr);
14839 explicit SCEVPredicateRewriter(
14848 return Pred && Pred->
implies(
P, SE);
14857 return addOverflowAssumption(
A);
14867 if (!isa<PHINode>(Expr->
getValue()))
14870 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14872 if (!PredicatedRewrite)
14874 for (
const auto *
P : PredicatedRewrite->second){
14876 if (
auto *WP = dyn_cast<const SCEVWrapPredicate>(
P)) {
14877 if (L != WP->getExpr()->getLoop())
14880 if (!addOverflowAssumption(
P))
14883 return PredicatedRewrite->first;
14896 return SCEVPredicateRewriter::rewrite(S, L, *
this,
nullptr, &Preds);
14903 S = SCEVPredicateRewriter::rewrite(S, L, *
this, &TransformPreds,
nullptr);
14904 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14919 : FastID(
ID), Kind(Kind) {}
14926 assert(
LHS !=
RHS &&
"LHS and RHS are the same SCEV");
14931 const auto *
Op = dyn_cast<SCEVComparePredicate>(
N);
14962 const auto *
Op = dyn_cast<SCEVWrapPredicate>(
N);
14974 const SCEV *OpStart =
Op->AR->getStart();
14979 const SCEV *OpStep =
Op->AR->getStepRecurrence(SE);
15032 if (Step->getValue()->getValue().isNonNegative())
15036 return ImpliedFlags;
15043 for (
const auto *
P : Preds)
15054 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(
N))
15056 return this->implies(I, SE);
15064 for (
const auto *Pred : Preds)
15069 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(
N)) {
15070 for (
const auto *Pred : Set->Preds)
15082 for (
auto *
P : Preds) {
15083 if (
N->implies(
P, SE))
15087 Preds = std::move(PrunedPreds);
15088 Preds.push_back(
N);
15095 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15100 for (
const auto *
Op : Ops)
15104 if (!isa<SCEVConstant>(
Op))
15105 SCEVUsers[
Op].insert(
User);
15110 RewriteEntry &Entry = RewriteMap[Expr];
15113 if (Entry.second && Generation == Entry.first)
15114 return Entry.second;
15119 Expr = Entry.second;
15122 Entry = {Generation, NewSCEV};
15128 if (!BackedgeCount) {
15131 for (
const auto *
P : Preds)
15134 return BackedgeCount;
15138 if (!SymbolicMaxBackedgeCount) {
15140 SymbolicMaxBackedgeCount =
15142 for (
const auto *
P : Preds)
15145 return SymbolicMaxBackedgeCount;
15149 if (!SmallConstantMaxTripCount) {
15152 for (
const auto *
P : Preds)
15155 return *SmallConstantMaxTripCount;
15159 if (Preds->implies(&Pred, SE))
15164 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15165 updateGeneration();
15172void PredicatedScalarEvolution::updateGeneration() {
15174 if (++Generation == 0) {
15175 for (
auto &
II : RewriteMap) {
15176 const SCEV *Rewritten =
II.second.second;
15185 const auto *AR = cast<SCEVAddRecExpr>(Expr);
15193 auto II = FlagsMap.insert({V, Flags});
15201 const auto *AR = cast<SCEVAddRecExpr>(Expr);
15206 auto II = FlagsMap.find(V);
15208 if (
II != FlagsMap.end())
15222 for (
const auto *
P : NewPreds)
15225 RewriteMap[SE.
getSCEV(V)] = {Generation, New};
15231 : RewriteMap(
Init.RewriteMap), SE(
Init.SE), L(
Init.L),
15234 Generation(
Init.Generation), BackedgeCount(
Init.BackedgeCount) {
15235 for (
auto I :
Init.FlagsMap)
15236 FlagsMap.insert(
I);
15241 for (
auto *BB : L.getBlocks())
15242 for (
auto &
I : *BB) {
15247 auto II = RewriteMap.find(Expr);
15249 if (
II == RewriteMap.end())
15253 if (
II->second.second == Expr)
15267bool ScalarEvolution::matchURem(
const SCEV *Expr,
const SCEV *&LHS,
15268 const SCEV *&RHS) {
15275 if (
const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
15276 if (
const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
15277 LHS = Trunc->getOperand();
15289 const auto *
Add = dyn_cast<SCEVAddExpr>(Expr);
15290 if (
Add ==
nullptr ||
Add->getNumOperands() != 2)
15293 const SCEV *
A =
Add->getOperand(1);
15294 const auto *
Mul = dyn_cast<SCEVMulExpr>(
Add->getOperand(0));
15296 if (
Mul ==
nullptr)
15299 const auto MatchURemWithDivisor = [&](
const SCEV *
B) {
15310 if (
Mul->getNumOperands() == 3 && isa<SCEVConstant>(
Mul->getOperand(0)))
15311 return MatchURemWithDivisor(
Mul->getOperand(1)) ||
15312 MatchURemWithDivisor(
Mul->getOperand(2));
15315 if (
Mul->getNumOperands() == 2)
15316 return MatchURemWithDivisor(
Mul->getOperand(1)) ||
15317 MatchURemWithDivisor(
Mul->getOperand(0)) ||
15331 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15335void ScalarEvolution::LoopGuards::collectFromPHI(
15343 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15344 auto GetMinMaxConst = [&](
unsigned IncomingIdx) -> MinMaxPattern {
15350 collectFromBlock(SE,
G->second, Phi.getParent(),
InBlock, VisitedBlocks,
15352 auto &RewriteMap =
G->second.RewriteMap;
15353 if (RewriteMap.empty())
15355 auto S = RewriteMap.find(SE.
getSCEV(Phi.getIncomingValue(IncomingIdx)));
15356 if (S == RewriteMap.end())
15358 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15361 if (
const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15362 return {C0, SM->getSCEVType()};
15365 auto MergeMinMaxConst = [](MinMaxPattern
P1,
15366 MinMaxPattern P2) -> MinMaxPattern {
15367 auto [C1,
T1] =
P1;
15368 auto [C2, T2] = P2;
15369 if (!C1 || !C2 || T1 != T2)
15373 return {C1->getAPInt().
ult(C2->getAPInt()) ? C1 : C2, T1};
15375 return {C1->getAPInt().
slt(C2->getAPInt()) ? C1 : C2, T1};
15377 return {C1->getAPInt().
ugt(C2->getAPInt()) ? C1 : C2, T1};
15379 return {C1->getAPInt().
sgt(C2->getAPInt()) ? C1 : C2, T1};
15384 auto P = GetMinMaxConst(0);
15385 for (
unsigned int In = 1;
In <
Phi.getNumIncomingValues();
In++) {
15388 P = MergeMinMaxConst(
P, GetMinMaxConst(In));
15394 Guards.RewriteMap.insert({
LHS,
RHS});
15398void ScalarEvolution::LoopGuards::collectFromBlock(
15413 if (isa<SCEVConstant>(LHS)) {
15422 &ExprsToRewrite]() {
15425 auto *C2 = dyn_cast<SCEVConstant>(RHS);
15436 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
15438 auto I = RewriteMap.find(LHSUnknown);
15439 const SCEV *RewrittenLHS =
I != RewriteMap.end() ?
I->second : LHSUnknown;
15447 if (MatchRangeCheckIdiom())
15453 auto IsMinMaxSCEVWithNonNegativeConstant =
15456 if (
auto *
MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15457 if (
MinMax->getNumOperands() != 2)
15459 if (
auto *
C = dyn_cast<SCEVConstant>(
MinMax->getOperand(0))) {
15460 if (
C->getAPInt().isNegative())
15462 SCTy =
MinMax->getSCEVType();
15473 auto GetNonNegExprAndPosDivisor = [&](
const SCEV *Expr,
const SCEV *Divisor,
15475 auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
15476 auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
15477 if (!ConstExpr || !ConstDivisor)
15479 ExprVal = ConstExpr->getAPInt();
15480 DivisorVal = ConstDivisor->getAPInt();
15481 return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
15487 auto GetNextSCEVDividesByDivisor = [&](
const SCEV *Expr,
15488 const SCEV *Divisor) {
15491 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15496 return SE.
getConstant(ExprVal + DivisorVal - Rem);
15503 auto GetPreviousSCEVDividesByDivisor = [&](
const SCEV *Expr,
15504 const SCEV *Divisor) {
15507 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15517 std::function<
const SCEV *(
const SCEV *,
const SCEV *)>
15518 ApplyDivisibiltyOnMinMaxExpr = [&](
const SCEV *MinMaxExpr,
15519 const SCEV *Divisor) {
15520 const SCEV *MinMaxLHS =
nullptr, *MinMaxRHS =
nullptr;
15522 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15526 isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15528 "Expected non-negative operand!");
15529 auto *DivisibleExpr =
15530 IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15531 : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15533 ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15542 const SCEV *URemLHS =
nullptr;
15543 const SCEV *URemRHS =
nullptr;
15544 if (SE.matchURem(LHS, URemLHS, URemRHS)) {
15545 if (
const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15546 auto I = RewriteMap.find(LHSUnknown);
15547 const SCEV *RewrittenLHS =
15548 I != RewriteMap.end() ?
I->second : LHSUnknown;
15549 RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15550 const auto *Multiple =
15552 RewriteMap[LHSUnknown] = Multiple;
15564 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15573 auto AddRewrite = [&](
const SCEV *
From,
const SCEV *FromRewritten,
15575 if (
From == FromRewritten)
15577 RewriteMap[
From] = To;
15583 auto GetMaybeRewritten = [&](
const SCEV *S) {
15584 auto I = RewriteMap.find(S);
15585 return I != RewriteMap.end() ?
I->second : S;
15595 std::function<
bool(
const SCEV *,
const SCEV *&)> HasDivisibiltyInfo =
15596 [&](
const SCEV *Expr,
const SCEV *&DividesBy) {
15597 if (
auto *
Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15598 if (
Mul->getNumOperands() != 2)
15600 auto *MulLHS =
Mul->getOperand(0);
15601 auto *MulRHS =
Mul->getOperand(1);
15602 if (isa<SCEVConstant>(MulLHS))
15604 if (
auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15605 if (Div->getOperand(1) == MulRHS) {
15606 DividesBy = MulRHS;
15610 if (
auto *
MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15611 return HasDivisibiltyInfo(
MinMax->getOperand(0), DividesBy) ||
15612 HasDivisibiltyInfo(
MinMax->getOperand(1), DividesBy);
15617 std::function<
bool(
const SCEV *,
const SCEV *&)> IsKnownToDivideBy =
15618 [&](
const SCEV *Expr,
const SCEV *DividesBy) {
15621 if (
auto *
MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15622 return IsKnownToDivideBy(
MinMax->getOperand(0), DividesBy) &&
15623 IsKnownToDivideBy(
MinMax->getOperand(1), DividesBy);
15627 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15628 const SCEV *DividesBy =
nullptr;
15629 if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15632 IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy :
nullptr;
15654 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) :
RHS;
15660 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) :
RHS;
15664 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) :
RHS;
15668 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) :
RHS;
15677 auto EnqueueOperands = [&Worklist](
const SCEVNAryExpr *S) {
15681 while (!Worklist.
empty()) {
15683 if (isa<SCEVConstant>(
From))
15687 const SCEV *FromRewritten = GetMaybeRewritten(
From);
15688 const SCEV *To =
nullptr;
15694 if (
auto *
UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15695 EnqueueOperands(
UMax);
15700 if (
auto *
SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15701 EnqueueOperands(
SMax);
15706 if (
auto *
UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15707 EnqueueOperands(
UMin);
15712 if (
auto *
SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15713 EnqueueOperands(
SMin);
15716 if (isa<SCEVConstant>(RHS))
15721 const SCEV *OneAlignedUp =
15722 DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15723 To = SE.
getUMaxExpr(FromRewritten, OneAlignedUp);
15731 AddRewrite(
From, FromRewritten, To);
15740 auto *AssumeI = cast<CallInst>(AssumeVH);
15748 SE.F.
getParent(), Intrinsic::experimental_guard);
15750 for (
const auto *GU : GuardDecl->users())
15751 if (
const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15752 if (Guard->getFunction() ==
Block->getParent() &&
15761 unsigned NumCollectedConditions = 0;
15763 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred,
Block);
15765 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15766 VisitedBlocks.
insert(Pair.second);
15768 dyn_cast<BranchInst>(Pair.first->getTerminator());
15774 NumCollectedConditions++;
15778 if (
Depth > 0 && NumCollectedConditions == 2)
15786 if (Pair.second->hasNPredecessorsOrMore(2) &&
15789 for (
auto &Phi : Pair.second->phis())
15790 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards,
Depth);
15797 for (
auto [Term, EnterIfTrue] :
reverse(Terms)) {
15801 while (!Worklist.
empty()) {
15806 if (
auto *Cmp = dyn_cast<ICmpInst>(
Cond)) {
15808 EnterIfTrue ?
Cmp->getPredicate() :
Cmp->getInversePredicate();
15811 CollectCondition(
Predicate, LHS, RHS, Guards.RewriteMap);
15827 Guards.PreserveNUW =
true;
15828 Guards.PreserveNSW =
true;
15829 for (
const SCEV *Expr : ExprsToRewrite) {
15830 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
15831 Guards.PreserveNUW &=
15833 Guards.PreserveNSW &=
15840 if (ExprsToRewrite.size() > 1) {
15841 for (
const SCEV *Expr : ExprsToRewrite) {
15842 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
15843 Guards.RewriteMap.erase(Expr);
15844 Guards.RewriteMap.insert({Expr, Guards.
rewrite(RewriteTo)});
15853 class SCEVLoopGuardRewriter
15863 if (Guards.PreserveNUW)
15865 if (Guards.PreserveNSW)
15872 auto I = Map.find(Expr);
15873 if (
I == Map.end())
15879 auto I = Map.find(Expr);
15880 if (
I == Map.end()) {
15886 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
15887 Bitwidth >
Op->getType()->getScalarSizeInBits()) {
15890 auto I = Map.find(NarrowExt);
15891 if (
I != Map.end())
15893 Bitwidth = Bitwidth / 2;
15903 auto I = Map.find(Expr);
15904 if (
I == Map.end())
15911 auto I = Map.find(Expr);
15912 if (
I == Map.end())
15918 auto I = Map.find(Expr);
15919 if (
I == Map.end())
15926 bool Changed =
false;
15934 return !Changed ? Expr
15942 bool Changed =
false;
15950 return !Changed ? Expr
15957 if (RewriteMap.empty())
15960 SCEVLoopGuardRewriter
Rewriter(SE, *
this);
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
block Block Frequency Analysis
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool isSigned(unsigned int Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
mir Rename Register Operands
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
void visit(MachineFunction &MF, MachineBasicBlock &Start, std::function< void(MachineBasicBlock *)> op)
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
static std::optional< int > CompareSCEVComplexity(EquivalenceClasses< const SCEV * > &EqCacheSCEV, const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static void GroupByComplexity(SmallVectorImpl< const SCEV * > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< const SCEV * > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static bool MatchBinarySub(const SCEV *S, const SCEV *&LHS, const SCEV *&RHS)
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool hasHugeExpression(ArrayRef< const SCEV * > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static cl::opt< unsigned > MaxPhiSCCAnalysisSize("scalar-evolution-max-scc-analysis-depth", cl::Hidden, cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " "Phi strongly connected components"), cl::init(8))
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static ConstantRange getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, const ArrayRef< const SCEV * > Ops, SCEV::NoWrapFlags Flags)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static bool CollectAddOperandsWithScales(SmallDenseMap< const SCEV *, APInt, 16 > &M, SmallVectorImpl< const SCEV * > &NewOps, APInt &AccumulatedConstant, ArrayRef< const SCEV * > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Virtual Register Rewriter
static const uint32_t IV[8]
Class for arbitrary precision integers.
APInt umul_ov(const APInt &RHS, bool &Overflow) const
APInt udiv(const APInt &RHS) const
Unsigned division operation.
APInt zext(unsigned width) const
Zero extend to a new width.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
uint64_t getZExtValue() const
Get zero extended value.
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
unsigned getActiveBits() const
Compute the number of active bits in the value.
APInt trunc(unsigned width) const
Truncate to new width.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
APInt abs() const
Get the absolute value.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
bool isNegative() const
Determine sign of this APInt.
bool sle(const APInt &RHS) const
Signed less or equal comparison.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
unsigned countTrailingZeros() const
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
APInt multiplicativeInverse() const
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
APInt sext(unsigned width) const
Sign extend to a new width.
APInt shl(unsigned shiftAmt) const
Left-shift function.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
bool slt(const APInt &RHS) const
Signed less than comparison.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
API to communicate dependencies between analyses during invalidation.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
size_t size() const
size - Get the array size.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptions()
Access the list of assumption handles currently tracked for this function.
bool isSingleEdge() const
Check if this is the only edge between Start and End.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const Instruction & front() const
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Conditional or Unconditional Branch instruction.
bool isConditional() const
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
This class represents a function call, abstracting a target machine's calling convention.
Value handle with callbacks on RAUW and destruction.
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static Constant * getNot(Constant *C)
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static Constant * getNeg(Constant *C, bool HasNSW=false)
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
static ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt & getLower() const
Return the lower value for this range.
ConstantRange truncate(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
void print(raw_ostream &OS) const
Print out the bounds to a stream.
ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
union - Merge the two equivalence sets for the specified values, inserting them if they do not alread...
bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const
FoldingSetNodeIDRef - This class describes a reference to an interned FoldingSetNodeID,...
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
FunctionPass class - This class is used to implement most global optimizations.
const BasicBlock & getEntryBlock() const
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
A Module instance is used to store all the information related to an LLVM module.
This is a utility class that provides an abstraction for the common functionality between Instruction...
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
const SCEVPredicate & getPredicate() const
bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've proved that V doesn't wrap by means of a SCEV predicate.
void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Proves that V doesn't overflow by adding SCEV predicate.
void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
constexpr bool isValid() const
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStart() const
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
const Loop * getLoop() const
This is the base class for unary cast operator classes.
const SCEV * getOperand() const
SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op, Type *ty)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
bool hasNoUnsignedWrap() const
bool hasNoSelfWrap() const
size_t getNumOperands() const
bool hasNoSignedWrap() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getOperand(unsigned i) const
const SCEV *const * Operands
ArrayRef< const SCEV * > operands() const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
virtual void print(raw_ostream &OS, unsigned Depth=0) const =0
Prints a textual representation of this predicate with an indentation of Depth.
This class represents a cast from a pointer to a pointer-sized integer value.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed maximum selection.
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
SCEVTypes getEquivalentNonSequentialSCEVType() const
This class represents a sequential/in-order unsigned minimum selection.
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
void visitAll(const SCEV *Root)
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
const SCEV * getLHS() const
const SCEV * getRHS() const
This class represents an unsigned maximum selection.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
ArrayRef< const SCEV * > operands() const
Return operands of this SCEV expression.
unsigned short getExpressionSize() const
bool isOne() const
Return true if the expression is a constant one.
bool isZero() const
Return true if the expression is a constant zero.
void dump() const
This method is used for debugging.
bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
Analysis pass that exposes the ScalarEvolution for a function.
ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
const SCEV * getSMaxExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
const SCEV * getGEPExpr(GEPOperator *GEP, const SmallVectorImpl< const SCEV * > &IndexExprs)
Returns an expression for a GEP.
std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
Type * getWiderType(Type *Ty1, Type *Ty2) const
const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
const SCEV * getURemExpr(const SCEV *LHS, const SCEV *RHS)
Represents an unsigned remainder expression based on unsigned division.
APInt getConstantMultiple(const SCEV *S)
Returns the max constant multiple of S.
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
const SCEV * getSMinExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?...
ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
const SCEV * getZeroExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty)
const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< const SCEV * > &Operands)
const SCEV * getLosslessPtrToIntExpr(const SCEV *Op, unsigned Depth=0)
std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
const SCEV * getPtrToIntExpr(const SCEV *Op, Type *Ty)
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
bool SimplifyICmpOperands(CmpPredicate &Pred, const SCEV *&LHS, const SCEV *&RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
const SCEV * getSignExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
const SCEV * getUDivExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
uint32_t getMinTrailingZeros(const SCEV *S)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
void print(raw_ostream &OS) const
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
void forgetTopmostLoop(const Loop *L)
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
@ MonotonicallyDecreasing
@ MonotonicallyIncreasing
std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
friend class SCEVCallbackVH
const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
const SCEV * getCouldNotCompute()
bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
const SCEV * getVScale(Type *Ty)
unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< const SCEV * > &Operands)
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
const SCEV * getUnknown(Value *V)
std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getElementCount(Type *Ty, ElementCount EC)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask)
Convenient NoWrapFlags manipulation that hides enum casts and is visible in the ScalarEvolution name ...
std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
const SCEV * getUDivExactExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
bool isKnownPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
bool isKnownViaInduction(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
TypeSize getElementOffset(unsigned Idx) const
TypeSize getSizeInBits() const
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static IntegerType * getInt8Ty(LLVMContext &C)
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
unsigned getValueID() const
Return an ID for the concrete type of this object.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVMContext & getContext() const
All values hold a context through their type.
StringRef getName() const
Return a constant reference to the value's name.
Represents an op.with.overflow intrinsic.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
@ C
The default llvm calling convention, compatible with C.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Function * getDeclarationIfExists(Module *M, ID id, ArrayRef< Type * > Tys, FunctionType *FT=nullptr)
This version supports overloaded intrinsics.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
bind_ty< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
bind_ty< const SCEVConstant > m_SCEVConstant(const SCEVConstant *&V)
bind_ty< const SCEV > m_SCEV(const SCEV *&V)
Match a SCEV, capturing it if we match.
SCEVBinaryExpr_match< SCEVAddExpr, Op0_t, Op1_t > m_scev_Add(const Op0_t &Op0, const Op1_t &Op1)
bool match(const SCEV *S, const Pattern &P)
bind_ty< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
NodeAddr< PhiNode * > Phi
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
void stable_sort(R &&Range)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
unsigned short computeExpressionSize(ArrayRef< const SCEV * > Args)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr)
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void initializeScalarEvolutionWrapperPassPass(PassRegistry &)
auto reverse(ContainerTy &&C)
bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
bool programUndefinedIfPoison(const Instruction *Inst)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isPointerTy(const Type *T)
ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits.
iterator_range< df_iterator< T > > depth_first(const T &G)
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
static KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
static KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
bool isNegative() const
Returns true if this value is known to be negative.
static KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
const SCEV * ExactNotTaken
const SCEV * SymbolicMaxNotTaken
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.
const SCEV * ConstantMaxNotTaken