99 #define DEBUG_TYPE "scalar-evolution"
102 "Number of trip counts computed with array length");
104 "Number of loops with predictable loop counts");
106 "Number of loops without predictable loop counts");
107 STATISTIC(NumBruteForceTripCountsComputed,
108 "Number of loops with trip counts computed by force");
112 cl::desc(
"Maximum number of iterations SCEV will "
113 "symbolically execute a constant "
120 cl::desc(
"Verify ScalarEvolution's backedge taken counts (slow)"));
123 cl::desc(
"Verify no dangling value in ScalarEvolution's "
124 "ExprValueMap (slow)"));
128 cl::desc(
"Threshold for inlining multiplication operands into a SCEV"),
133 cl::desc(
"Threshold for inlining addition operands into a SCEV"),
137 "scalar-evolution-max-scev-compare-depth",
cl::Hidden,
138 cl::desc(
"Maximum depth of recursive SCEV complexity comparisons"),
142 "scalar-evolution-max-scev-operations-implication-depth",
cl::Hidden,
143 cl::desc(
"Maximum depth of recursive SCEV operations implication analysis"),
147 "scalar-evolution-max-value-compare-depth",
cl::Hidden,
148 cl::desc(
"Maximum depth of recursive value complexity comparisons"),
153 cl::desc(
"Maximum depth of recursive arithmetics"),
157 "scalar-evolution-max-constant-evolving-depth",
cl::Hidden,
162 cl::desc(
"Maximum depth of recursive SExt/ZExt"),
167 cl::desc(
"Max coefficients in AddRec during evolving"),
178 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
188 cast<SCEVConstant>(
this)->getValue()->printAsOperand(OS,
false);
193 OS <<
"(trunc " << *Op->getType() <<
" " << *Op <<
" to "
200 OS <<
"(zext " << *Op->getType() <<
" " << *Op <<
" to "
207 OS <<
"(sext " << *Op->getType() <<
" " << *Op <<
" to "
233 const char *OpStr =
nullptr;
244 if (std::next(I) !=
E)
260 OS <<
"(" << *UDiv->
getLHS() <<
" /u " << *UDiv->
getRHS() <<
")";
267 OS <<
"sizeof(" << *AllocTy <<
")";
271 OS <<
"alignof(" << *AllocTy <<
")";
278 OS <<
"offsetof(" << *CTy <<
", ";
289 OS <<
"***COULDNOTCOMPUTE***";
298 return cast<SCEVConstant>(
this)->
getType();
302 return cast<SCEVCastExpr>(
this)->
getType();
307 return cast<SCEVNAryExpr>(
this)->
getType();
309 return cast<SCEVAddExpr>(
this)->
getType();
311 return cast<SCEVUDivExpr>(
this)->
getType();
313 return cast<SCEVUnknown>(
this)->
getType();
322 return SC->getValue()->isZero();
328 return SC->getValue()->isOne();
334 return SC->getValue()->isMinusOne();
340 if (!Mul)
return false;
344 if (!SC)
return false;
362 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
364 UniqueSCEVs.InsertNode(S, IP);
380 :
SCEV(ID, SCEVTy),
Op(op), Ty(ty) {}
387 "Cannot truncate non-integer value!");
395 "Cannot zero extend non-integer value!");
403 "Cannot sign extend non-integer value!");
406 void SCEVUnknown::deleted() {
408 SE->forgetMemoizedResults(
this);
411 SE->UniqueSCEVs.RemoveNode(
this);
417 void SCEVUnknown::allUsesReplacedWith(
Value *New) {
419 SE->forgetMemoizedResults(
this);
422 SE->UniqueSCEVs.RemoveNode(
this);
432 if (VCE->getOpcode() == Instruction::PtrToInt)
433 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
434 if (CE->getOpcode() == Instruction::GetElementPtr &&
435 CE->getOperand(0)->isNullValue() &&
436 CE->getNumOperands() == 2)
437 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
439 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
449 if (VCE->getOpcode() == Instruction::PtrToInt)
450 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
451 if (CE->getOpcode() == Instruction::GetElementPtr &&
452 CE->getOperand(0)->isNullValue()) {
454 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
455 if (
StructType *STy = dyn_cast<StructType>(Ty))
456 if (!STy->isPacked() &&
457 CE->getNumOperands() == 3 &&
458 CE->getOperand(1)->isNullValue()) {
459 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
461 STy->getNumElements() == 2 &&
462 STy->getElementType(0)->isIntegerTy(1)) {
463 AllocTy = STy->getElementType(1);
474 if (VCE->getOpcode() == Instruction::PtrToInt)
475 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
476 if (CE->getOpcode() == Instruction::GetElementPtr &&
477 CE->getNumOperands() == 3 &&
478 CE->getOperand(0)->isNullValue() &&
479 CE->getOperand(1)->isNullValue()) {
481 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
486 FieldNo = CE->getOperand(2);
525 bool LIsPointer = LV->getType()->isPointerTy(),
526 RIsPointer = RV->getType()->isPointerTy();
527 if (LIsPointer != RIsPointer)
528 return (
int)LIsPointer - (int)RIsPointer;
531 unsigned LID = LV->getValueID(), RID = RV->getValueID();
533 return (
int)LID - (int)RID;
536 if (
const auto *LA = dyn_cast<Argument>(LV)) {
537 const auto *RA = cast<Argument>(RV);
538 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
539 return (
int)LArgNo - (int)RArgNo;
542 if (
const auto *LGV = dyn_cast<GlobalValue>(LV)) {
543 const auto *RGV = cast<GlobalValue>(RV);
545 const auto IsGVNameSemantic = [&](
const GlobalValue *GV) {
546 auto LT = GV->getLinkage();
553 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
554 return LGV->getName().compare(RGV->getName());
559 if (
const auto *LInst = dyn_cast<Instruction>(LV)) {
560 const auto *RInst = cast<Instruction>(RV);
565 if (LParent != RParent) {
566 unsigned LDepth = LI->getLoopDepth(LParent),
567 RDepth = LI->getLoopDepth(RParent);
568 if (LDepth != RDepth)
569 return (
int)LDepth - (int)RDepth;
573 unsigned LNumOps = LInst->getNumOperands(),
574 RNumOps = RInst->getNumOperands();
575 if (LNumOps != RNumOps)
576 return (
int)LNumOps - (int)RNumOps;
578 for (
unsigned Idx :
seq(0u, LNumOps)) {
581 RInst->getOperand(Idx),
Depth + 1);
587 EqCache.insert({LV, RV});
595 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
605 return (
int)LType - (int)RType;
612 switch (static_cast<SCEVTypes>(LType)) {
621 EqCacheSCEV.insert({LHS, RHS});
631 const APInt &RA = RC->getAPInt();
633 if (LBitWidth != RBitWidth)
634 return (
int)LBitWidth - (int)RBitWidth;
635 return LA.ult(RA) ? -1 : 1;
645 const Loop *LLoop = LA->
getLoop(), *RLoop = RA->getLoop();
646 if (LLoop != RLoop) {
647 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
648 assert(LHead != RHead &&
"Two loops share the same header?");
649 if (DT.dominates(LHead, RHead))
652 assert(DT.dominates(RHead, LHead) &&
653 "No dominance between recurrences used by one SCEV?");
658 unsigned LNumOps = LA->
getNumOperands(), RNumOps = RA->getNumOperands();
659 if (LNumOps != RNumOps)
660 return (
int)LNumOps - (int)RNumOps;
663 for (
unsigned i = 0; i != LNumOps; ++i) {
665 RA->getOperand(i), DT,
Depth + 1);
669 EqCacheSCEV.insert({LHS, RHS});
681 unsigned LNumOps = LC->
getNumOperands(), RNumOps = RC->getNumOperands();
682 if (LNumOps != RNumOps)
683 return (
int)LNumOps - (int)RNumOps;
685 for (
unsigned i = 0; i != LNumOps; ++i) {
689 RC->getOperand(i), DT,
Depth + 1);
693 EqCacheSCEV.insert({LHS, RHS});
709 EqCacheSCEV.insert({LHS, RHS});
721 RC->getOperand(), DT,
Depth + 1);
723 EqCacheSCEV.insert({LHS, RHS});
745 if (Ops.
size() < 2)
return;
748 if (Ops.
size() == 2) {
751 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
758 std::stable_sort(Ops.
begin(), Ops.
end(),
759 [&EqCache, LI, &DT](
const SCEV *LHS,
const SCEV *RHS) {
768 for (
unsigned i = 0, e = Ops.
size(); i != e-2; ++i) {
769 const SCEV *S = Ops[i];
774 for (
unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
779 if (i == e-2)
return;
787 struct FindSCEVSize {
789 FindSCEVSize() :
Size(0) {}
791 bool follow(
const SCEV *S) {
796 bool isDone()
const {
809 struct SCEVDivision :
public SCEVVisitor<SCEVDivision, void> {
814 const SCEV *Denominator,
const SCEV **Quotient,
815 const SCEV **Remainder) {
816 assert(Numerator && Denominator &&
"Uninitialized SCEV");
818 SCEVDivision
D(SE, Numerator, Denominator);
822 if (Numerator == Denominator) {
828 if (Numerator->
isZero()) {
835 if (Denominator->
isOne()) {
836 *Quotient = Numerator;
842 if (
const SCEVMulExpr *
T = dyn_cast<SCEVMulExpr>(Denominator)) {
844 *Quotient = Numerator;
845 for (
const SCEV *
Op :
T->operands()) {
846 divide(SE, *Quotient,
Op, &Q, &R);
853 *Remainder = Numerator;
862 *Quotient =
D.Quotient;
863 *Remainder =
D.Remainder;
878 if (
const SCEVConstant *
D = dyn_cast<SCEVConstant>(Denominator)) {
880 APInt DenominatorVal =
D->getAPInt();
884 if (NumeratorBW > DenominatorBW)
885 DenominatorVal = DenominatorVal.
sext(NumeratorBW);
886 else if (NumeratorBW < DenominatorBW)
887 NumeratorVal = NumeratorVal.
sext(DenominatorBW);
891 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
899 const SCEV *StartQ, *StartR, *StepQ, *StepR;
901 return cannotDivide(Numerator);
902 divide(SE, Numerator->
getStart(), Denominator, &StartQ, &StartR);
906 if (Ty != StartQ->getType() || Ty != StartR->
getType() ||
907 Ty != StepQ->getType() || Ty != StepR->
getType())
908 return cannotDivide(Numerator);
921 divide(SE,
Op, Denominator, &Q, &R);
925 return cannotDivide(Numerator);
931 if (Qs.
size() == 1) {
945 bool FoundDenominatorTerm =
false;
948 if (Ty !=
Op->getType())
949 return cannotDivide(Numerator);
951 if (FoundDenominatorTerm) {
958 divide(SE,
Op, Denominator, &Q, &R);
966 return cannotDivide(Numerator);
968 FoundDenominatorTerm =
true;
972 if (FoundDenominatorTerm) {
981 if (!isa<SCEVUnknown>(Denominator))
982 return cannotDivide(Numerator);
986 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
987 cast<SCEVConstant>(
Zero)->getValue();
990 if (Remainder->
isZero()) {
992 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
993 cast<SCEVConstant>(One)->getValue();
1004 return cannotDivide(Numerator);
1005 divide(SE, Diff, Denominator, &Q, &R);
1007 return cannotDivide(Numerator);
1013 const SCEV *Denominator)
1014 : SE(S), Denominator(Denominator) {
1021 cannotDivide(Numerator);
1026 void cannotDivide(
const SCEV *Numerator) {
1028 Remainder = Numerator;
1032 const SCEV *Denominator, *Quotient, *Remainder, *
Zero, *One;
1109 APInt OddFactorial(W, 1);
1111 for (
unsigned i = 3; i <= K; ++i) {
1116 OddFactorial *=
Mult;
1120 unsigned CalculationBits = W +
T;
1123 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1128 APInt Mod = APInt::getSignedMinValue(W+1);
1129 APInt MultiplyFactor = OddFactorial.
zext(W+1);
1131 MultiplyFactor = MultiplyFactor.
trunc(W);
1137 for (
unsigned i = 1; i != K; ++i) {
1161 const SCEV *SCEVAddRecExpr::evaluateAtIteration(
const SCEV *It,
1169 if (isa<SCEVCouldNotCompute>(Coeff))
1184 "This is not a truncating conversion!");
1186 "This is not a conversion to a SCEVable type!");
1194 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1215 if (
const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1217 bool hasTrunc =
false;
1218 for (
unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1220 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1221 hasTrunc = isa<SCEVTruncateExpr>(S);
1226 UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
1231 if (
const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1233 bool hasTrunc =
false;
1234 for (
unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1236 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1237 hasTrunc = isa<SCEVTruncateExpr>(S);
1242 UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
1246 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1248 for (
const SCEV *Op : AddRec->operands())
1258 UniqueSCEVs.InsertNode(S, IP);
1297 struct ExtendOpTraitsBase {
1303 template <
typename ExtendOp>
struct ExtendOpTraits {
1319 static const GetExtendExprTy GetExtendExpr;
1321 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1328 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1335 static const GetExtendExprTy GetExtendExpr;
1337 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1344 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1355 template <
typename ExtendOpTy>
1358 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1359 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1385 auto PreStartFlags =
1403 const SCEV *OperandExtendedStart =
1404 SE->
getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1405 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1406 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1418 const SCEV *OverflowLimit =
1419 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1421 if (OverflowLimit &&
1429 template <
typename ExtendOpTy>
1433 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1435 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE,
Depth);
1437 return (SE->*GetExtendExpr)(AR->getStart(), Ty,
Depth);
1439 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1441 (SE->*GetExtendExpr)(PreStart, Ty,
Depth));
1477 template <
typename ExtendOpTy>
1478 bool ScalarEvolution::proveNoWrapByVaryingStart(
const SCEV *Start,
1481 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1494 for (
unsigned Delta : {-2, -1, 1, 2}) {
1504 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1508 if (PreAR && PreAR->getNoWrapFlags(WrapType)) {
1511 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1512 DeltaS, &Pred,
this);
1524 "This is not an extending conversion!");
1526 "This is not a conversion to a SCEVable type!");
1545 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1549 UniqueSCEVs.InsertNode(S, IP);
1557 const SCEV *X =
ST->getOperand();
1571 if (AR->isAffine()) {
1572 const SCEV *Start = AR->getStart();
1573 const SCEV *Step = AR->getStepRecurrence(*
this);
1575 const Loop *L = AR->getLoop();
1577 if (!AR->hasNoUnsignedWrap()) {
1578 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1584 if (AR->hasNoUnsignedWrap())
1586 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1598 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1604 const SCEV *CastedMaxBECount =
1606 const SCEV *RecastedMaxBECount =
1608 if (MaxBECount == RecastedMaxBECount) {
1618 const SCEV *WideMaxBECount =
1620 const SCEV *OperandExtendedAdd =
1626 if (ZAdd == OperandExtendedAdd) {
1631 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1634 AR->getNoWrapFlags());
1638 OperandExtendedAdd =
1644 if (ZAdd == OperandExtendedAdd) {
1650 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1653 AR->getNoWrapFlags());
1665 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1678 AR->getPostIncExpr(*
this),
N))) {
1684 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1687 AR->getNoWrapFlags());
1695 AR->getPostIncExpr(*
this),
N))) {
1702 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1705 AR->getNoWrapFlags());
1710 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1713 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1718 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1720 if (SA->hasNoUnsignedWrap()) {
1724 for (
const auto *Op : SA->operands())
1732 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1735 UniqueSCEVs.InsertNode(S, IP);
1742 "This is not an extending conversion!");
1744 "This is not a conversion to a SCEVable type!");
1767 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1772 UniqueSCEVs.InsertNode(S, IP);
1780 const SCEV *X =
ST->getOperand();
1790 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1791 if (SA->getNumOperands() == 2) {
1795 if (
auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1796 const APInt &C1 = SC1->getAPInt();
1797 const APInt &C2 = SC2->getAPInt();
1808 if (SA->hasNoSignedWrap()) {
1812 for (
const auto *Op : SA->operands())
1822 if (AR->isAffine()) {
1823 const SCEV *Start = AR->getStart();
1824 const SCEV *Step = AR->getStepRecurrence(*
this);
1826 const Loop *L = AR->getLoop();
1828 if (!AR->hasNoSignedWrap()) {
1829 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1835 if (AR->hasNoSignedWrap())
1837 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
1849 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1855 const SCEV *CastedMaxBECount =
1857 const SCEV *RecastedMaxBECount =
1859 if (MaxBECount == RecastedMaxBECount) {
1869 const SCEV *WideMaxBECount =
1871 const SCEV *OperandExtendedAdd =
1877 if (SAdd == OperandExtendedAdd) {
1882 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
1885 AR->getNoWrapFlags());
1889 OperandExtendedAdd =
1895 if (SAdd == OperandExtendedAdd) {
1908 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
1911 AR->getNoWrapFlags());
1924 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1932 const SCEV *OverflowLimit =
1934 if (OverflowLimit &&
1942 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
1953 const APInt &C1 = SC1->getAPInt();
1954 const APInt &C2 = SC2->getAPInt();
1959 AR->getNoWrapFlags());
1965 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1968 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
1980 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1983 UniqueSCEVs.InsertNode(S, IP);
1993 "This is not an extending conversion!");
1995 "This is not a conversion to a SCEVable type!");
2000 if (
SC->getAPInt().isNegative())
2005 const SCEV *NewOp =
T->getOperand();
2013 if (!isa<SCEVZeroExtendExpr>(ZExt))
2018 if (!isa<SCEVSignExtendExpr>(SExt))
2024 for (
const SCEV *Op : AR->operands())
2030 if (isa<SCEVSMaxExpr>(Op))
2064 APInt &AccumulatedConstant,
2065 const SCEV *
const *Ops,
size_t NumOperands,
2068 bool Interesting =
false;
2072 while (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2075 if (Scale != 1 || AccumulatedConstant != 0 ||
C->getValue()->isZero())
2077 AccumulatedConstant += Scale *
C->getAPInt();
2082 for (; i != NumOperands; ++i) {
2084 if (Mul && isa<SCEVConstant>(Mul->
getOperand(0))) {
2086 Scale * cast<SCEVConstant>(Mul->
getOperand(0))->getAPInt();
2099 auto Pair = M.
insert({Key, NewScale});
2103 Pair.first->second += NewScale;
2111 std::pair<DenseMap<const SCEV *, APInt>::iterator,
bool> Pair =
2112 M.
insert({Ops[i], Scale});
2116 Pair.first->second += Scale;
2134 using namespace std::placeholders;
2140 assert(CanAnalyze &&
"don't call from other places!");
2147 auto IsKnownNonNegative = [&](
const SCEV *S) {
2157 if (SignOrUnsignWrap != SignOrUnsignMask && Type ==
scAddExpr &&
2158 Ops.
size() == 2 && isa<SCEVConstant>(Ops[0])) {
2163 const APInt &
C = cast<SCEVConstant>(Ops[0])->getAPInt();
2186 struct FindDominatedSCEVUnknown {
2193 :
L(L), DT(DT), LI(LI) {}
2196 if (
auto *
I = dyn_cast<Instruction>(SU->
getValue())) {
2201 "No dominance relationship between SCEV and loop?");
2206 bool follow(
const SCEV *S) {
2207 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
2221 return checkSCEVUnknown(cast<SCEVUnknown>(S));
2228 bool isDone() {
return Found; }
2231 FindDominatedSCEVUnknown FSU(L, DT, LI);
2242 "only nuw or nsw allowed");
2244 if (Ops.
size() == 1)
return Ops[0];
2247 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
2249 "SCEVAddExpr operand types don't match!");
2259 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2262 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2264 Ops[0] =
getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2265 if (Ops.
size() == 2)
return Ops[0];
2267 LHSC = cast<SCEVConstant>(Ops[0]);
2271 if (LHSC->getValue()->isZero()) {
2276 if (Ops.
size() == 1)
return Ops[0];
2281 return getOrCreateAddExpr(Ops, Flags);
2286 Type *Ty = Ops[0]->getType();
2287 bool FoundMatch =
false;
2288 for (
unsigned i = 0, e = Ops.
size(); i != e-1; ++i)
2289 if (Ops[i] == Ops[i+1]) {
2292 while (i+Count != e && Ops[i+Count] == Ops[i])
2297 if (Ops.
size() == Count)
2301 --i; e -= Count - 1;
2311 for (; Idx < Ops.
size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2319 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
2321 if (
T->getOperand()->getType() != SrcType) {
2326 }
else if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2328 }
else if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2330 for (
unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2332 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2333 if (
T->getOperand()->getType() != SrcType) {
2338 }
else if (
const auto *
C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2356 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2362 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scAddExpr)
2366 if (Idx < Ops.
size()) {
2367 bool DeletedAdd =
false;
2368 while (
const SCEVAddExpr *
Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2387 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
2392 if (Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx])) {
2396 APInt AccumulatedConstant(BitWidth, 0);
2399 APInt(BitWidth, 1), *
this)) {
2400 struct APIntCompare {
2401 bool operator()(
const APInt &LHS,
const APInt &RHS)
const {
2402 return LHS.
ult(RHS);
2409 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2410 for (
const SCEV *NewOp : NewOps)
2411 MulOpLists[M.
find(NewOp)->second].push_back(NewOp);
2414 if (AccumulatedConstant != 0)
2416 for (
auto &MulOp : MulOpLists)
2417 if (MulOp.first != 0)
2424 if (Ops.
size() == 1)
2433 for (; Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2434 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2435 for (
unsigned MulOp = 0, e = Mul->
getNumOperands(); MulOp != e; ++MulOp) {
2437 if (isa<SCEVConstant>(MulOpSCEV))
2439 for (
unsigned AddOp = 0, e = Ops.
size(); AddOp != e; ++AddOp)
2440 if (MulOpSCEV == Ops[AddOp]) {
2455 if (Ops.
size() == 2)
return OuterMul;
2468 for (
unsigned OtherMulIdx = Idx+1;
2469 OtherMulIdx < Ops.
size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2471 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2475 OMulOp != e; ++OMulOp)
2476 if (OtherMul->
getOperand(OMulOp) == MulOpSCEV) {
2493 const SCEV *InnerMulSum =
2497 if (Ops.
size() == 2)
return OuterMul;
2514 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2520 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2528 if (!LIOps.
empty()) {
2537 AddRecOps[0] =
getAddExpr(LIOps, Flags, Depth + 1);
2546 if (Ops.
size() == 1)
return NewRec;
2549 for (
unsigned i = 0;; ++i)
2550 if (Ops[i] == AddRec) {
2560 for (
unsigned OtherIdx = Idx+1;
2561 OtherIdx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2566 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2568 "AddRecExprs are not sorted in reverse dominance order?");
2569 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2573 for (; OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2575 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2576 if (OtherAddRec->getLoop() == AddRecLoop) {
2577 for (
unsigned i = 0, e = OtherAddRec->getNumOperands();
2579 if (i >= AddRecOps.size()) {
2580 AddRecOps.
append(OtherAddRec->op_begin()+i,
2581 OtherAddRec->op_end());
2585 AddRecOps[i], OtherAddRec->getOperand(i)};
2588 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
2603 return getOrCreateAddExpr(Ops, Flags);
2611 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2615 static_cast<SCEVAddExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2618 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
2619 S =
new (SCEVAllocator)
2621 UniqueSCEVs.InsertNode(S, IP);
2623 S->setNoWrapFlags(Flags);
2632 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2636 static_cast<SCEVMulExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2639 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
2642 UniqueSCEVs.InsertNode(S, IP);
2644 S->setNoWrapFlags(Flags);
2648 static uint64_t
umul_ov(uint64_t i, uint64_t j,
bool &Overflow) {
2650 if (j > 1 && k / j != i) Overflow =
true;
2657 static uint64_t
Choose(uint64_t n, uint64_t k,
bool &Overflow) {
2666 if (n == 0 || n == k)
return 1;
2667 if (k > n)
return 0;
2673 for (uint64_t i = 1; i <= k; ++i) {
2674 r =
umul_ov(r, n-(i-1), Overflow);
2685 while (!Ops.
empty()) {
2687 if (isa<SCEVConstant>(*CurrentExpr))
2690 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2691 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2692 Ops.
append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2703 "only nuw or nsw allowed");
2705 if (Ops.
size() == 1)
return Ops[0];
2708 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
2710 "SCEVMulExpr operand types don't match!");
2720 return getOrCreateMulExpr(Ops, Flags);
2724 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2727 if (Ops.
size() == 2)
2731 if (
Add->getNumOperands() == 2)
2740 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2745 Ops.erase(Ops.begin()+1);
2746 if (Ops.size() == 1)
return Ops[0];
2747 LHSC = cast<SCEVConstant>(Ops[0]);
2751 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2754 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2757 }
else if (Ops[0]->isAllOnesValue()) {
2760 if (Ops.
size() == 2) {
2763 bool AnyFolded =
false;
2764 for (
const SCEV *AddOp :
Add->operands()) {
2767 if (!isa<SCEVMulExpr>(Mul)) AnyFolded =
true;
2772 }
else if (
const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2775 for (
const SCEV *AddRecOp : AddRec->operands())
2785 if (Ops.
size() == 1)
2790 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
2794 if (Idx < Ops.
size()) {
2795 bool DeletedMul =
false;
2796 while (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2802 Ops.
append(Mul->op_begin(), Mul->op_end());
2820 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2826 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2834 if (!LIOps.
empty()) {
2852 if (Ops.
size() == 1)
return NewRec;
2855 for (
unsigned i = 0;; ++i)
2856 if (Ops[i] == AddRec) {
2877 bool OpsModified =
false;
2878 for (
unsigned OtherIdx = Idx+1;
2879 OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2883 if (!OtherAddRec || OtherAddRec->
getLoop() != AddRecLoop)
2892 bool Overflow =
false;
2899 for (
int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2900 uint64_t Coeff1 =
Choose(x, 2*x - y, Overflow);
2903 z < ze && !Overflow; ++z) {
2904 uint64_t Coeff2 =
Choose(2*x - y, x-z, Overflow);
2906 if (LargerThan64Bits)
2907 Coeff =
umul_ov(Coeff1, Coeff2, Overflow);
2909 Coeff = Coeff1*Coeff2;
2923 if (Ops.
size() == 2)
return NewAddRec;
2924 Ops[Idx] = NewAddRec;
2925 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
2941 return getOrCreateMulExpr(Ops, Flags);
2950 "SCEVUDivExpr operand types don't match!");
2952 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2953 if (RHSC->getValue()->isOne())
2958 if (!RHSC->getValue()->isZero()) {
2963 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2967 if (!RHSC->getAPInt().isPowerOf2())
2973 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*
this))) {
2975 const APInt &StepInt = Step->getAPInt();
2976 const APInt &DivInt = RHSC->getAPInt();
2977 if (!StepInt.
urem(DivInt) &&
2983 for (
const SCEV *
Op : AR->operands())
2991 if (StartC && !DivInt.
urem(StepInt) &&
2997 const APInt &StartRem = StartInt.
urem(StepInt);
3004 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3006 for (
const SCEV *
Op : M->operands())
3010 for (
unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3011 const SCEV *
Op = M->getOperand(i);
3013 if (!isa<SCEVUDivExpr>(Div) &&
getMulExpr(Div, RHSC) == Op) {
3022 if (
const SCEVAddExpr *
A = dyn_cast<SCEVAddExpr>(LHS)) {
3024 for (
const SCEV *
Op :
A->operands())
3028 for (
unsigned i = 0, e =
A->getNumOperands(); i != e; ++i) {
3030 if (isa<SCEVUDivExpr>(Op) ||
3035 if (Operands.
size() ==
A->getNumOperands())
3041 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3042 Constant *LHSCV = LHSC->getValue();
3043 Constant *RHSCV = RHSC->getValue();
3055 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3058 UniqueSCEVs.InsertNode(S, IP);
3090 if (
const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3093 if (
const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->
getOperand(0))) {
3094 if (LHSCst == RHSCst) {
3103 APInt Factor =
gcd(LHSCst, RHSCst);
3106 cast<SCEVConstant>(
getConstant(LHSCst->getAPInt().udiv(Factor)));
3108 cast<SCEVConstant>(
getConstant(RHSCst->getAPInt().udiv(Factor)));
3140 if (
const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3141 if (StepChrec->getLoop() ==
L) {
3142 Operands.
append(StepChrec->op_begin(), StepChrec->op_end());
3155 if (Operands.
size() == 1)
return Operands[0];
3158 for (
unsigned i = 1, e = Operands.
size(); i != e; ++i)
3160 "SCEVAddRecExpr operand types don't match!");
3161 for (
unsigned i = 0, e = Operands.
size(); i != e; ++i)
3163 "SCEVAddRecExpr operand is not loop-invariant!");
3180 if (
const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3181 const Loop *NestedLoop = NestedAR->getLoop();
3187 NestedAR->op_end());
3188 Operands[0] = NestedAR->getStart();
3192 bool AllInvariant =
all_of(
3204 AllInvariant =
all_of(NestedOperands, [&](
const SCEV *Op) {
3215 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3219 Operands[0] = NestedAR;
3227 for (
unsigned i = 0, e = Operands.
size(); i != e; ++i)
3232 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3235 std::uninitialized_copy(Operands.
begin(), Operands.
end(), O);
3237 O, Operands.
size(),
L);
3238 UniqueSCEVs.InsertNode(S, IP);
3263 for (
const SCEV *IndexExpr : IndexExprs) {
3265 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
3267 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3272 TotalOffset =
getAddExpr(TotalOffset, FieldOffset);
3275 CurTy = STy->getTypeAtIndex(Index);
3278 CurTy = cast<SequentialType>(CurTy)->getElementType();
3285 const SCEV *LocalOffset =
getMulExpr(IndexExpr, ElementSize, Wrap);
3288 TotalOffset =
getAddExpr(TotalOffset, LocalOffset);
3293 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3305 if (Ops.
size() == 1)
return Ops[0];
3308 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
3310 "SCEVSMaxExpr operand types don't match!");
3318 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3321 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3327 if (Ops.
size() == 1)
return Ops[0];
3328 LHSC = cast<SCEVConstant>(Ops[0]);
3332 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(
true)) {
3335 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(
true)) {
3341 if (Ops.
size() == 1)
return Ops[0];
3350 if (Idx < Ops.
size()) {
3351 bool DeletedSMax =
false;
3352 while (
const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3354 Ops.
append(SMax->op_begin(), SMax->op_end());
3365 for (
unsigned i = 0, e = Ops.
size()-1; i != e; ++i)
3368 if (Ops[i] == Ops[i+1] ||
3377 if (Ops.
size() == 1)
return Ops[0];
3379 assert(!Ops.
empty() &&
"Reduced smax down to nothing!");
3385 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
3386 ID.AddPointer(Ops[i]);
3388 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3390 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
3393 UniqueSCEVs.InsertNode(S, IP);
3406 if (Ops.
size() == 1)
return Ops[0];
3409 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
3411 "SCEVUMaxExpr operand types don't match!");
3419 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3422 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3428 if (Ops.
size() == 1)
return Ops[0];
3429 LHSC = cast<SCEVConstant>(Ops[0]);
3433 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(
false)) {
3436 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(
false)) {
3442 if (Ops.
size() == 1)
return Ops[0];
3451 if (Idx < Ops.
size()) {
3452 bool DeletedUMax =
false;
3453 while (
const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3455 Ops.
append(UMax->op_begin(), UMax->op_end());
3466 for (
unsigned i = 0, e = Ops.
size()-1; i != e; ++i)
3469 if (Ops[i] == Ops[i+1] ||
3478 if (Ops.
size() == 1)
return Ops[0];
3480 assert(!Ops.
empty() &&
"Reduced umax down to nothing!");
3486 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
3487 ID.AddPointer(Ops[i]);
3489 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3491 std::uninitialized_copy(Ops.
begin(), Ops.
end(), O);
3494 UniqueSCEVs.InsertNode(S, IP);
3524 IntTy,
getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3537 if (
SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3538 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3539 "Stale SCEVUnknown in uniquing map!");
3544 FirstUnknown = cast<SCEVUnknown>(S);
3545 UniqueSCEVs.InsertNode(S, IP);
3588 return CouldNotCompute.get();
3591 bool ScalarEvolution::checkValidity(
const SCEV *S)
const {
3594 return SU && SU->
getValue() ==
nullptr;
3597 return !ContainsNulls;
3602 if (I != HasRecMap.
end())
3606 HasRecMap.
insert({S, FoundAddRec});
3616 return {S,
nullptr};
3618 if (
Add->getNumOperands() != 2)
3619 return {S,
nullptr};
3623 return {S,
nullptr};
3625 return {
Add->getOperand(1), ConstOp->getValue()};
3633 if (SI == ExprValueMap.
end())
3638 for (
const auto &VE : SI->second)
3650 if (I != ValueExprMap.
end()) {
3651 const SCEV *S = I->second;
3654 SV->remove({V,
nullptr});
3657 const SCEV *Stripped;
3660 if (Offset !=
nullptr) {
3662 SV->remove({V, Offset});
3664 ValueExprMap.
erase(V);
3673 const SCEV *S = getExistingSCEV(V);
3679 std::pair<ValueExprMapType::iterator, bool> Pair =
3682 ExprValueMap[S].
insert({V,
nullptr});
3686 const SCEV *Stripped = S;
3694 if (Offset !=
nullptr && !isa<SCEVUnknown>(Stripped) &&
3695 !isa<GetElementPtrInst>(V))
3696 ExprValueMap[Stripped].
insert({V, Offset});
3702 const SCEV *ScalarEvolution::getExistingSCEV(
Value *V) {
3706 if (I != ValueExprMap.
end()) {
3707 const SCEV *S = I->second;
3708 if (checkValidity(S))
3711 forgetMemoizedResults(S);
3738 const SCEV *AllOnes =
3753 const bool RHSIsNotMinSigned =
3787 "Cannot truncate or zero extend with non-integer arguments!");
3801 "Cannot truncate or zero extend with non-integer arguments!");
3814 "Cannot noop or zero extend with non-integer arguments!");
3816 "getNoopOrZeroExtend cannot truncate!");
3827 "Cannot noop or sign extend with non-integer arguments!");
3829 "getNoopOrSignExtend cannot truncate!");
3840 "Cannot noop or any extend with non-integer arguments!");
3842 "getNoopOrAnyExtend cannot truncate!");
3853 "Cannot truncate or noop with non-integer arguments!");
3855 "getTruncateOrNoop cannot extend!");
3863 const SCEV *PromotedLHS = LHS;
3864 const SCEV *PromotedRHS = RHS;
3876 const SCEV *PromotedLHS = LHS;
3877 const SCEV *PromotedRHS = RHS;
3892 if (
const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3894 }
else if (
const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3895 const SCEV *PtrOp =
nullptr;
3896 for (
const SCEV *NAryOp : NAry->operands()) {
3897 if (NAryOp->getType()->isPointerTy()) {
3917 Worklist.
push_back(cast<Instruction>(U));
3920 void ScalarEvolution::forgetSymbolicName(
Instruction *PN,
const SCEV *SymName) {
3926 while (!Worklist.
empty()) {
3928 if (!Visited.
insert(I).second)
3931 auto It = ValueExprMap.
find_as(static_cast<Value *>(I));
3932 if (It != ValueExprMap.
end()) {
3933 const SCEV *Old = It->second;
3937 if (Old != SymName && !
hasOperand(Old, SymName))
3947 if (!isa<PHINode>(I) ||
3948 !isa<SCEVUnknown>(Old) ||
3949 (I != PN && Old == SymName)) {
3951 forgetMemoizedResults(Old);
3962 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
3986 bool isValid() {
return Valid; }
3995 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
4018 bool isValid() {
return Valid; }
4027 ScalarEvolution::proveNoWrapViaConstantRanges(
const SCEVAddRecExpr *AR) {
4040 if (NSWRegion.contains(AddRecRange))
4050 if (NUWRegion.contains(AddRecRange))
4073 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4075 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4076 IsNSW = OBO->hasNoSignedWrap();
4077 IsNUW = OBO->hasNoUnsignedWrap();
4081 explicit BinaryOp(
unsigned Opcode,
Value *LHS,
Value *RHS,
bool IsNSW =
false,
4083 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4101 case Instruction::Sub:
4102 case Instruction::Mul:
4103 case Instruction::UDiv:
4104 case Instruction::And:
4105 case Instruction::Or:
4106 case Instruction::AShr:
4107 case Instruction::Shl:
4108 return BinaryOp(Op);
4110 case Instruction::Xor:
4111 if (
auto *RHSC = dyn_cast<ConstantInt>(Op->
getOperand(1)))
4114 if (RHSC->getValue().isSignMask())
4116 return BinaryOp(Op);
4118 case Instruction::LShr:
4127 if (SA->getValue().ult(BitWidth)) {
4131 return BinaryOp(Instruction::UDiv, Op->
getOperand(0),
X);
4134 return BinaryOp(Op);
4136 case Instruction::ExtractValue: {
4137 auto *EVI = cast<ExtractValueInst>(
Op);
4138 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4145 if (
auto *
F = CI->getCalledFunction())
4146 switch (
F->getIntrinsicID()) {
4147 case Intrinsic::sadd_with_overflow:
4148 case Intrinsic::uadd_with_overflow: {
4151 CI->getArgOperand(1));
4156 if (
F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4158 CI->getArgOperand(1),
true,
4162 CI->getArgOperand(1),
false,
4166 case Intrinsic::ssub_with_overflow:
4167 case Intrinsic::usub_with_overflow:
4168 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4169 CI->getArgOperand(1));
4171 case Intrinsic::smul_with_overflow:
4172 case Intrinsic::umul_with_overflow:
4173 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4174 CI->getArgOperand(1));
4211 if (Op == SymbolicPHI)
4216 if (SourceBits != NewBits)
4225 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4229 if (X != SymbolicPHI)
4231 Signed = SExt ?
true :
false;
4299 ScalarEvolution::createAddRecFromPHIWithCastsImpl(
const SCEVUnknown *SymbolicPHI) {
4305 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4307 assert (L &&
"Expecting an integer loop header phi");
4312 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
4313 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4314 Value *V = PN->getIncomingValue(i);
4315 if (L->contains(PN->getIncomingBlock(i))) {
4318 }
else if (BEValueV != V) {
4322 }
else if (!StartValueV) {
4324 }
else if (StartValueV != V) {
4325 StartValueV =
nullptr;
4329 if (!BEValueV || !StartValueV)
4343 unsigned FoundIndex =
Add->getNumOperands();
4344 Type *TruncTy =
nullptr;
4346 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4349 if (FoundIndex == e) {
4354 if (FoundIndex ==
Add->getNumOperands())
4359 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4360 if (i != FoundIndex)
4422 const SCEV *PHISCEV =
4425 const auto *AR = cast<SCEVAddRecExpr>(PHISCEV);
4434 auto AppendPredicate = [&](
const SCEV *Expr) ->
void {
4437 const SCEV *ExtendedExpr =
4440 if (Expr != ExtendedExpr &&
4443 DEBUG (
dbgs() <<
"Added Predicate: " << *Pred);
4448 AppendPredicate(StartVal);
4449 AppendPredicate(Accum);
4457 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4458 std::make_pair(NewAR, Predicates);
4460 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4467 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4473 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4474 if (I != PredicatedSCEVRewrites.end()) {
4475 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4478 if (Rewrite.first == SymbolicPHI)
4482 assert(isa<SCEVAddRecExpr>(Rewrite.first) &&
"Expected an AddRec");
4483 assert(!(Rewrite.second).empty() &&
"Expected to find Predicates");
4488 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4493 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4506 const SCEV *ScalarEvolution::createSimpleAffineAddRec(
PHINode *PN,
4508 Value *StartValueV) {
4511 assert(BEValueV && StartValueV);
4520 const SCEV *Accum =
nullptr;
4543 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
4550 const SCEV *ScalarEvolution::createAddRecFromPHI(
PHINode *PN) {
4558 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
4564 }
else if (BEValueV != V) {
4568 }
else if (!StartValueV) {
4570 }
else if (StartValueV != V) {
4571 StartValueV =
nullptr;
4575 if (!BEValueV || !StartValueV)
4579 "PHI node already processed?");
4583 if (
auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4602 unsigned FoundIndex =
Add->getNumOperands();
4603 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4604 if (
Add->getOperand(i) == SymbolicName)
4605 if (FoundIndex == e) {
4610 if (FoundIndex !=
Add->getNumOperands()) {
4613 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4614 if (i != FoundIndex)
4621 (isa<SCEVAddRecExpr>(Accum) &&
4622 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4639 if (
GEP->isInBounds() &&
GEP->getOperand(0) == PN) {
4658 forgetSymbolicName(PN, SymbolicName);
4664 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
4681 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *
this);
4682 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *
this);
4686 if (Start == StartVal) {
4690 forgetSymbolicName(PN, SymbolicName);
4710 struct CheckAvailable {
4711 bool TraversalDone =
false;
4712 bool Available =
true;
4714 const Loop *L =
nullptr;
4719 :
L(L), BB(BB), DT(DT) {}
4721 bool setUnavailable() {
4722 TraversalDone =
true;
4727 bool follow(
const SCEV *S) {
4740 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4741 if (L && (ARLoop == L || ARLoop->
contains(L)))
4744 return setUnavailable();
4749 const auto *SU = cast<SCEVUnknown>(S);
4750 Value *V = SU->getValue();
4752 if (isa<Argument>(V))
4755 if (isa<Instruction>(V) && DT.
dominates(cast<Instruction>(V), BB))
4758 return setUnavailable();
4764 return setUnavailable();
4769 bool isDone() {
return TraversalDone; }
4772 CheckAvailable CA(L, BB, DT);
4776 return CA.Available;
4789 if (!LeftEdge.isSingleEdge())
4792 assert(RightEdge.isSingleEdge() &&
"Follows from LeftEdge.isSingleEdge()");
4812 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(
PHINode *PN) {
4836 assert(IDom &&
"At least the entry block should dominate PN");
4839 Value *Cond =
nullptr, *LHS =
nullptr, *RHS =
nullptr;
4841 if (BI && BI->isConditional() &&
4845 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4851 const SCEV *ScalarEvolution::createNodeForPHI(
PHINode *PN) {
4852 if (
const SCEV *S = createAddRecFromPHI(PN))
4855 if (
const SCEV *S = createNodeFromSelectLikePHI(PN))
4876 if (
auto *CI = dyn_cast<ConstantInt>(Cond))
4877 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4884 Value *LHS = ICI->getOperand(0);
4885 Value *RHS = ICI->getOperand(1);
4887 switch (ICI->getPredicate()) {
4937 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
4951 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
4982 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(
const SCEV *S) {
4984 return C->getAPInt().countTrailingZeros();
5007 for (
unsigned i = 1, e =
A->getNumOperands(); MinOpRes && i != e; ++i)
5012 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5016 for (
unsigned i = 1, e = M->getNumOperands();
5017 SumOpRes != BitWidth && i != e; ++i)
5026 for (
unsigned i = 1, e =
A->getNumOperands(); MinOpRes && i != e; ++i)
5031 if (
const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5034 for (
unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5039 if (
const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5042 for (
unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5047 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5058 auto I = MinTrailingZerosCache.find(S);
5059 if (I != MinTrailingZerosCache.end())
5062 uint32_t Result = GetMinTrailingZerosImpl(S);
5063 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5064 assert(InsertPair.second &&
"Should insert a new key");
5065 return InsertPair.first->second;
5081 ScalarEvolution::getRangeRef(
const SCEV *S,
5082 ScalarEvolution::RangeSignHint SignHint) {
5084 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5089 if (I != Cache.
end())
5102 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5103 ConservativeResult =
5114 for (
unsigned i = 1, e =
Add->getNumOperands(); i != e; ++i)
5115 X = X.
add(getRangeRef(
Add->getOperand(i), SignHint));
5116 return setRange(
Add, SignHint, ConservativeResult.intersectWith(X));
5119 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5120 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5121 for (
unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5122 X = X.
multiply(getRangeRef(Mul->getOperand(i), SignHint));
5123 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5126 if (
const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5127 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5128 for (
unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5129 X = X.
smax(getRangeRef(SMax->getOperand(i), SignHint));
5130 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5133 if (
const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5134 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5135 for (
unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5136 X = X.
umax(getRangeRef(UMax->getOperand(i), SignHint));
5137 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5140 if (
const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5143 return setRange(UDiv, SignHint,
5144 ConservativeResult.intersectWith(X.
udiv(Y)));
5148 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5149 return setRange(ZExt, SignHint,
5150 ConservativeResult.intersectWith(X.
zeroExtend(BitWidth)));
5154 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5155 return setRange(SExt, SignHint,
5156 ConservativeResult.intersectWith(X.
signExtend(BitWidth)));
5160 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5161 return setRange(Trunc, SignHint,
5162 ConservativeResult.intersectWith(X.
truncate(BitWidth)));
5165 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5168 if (AddRec->hasNoUnsignedWrap())
5169 if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5170 if (!
C->getValue()->isZero())
5171 ConservativeResult = ConservativeResult.intersectWith(
5176 if (AddRec->hasNoSignedWrap()) {
5177 bool AllNonNeg =
true;
5178 bool AllNonPos =
true;
5179 for (
unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5184 ConservativeResult = ConservativeResult.intersectWith(
5188 ConservativeResult = ConservativeResult.intersectWith(
5190 APInt(BitWidth, 1)));
5194 if (AddRec->isAffine()) {
5196 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5198 auto RangeFromAffine = getRangeForAffineAR(
5199 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5201 if (!RangeFromAffine.isFullSet())
5202 ConservativeResult =
5205 auto RangeFromFactoring = getRangeViaFactoring(
5206 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5208 if (!RangeFromFactoring.isFullSet())
5209 ConservativeResult =
5214 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5217 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5221 ConservativeResult = ConservativeResult.intersectWith(MDRange.
getValue());
5227 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5230 if (Known.
One != ~Known.
Zero + 1)
5231 ConservativeResult =
5235 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5236 "generalize as needed!");
5239 ConservativeResult = ConservativeResult.intersectWith(
5244 return setRange(U, SignHint, std::move(ConservativeResult));
5247 return setRange(S, SignHint, std::move(ConservativeResult));
5256 const APInt &MaxBECount,
5257 unsigned BitWidth,
bool Signed) {
5260 if (Step == 0 || MaxBECount == 0)
5271 bool Descending = Signed && Step.
isNegative();
5295 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5296 : (StartUpper + std::move(Offset));
5301 if (StartRange.
contains(MovedBoundary))
5305 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5307 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5311 if (NewLower == NewUpper)
5315 return ConstantRange(std::move(NewLower), std::move(NewUpper));
5320 const SCEV *MaxBECount,
5321 unsigned BitWidth) {
5322 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5337 MaxBECountValue, BitWidth,
true);
5339 StartSRange, MaxBECountValue,
5345 MaxBECountValue, BitWidth,
false);
5348 return SR.intersectWith(UR);
5353 const SCEV *MaxBECount,
5354 unsigned BitWidth) {
5358 struct SelectPattern {
5359 Value *Condition =
nullptr;
5372 if (
auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5375 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5378 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5379 S = SA->getOperand(1);
5383 if (
auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5384 CastOp = SCast->getSCEVType();
5385 S = SCast->getOperand();
5388 using namespace llvm::PatternMatch;
5391 const APInt *TrueVal, *FalseVal;
5395 Condition =
nullptr;
5399 TrueValue = *TrueVal;
5400 FalseValue = *FalseVal;
5409 TrueValue = TrueValue.trunc(BitWidth);
5410 FalseValue = FalseValue.trunc(BitWidth);
5413 TrueValue = TrueValue.zext(BitWidth);
5414 FalseValue = FalseValue.zext(BitWidth);
5417 TrueValue = TrueValue.sext(BitWidth);
5418 FalseValue = FalseValue.sext(BitWidth);
5427 bool isRecognized() {
return Condition !=
nullptr; }
5430 SelectPattern StartPattern(*
this, BitWidth, Start);
5431 if (!StartPattern.isRecognized())
5434 SelectPattern StepPattern(*
this, BitWidth, Step);
5435 if (!StepPattern.isRecognized())
5438 if (StartPattern.Condition != StepPattern.Condition) {
5459 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5461 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5463 return TrueRange.unionWith(FalseRange);
5482 bool ScalarEvolution::isSCEVExprNeverPoison(
const Instruction *I) {
5489 if (InnermostContainingLoop ==
nullptr ||
5512 for (
unsigned OpIndex = 0; OpIndex < I->
getNumOperands(); ++OpIndex) {
5518 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5519 bool AllOtherOpsLoopInvariant =
true;
5520 for (
unsigned OtherOpIndex = 0; OtherOpIndex < I->
getNumOperands();
5522 if (OtherOpIndex != OpIndex) {
5525 AllOtherOpsLoopInvariant =
false;
5530 if (AllOtherOpsLoopInvariant &&
5538 bool ScalarEvolution::isAddRecNeverPoison(
const Instruction *I,
const Loop *L) {
5540 if (isSCEVExprNeverPoison(I))
5567 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5579 bool LatchControlDependentOnPoison =
false;
5580 while (!PoisonStack.
empty() && !LatchControlDependentOnPoison) {
5583 for (
auto *PoisonUser : Poison->
users()) {
5585 if (Pushed.
insert(cast<Instruction>(PoisonUser)).second)
5586 PoisonStack.
push_back(cast<Instruction>(PoisonUser));
5587 }
else if (
auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5588 assert(BI->isConditional() &&
"Only possibility!");
5589 if (BI->getParent() == LatchBB) {
5590 LatchControlDependentOnPoison =
true;
5597 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5600 ScalarEvolution::LoopProperties
5601 ScalarEvolution::getLoopProperties(
const Loop *L) {
5602 typedef ScalarEvolution::LoopProperties LoopProperties;
5604 auto Itr = LoopPropertiesCache.find(L);
5605 if (Itr == LoopPropertiesCache.end()) {
5607 if (
auto *SI = dyn_cast<StoreInst>(I))
5608 return !
SI->isSimple();
5613 LoopProperties LP = {
true,
5617 for (
auto &I : *BB) {
5619 LP.HasNoAbnormalExits =
false;
5620 if (HasSideEffects(&I))
5621 LP.HasNoSideEffects =
false;
5622 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5626 auto InsertPair = LoopPropertiesCache.insert({
L, LP});
5627 assert(InsertPair.second &&
"We just checked!");
5628 Itr = InsertPair.first;
5634 const SCEV *ScalarEvolution::createSCEV(
Value *V) {
5645 }
else if (
ConstantInt *CI = dyn_cast<ConstantInt>(V))
5647 else if (isa<ConstantPointerNull>(V))
5649 else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5651 else if (!isa<ConstantExpr>(V))
5656 switch (BO->Opcode) {
5667 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
5683 if (BO->Opcode == Instruction::Sub)
5691 if (BO->Opcode == Instruction::Sub)
5698 NewBO->Opcode != Instruction::Sub)) {
5708 case Instruction::Mul: {
5712 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
5727 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5736 case Instruction::UDiv:
5738 case Instruction::Sub: {
5741 Flags = getNoWrapFlagsFromUB(BO->Op);
5744 case Instruction::And:
5747 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5750 if (CI->isMinusOne())
5752 const APInt &
A = CI->getValue();
5763 0, &AC,
nullptr, &DT);
5765 APInt EffectiveMask =
5767 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.
Zero) & EffectiveMask)) {
5770 const SCEV *ShiftedLHS =
nullptr;
5771 if (
auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5772 if (
auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5774 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5775 unsigned GCD =
std::min(MulZeros, TZ);
5779 MulOps.
append(LHSMul->op_begin() + 1, LHSMul->op_end());
5780 auto *NewMul =
getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5796 case Instruction::Or:
5803 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5805 const APInt &CIVal = CI->getValue();
5822 case Instruction::Xor:
5823 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5825 if (CI->isMinusOne())
5832 if (
auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5833 if (
ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5834 if (LBO->getOpcode() == Instruction::And &&
5835 LCI->getValue() == CI->getValue())
5837 dyn_cast<SCEVZeroExtendExpr>(
getSCEV(BO->LHS))) {
5838 Type *UTy = BO->LHS->getType();
5839 const SCEV *Z0 =
Z->getOperand();
5846 if (CI->getValue().isMask(Z0TySize))
5852 APInt Trunc = CI->getValue().
trunc(Z0TySize);
5861 case Instruction::Shl:
5863 if (
ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5870 if (SA->getValue().uge(BitWidth))
5880 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5881 Flags = getNoWrapFlagsFromUB(BO->Op);
5889 case Instruction::AShr:
5895 Type *OuterTy = BO->LHS->getType();
5911 if (L && L->
getOpcode() == Instruction::Shl) {
5924 if (ShlAmtCI && ShlAmtCI->
getValue().
ult(BitWidth)) {
5926 if (ShlAmt > AShrAmt) {
5944 case Instruction::Trunc:
5947 case Instruction::ZExt:
5950 case Instruction::SExt:
5953 case Instruction::BitCast:
5964 case Instruction::GetElementPtr:
5965 return createNodeForGEP(cast<GEPOperator>(U));
5967 case Instruction::PHI:
5968 return createNodeForPHI(cast<PHINode>(U));
5975 if (isa<Instruction>(U))
5976 return createNodeForSelectOrPHI(cast<Instruction>(U), U->
getOperand(0),
5981 case Instruction::Invoke:
6020 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6022 "Exiting block must actually branch out of the loop!");
6029 const auto *MaxExitCount =
6057 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6059 "Exiting block must actually branch out of the loop!");
6091 return getBackedgeTakenInfo(L).getExact(ExitingBlock,
this);
6097 return getPredicatedBackedgeTakenInfo(L).getExact(
this, &Preds);
6101 return getBackedgeTakenInfo(L).getExact(
this);
6107 return getBackedgeTakenInfo(L).getMax(
this);
6111 return getBackedgeTakenInfo(L).isMaxOrZero(
this);
6125 const ScalarEvolution::BackedgeTakenInfo &
6126 ScalarEvolution::getPredicatedBackedgeTakenInfo(
const Loop *L) {
6127 auto &BTI = getBackedgeTakenInfo(L);
6128 if (BTI.hasFullInfo())
6131 auto Pair = PredicatedBackedgeTakenCounts.insert({
L, BackedgeTakenInfo()});
6134 return Pair.first->second;
6136 BackedgeTakenInfo Result =
6137 computeBackedgeTakenCount(L,
true);
6139 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6142 const ScalarEvolution::BackedgeTakenInfo &
6143 ScalarEvolution::getBackedgeTakenInfo(
const Loop *L) {
6149 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator,
bool> Pair =
6150 BackedgeTakenCounts.insert({
L, BackedgeTakenInfo()});
6152 return Pair.first->second;
6157 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6162 "Computed backedge-taken count isn't loop invariant for loop!");
6163 ++NumTripCountsComputed;
6166 isa<PHINode>(L->
getHeader()->begin())) {
6168 ++NumTripCountsNotComputed;
6176 if (Result.hasAnyInfo()) {
6181 while (!Worklist.
empty()) {
6183 if (!Visited.
insert(I).second)
6187 ValueExprMap.
find_as(static_cast<Value *>(I));
6188 if (It != ValueExprMap.
end()) {
6189 const SCEV *Old = It->second;
6197 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6199 forgetMemoizedResults(Old);
6201 if (
PHINode *PN = dyn_cast<PHINode>(I))
6202 ConstantEvolutionLoopExitValue.erase(PN);
6214 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6219 auto RemoveLoopFromBackedgeMap =
6221 auto BTCPos = Map.find(L);
6222 if (BTCPos != Map.end()) {
6223 BTCPos->second.clear();
6228 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
6229 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
6232 for (
auto I = PredicatedSCEVRewrites.begin();
6233 I != PredicatedSCEVRewrites.end();) {
6234 std::pair<const SCEV *, const Loop *> Entry = I->first;
6235 if (Entry.second == L)
6236 PredicatedSCEVRewrites.erase(I++);
6246 while (!Worklist.
empty()) {
6248 if (!Visited.
insert(I).second)
6252 ValueExprMap.
find_as(static_cast<Value *>(I));
6253 if (It != ValueExprMap.
end()) {
6255 forgetMemoizedResults(It->second);
6256 if (
PHINode *PN = dyn_cast<PHINode>(I))
6257 ConstantEvolutionLoopExitValue.erase(PN);
6268 LoopPropertiesCache.erase(L);
6280 while (!Worklist.
empty()) {
6282 if (!Visited.
insert(I).second)
6286 ValueExprMap.
find_as(static_cast<Value *>(I));
6287 if (It != ValueExprMap.
end()) {
6289 forgetMemoizedResults(It->second);
6290 if (
PHINode *PN = dyn_cast<PHINode>(I))
6291 ConstantEvolutionLoopExitValue.erase(PN);
6310 if (!isComplete() || ExitNotTaken.empty())
6313 const SCEV *BECount =
nullptr;
6314 for (
auto &ENT : ExitNotTaken) {
6318 BECount = ENT.ExactNotTaken;
6319 else if (BECount != ENT.ExactNotTaken)
6321 if (Preds && !ENT.hasAlwaysTruePredicate())
6322 Preds->
add(ENT.Predicate.get());
6324 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6325 "Predicate should be always true!");
6328 assert(BECount &&
"Invalid not taken count for loop exit");
6334 ScalarEvolution::BackedgeTakenInfo::getExact(
BasicBlock *ExitingBlock,
6336 for (
auto &ENT : ExitNotTaken)
6337 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6338 return ENT.ExactNotTaken;
6345 ScalarEvolution::BackedgeTakenInfo::getMax(
ScalarEvolution *SE)
const {
6346 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
6347 return !ENT.hasAlwaysTruePredicate();
6350 if (
any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6353 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6354 "No point in having a non-constant max backedge taken count!");
6358 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(
ScalarEvolution *SE)
const {
6359 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
6360 return !ENT.hasAlwaysTruePredicate();
6362 return MaxOrZero && !
any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6365 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(
const SCEV *S,
6371 for (
auto &ENT : ExitNotTaken)
6379 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *
E)
6380 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(
false) {
6381 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6382 isa<SCEVConstant>(MaxNotTaken)) &&
6383 "No point in having a non-constant max backedge taken count!");
6386 ScalarEvolution::ExitLimit::ExitLimit(
6387 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
6389 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6390 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6391 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6392 "Exact is not allowed to be less precise than Max");
6393 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6394 isa<SCEVConstant>(MaxNotTaken)) &&
6395 "No point in having a non-constant max backedge taken count!");
6396 for (
auto *PredSet : PredSetList)
6397 for (
auto *
P : *PredSet)
6401 ScalarEvolution::ExitLimit::ExitLimit(
6402 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
6404 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6405 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6406 isa<SCEVConstant>(MaxNotTaken)) &&
6407 "No point in having a non-constant max backedge taken count!");
6410 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *E,
const SCEV *M,
6412 : ExitLimit(E, M, MaxOrZero,
None) {
6413 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6414 isa<SCEVConstant>(MaxNotTaken)) &&
6415 "No point in having a non-constant max backedge taken count!");
6420 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6423 bool Complete,
const SCEV *MaxCount,
bool MaxOrZero)
6424 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6425 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6426 ExitNotTaken.reserve(ExitCounts.size());
6428 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6429 [&](
const EdgeExitInfo &EEI) {
6431 const ExitLimit &EL = EEI.second;
6432 if (EL.Predicates.empty())
6433 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
nullptr);
6436 for (
auto *Pred : EL.Predicates)
6439 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(
Predicate));
6441 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6442 "No point in having a non-constant max backedge taken count!");
6447 ExitNotTaken.clear();
6451 ScalarEvolution::BackedgeTakenInfo
6452 ScalarEvolution::computeBackedgeTakenCount(
const Loop *L,
6453 bool AllowPredicates) {
6457 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6460 bool CouldComputeBECount =
true;
6462 const SCEV *MustExitMaxBECount =
nullptr;
6463 const SCEV *MayExitMaxBECount =
nullptr;
6464 bool MustExitMaxOrZero =
false;
6469 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
6471 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6473 assert((AllowPredicates || EL.Predicates.empty()) &&
6474 "Predicated exit limit when predicates are not allowed!");
6481 CouldComputeBECount =
false;
6497 if (!MustExitMaxBECount) {
6498 MustExitMaxBECount = EL.MaxNotTaken;
6499 MustExitMaxOrZero = EL.MaxOrZero;
6501 MustExitMaxBECount =
6506 MayExitMaxBECount = EL.MaxNotTaken;
6513 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6517 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.
size() == 1);
6518 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6519 MaxBECount, MaxOrZero);
6522 ScalarEvolution::ExitLimit
6523 ScalarEvolution::computeExitLimit(
const Loop *L,
BasicBlock *ExitingBlock,
6524 bool AllowPredicates) {
6529 bool MustExecuteLoopHeader =
true;
6537 MustExecuteLoopHeader =
false;
6557 if (!MustExecuteLoopHeader && ExitingBlock != L->
getHeader()) {
6586 if (
BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6587 assert(BI->isConditional() &&
"If unconditional, it can't be in loop!");
6589 return computeExitLimitFromCond(
6590 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6591 IsOnlyExit, AllowPredicates);
6594 if (
SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6595 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6601 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6603 bool ControlsExit,
bool AllowPredicates) {
6604 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6605 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6606 ControlsExit, AllowPredicates);
6612 bool ControlsExit,
bool AllowPredicates) {
6616 (void)this->AllowPredicates;
6618 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6619 this->AllowPredicates == AllowPredicates &&
6620 "Variance in assumed invariant key components!");
6621 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6622 if (Itr == TripCountMap.end())
6627 void ScalarEvolution::ExitLimitCache::insert(
const Loop *L,
Value *ExitCond,
6630 bool AllowPredicates,
6631 const ExitLimit &EL) {
6632 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6633 this->AllowPredicates == AllowPredicates &&
6634 "Variance in assumed invariant key components!");
6636 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6637 assert(InsertResult.second &&
"Expected successful insertion!");
6641 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6643 BasicBlock *FBB,
bool ControlsExit,
bool AllowPredicates) {
6646 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6649 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6650 ControlsExit, AllowPredicates);
6651 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6655 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6657 BasicBlock *FBB,
bool ControlsExit,
bool AllowPredicates) {
6660 if (BO->getOpcode() == Instruction::And) {
6662 bool EitherMayExit = L->
contains(TBB);
6663 ExitLimit EL0 = computeExitLimitFromCondCached(
6664 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6666 ExitLimit EL1 = computeExitLimitFromCondCached(
6667 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6671 if (EitherMayExit) {
6681 MaxBECount = EL1.MaxNotTaken;
6683 MaxBECount = EL0.MaxNotTaken;
6690 assert(L->
contains(FBB) &&
"Loop block has no successor in loop!");
6691 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6692 MaxBECount = EL0.MaxNotTaken;
6693 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6694 BECount = EL0.ExactNotTaken;
6702 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6703 !isa<SCEVCouldNotCompute>(BECount))
6706 return ExitLimit(BECount, MaxBECount,
false,
6707 {&EL0.Predicates, &EL1.Predicates});
6709 if (BO->getOpcode() == Instruction::Or) {
6711 bool EitherMayExit = L->
contains(FBB);
6712 ExitLimit EL0 = computeExitLimitFromCondCached(
6713 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6715 ExitLimit EL1 = computeExitLimitFromCondCached(
6716 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6720 if (EitherMayExit) {
6730 MaxBECount = EL1.MaxNotTaken;
6732 MaxBECount = EL0.MaxNotTaken;
6739 assert(L->
contains(TBB) &&
"Loop block has no successor in loop!");
6740 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6741 MaxBECount = EL0.MaxNotTaken;
6742 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6743 BECount = EL0.ExactNotTaken;
6746 return ExitLimit(BECount, MaxBECount,
false,
6747 {&EL0.Predicates, &EL1.Predicates});
6753 if (
ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6755 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6756 if (EL.hasFullInfo() || !AllowPredicates)
6760 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6768 if (
ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6778 return computeExitCountExhaustively(L, ExitCond, !L->
contains(TBB));
6781 ScalarEvolution::ExitLimit
6782 ScalarEvolution::computeExitLimitFromICmp(
const Loop *L,
6787 bool AllowPredicates) {
6800 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6801 if (ItCnt.hasAnyInfo())
6825 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6826 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6827 if (AddRec->getLoop() ==
L) {
6832 const SCEV *
Ret = AddRec->getNumIterationsInRange(CompRange, *
this);
6833 if (!isa<SCEVCouldNotCompute>(Ret))
return Ret;
6839 ExitLimit EL = howFarToZero(
getMinusSCEV(LHS, RHS), L, ControlsExit,
6841 if (EL.hasAnyInfo())
return EL;
6846 ExitLimit EL = howFarToNonZero(
getMinusSCEV(LHS, RHS), L);
6847 if (EL.hasAnyInfo())
return EL;
6853 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6855 if (EL.hasAnyInfo())
return EL;
6862 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6864 if (EL.hasAnyInfo())
return EL;
6871 auto *ExhaustiveCount =
6872 computeExitCountExhaustively(L, ExitCond, !L->
contains(TBB));
6874 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6875 return ExhaustiveCount;
6877 return computeShiftCompareExitLimit(ExitCond->
getOperand(0),
6881 ScalarEvolution::ExitLimit
6882 ScalarEvolution::computeExitLimitFromSingleExitSwitch(
const Loop *L,
6885 bool ControlsExit) {
6893 "Default case must not exit the loop!");
6898 ExitLimit EL = howFarToZero(
getMinusSCEV(LHS, RHS), L, ControlsExit);
6899 if (EL.hasAnyInfo())
6910 assert(isa<SCEVConstant>(Val) &&
6911 "Evaluation of SCEV at constant didn't fold correctly?");
6912 return cast<SCEVConstant>(Val)->getValue();
6917 ScalarEvolution::ExitLimit
6918 ScalarEvolution::computeLoadConstantCompareExitLimit(
6936 !cast<Constant>(GEP->
getOperand(1))->isNullValue())
6940 Value *VarIdx =
nullptr;
6941 std::vector<Constant*> Indexes;
6942 unsigned VarIdxNum = 0;
6945 Indexes.push_back(CI);
6946 }
else if (!isa<ConstantInt>(GEP->
getOperand(i))) {
6950 Indexes.push_back(
nullptr);
6966 !isa<SCEVConstant>(IdxExpr->
getOperand(0)) ||
6971 for (
unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6973 cast<IntegerType>(IdxExpr->
getType()), IterationNum);
6977 Indexes[VarIdxNum] = Val;
6985 if (!isa<ConstantInt>(Result))
break;
6986 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6987 ++NumArrayLenItCounts;
6994 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7010 auto MatchPositiveShift =
7013 using namespace PatternMatch;
7017 OutOpCode = Instruction::LShr;
7019 OutOpCode = Instruction::AShr;
7021 OutOpCode = Instruction::Shl;
7036 auto MatchShiftRecurrence =
7053 if (MatchPositiveShift(LHS, V, OpC)) {
7054 PostShiftOpCode = OpC;
7060 if (!PNOut || PNOut->getParent() != L->
getHeader())
7063 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7069 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7076 (!PostShiftOpCode.
hasValue() || *PostShiftOpCode == OpCodeOut);
7081 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7098 case Instruction::AShr: {
7104 auto *Ty = cast<IntegerType>(RHS->
getType());
7114 case Instruction::LShr:
7115 case Instruction::Shl:
7125 "Otherwise cannot be an operand to a branch instruction");
7129 const SCEV *UpperBound =
7140 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7141 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7145 if (
const CallInst *CI = dyn_cast<CallInst>(I))
7146 if (
const Function *F = CI->getCalledFunction())
7157 if (isa<PHINode>(I)) {
7181 if (isa<Constant>(Op))
continue;
7191 P = PHIMap.
lookup(OpInst);
7200 if (PHI && PHI != P)
7217 if (
PHINode *PN = dyn_cast<PHINode>(I))
7234 if (
Constant *
C = dyn_cast<Constant>(V))
return C;
7236 if (!I)
return nullptr;
7247 if (isa<PHINode>(I))
return nullptr;
7255 if (!Operands[i])
return nullptr;
7260 if (!C)
return nullptr;
7264 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
7266 Operands[1],
DL, TLI);
7267 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
7288 if (IncomingVal != CurrentVal) {
7291 IncomingVal = CurrentVal;
7303 ScalarEvolution::getConstantEvolutionLoopExitValue(
PHINode *PN,
7306 auto I = ConstantEvolutionLoopExitValue.find(PN);
7307 if (I != ConstantEvolutionLoopExitValue.end())
7311 return ConstantEvolutionLoopExitValue[PN] =
nullptr;
7313 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7317 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
7323 for (
auto &I : *Header) {
7327 if (!StartCST)
continue;
7328 CurrentIterVals[PHI] = StartCST;
7330 if (!CurrentIterVals.
count(PN))
7331 return RetVal =
nullptr;
7337 return RetVal =
nullptr;
7340 unsigned IterationNum = 0;
7342 for (; ; ++IterationNum) {
7343 if (IterationNum == NumIterations)
7344 return RetVal = CurrentIterVals[PN];
7353 NextIterVals[PN] = NextPHI;
7355 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7361 for (
const auto &I : CurrentIterVals) {
7363 if (!PHI || PHI == PN || PHI->
getParent() != Header)
continue;
7368 for (
const auto &I : PHIsToCompute) {
7370 Constant *&NextPHI = NextIterVals[PHI];
7375 if (NextPHI != I.second)
7376 StoppedEvolving =
false;
7381 if (StoppedEvolving)
7382 return RetVal = CurrentIterVals[PN];
7384 CurrentIterVals.swap(NextIterVals);
7388 const SCEV *ScalarEvolution::computeExitCountExhaustively(
const Loop *L,
7400 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
7403 assert(Latch &&
"Should follow from NumIncomingValues == 2!");
7405 for (
auto &I : *Header) {
7410 if (!StartCST)
continue;
7411 CurrentIterVals[PHI] = StartCST;
7413 if (!CurrentIterVals.
count(PN))
7421 for (
unsigned IterationNum = 0; IterationNum !=
MaxIterations;++IterationNum){
7422 auto *CondVal = dyn_cast_or_null<ConstantInt>(
7428 if (CondVal->getValue() == uint64_t(ExitWhen)) {
7429 ++NumBruteForceTripCountsComputed;
7440 for (
const auto &I : CurrentIterVals) {
7442 if (!PHI || PHI->
getParent() != Header)
continue;
7445 for (
PHINode *PHI : PHIsToCompute) {
7446 Constant *&NextPHI = NextIterVals[PHI];
7447 if (NextPHI)
continue;
7452 CurrentIterVals.swap(NextIterVals);
7463 for (
auto &LS : Values)
7465 return LS.second ? LS.second : V;
7467 Values.emplace_back(L,
nullptr);
7470 const SCEV *
C = computeSCEVAtScope(V, L);
7471 for (
auto &LS :
reverse(ValuesAtScopes[V]))
7472 if (LS.first == L) {
7484 switch (static_cast<SCEVTypes>(V->
getSCEVType())) {
7489 return cast<SCEVConstant>(V)->getValue();
7513 if (
PointerType *PTy = dyn_cast<PointerType>(
C->getType())) {
7514 unsigned AS = PTy->getAddressSpace();
7520 if (!C2)
return nullptr;
7537 if (
PointerType *PTy = dyn_cast<PointerType>(
C->getType())) {
7538 if (PTy->getElementType()->isStructTy())
7553 if (
C->getType()->isPointerTy())
return nullptr;
7578 const SCEV *ScalarEvolution::computeSCEVAtScope(
const SCEV *V,
const Loop *L) {
7579 if (isa<SCEVConstant>(V))
return V;
7583 if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7584 if (
Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7587 if (
PHINode *PN = dyn_cast<PHINode>(I))
7595 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7599 if (BTCC->getValue()->isZero()) {
7600 Value *InitValue =
nullptr;
7601 bool MultipleInitValues =
false;
7607 MultipleInitValues =
true;
7611 if (!MultipleInitValues && InitValue)
7619 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7630 bool MadeImprovement =
false;
7632 if (
Constant *
C = dyn_cast<Constant>(Op)) {
7645 MadeImprovement |= OrigV != OpV;
7658 if (MadeImprovement) {
7661 if (
const CmpInst *CI = dyn_cast<CmpInst>(I))
7663 Operands[1],
DL, &TLI);
7664 else if (
const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7665 if (!LI->isVolatile())
7682 for (
unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7684 if (OpAtScope != Comm->getOperand(i)) {
7688 Comm->op_begin()+i);
7691 for (++i; i != e; ++i) {
7693 NewOps.push_back(OpAtScope);
7695 if (isa<SCEVAddExpr>(Comm))
7697 if (isa<SCEVMulExpr>(Comm))
7699 if (isa<SCEVSMaxExpr>(Comm))
7701 if (isa<SCEVUMaxExpr>(Comm))
7710 if (
const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7713 if (LHS == Div->getLHS() && RHS == Div->getRHS())
7720 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7724 for (
unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7726 if (OpAtScope == AddRec->getOperand(i))
7732 AddRec->op_begin()+i);
7734 for (++i; i != e; ++i)
7737 const SCEV *FoldedRec =
7751 if (!AddRec->getLoop()->contains(L)) {
7758 return AddRec->evaluateAtIteration(BackedgeTakenCount, *
this);
7766 if (Op == Cast->getOperand())
7773 if (Op == Cast->getOperand())
7780 if (Op == Cast->getOperand())
7804 assert(A != 0 &&
"A must be non-zero.");
7827 APInt Mod(BW + 1, 0);
7851 if (!LC || !MC || !NC)
7854 uint32_t BitWidth = LC->getAPInt().getBitWidth();
7855 const APInt &L = LC->getAPInt();
7856 const APInt &M = MC->getAPInt();
7857 const APInt &
N = NC->getAPInt();
7858 APInt Two(BitWidth, 2);
7875 SqrtTerm -= 4 * (A *
C);
7888 APInt NegB = -std::move(B);
7889 APInt TwoA = std::move(A);
7901 return std::make_pair(cast<SCEVConstant>(SE.
getConstant(Solution1)),
7905 ScalarEvolution::ExitLimit
7906 ScalarEvolution::howFarToZero(
const SCEV *V,
const Loop *L,
bool ControlsExit,
7907 bool AllowPredicates) {
7916 if (
const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7918 if (C->getValue()->isZero())
return C;
7923 if (!AddRec && AllowPredicates)
7929 if (!AddRec || AddRec->
getLoop() !=
L)
7941 if (!CB->getZExtValue())
7950 return ExitLimit(R1, R1,
false, Predicates);
7982 if (!StepC || StepC->getValue()->isZero())
7990 bool CountDown = StepC->getAPInt().isNegative();
7996 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8015 return ExitLimit(Distance,
getConstant(MaxBECount),
false, Predicates);
8024 loopHasNoAbnormalExits(AddRec->
getLoop())) {
8031 return ExitLimit(Exact, Max,
false, Predicates);
8040 return ExitLimit(E, M,
false, Predicates);
8043 ScalarEvolution::ExitLimit
8044 ScalarEvolution::howFarToNonZero(
const SCEV *V,
const Loop *L) {
8051 if (
const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8052 if (!C->getValue()->isZero())
8062 std::pair<BasicBlock *, BasicBlock *>
8063 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(
BasicBlock *BB) {
8073 if (
Loop *L = LI.getLoopFor(BB))
8076 return {
nullptr,
nullptr};
8086 if (A == B)
return true;
8092 return A->
isIdenticalTo(B) && (isa<BinaryOperator>(
A) || isa<GetElementPtrInst>(A));
8097 if (
const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8098 if (
const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8099 if (
const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8100 if (
const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8101 if (ComputesEqualValues(AI, BI))
8109 const SCEV *&LHS,
const SCEV *&RHS,
8111 bool Changed =
false;
8118 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8120 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8123 RHSC->getValue())->isNullValue())
8124 goto trivially_false;
8126 goto trivially_true;
8148 if (
const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8149 const APInt &RA = RC->getAPInt();
8151 bool SimplifiedByConstantRange =
false;
8156 goto trivially_true;
8158 goto trivially_false;
8167 Changed = SimplifiedByConstantRange =
true;
8171 if (!SimplifiedByConstantRange) {
8179 if (
const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8181 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8182 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8183 ME->getOperand(0)->isAllOnesValue()) {
8184 RHS = AE->getOperand(1);
8185 LHS = ME->getOperand(1);
8227 goto trivially_true;
8229 goto trivially_false;
8332 const SCEV *LHS,
const SCEV *RHS) {
8342 bool LeftGuarded =
false;
8343 bool RightGuarded =
false;
8348 if (!RAR)
return true;
8353 const Loop *L = RAR->getLoop();
8356 if (!LAR)
return true;
8357 RightGuarded =
true;
8360 if (LeftGuarded && RightGuarded)
8363 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8367 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8373 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8378 bool IncreasingSwapped;
8379 bool ResultSwapped = isMonotonicPredicateImpl(
8382 assert(Result == ResultSwapped &&
"should be able to analyze both!");
8384 assert(Increasing == !IncreasingSwapped &&
8385 "monotonicity should flip as we flip the predicate");
8391 bool ScalarEvolution::isMonotonicPredicateImpl(
const SCEVAddRecExpr *LHS,
8449 const SCEV *&InvariantRHS) {
8461 if (!ArLHS || ArLHS->
getLoop() !=
L)
8491 InvariantPred = Pred;
8497 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8533 auto MatchBinaryAddToConst =
8536 const SCEV *NonConstOp, *ConstOp;
8539 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8540 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8543 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8544 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8607 bool ScalarEvolution::isImpliedViaGuard(
BasicBlock *BB,
8609 const SCEV *LHS,
const SCEV *RHS) {
8615 using namespace llvm::PatternMatch;
8618 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8620 isImpliedCond(Pred, LHS, RHS, Condition,
false);
8630 const SCEV *LHS,
const SCEV *RHS) {
8633 if (!L)
return true;
8635 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8644 if (LoopContinuePredicate && LoopContinuePredicate->
isConditional() &&
8645 isImpliedCond(Pred, LHS, RHS,
8652 if (WalkingBEDominatingConds)
8658 const auto &BETakenInfo = getBackedgeTakenInfo(L);
8659 const SCEV *LatchBECount = BETakenInfo.getExact(Latch,
this);
8666 const SCEV *LoopCounter =
8674 for (
auto &AssumeVH : AC.assumptions()) {
8677 auto *CI = cast<CallInst>(AssumeVH);
8681 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0),
false))
8691 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8695 DTN != HeaderDTN; DTN = DTN->getIDom()) {
8697 assert(DTN &&
"should reach the loop header before reaching the root!");
8700 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8708 if (!ContinuePredicate || !ContinuePredicate->
isConditional())
8724 if (isImpliedCond(Pred, LHS, RHS, Condition,
8736 const SCEV *LHS,
const SCEV *RHS) {
8739 if (!L)
return false;
8741 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8747 for (std::pair<BasicBlock *, BasicBlock *>
8750 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8752 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8757 if (!LoopEntryPredicate ||
8761 if (isImpliedCond(Pred, LHS, RHS,
8768 for (
auto &AssumeVH : AC.assumptions()) {
8771 auto *CI = cast<CallInst>(AssumeVH);
8775 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0),
false))
8784 Value *FoundCondValue,
8786 if (!PendingLoopPredicates.insert(FoundCondValue).second)
8790 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8793 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8794 if (BO->getOpcode() == Instruction::And) {
8796 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8797 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8798 }
else if (BO->getOpcode() == Instruction::Or) {
8800 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8801 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8806 if (!ICI)
return false;
8819 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8825 const SCEV *FoundLHS,
8826 const SCEV *FoundRHS) {
8854 if (FoundLHS == FoundRHS)
8858 if (LHS == FoundRHS || RHS == FoundLHS) {
8859 if (isa<SCEVConstant>(RHS)) {
8869 if (FoundPred == Pred)
8870 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8875 if (isa<SCEVConstant>(RHS))
8876 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8879 RHS, LHS, FoundLHS, FoundRHS);
8887 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8891 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8894 const SCEV *V =
nullptr;
8896 if (isa<SCEVConstant>(FoundLHS)) {
8897 C = cast<SCEVConstant>(FoundLHS);
8900 C = cast<SCEVConstant>(FoundRHS);
8917 APInt SharperMin = Min + 1;
8924 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8940 if (isImpliedCondOperands(Pred, LHS, RHS, V,
getConstant(Min)))
8954 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8958 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8965 bool ScalarEvolution::splitBinaryAdd(
const SCEV *Expr,
8969 if (!AE || AE->getNumOperands() != 2)
8972 L = AE->getOperand(0);
8973 R = AE->getOperand(1);
8974 Flags = AE->getNoWrapFlags();
8983 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8984 const auto *LAR = cast<SCEVAddRecExpr>(
Less);
8985 const auto *MAR = cast<SCEVAddRecExpr>(More);
8987 if (LAR->getLoop() != MAR->getLoop())
8992 if (!LAR->isAffine() || !MAR->isAffine())
8995 if (LAR->getStepRecurrence(*
this) != MAR->getStepRecurrence(*
this))
8998 Less = LAR->getStart();
8999 More = MAR->getStart();
9004 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9005 const auto &M = cast<SCEVConstant>(More)->getAPInt();
9006 const auto &L = cast<SCEVConstant>(
Less)->getAPInt();
9012 if (splitBinaryAdd(Less, L, R, Flags))
9013 if (
const auto *LC = dyn_cast<SCEVConstant>(L))
9015 return -(LC->getAPInt());
9017 if (splitBinaryAdd(More, L, R, Flags))
9018 if (
const auto *LC = dyn_cast<SCEVConstant>(L))
9020 return LC->getAPInt();
9025 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9027 const SCEV *FoundLHS,
const SCEV *FoundRHS) {
9036 if (!AddRecFoundLHS)
9043 const Loop *L = AddRecFoundLHS->getLoop();
9044 if (L != AddRecLHS->getLoop())
9081 if (!LDiff || !RDiff || *LDiff != *RDiff)
9087 APInt FoundRHSLimit;
9090 FoundRHSLimit = -(*RDiff);
9103 const SCEV *FoundLHS,
9104 const SCEV *FoundRHS) {
9105 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9108 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9111 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9112 FoundLHS, FoundRHS) ||
9114 isImpliedCondOperandsHelper(Pred, LHS, RHS,
9137 template<
typename MaxExprType>
9139 const SCEV *Candidate) {
9140 const MaxExprType *MaxExpr =
dyn_cast<MaxExprType>(MaybeMaxExpr);
9141 if (!MaxExpr)
return false;
9143 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9148 template<
typename MaxExprType>
9150 const SCEV *MaybeMinExpr,
9151 const SCEV *Candidate) {
9156 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.
getNotSCEV(Candidate));
9161 const SCEV *LHS,
const SCEV *RHS) {
9196 const SCEV *LHS,
const SCEV *RHS) {
9207 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9209 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9217 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9219 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9227 const SCEV *FoundLHS,
9228 const SCEV *FoundRHS,
9232 "LHS and RHS have different sizes?");
9235 "FoundLHS and FoundRHS have different sizes?");
9249 auto GetOpFromSExt = [&](
const SCEV *S) {
9250 if (
auto *
Ext = dyn_cast<SCEVSignExtendExpr>(S))
9251 return Ext->getOperand();
9258 auto *OrigFoundLHS = FoundLHS;
9259 LHS = GetOpFromSExt(LHS);
9260 FoundLHS = GetOpFromSExt(FoundLHS);
9263 auto IsSGTViaContext = [&](
const SCEV *S1,
const SCEV *S2) {
9266 FoundRHS, Depth + 1);
9269 if (
auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9279 if (!LHSAddExpr->hasNoSignedWrap())
9282 auto *LL = LHSAddExpr->getOperand(0);
9283 auto *LR = LHSAddExpr->getOperand(1);
9287 auto IsSumGreaterThanRHS = [&](
const SCEV *S1,
const SCEV *S2) {
9288 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9293 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9295 }
else if (
auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9298 using namespace llvm::PatternMatch;
9308 if (!isa<ConstantInt>(LR))
9311 auto *Denominator = cast<SCEVConstant>(
getSCEV(LR));
9315 auto *Numerator = getExistingSCEV(LL);
9316 if (!Numerator || Numerator->getType() != FoundLHS->
getType())
9324 auto *DTy = Denominator->
getType();
9325 auto *FRHSTy = FoundRHS->
getType();
9326 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9345 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9356 auto *NegDenomMinusOne =
getMinusSCEV(MinusOne, DenominatorExt);
9358 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9368 const SCEV *LHS,
const SCEV *RHS) {
9369 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9372 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9378 const SCEV *FoundLHS,
9379 const SCEV *FoundRHS) {
9414 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9423 const SCEV *FoundLHS,
9424 const SCEV *FoundRHS) {
9425 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9434 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9446 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9452 return SatisfyingLHSRange.
contains(LHSRange);
9455 bool ScalarEvolution::doesIVOverflowOnLT(
const SCEV *RHS,
const SCEV *Stride,
9456 bool IsSigned,
bool NoWrap) {
9459 if (NoWrap)
return false;
9470 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9478 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9481 bool ScalarEvolution::doesIVOverflowOnGT(
const SCEV *RHS,
const SCEV *Stride,
9482 bool IsSigned,
bool NoWrap) {
9483 if (NoWrap)
return false;
9494 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9502 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9505 const SCEV *ScalarEvolution::computeBECount(
const SCEV *Delta,
const SCEV *Step,
9513 ScalarEvolution::ExitLimit
9514 ScalarEvolution::howManyLessThans(
const SCEV *LHS,
const SCEV *RHS,
9515 const Loop *L,
bool IsSigned,
9516 bool ControlsExit,
bool AllowPredicates) {
9523 bool PredicatedIV =
false;
9525 if (!IV && AllowPredicates) {
9530 PredicatedIV =
true;
9537 bool NoWrap = ControlsExit &&
9545 if (!PositiveStride) {
9589 !loopHasNoSideEffects(L))
9592 }
else if (!Stride->
isOne() &&
9593 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9608 const SCEV *BECountIfBackedgeTaken =
9609 computeBECount(
getMinusSCEV(End, Start), Stride,
false);
9617 const SCEV *BECount;
9619 BECount = BECountIfBackedgeTaken;
9622 BECount = computeBECount(
getMinusSCEV(End, Start), Stride,
false);
9625 const SCEV *MaxBECount;
9626 bool MaxOrZero =
false;
9627 if (isa<SCEVConstant>(BECount))
9628 MaxBECount = BECount;
9629 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9633 MaxBECount = BECountIfBackedgeTaken;
9643 APInt StrideForMaxBECount;
9646 StrideForMaxBECount =
9652 StrideForMaxBECount =
APInt(BitWidth, 1, IsSigned);
9665 MaxBECount = computeBECount(
getConstant(MaxEnd - MinStart),
9669 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9670 !isa<SCEVCouldNotCompute>(BECount))
9673 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9676 ScalarEvolution::ExitLimit
9677 ScalarEvolution::howManyGreaterThans(
const SCEV *LHS,
const SCEV *RHS,
9678 const Loop *L,
bool IsSigned,
9679 bool ControlsExit,
bool AllowPredicates) {
9686 if (!IV && AllowPredicates)
9696 bool NoWrap = ControlsExit &&
9709 if (!Stride->
isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9716 const SCEV *End = RHS;
9720 const SCEV *BECount = computeBECount(
getMinusSCEV(Start, End), Stride,
false);
9741 if (isa<SCEVConstant>(BECount))
9742 MaxBECount = BECount;
9744 MaxBECount = computeBECount(
getConstant(MaxStart - MinEnd),
9747 if (isa<SCEVCouldNotCompute>(MaxBECount))
9748 MaxBECount = BECount;
9750 return ExitLimit(BECount, MaxBECount,
false, Predicates);
9760 if (!
SC->getValue()->isZero()) {
9762 Operands[0] = SE.
getZero(
SC->getType());
9764 getNoWrapFlags(FlagNW));
9765 if (
const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9766 return ShiftedAddRec->getNumIterationsInRange(
9774 if (
any_of(operands(), [](
const SCEV *Op) {
return !isa<SCEVConstant>(
Op); }))
9794 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9798 APInt ExitVal = (End +
A).udiv(A);
9805 if (Range.
contains(Val->getValue()))
9812 "Linear scev computation is off in a bad way!");
9814 }
else if (isQuadratic()) {
9831 if (!CB->getZExtValue())
9845 if (!Range.
contains(R1Val->getValue()))
9855 if (Range.
contains(R1Val->getValue()))
9868 if (
const auto *SU = dyn_cast<SCEVUnknown>(S))
9869 return isa<UndefValue>(SU->getValue());
9870 else if (
const auto *
SC = dyn_cast<SCEVConstant>(S))
9871 return isa<UndefValue>(
SC->getValue());
9878 struct SCEVCollectStrides {
9883 : SE(SE), Strides(S) {}
9885 bool follow(
const SCEV *S) {
9890 bool isDone()
const {
return false; }
9894 struct SCEVCollectTerms {
9900 bool follow(
const SCEV *S) {
9901 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9902 isa<SCEVSignExtendExpr>(S)) {
9913 bool isDone()
const {
return false; }
9917 struct SCEVHasAddRec {
9918 bool &ContainsAddRec;
9920 SCEVHasAddRec(
bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9921 ContainsAddRec =
false;
9924 bool follow(
const SCEV *S) {
9925 if (isa<SCEVAddRecExpr>(S)) {
9926 ContainsAddRec =
true;
9935 bool isDone()
const {
return false; }
9950 struct SCEVCollectAddRecMultiplies {
9955 : Terms(T), SE(SE) {}
9957 bool follow(
const SCEV *S) {
9958 if (
auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9959 bool HasAddRec =
false;
9961 for (
auto Op : Mul->operands()) {
9963 if (Unknown && !isa<CallInst>(Unknown->
getValue())) {
9965 }
else if (Unknown) {
9968 bool ContainsAddRec;
9969 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9971 HasAddRec |= ContainsAddRec;
9974 if (Operands.
size() == 0)
9988 bool isDone()
const {
return false; }
9999 SCEVCollectStrides StrideCollector(*
this, Strides);
10003 dbgs() <<
"Strides:\n";
10004 for (
const SCEV *S : Strides)
10005 dbgs() << *S <<
"\n";
10008 for (
const SCEV *S : Strides) {
10009 SCEVCollectTerms TermCollector(Terms);
10014 dbgs() <<
"Terms:\n";
10015 for (
const SCEV *
T : Terms)
10016 dbgs() << *
T <<
"\n";
10019 SCEVCollectAddRecMultiplies MulCollector(Terms, *
this);
10026 int Last = Terms.
size() - 1;
10027 const SCEV *Step = Terms[Last];
10031 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10033 for (
const SCEV *Op : M->operands())
10034 if (!isa<SCEVConstant>(Op))
10044 for (
const SCEV *&Term : Terms) {
10047 SCEVDivision::divide(SE, Term, Step, &Q, &R);
10058 remove_if(Terms, [](
const SCEV *E) {
return isa<SCEVConstant>(
E); }),
10061 if (Terms.size() > 0)
10072 for (
const SCEV *
T : Terms)
10080 if (
const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10081 return Expr->getNumOperands();
10086 if (isa<SCEVConstant>(T))
10089 if (isa<SCEVUnknown>(T))
10092 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10094 for (
const SCEV *Op : M->operands())
10095 if (!isa<SCEVConstant>(Op))
10108 Ty =
Store->getValueOperand()->getType();
10110 Ty =
Load->getType();
10120 const SCEV *ElementSize) {
10121 if (Terms.
size() < 1 || !ElementSize)
10130 dbgs() <<
"Terms:\n";
10131 for (
const SCEV *
T : Terms)
10132 dbgs() << *
T <<
"\n";
10146 for (
const SCEV *&Term : Terms) {
10148 SCEVDivision::divide(*
this, Term, ElementSize, &Q, &R);
10156 for (
const SCEV *
T : Terms)
10161 dbgs() <<
"Terms after sorting:\n";
10162 for (
const SCEV *
T : NewTerms)
10163 dbgs() << *
T <<
"\n";
10175 dbgs() <<
"Sizes:\n";
10176 for (
const SCEV *S : Sizes)
10177 dbgs() << *S <<
"\n";
10189 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10193 const SCEV *Res = Expr;
10194 int Last = Sizes.
size() - 1;
10195 for (
int i = Last; i >= 0; i--) {
10197 SCEVDivision::divide(*
this, Res, Sizes[i], &Q, &R);
10200 dbgs() <<
"Res: " << *Res <<
"\n";
10201 dbgs() <<
"Sizes[i]: " << *Sizes[i] <<
"\n";
10202 dbgs() <<
"Res divided by Sizes[i]:\n";
10203 dbgs() <<
"Quotient: " << *Q <<
"\n";
10204 dbgs() <<
"Remainder: " << *R <<
"\n";
10214 if (isa<SCEVAddRecExpr>(R)) {
10215 Subscripts.
clear();
10234 dbgs() <<
"Subscripts:\n";
10235 for (
const SCEV *S : Subscripts)
10236 dbgs() << *S <<
"\n";
10292 const SCEV *ElementSize) {
10309 if (Subscripts.
empty())
10313 dbgs() <<
"succeeded to delinearize " << *Expr <<
"\n";
10314 dbgs() <<
"ArrayDecl[UnknownSize]";
10315 for (
const SCEV *S : Sizes)
10316 dbgs() <<
"[" << *S <<
"]";
10318 dbgs() <<
"\nArrayRef";
10319 for (
const SCEV *S : Subscripts)
10320 dbgs() <<
"[" << *S <<
"]";
10329 void ScalarEvolution::SCEVCallbackVH::deleted() {
10330 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
10331 if (
PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10332 SE->ConstantEvolutionLoopExitValue.erase(PN);
10337 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(
Value *V) {
10338 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
10343 Value *Old = getValPtr();
10346 while (!Worklist.
empty()) {
10352 if (!Visited.
insert(U).second)
10354 if (
PHINode *PN = dyn_cast<PHINode>(U))
10355 SE->ConstantEvolutionLoopExitValue.erase(PN);
10360 if (
PHINode *PN = dyn_cast<PHINode>(Old))
10361 SE->ConstantEvolutionLoopExitValue.erase(PN);
10376 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10378 WalkingBEDominatingConds(
false), ProvingSplitPredicate(
false),
10379 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
10380 FirstUnknown(nullptr) {
10394 HasGuards = GuardDecl && !GuardDecl->use_empty();
10398 :
F(Arg.
F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10399 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10400 ValueExprMap(std::move(Arg.ValueExprMap)),
10401 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10402 WalkingBEDominatingConds(
false), ProvingSplitPredicate(
false),
10403 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10404 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10405 PredicatedBackedgeTakenCounts(
10406 std::move(Arg.PredicatedBackedgeTakenCounts)),
10407 ConstantEvolutionLoopExitValue(
10408 std::move(Arg.ConstantEvolutionLoopExitValue)),
10409 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10410 LoopDispositions(std::move(Arg.LoopDispositions)),
10411 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10412 BlockDispositions(std::move(Arg.BlockDispositions)),
10413 UnsignedRanges(std::move(Arg.UnsignedRanges)),
10414 SignedRanges(std::move(Arg.SignedRanges)),
10415 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10416 UniquePreds(std::move(Arg.UniquePreds)),
10417 SCEVAllocator(std::move(Arg.SCEVAllocator)),
10418 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10419 FirstUnknown(Arg.FirstUnknown) {
10420 Arg.FirstUnknown =
nullptr;
10429 Tmp->~SCEVUnknown();
10431 FirstUnknown =
nullptr;
10433 ExprValueMap.
clear();
10434 ValueExprMap.
clear();
10439 for (
auto &BTCI : BackedgeTakenCounts)
10440 BTCI.second.clear();
10441 for (
auto &BTCI : PredicatedBackedgeTakenCounts)
10442 BTCI.second.clear();
10444 assert(PendingLoopPredicates.empty() &&
"isImpliedCond garbage");
10445 assert(!WalkingBEDominatingConds &&
"isLoopBackedgeGuardedByCond garbage!");
10446 assert(!ProvingSplitPredicate &&
"ProvingSplitPredicate garbage!");
10460 L->getHeader()->printAsOperand(OS,
false);
10464 L->getExitBlocks(ExitBlocks);
10465 if (ExitBlocks.
size() != 1)
10466 OS <<
"<multiple exits> ";
10471 OS <<
"Unpredictable backedge-taken count. ";
10476 L->getHeader()->printAsOperand(OS,
false);
10482 OS <<
", actual taken count either this or zero.";
10484 OS <<
"Unpredictable max backedge-taken count. ";
10489 L->getHeader()->printAsOperand(OS,
false);
10494 if (!isa<SCEVCouldNotCompute>(PBT)) {
10495 OS <<
"Predicated backedge-taken count is " << *PBT <<
"\n";
10496 OS <<
" Predicates:\n";
10499 OS <<
"Unpredictable predicated backedge-taken count. ";
10505 L->getHeader()->printAsOperand(OS,
false);
10516 return "Invariant";
10518 return "Computable";
10532 OS <<
"Classifying expressions for: ";
10541 if (!isa<SCEVCouldNotCompute>(SV)) {
10548 const Loop *L = LI.getLoopFor(I.getParent());
10554 if (!isa<SCEVCouldNotCompute>(AtUse)) {
10563 OS <<
"\t\t" "Exits: ";
10566 OS <<
"<<Unknown>>";
10574 OS <<
"\t\t" "LoopDispositions: { ";
10580 Iter->getHeader()->printAsOperand(OS,
false);
10588 OS <<
"\t\t" "LoopDispositions: { ";
10594 InnerL->getHeader()->printAsOperand(OS,
false);
10604 OS <<
"Determining loop execution counts for: ";
10613 auto &Values = LoopDispositions[S];
10614 for (
auto &V : Values) {
10615 if (V.getPointer() ==
L)
10620 auto &Values2 = LoopDispositions[S];
10621 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
10622 if (V.getPointer() ==
L) {
10631 ScalarEvolution::computeLoopDisposition(
const SCEV *S,
const Loop *L) {
10632 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
10671 bool HasVarying =
false;
10672 for (
auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10697 if (
auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10716 auto &Values = BlockDispositions[S];
10717 for (
auto &V : Values) {
10718 if (V.getPointer() == BB)
10723 auto &Values2 = BlockDispositions[S];
10724 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
10725 if (V.getPointer() == BB) {
10734 ScalarEvolution::computeBlockDisposition(
const SCEV *S,
const BasicBlock *BB) {
10735 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
10759 bool Proper =
true;
10783 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10809 void ScalarEvolution::forgetMemoizedResults(
const SCEV *S) {
10810 ValuesAtScopes.erase(S);
10811 LoopDispositions.erase(S);
10812 BlockDispositions.erase(S);
10813 UnsignedRanges.erase(S);
10814 SignedRanges.erase(S);
10815 ExprValueMap.
erase(S);
10816 HasRecMap.
erase(S);
10817 MinTrailingZerosCache.erase(S);
10819 for (
auto I = PredicatedSCEVRewrites.begin();
10820 I != PredicatedSCEVRewrites.end();) {
10821 std::pair<const SCEV *, const Loop *> Entry = I->first;
10822 if (Entry.first == S)
10823 PredicatedSCEVRewrites.erase(I++);
10828 auto RemoveSCEVFromBackedgeMap =
10830 for (
auto I = Map.begin(), E = Map.end(); I !=
E;) {
10831 BackedgeTakenInfo &BEInfo = I->second;
10832 if (BEInfo.hasOperand(S,
this)) {
10840 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10841 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10865 SCEVMapper SCM(SE2);
10867 while (!LoopStack.empty()) {
10868 auto *L = LoopStack.pop_back_val();
10869 LoopStack.insert(LoopStack.end(), L->
begin(), L->
end());
10871 auto *CurBECount = SCM.visit(
10902 auto *ConstantDelta =
10905 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10906 dbgs() <<
"Trip Count Changed!\n";
10907 dbgs() <<
"Old: " << *CurBECount <<
"\n";
10908 dbgs() <<
"New: " << *NewBECount <<
"\n";
10909 dbgs() <<
"Delta: " << *ConstantDelta <<
"\n";
10944 "Scalar Evolution Analysis",
false,
true)
10951 char ScalarEvolutionWrapperPass::ID = 0;
10959 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10960 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10961 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10962 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10991 "Type mismatch between LHS and RHS");
10996 void *IP =
nullptr;
10997 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11001 UniquePreds.InsertNode(Eq, IP);
11013 void *IP =
nullptr;
11014 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11016 auto *OF =
new (SCEVAllocator)
11018 UniquePreds.InsertNode(OF, IP);
11037 SCEVPredicateRewriter
Rewriter(L, SE, NewPreds, Pred);
11049 for (
auto *Pred : ExprPreds)
11050 if (
const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11051 if (IPred->getLHS() == Expr)
11052 return IPred->getRHS();
11054 return convertToAddRecWithPreds(Expr);
11060 if (AR && AR->getLoop() == L && AR->isAffine()) {
11063 const SCEV *Step = AR->getStepRecurrence(SE);
11068 AR->getNoWrapFlags());
11076 if (AR && AR->getLoop() == L && AR->isAffine()) {
11079 const SCEV *Step = AR->getStepRecurrence(SE);
11084 AR->getNoWrapFlags());
11093 return Pred && Pred->
implies(P);
11102 return addOverflowAssumption(A);
11112 if (!isa<PHINode>(Expr->
getValue()))
11116 if (!PredicatedRewrite)
11118 for (
auto *P : PredicatedRewrite->second){
11119 if (!addOverflowAssumption(P))
11122 return PredicatedRewrite->first;
11133 return SCEVPredicateRewriter::rewrite(S, L, *
this,
nullptr, &Preds);
11141 S = SCEVPredicateRewriter::rewrite(S, L, *
this, &TransformPreds,
nullptr);
11149 for (
auto *P : TransformPreds)
11158 : FastID(ID), Kind(Kind) {}
11164 assert(LHS != RHS &&
"LHS and RHS are the same SCEV");
11173 return Op->LHS == LHS && Op->RHS == RHS;
11181 OS.
indent(Depth) <<
"Equal predicate: " << *LHS <<
" == " << *RHS <<
"\n";
11194 return Op && Op->AR == AR &&
setFlags(Flags, Op->Flags) == Flags;
11230 if (Step->getValue()->getValue().isNonNegative())
11234 return ImpliedFlags;
11248 auto I = SCEVToPreds.
find(Expr);
11249 if (I == SCEVToPreds.
end())
11255 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11256 return all_of(Set->Preds,
11257 [
this](
const SCEVPredicate *I) {
return this->implies(I); });
11259 auto ScevPredsIt = SCEVToPreds.find(
N->getExpr());
11260 if (ScevPredsIt == SCEVToPreds.end())
11262 auto &SCEVPreds = ScevPredsIt->second;
11264 return any_of(SCEVPreds,
11271 for (
auto Pred : Preds)
11272 Pred->
print(OS, Depth);
11276 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11277 for (
auto Pred : Set->Preds)
11286 assert(Key &&
"Only SCEVUnionPredicate doesn't have an "
11287 " associated expression!");
11289 SCEVToPreds[Key].push_back(N);
11290 Preds.push_back(N);
11295 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
11299 RewriteEntry &Entry = RewriteMap[Expr];
11302 if (Entry.second && Generation == Entry.first)
11303 return Entry.second;
11308 Expr = Entry.second;
11311 Entry = {Generation, NewSCEV};
11317 if (!BackedgeCount) {
11322 return BackedgeCount;
11329 updateGeneration();
11336 void PredicatedScalarEvolution::updateGeneration() {
11338 if (++Generation == 0) {
11339 for (
auto &II : RewriteMap) {
11340 const SCEV *Rewritten = II.second.second;
11349 const auto *AR = cast<SCEVAddRecExpr>(Expr);
11357 auto II = FlagsMap.insert({V, Flags});
11365 const auto *AR = cast<SCEVAddRecExpr>(Expr);
11370 auto II = FlagsMap.find(V);
11372 if (II != FlagsMap.end())
11386 for (
auto *P : NewPreds)
11389 updateGeneration();
11390 RewriteMap[SE.
getSCEV(V)] = {Generation, New};
11396 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11397 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11398 for (
const auto &I : Init.FlagsMap)
11399 FlagsMap.insert(I);
11405 for (
auto &I : *BB) {
11410 auto II = RewriteMap.
find(Expr);
11412 if (II == RewriteMap.
end())
11416 if (II->second.second == Expr)
11419 OS.
indent(Depth) <<
"[PSE]" << I <<
":\n";
11420 OS.
indent(Depth + 2) << *Expr <<
"\n";
11421 OS.
indent(Depth + 2) <<
"--> " << *II->second.second <<
"\n";
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer 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 Use & getOperandUse(unsigned i) const
virtual const SCEV * getExpr() const =0
Returns the SCEV to which this predicate applies, or nullptr if this is a SCEVUnionPredicate.
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
static bool containsParameters(SmallVectorImpl< const SCEV * > &Terms)
void AddPointer(const void *Ptr)
Add* - Add various data types to Bit data.
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
APInt multiplicativeInverse(const APInt &modulo) const
Computes the multiplicative inverse of this APInt for a given modulo.
Type * getSourceElementType() const
void push_back(const T &Elt)
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
This routine provides some synthesis utilities to produce sequences of values.
A parsed version of the target data layout string in and methods for querying it. ...
static cl::opt< bool > VerifySCEV("verify-scev", cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static ConstantInt * getFalse(LLVMContext &Context)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Proves that V doesn't overflow by adding SCEV predicate.
This class is the base class for the comparison instructions.
The SCEV properly dominates the block.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
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...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const SCEV * getGEPExpr(GEPOperator *GEP, const SmallVectorImpl< const SCEV * > &IndexExprs)
Returns an expression for a GEP.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
SCEVCastExpr(const FoldingSetNodeIDRef ID, unsigned SCEVTy, const SCEV *op, Type *ty)
uint64_t getZExtValue() const
Get zero extended value.
unsigned getSmallConstantTripMultiple(const Loop *L)
Returns the largest constant divisor of the trip count of the loop if it is a single-exit loop and we...
bool isOne() const
Return true if the expression is a constant one.
const SCEV * getConstant(ConstantInt *V)
STATISTIC(NumFunctions,"Total number of functions")
ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static const SCEV * removeConstantFactors(ScalarEvolution &SE, const SCEV *T)
A Module instance is used to store all the information related to an LLVM module. ...
LLVMContext & getContext() const
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist)
Push users of the given Instruction onto the given Worklist.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
SCEVUnionPredicate()
Union predicates don't get cached so create a dummy set ID for it.
bool isZero() const
Return true if the expression is a constant zero.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
virtual bool implies(const SCEVPredicate *N) const =0
Returns true if this predicate implies N.
unsigned getNumOperands() const
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
The main scalar evolution driver.
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This class represents a function call, abstracting a target machine's calling convention.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW. ...
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
An immutable pass that tracks lazily created AssumptionCache objects.
scalar Scalar Evolution false
bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_NODISCARD SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
bool isSigned() const
Determine if this instruction is using a signed comparison.
A cache of .assume calls within a function.
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist)
Push PHI nodes in the header of the given loop onto the given Worklist.
uint32_t GetMinTrailingZeros(const SCEV *S)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration)...
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
This class represents a truncation of an integer value to a smaller integer value.
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass,"scalar-evolution","Scalar Evolution Analysis", false, true) INITIALIZE_PASS_END(ScalarEvolutionWrapperPass
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred, bool &Increasing)
Return true if, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or...
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS...
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
static std::pair< const SCEV *, ConstantInt * > splitAddExpr(const SCEV *S)
Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
An object of this class is returned by queries that could not be answered.
void reserve(size_type N)
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
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 * getExpr() const override
Returns the SCEV to which this predicate applies, or nullptr if this is a SCEVUnionPredicate.
static Optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
bool hasNoSelfWrap() const
BlockT * getHeader() const
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
This is the base class for unary cast operator classes.
bool propagatesFullPoison(const Instruction *I)
Return true if this function can prove that I is guaranteed to yield full-poison (all bits poison) if...
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
bool isOffsetOf(Type *&STy, Constant *&FieldNo) const
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
const SCEV * getStart() const
MutableArrayRef< WeakTrackingVH > assumptions()
Access the list of assumption handles currently tracked for this function.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
Predicate getSignedPredicate()
For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
bool isNegative() const
Determine sign of this APInt.
The SCEV is loop-invariant.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
bool match(Val *V, const Pattern &P)
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isNonNegative() const
Returns true if this value is known to be non-negative.
void computeAccessFunctions(const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes)
Return in Subscripts the access functions for each dimension in Sizes (third step of delinearization)...
bool isUnconditional() const
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
ArrayRef< const SCEVPredicate * > getPredicatesForExpr(const SCEV *Expr)
Returns a reference to a vector containing all predicates which apply to Expr.
Type * getWiderType(Type *Ty1, Type *Ty2) const
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
bool isAlignOf(Type *&AllocTy) const
void setBit(unsigned BitPosition)
Set a given bit to 1.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
ConstantRange truncate(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
const APInt & getValue() const
Return the constant as an APInt value reference.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
Class to represent struct types.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
A Use represents the edge between a Value definition and its users.
bool hasNoSignedWrap() const
const SCEV *const * op_iterator
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static Constant * AddOne(Constant *C)
Add one to a Constant.
bool Eq(const uint8_t *Data, size_t Size, const char *Str)
const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
static int CompareValueComplexity(SmallSet< std::pair< Value *, Value * >, 8 > &EqCache, 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 ...
void AddInteger(signed I)
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This node is the base class for n'ary commutative operators.
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Analysis pass that exposes the LoopInfo for a function.
ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
op_iterator op_begin() const
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
This node represents multiplication of some number of SCEVs.
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, ScalarEvolution &SE)
Finds the minimum unsigned root of the following equation:
void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
zlib-gnu style compression
ConstantRange multiply(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
bool programUndefinedIfFullPoison(const Instruction *PoisonI)
Return true if this function can prove that if PoisonI is executed and yields a full-poison value (al...
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.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
APInt shl(unsigned shiftAmt) const
Left-shift function.
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS...
static bool isPrivateLinkage(LinkageTypes Linkage)
A constant value that is initialized with an expression using other constant values.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
bool implies(const SCEVPredicate *N) const override
Implementation of the SCEVPredicate interface.
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.
const T & getValue() const LLVM_LVALUE_FUNCTION
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
BasicBlock * getSuccessor(unsigned i) const
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
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 SCEV * getSizeOfExpr(Type *IntTy, Type *AllocTy)
Return an expression for sizeof AllocTy that is type IntTy.
const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getActiveBits() const
Compute the number of active bits in the value.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
An instruction for storing to memory.
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))
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
bool isArrayTy() const
True if this is an instance of ArrayType.
SelectClass_match< Cond, LHS, RHS > m_Select(const Cond &C, const LHS &L, const RHS &R)
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
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...
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
void findArrayDimensions(SmallVectorImpl< const SCEV * > &Terms, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Compute the array dimensions Sizes from the set of Terms extracted from the memory access function of...
size_t getNumOperands() const
Class to represent pointers.
static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the largest range such that all values in the returned range satisfy the given predicate with...
static cl::opt< unsigned > MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4))
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool implies(const SCEVPredicate *N) const override
Returns true if this predicate implies N.
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
iterator find(const_arg_type_t< KeyT > Val)
bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS. ...
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
ValTy * getReturnedArgOperand() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
const SCEV * getCouldNotCompute()
Visit all nodes in the expression tree using worklist traversal.
ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
bool erase(const KeyT &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
static bool isInternalLinkage(LinkageTypes Linkage)
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
static cl::opt< bool > VerifySCEVMap("verify-scev-maps", cl::desc("Verify no dangling value in ScalarEvolution's ""ExprValueMap (slow)"))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
This class defines a simple visitor class that may be used for various SCEV analysis purposes...
static cl::opt< unsigned > MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt"), cl::init(8))
bool isSizeOf(Type *&AllocTy) const
APInt trunc(unsigned width) const
Truncate to new width.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
bool isNegative() const
Returns true if this value is known to be negative.
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM Basic Block Representation.
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
Type * getType() const
Return the LLVM type of this SCEV expression.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
Conditional or Unconditional Branch instruction.
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
bool sge(const APInt &RHS) const
Signed greather or equal comparison.
static bool IsMinConsistingOf(ScalarEvolution &SE, const SCEV *MaybeMinExpr, const SCEV *Candidate)
Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
bool isEquality() const
Return true if this predicate is either EQ or NE.
This is an important base class in LLVM.
bool isMaxSignedValue() const
Determine if this is the largest signed value.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const SCEV * getOperand(unsigned i) const
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
const SCEV * getExpr() const override
Implementation of the SCEVPredicate interface.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEV *LHS, const SCEV *RHS)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void add(const SCEVPredicate *N)
Adds a predicate to this union.
bool isZeroValue() const
Return true if the value is negative zero or null value.
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
void visitAll(const SCEV *Root)
const SCEV * getSMaxExpr(const SCEV *LHS, const SCEV *RHS)
bool isOverflowIntrinsicNoWrap(const IntrinsicInst *II, const DominatorTree &DT)
Returns true if the arithmetic part of the II 's result is used only along the paths control dependen...
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
APInt sext(unsigned width) const
Sign extend to a new width.
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
Represent the analysis usage information of a pass.
ConstantRange udiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned division of a value in...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
bool isFalseWhenEqual() const
This is just a convenience.
bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
const SCEV * getMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer arithmetic operators which may exhibit overflow - Add, Sub, and Mul.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
static const unsigned End
const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, SCEVUnionPredicate &A)
Re-writes the SCEV according to the Predicates in A.
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
op_range operands() const
const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead...
const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SCEVUnionPredicate &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
Value * getPointerOperand()
FunctionPass class - This class is used to implement most global optimizations.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
bool isMaxValue() const
Determine if this is the largest unsigned value.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Value * getOperand(unsigned i) const
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
iterator_range< block_iterator > blocks()
void print(raw_ostream &OS) const
Print out the bounds to a stream.
Class to represent integer types.
static LLVM_NODISCARD SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
Predicate getPredicate() const
Return the predicate for this instruction.
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 isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
static Constant * getNot(Constant *C)
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
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...
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
const SCEV * getLHS() const
const APInt & getAPInt() const
bool isEmptySet() const
Return true if this set contains no members.
const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, BasicBlock *BB)
bool isPointerTy() const
True if this is an instance of PointerType.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallPtrSetImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static wasm::ValType getType(const TargetRegisterClass *RC)
void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
const SCEV * getRHS() const
const SCEV * getUDivExactExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
The SCEV is loop-variant (unknown).
This class represents an assumption made using SCEV expressions which can be checked at run-time...
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, evaluate its value assuming the PHI node in the loop has the value PHIVal.
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))
void dump() const
This method is used for debugging.
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))
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool isConditional() const
const SCEV * getSMinExpr(const SCEV *LHS, const SCEV *RHS)
RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S)
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
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...
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static int numberOfTerms(const SCEV *S)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've proved that V doesn't wrap by means of a SCEV predicate.
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
Iterator for intrusive lists based on ilist_node.
static void Merge(const std::string &Input, const std::vector< std::string > Result, size_t NumNewFeatures)
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 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...
static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
This is the shared class of boolean and integer constants.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return the number of times the sign bit of the register is replicated into the other bits...
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
void initializeScalarEvolutionWrapperPassPass(PassRegistry &)
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty)
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
void delinearize(const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an array...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
This is a utility class that provides an abstraction for the common functionality between Instruction...
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
The SCEV dominates the block.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
This class represents a range of values.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const APInt & getLower() const
Return the lower value for this range.
bool isTrueWhenEqual() const
This is just a convenience.
LLVM_NODISCARD T pop_back_val()
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
CHAIN = SC CHAIN, Imm128 - System call.
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
APInt sqrt() const
Compute the square root.
iterator_range< detail::value_sequence_iterator< ValueT > > seq(ValueT Begin, ValueT End)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
ConstantInt * getValue() const
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.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
scalar Scalar Evolution Analysis
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
Class for arbitrary precision integers.
This node represents an addition of some number of SCEVs.
SetVector< ValueOffsetPair > * getSCEVValues(const SCEV *S)
Return the Value set from which the SCEV expr is generated.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents a signed maximum selection.
iterator_range< user_iterator > users()
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
static void clear(coro::Shape &Shape)
Value * getCondition() const
iterator insert(iterator I, T &&Elt)
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(16))
A utility class that uses RAII to save and restore the value of a variable.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
bool isMinValue() const
Determine if this is the smallest unsigned value.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
SCEVPredicate(const SCEVPredicate &)=default
llvm_unreachable("Unknown RegBank!")
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
bool isStructTy() const
True if this is an instance of StructType.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Analysis pass that exposes the ScalarEvolution for a function.
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
This class represents a zero extension of a small integer value to a larger integer value...
Virtual Register Rewriter
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
static std::vector< std::string > Flags
static Optional< std::pair< const SCEVConstant *, const SCEVConstant * > > SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Find the roots of the quadratic equation for the given quadratic chrec {L,+,M,+,N}.
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
const SCEVUnionPredicate & getUnionPredicate() const
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
void collectParametricTerms(const SCEV *Expr, SmallVectorImpl< const SCEV * > &Terms)
Collect parametric terms occurring in step expressions (first step of delinearization).
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
void emplace_back(ArgTypes &&...Args)
BasicBlock * getDefaultDest() const
static int CompareSCEVComplexity(SmallSet< std::pair< const SCEV *, const SCEV * >, 8 > &EqCacheSCEV, const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
The SCEV does not dominate the block.
FoldingSetNodeIDRef - This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node id data rather than using plain FoldingSetNodeIDs, since the 32-element SmallVector is often much larger than necessary, and the possibility of heap allocation means it requires a non-trivial destructor call.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
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...
pointer data()
Return a pointer to the vector's buffer, even if empty().
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
unsigned greater or equal
Represents a single loop in the control flow graph.
DenseMapIterator< SCEVCallbackVH, const SCEV *, DenseMapInfo< Value * >, detail::DenseMapPair< SCEVCallbackVH, const SCEV * > > iterator
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
This class represents a sign extension of a small integer value to a larger integer value...
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
This class represents an unsigned maximum selection.
static LLVM_NODISCARD SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask)
Convenient NoWrapFlags manipulation that hides enum casts and is visible in the ScalarEvolution name ...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool CollectAddOperandsWithScales(DenseMap< const SCEV *, APInt > &M, SmallVectorImpl< const SCEV * > &NewOps, APInt &AccumulatedConstant, const SCEV *const *Ops, size_t NumOperands, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale...
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
AnalysisUsage & addRequiredTransitive()
const Loop * getLoop() const
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void print(raw_ostream &OS) const
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD)
API to communicate dependencies between analyses during invalidation.
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive, key type.
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
bool isUnsigned() const
Determine if this instruction is using an unsigned comparison.
const APInt & getUpper() const
Return the upper value for this range.
bool isSingleEdge() const
Check if this is the only edge between Start and End.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Return the largest range containing all X such that "X BinOpC Y" is guaranteed not to wrap (overflow)...
bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS, const SCEV *&RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over \<a particular IR unit\>" (e...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
user_iterator user_begin()
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
unsigned getSCEVType() const
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS)
static Optional< BinaryOp > MatchBinaryOp(Value *V, DominatorTree &DT)
Try to map V into a BinaryOp, and return None on failure.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
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...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
const SCEV * getExpr() const override
Returns the SCEV to which this predicate applies, or nullptr if this is a SCEVUnionPredicate.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
A vector that has set insertion semantics.
void eraseValueFromMap(Value *V)
Erase Value from ValueExprMap and ExprValueMap.
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
bool canConstantFoldCallTo(ImmutableCallSite CS, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
This file provides utility classes that use RAII to save and restore values.
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))
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static bool containsConstantSomewhere(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
This class implements an extremely fast bulk output stream that can only output to a stream...
bool implies(const SCEVPredicate *N) const override
Returns true if this predicate implies N.
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getMaxBackedgeTakenCount or z...
const SCEV * getUDivExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
const SCEV * getUnknown(Value *V)
FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const
Intern - Copy this node's data to a memory region allocated from the given allocator and return a Fol...
The SCEV varies predictably with the loop.
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToValueMap &Map, bool InterpretConsts=false)
The legacy pass manager's analysis pass to compute loop information.
static bool findArrayDimensionsRec(ScalarEvolution &SE, SmallVectorImpl< const SCEV * > &Terms, SmallVectorImpl< const SCEV * > &Sizes)
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block...
op_iterator op_end() const
Value handle with callbacks on RAUW and destruction.
static int sizeOfSCEV(const SCEV *S)
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
APInt zext(unsigned width) const
Zero extend to a new width.
A container for analyses that lazily runs them and caches their results.
bool isNullValue() const
Determine if all bits are clear.
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock)
Get the expression for the number of loop iterations for which this loop is guaranteed not to exit vi...
Legacy analysis pass which computes a DominatorTree.
BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, const SCEV *Candidate)
Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
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 isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
static bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
Constant * ConstantFoldLoadThroughGEPIndices(Constant *C, ArrayRef< Constant * > Indices)
ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr indices (with an implied zero ...
bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, const SCEV *&InvariantRHS)
Return true if the result of the predicate LHS Pred RHS is loop invariant with respect to L...
APInt abs() const
Get the absolute value;.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static bool containsUndefs(const SCEV *S)
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop. ...
This node is a base class providing common functionality for n'ary operators.
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
This class represents an assumption made on an AddRec expression.
PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
friend class SCEVCallbackVH
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, const SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags)
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
const SCEV * getOperand() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
A special type used by analysis passes to provide an address that identifies that particular analysis...
const BasicBlock * getParent() const
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
bool hasNoUnsignedWrap() const
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
This visitor recursively visits a SCEV expression and re-writes it.
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...
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
static ConstantRange getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, unsigned BitWidth, bool Signed)
This class represents a constant integer value.
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 properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
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 bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, ICmpInst::Predicate 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?