85 #include "llvm/Config/llvm-config.h" 137 using namespace llvm;
139 #define DEBUG_TYPE "scalar-evolution" 142 "Number of trip counts computed with array length");
144 "Number of loops with predictable loop counts");
146 "Number of loops without predictable loop counts");
147 STATISTIC(NumBruteForceTripCountsComputed,
148 "Number of loops with trip counts computed by force");
153 cl::desc(
"Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 161 cl::desc(
"Verify ScalarEvolution's backedge taken counts (slow)"));
164 cl::desc(
"Enable stricter verification with -verify-scev is passed"));
167 cl::desc(
"Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)"));
172 cl::desc(
"Verify IR correctness when making sensitive SCEV queries (slow)"),
177 cl::desc(
"Threshold for inlining multiplication operands into a SCEV"),
182 cl::desc(
"Threshold for inlining addition operands into a SCEV"),
186 "scalar-evolution-max-scev-compare-depth",
cl::Hidden,
187 cl::desc(
"Maximum depth of recursive SCEV complexity comparisons"),
191 "scalar-evolution-max-scev-operations-implication-depth",
cl::Hidden,
192 cl::desc(
"Maximum depth of recursive SCEV operations implication analysis"),
196 "scalar-evolution-max-value-compare-depth",
cl::Hidden,
197 cl::desc(
"Maximum depth of recursive value complexity comparisons"),
202 cl::desc(
"Maximum depth of recursive arithmetics"),
206 "scalar-evolution-max-constant-evolving-depth",
cl::Hidden,
211 cl::desc(
"Maximum depth of recursive SExt/ZExt/Trunc"),
216 cl::desc(
"Max coefficients in AddRec during evolving"),
221 cl::desc(
"Size of the expression which is considered huge"),
227 cl::desc(
"When printing analysis, include information on every instruction"));
238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 248 cast<SCEVConstant>(
this)->getValue()->printAsOperand(OS,
false);
253 OS <<
"(trunc " << *Op->getType() <<
" " << *Op <<
" to " 260 OS <<
"(zext " << *Op->getType() <<
" " << *Op <<
" to " 267 OS <<
"(sext " << *Op->getType() <<
" " << *Op <<
" to " 295 const char *OpStr =
nullptr;
312 if (std::next(I) !=
E)
328 OS <<
"(" << *UDiv->
getLHS() <<
" /u " << *UDiv->
getRHS() <<
")";
335 OS <<
"sizeof(" << *AllocTy <<
")";
339 OS <<
"alignof(" << *AllocTy <<
")";
346 OS <<
"offsetof(" << *CTy <<
", ";
357 OS <<
"***COULDNOTCOMPUTE***";
366 return cast<SCEVConstant>(
this)->
getType();
370 return cast<SCEVCastExpr>(
this)->
getType();
377 return cast<SCEVNAryExpr>(
this)->
getType();
379 return cast<SCEVAddExpr>(
this)->
getType();
381 return cast<SCEVUDivExpr>(
this)->
getType();
383 return cast<SCEVUnknown>(
this)->
getType();
392 return SC->getValue()->isZero();
398 return SC->getValue()->isOne();
404 return SC->getValue()->isMinusOne();
410 if (!Mul)
return false;
414 if (!SC)
return false;
432 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
434 UniqueSCEVs.InsertNode(S, IP);
444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
456 "Cannot truncate non-integer value!");
463 "Cannot zero extend non-integer value!");
470 "Cannot sign extend non-integer value!");
473 void SCEVUnknown::deleted() {
475 SE->forgetMemoizedResults(
this);
478 SE->UniqueSCEVs.RemoveNode(
this);
484 void SCEVUnknown::allUsesReplacedWith(
Value *New) {
486 SE->UniqueSCEVs.RemoveNode(
this);
495 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
496 if (VCE->getOpcode() == Instruction::PtrToInt)
497 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
498 if (CE->getOpcode() == Instruction::GetElementPtr &&
499 CE->getOperand(0)->isNullValue() &&
500 CE->getNumOperands() == 2)
501 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
503 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
512 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
513 if (VCE->getOpcode() == Instruction::PtrToInt)
514 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
515 if (CE->getOpcode() == Instruction::GetElementPtr &&
516 CE->getOperand(0)->isNullValue()) {
518 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
519 if (
StructType *STy = dyn_cast<StructType>(Ty))
520 if (!STy->isPacked() &&
521 CE->getNumOperands() == 3 &&
522 CE->getOperand(1)->isNullValue()) {
523 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
525 STy->getNumElements() == 2 &&
526 STy->getElementType(0)->isIntegerTy(1)) {
527 AllocTy = STy->getElementType(1);
537 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
538 if (VCE->getOpcode() == Instruction::PtrToInt)
539 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
540 if (CE->getOpcode() == Instruction::GetElementPtr &&
541 CE->getNumOperands() == 3 &&
542 CE->getOperand(0)->isNullValue() &&
543 CE->getOperand(1)->isNullValue()) {
545 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
550 FieldNo = CE->getOperand(2);
591 if (LIsPointer != RIsPointer)
592 return (
int)LIsPointer - (int)RIsPointer;
597 return (
int)LID - (int)RID;
600 if (
const auto *LA = dyn_cast<Argument>(LV)) {
601 const auto *
RA = cast<Argument>(RV);
602 unsigned LArgNo = LA->getArgNo(), RArgNo =
RA->getArgNo();
603 return (
int)LArgNo - (int)RArgNo;
606 if (
const auto *LGV = dyn_cast<GlobalValue>(LV)) {
607 const auto *RGV = cast<GlobalValue>(RV);
609 const auto IsGVNameSemantic = [&](
const GlobalValue *GV) {
610 auto LT = GV->getLinkage();
617 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
618 return LGV->getName().compare(RGV->getName());
623 if (
const auto *LInst = dyn_cast<Instruction>(LV)) {
624 const auto *RInst = cast<Instruction>(RV);
629 if (LParent != RParent) {
632 if (LDepth != RDepth)
633 return (
int)LDepth - (int)RDepth;
637 unsigned LNumOps = LInst->getNumOperands(),
638 RNumOps = RInst->getNumOperands();
639 if (LNumOps != RNumOps)
640 return (
int)LNumOps - (int)RNumOps;
642 for (
unsigned Idx :
seq(0u, LNumOps)) {
645 RInst->getOperand(Idx), Depth + 1);
670 return (
int)LType - (int)RType;
677 switch (static_cast<SCEVTypes>(LType)) {
683 RU->getValue(),
Depth + 1);
695 const APInt &
RA = RC->getAPInt();
696 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.
getBitWidth();
697 if (LBitWidth != RBitWidth)
698 return (
int)LBitWidth - (int)RBitWidth;
699 return LA.ult(RA) ? -1 : 1;
709 const Loop *LLoop = LA->
getLoop(), *RLoop = RA->getLoop();
710 if (LLoop != RLoop) {
711 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
712 assert(LHead != RHead &&
"Two loops share the same header?");
717 "No dominance between recurrences used by one SCEV?");
722 unsigned LNumOps = LA->
getNumOperands(), RNumOps = RA->getNumOperands();
723 if (LNumOps != RNumOps)
724 return (
int)LNumOps - (int)RNumOps;
727 for (
unsigned i = 0; i != LNumOps; ++i) {
748 unsigned LNumOps = LC->
getNumOperands(), RNumOps = RC->getNumOperands();
749 if (LNumOps != RNumOps)
750 return (
int)LNumOps - (int)RNumOps;
752 for (
unsigned i = 0; i != LNumOps; ++i) {
769 RC->getLHS(), DT,
Depth + 1);
773 RC->getRHS(), DT,
Depth + 1);
811 if (Ops.
size() < 2)
return;
815 if (Ops.
size() == 2) {
818 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
834 for (
unsigned i = 0,
e = Ops.
size(); i !=
e-2; ++i) {
835 const SCEV *S = Ops[i];
840 for (
unsigned j = i+1; j !=
e && Ops[j]->getSCEVType() == Complexity; ++j) {
845 if (i ==
e-2)
return;
853 struct FindSCEVSize {
856 FindSCEVSize() =
default;
858 bool follow(
const SCEV *S) {
864 bool isDone()
const {
888 struct SCEVDivision :
public SCEVVisitor<SCEVDivision, void> {
893 const SCEV *Denominator,
const SCEV **Quotient,
894 const SCEV **Remainder) {
895 assert(Numerator && Denominator &&
"Uninitialized SCEV");
897 SCEVDivision
D(SE, Numerator, Denominator);
901 if (Numerator == Denominator) {
907 if (Numerator->
isZero()) {
914 if (Denominator->
isOne()) {
915 *Quotient = Numerator;
921 if (
const SCEVMulExpr *
T = dyn_cast<SCEVMulExpr>(Denominator)) {
923 *Quotient = Numerator;
924 for (
const SCEV *
Op :
T->operands()) {
925 divide(SE, *Quotient,
Op, &Q, &R);
932 *Remainder = Numerator;
941 *Quotient = D.Quotient;
942 *Remainder = D.Remainder;
959 if (
const SCEVConstant *
D = dyn_cast<SCEVConstant>(Denominator)) {
961 APInt DenominatorVal =
D->getAPInt();
965 if (NumeratorBW > DenominatorBW)
966 DenominatorVal = DenominatorVal.
sext(NumeratorBW);
967 else if (NumeratorBW < DenominatorBW)
968 NumeratorVal = NumeratorVal.
sext(DenominatorBW);
972 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
980 const SCEV *StartQ, *StartR, *StepQ, *StepR;
982 return cannotDivide(Numerator);
983 divide(SE, Numerator->
getStart(), Denominator, &StartQ, &StartR);
987 if (Ty != StartQ->getType() || Ty != StartR->
getType() ||
988 Ty != StepQ->getType() || Ty != StepR->
getType())
989 return cannotDivide(Numerator);
1002 divide(SE,
Op, Denominator, &Q, &R);
1006 return cannotDivide(Numerator);
1012 if (Qs.
size() == 1) {
1026 bool FoundDenominatorTerm =
false;
1030 return cannotDivide(Numerator);
1032 if (FoundDenominatorTerm) {
1039 divide(SE,
Op, Denominator, &Q, &R);
1047 return cannotDivide(Numerator);
1049 FoundDenominatorTerm =
true;
1053 if (FoundDenominatorTerm) {
1062 if (!isa<SCEVUnknown>(Denominator))
1063 return cannotDivide(Numerator);
1067 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1068 cast<SCEVConstant>(Zero)->getValue();
1071 if (Remainder->
isZero()) {
1073 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1074 cast<SCEVConstant>(One)->getValue();
1085 return cannotDivide(Numerator);
1086 divide(SE, Diff, Denominator, &Q, &R);
1088 return cannotDivide(Numerator);
1094 const SCEV *Denominator)
1095 : SE(S), Denominator(Denominator) {
1102 cannotDivide(Numerator);
1107 void cannotDivide(
const SCEV *Numerator) {
1109 Remainder = Numerator;
1113 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1190 APInt OddFactorial(W, 1);
1192 for (
unsigned i = 3; i <= K; ++i) {
1197 OddFactorial *=
Mult;
1201 unsigned CalculationBits = W +
T;
1210 APInt MultiplyFactor = OddFactorial.
zext(W+1);
1212 MultiplyFactor = MultiplyFactor.
trunc(W);
1218 for (
unsigned i = 1; i != K; ++i) {
1243 const SCEV *Result = getStart();
1244 for (
unsigned i = 1,
e = getNumOperands(); i !=
e; ++i) {
1249 if (isa<SCEVCouldNotCompute>(Coeff))
1263 assert(getTypeSizeInBits(Op->
getType()) > getTypeSizeInBits(Ty) &&
1264 "This is not a truncating conversion!");
1266 "This is not a conversion to a SCEVable type!");
1267 Ty = getEffectiveSCEVType(Ty);
1274 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1283 return getTruncateExpr(
ST->getOperand(),
Ty, Depth + 1);
1287 return getTruncateOrSignExtend(
SS->getOperand(),
Ty, Depth + 1);
1291 return getTruncateOrZeroExtend(SZ->getOperand(),
Ty, Depth + 1);
1296 UniqueSCEVs.InsertNode(S, IP);
1297 addToLoopUseLists(S);
1305 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1306 auto *CommOp = cast<SCEVCommutativeExpr>(
Op);
1308 unsigned numTruncs = 0;
1309 for (
unsigned i = 0,
e = CommOp->getNumOperands(); i !=
e && numTruncs < 2;
1311 const SCEV *S = getTruncateExpr(CommOp->getOperand(i),
Ty, Depth + 1);
1312 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1314 Operands.push_back(S);
1316 if (numTruncs < 2) {
1317 if (isa<SCEVAddExpr>(Op))
1318 return getAddExpr(Operands);
1319 else if (isa<SCEVMulExpr>(Op))
1320 return getMulExpr(Operands);
1327 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1332 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1334 for (
const SCEV *Op : AddRec->operands())
1335 Operands.
push_back(getTruncateExpr(Op, Ty, Depth + 1));
1344 UniqueSCEVs.InsertNode(S, IP);
1345 addToLoopUseLists(S);
1384 struct ExtendOpTraitsBase {
1390 template <
typename ExtendOp>
struct ExtendOpTraits {
1403 struct ExtendOpTraits<SCEVSignExtendExpr> :
public ExtendOpTraitsBase {
1406 static const GetExtendExprTy GetExtendExpr;
1408 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1415 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1419 struct ExtendOpTraits<SCEVZeroExtendExpr> :
public ExtendOpTraitsBase {
1422 static const GetExtendExprTy GetExtendExpr;
1424 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1431 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1443 template <
typename ExtendOpTy>
1446 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1447 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1473 auto PreStartFlags =
1491 const SCEV *OperandExtendedStart =
1492 SE->
getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1493 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1494 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1506 const SCEV *OverflowLimit =
1507 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1509 if (OverflowLimit &&
1517 template <
typename ExtendOpTy>
1521 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1523 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR,
Ty, SE,
Depth);
1525 return (SE->*GetExtendExpr)(AR->getStart(),
Ty,
Depth);
1527 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE),
Ty,
1529 (SE->*GetExtendExpr)(PreStart,
Ty,
Depth));
1564 template <
typename ExtendOpTy>
1565 bool ScalarEvolution::proveNoWrapByVaryingStart(
const SCEV *Start,
1568 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1580 for (
unsigned Delta : {-2, -1, 1, 2}) {
1581 const SCEV *PreStart = getConstant(StartAI - Delta);
1590 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1594 if (PreAR && PreAR->getNoWrapFlags(WrapType)) {
1595 const SCEV *DeltaS = getConstant(StartC->
getType(), Delta);
1597 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1598 DeltaS, &Pred,
this);
1599 if (Limit && isKnownPredicate(Pred, PreAR, Limit))
1624 return TZ < BitWidth ? C.
trunc(TZ).
zext(BitWidth) :
C;
1626 return APInt(BitWidth, 0);
1634 const APInt &ConstantStart,
1636 const unsigned BitWidth = ConstantStart.
getBitWidth();
1639 return TZ < BitWidth ? ConstantStart.
trunc(TZ).
zext(BitWidth)
1641 return APInt(BitWidth, 0);
1646 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
1647 "This is not an extending conversion!");
1649 "This is not a conversion to a SCEVable type!");
1650 Ty = getEffectiveSCEVType(Ty);
1659 return getZeroExtendExpr(SZ->getOperand(),
Ty, Depth + 1);
1668 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1672 UniqueSCEVs.InsertNode(S, IP);
1673 addToLoopUseLists(S);
1681 const SCEV *
X =
ST->getOperand();
1683 unsigned TruncBits = getTypeSizeInBits(
ST->getType());
1684 unsigned NewBits = getTypeSizeInBits(Ty);
1687 return getTruncateOrZeroExtend(X, Ty, Depth);
1695 if (AR->isAffine()) {
1696 const SCEV *Start = AR->getStart();
1697 const SCEV *Step = AR->getStepRecurrence(*
this);
1698 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1699 const Loop *L = AR->getLoop();
1701 if (!AR->hasNoUnsignedWrap()) {
1702 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1708 if (AR->hasNoUnsignedWrap())
1709 return getAddRecExpr(
1710 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1711 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1721 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1722 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1728 const SCEV *CastedMaxBECount =
1729 getTruncateOrZeroExtend(MaxBECount, Start->
getType(),
Depth);
1730 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1732 if (MaxBECount == RecastedMaxBECount) {
1735 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1737 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1741 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1742 const SCEV *WideMaxBECount =
1743 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1744 const SCEV *OperandExtendedAdd =
1745 getAddExpr(WideStart,
1746 getMulExpr(WideMaxBECount,
1747 getZeroExtendExpr(Step, WideTy, Depth + 1),
1750 if (ZAdd == OperandExtendedAdd) {
1754 return getAddRecExpr(
1755 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1757 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1758 AR->getNoWrapFlags());
1762 OperandExtendedAdd =
1763 getAddExpr(WideStart,
1764 getMulExpr(WideMaxBECount,
1765 getSignExtendExpr(Step, WideTy, Depth + 1),
1768 if (ZAdd == OperandExtendedAdd) {
1773 return getAddRecExpr(
1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1776 getSignExtendExpr(Step, Ty, Depth + 1), L,
1777 AR->getNoWrapFlags());
1789 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1790 !AC.assumptions().empty()) {
1798 getUnsignedRangeMax(Step));
1805 return getAddRecExpr(
1806 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1808 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1809 AR->getNoWrapFlags());
1813 getSignedRangeMin(Step));
1821 return getAddRecExpr(
1822 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1824 getSignExtendExpr(Step, Ty, Depth + 1), L,
1825 AR->getNoWrapFlags());
1833 if (
const auto *
SC = dyn_cast<SCEVConstant>(Start)) {
1837 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1838 const SCEV *SResidual =
1839 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1840 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1841 return getAddExpr(SZExtD, SZExtR,
1847 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1849 return getAddRecExpr(
1850 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1851 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1859 if (matchURem(Op, LHS, RHS))
1860 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1861 getZeroExtendExpr(RHS, Ty, Depth + 1));
1865 if (
auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1866 return getUDivExpr(getZeroExtendExpr(Div->getLHS(),
Ty, Depth + 1),
1867 getZeroExtendExpr(Div->getRHS(),
Ty, Depth + 1));
1869 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1871 if (SA->hasNoUnsignedWrap()) {
1875 for (
const auto *Op : SA->operands())
1876 Ops.
push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1888 if (
const auto *
SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1891 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1892 const SCEV *SResidual =
1894 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1895 return getAddExpr(SZExtD, SZExtR,
1902 if (
auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1904 if (SM->hasNoUnsignedWrap()) {
1908 for (
const auto *Op : SM->operands())
1909 Ops.
push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1925 if (SM->getNumOperands() == 2)
1926 if (
auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1927 if (MulLHS->getAPInt().isPowerOf2())
1928 if (
auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1929 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1930 MulLHS->getAPInt().logBase2();
1933 getZeroExtendExpr(MulLHS, Ty),
1935 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1942 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1945 UniqueSCEVs.InsertNode(S, IP);
1946 addToLoopUseLists(S);
1952 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
1953 "This is not an extending conversion!");
1955 "This is not a conversion to a SCEVable type!");
1956 Ty = getEffectiveSCEVType(Ty);
1965 return getSignExtendExpr(
SS->getOperand(),
Ty, Depth + 1);
1969 return getZeroExtendExpr(SZ->getOperand(),
Ty, Depth + 1);
1978 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1983 UniqueSCEVs.InsertNode(S, IP);
1984 addToLoopUseLists(S);
1992 const SCEV *
X =
ST->getOperand();
1994 unsigned TruncBits = getTypeSizeInBits(
ST->getType());
1995 unsigned NewBits = getTypeSizeInBits(Ty);
1998 return getTruncateOrSignExtend(X, Ty, Depth);
2001 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2003 if (SA->hasNoSignedWrap()) {
2007 for (
const auto *Op : SA->operands())
2008 Ops.
push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2021 if (
const auto *
SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2024 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2025 const SCEV *SResidual =
2027 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2028 return getAddExpr(SSExtD, SSExtR,
2039 if (AR->isAffine()) {
2040 const SCEV *Start = AR->getStart();
2041 const SCEV *Step = AR->getStepRecurrence(*
this);
2042 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2043 const Loop *L = AR->getLoop();
2045 if (!AR->hasNoSignedWrap()) {
2046 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2052 if (AR->hasNoSignedWrap())
2053 return getAddRecExpr(
2054 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2065 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2066 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2072 const SCEV *CastedMaxBECount =
2073 getTruncateOrZeroExtend(MaxBECount, Start->
getType(),
Depth);
2074 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2076 if (MaxBECount == RecastedMaxBECount) {
2079 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2081 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2085 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2086 const SCEV *WideMaxBECount =
2087 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2088 const SCEV *OperandExtendedAdd =
2089 getAddExpr(WideStart,
2090 getMulExpr(WideMaxBECount,
2091 getSignExtendExpr(Step, WideTy, Depth + 1),
2094 if (SAdd == OperandExtendedAdd) {
2098 return getAddRecExpr(
2099 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2101 getSignExtendExpr(Step, Ty, Depth + 1), L,
2102 AR->getNoWrapFlags());
2106 OperandExtendedAdd =
2107 getAddExpr(WideStart,
2108 getMulExpr(WideMaxBECount,
2109 getZeroExtendExpr(Step, WideTy, Depth + 1),
2112 if (SAdd == OperandExtendedAdd) {
2124 return getAddRecExpr(
2125 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2127 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2128 AR->getNoWrapFlags());
2141 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2142 !AC.assumptions().empty()) {
2149 const SCEV *OverflowLimit =
2151 if (OverflowLimit &&
2152 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2153 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2156 return getAddRecExpr(
2157 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2158 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2165 if (
const auto *
SC = dyn_cast<SCEVConstant>(Start)) {
2169 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2170 const SCEV *SResidual =
2171 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2172 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2173 return getAddExpr(SSExtD, SSExtR,
2179 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2181 return getAddRecExpr(
2182 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2183 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2190 return getZeroExtendExpr(Op, Ty, Depth + 1);
2194 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
2197 UniqueSCEVs.InsertNode(S, IP);
2198 addToLoopUseLists(S);
2206 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
2207 "This is not an extending conversion!");
2209 "This is not a conversion to a SCEVable type!");
2210 Ty = getEffectiveSCEVType(Ty);
2214 if (
SC->getAPInt().isNegative())
2215 return getSignExtendExpr(Op, Ty);
2219 const SCEV *NewOp =
T->getOperand();
2220 if (getTypeSizeInBits(NewOp->
getType()) < getTypeSizeInBits(Ty))
2221 return getAnyExtendExpr(NewOp, Ty);
2222 return getTruncateOrNoop(NewOp, Ty);
2226 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2227 if (!isa<SCEVZeroExtendExpr>(ZExt))
2231 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2232 if (!isa<SCEVSignExtendExpr>(SExt))
2238 for (
const SCEV *Op : AR->operands())
2239 Ops.
push_back(getAnyExtendExpr(Op, Ty));
2240 return getAddRecExpr(Ops, AR->getLoop(),
SCEV::FlagNW);
2244 if (isa<SCEVSMaxExpr>(Op))
2277 APInt &AccumulatedConstant,
2278 const SCEV *
const *Ops,
size_t NumOperands,
2281 bool Interesting =
false;
2285 while (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2288 if (Scale != 1 || AccumulatedConstant != 0 ||
C->getValue()->isZero())
2290 AccumulatedConstant += Scale *
C->getAPInt();
2295 for (; i != NumOperands; ++i) {
2297 if (Mul && isa<SCEVConstant>(Mul->
getOperand(0))) {
2299 Scale * cast<SCEVConstant>(Mul->
getOperand(0))->getAPInt();
2316 Pair.first->second += NewScale;
2324 std::pair<DenseMap<const SCEV *, APInt>::iterator,
bool> Pair =
2325 M.
insert({Ops[i], Scale});
2329 Pair.first->second += Scale;
2347 using namespace std::placeholders;
2354 assert(CanAnalyze &&
"don't call from other places!");
2361 auto IsKnownNonNegative = [&](
const SCEV *S) {
2371 if (SignOrUnsignWrap != SignOrUnsignMask &&
2373 isa<SCEVConstant>(Ops[0])) {
2380 return Instruction::Mul;
2386 const APInt &
C = cast<SCEVConstant>(Ops[0])->getAPInt();
2391 Opcode, C, OBO::NoSignedWrap);
2399 Opcode, C, OBO::NoUnsignedWrap);
2409 return isLoopInvariant(S, L) && properlyDominates(S, L->
getHeader());
2417 "only nuw or nsw allowed");
2419 if (Ops.
size() == 1)
return Ops[0];
2421 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
2422 for (
unsigned i = 1,
e = Ops.
size(); i !=
e; ++i)
2424 "SCEVAddExpr operand types don't match!");
2434 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2437 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2439 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2440 if (Ops.
size() == 2)
return Ops[0];
2442 LHSC = cast<SCEVConstant>(Ops[0]);
2446 if (LHSC->getValue()->isZero()) {
2451 if (Ops.
size() == 1)
return Ops[0];
2456 return getOrCreateAddExpr(Ops, Flags);
2461 Type *
Ty = Ops[0]->getType();
2462 bool FoundMatch =
false;
2463 for (
unsigned i = 0,
e = Ops.
size(); i !=
e-1; ++i)
2464 if (Ops[i] == Ops[i+1]) {
2467 while (i+Count !=
e && Ops[i+Count] == Ops[i])
2470 const SCEV *Scale = getConstant(Ty, Count);
2472 if (Ops.
size() == Count)
2476 --i;
e -= Count - 1;
2480 return getAddExpr(Ops, Flags, Depth + 1);
2486 auto FindTruncSrcType = [&]() ->
Type * {
2491 if (
auto *
T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2492 return T->getOperand()->getType();
2493 if (
const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2494 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2495 if (
const auto *
T = dyn_cast<SCEVTruncateExpr>(LastOp))
2496 return T->getOperand()->getType();
2500 if (
auto *SrcType = FindTruncSrcType()) {
2505 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
2507 if (
T->getOperand()->getType() != SrcType) {
2512 }
else if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2513 LargeOps.
push_back(getAnyExtendExpr(
C, SrcType));
2514 }
else if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2516 for (
unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2518 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2519 if (
T->getOperand()->getType() != SrcType) {
2524 }
else if (
const auto *
C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2525 LargeMulOps.
push_back(getAnyExtendExpr(
C, SrcType));
2542 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2543 return getTruncateExpr(Fold, Ty);
2548 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scAddExpr)
2552 if (Idx < Ops.
size()) {
2553 bool DeletedAdd =
false;
2554 while (
const SCEVAddExpr *
Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2573 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
2578 if (Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx])) {
2579 uint64_t BitWidth = getTypeSizeInBits(Ty);
2582 APInt AccumulatedConstant(BitWidth, 0);
2585 APInt(BitWidth, 1), *
this)) {
2586 struct APIntCompare {
2587 bool operator()(
const APInt &LHS,
const APInt &RHS)
const {
2588 return LHS.
ult(RHS);
2595 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2596 for (
const SCEV *NewOp : NewOps)
2597 MulOpLists[M.
find(NewOp)->second].push_back(NewOp);
2600 if (AccumulatedConstant != 0)
2601 Ops.
push_back(getConstant(AccumulatedConstant));
2602 for (
auto &MulOp : MulOpLists)
2603 if (MulOp.first != 0)
2605 getConstant(MulOp.first),
2610 if (Ops.
size() == 1)
2619 for (; Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2620 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2623 if (isa<SCEVConstant>(MulOpSCEV))
2625 for (
unsigned AddOp = 0,
e = Ops.
size(); AddOp !=
e; ++AddOp)
2626 if (MulOpSCEV == Ops[AddOp]) {
2639 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2641 if (Ops.
size() == 2)
return OuterMul;
2654 for (
unsigned OtherMulIdx = Idx+1;
2655 OtherMulIdx < Ops.
size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2657 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2661 OMulOp !=
e; ++OMulOp)
2662 if (OtherMul->
getOperand(OMulOp) == MulOpSCEV) {
2679 const SCEV *InnerMulSum =
2681 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2683 if (Ops.
size() == 2)
return OuterMul;
2700 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2706 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
2707 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2714 if (!LIOps.
empty()) {
2723 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2729 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2732 if (Ops.
size() == 1)
return NewRec;
2735 for (
unsigned i = 0;; ++i)
2736 if (Ops[i] == AddRec) {
2746 for (
unsigned OtherIdx = Idx+1;
2747 OtherIdx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2752 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2754 "AddRecExprs are not sorted in reverse dominance order?");
2755 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2759 for (; OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2761 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2762 if (OtherAddRec->getLoop() == AddRecLoop) {
2763 for (
unsigned i = 0,
e = OtherAddRec->getNumOperands();
2765 if (i >= AddRecOps.size()) {
2766 AddRecOps.
append(OtherAddRec->op_begin()+i,
2767 OtherAddRec->op_end());
2771 AddRecOps[i], OtherAddRec->getOperand(i)};
2774 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
2789 return getOrCreateAddExpr(Ops, Flags);
2797 for (
const SCEV *
Op : Ops)
2801 static_cast<SCEVAddExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2803 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.size());
2804 std::uninitialized_copy(Ops.begin(), Ops.end(),
O);
2805 S =
new (SCEVAllocator)
2807 UniqueSCEVs.InsertNode(S, IP);
2808 addToLoopUseLists(S);
2819 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
2824 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2826 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
2827 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
2828 S =
new (SCEVAllocator)
2830 UniqueSCEVs.InsertNode(S, IP);
2831 addToLoopUseLists(S);
2842 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
2846 static_cast<SCEVMulExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2848 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
2849 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
2852 UniqueSCEVs.InsertNode(S, IP);
2853 addToLoopUseLists(S);
2859 static uint64_t
umul_ov(uint64_t i, uint64_t j,
bool &Overflow) {
2861 if (j > 1 && k / j != i) Overflow =
true;
2868 static uint64_t
Choose(uint64_t n, uint64_t k,
bool &Overflow) {
2877 if (n == 0 || n == k)
return 1;
2878 if (k > n)
return 0;
2884 for (uint64_t i = 1; i <= k; ++i) {
2885 r =
umul_ov(r, n-(i-1), Overflow);
2894 struct FindConstantInAddMulChain {
2895 bool FoundConstant =
false;
2897 bool follow(
const SCEV *S) {
2898 FoundConstant |= isa<SCEVConstant>(S);
2899 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2902 bool isDone()
const {
2903 return FoundConstant;
2907 FindConstantInAddMulChain
F;
2910 return F.FoundConstant;
2918 "only nuw or nsw allowed");
2920 if (Ops.
size() == 1)
return Ops[0];
2922 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
2923 for (
unsigned i = 1,
e = Ops.
size(); i !=
e; ++i)
2925 "SCEVMulExpr operand types don't match!");
2935 return getOrCreateMulExpr(Ops, Flags);
2939 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2941 if (Ops.
size() == 2)
2951 return getAddExpr(getMulExpr(LHSC,
Add->getOperand(0),
2953 getMulExpr(LHSC,
Add->getOperand(1),
2958 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2962 Ops[0] = getConstant(Fold);
2963 Ops.erase(Ops.begin()+1);
2964 if (Ops.size() == 1)
return Ops[0];
2965 LHSC = cast<SCEVConstant>(Ops[0]);
2969 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2972 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2978 if (Ops.
size() == 2) {
2981 bool AnyFolded =
false;
2982 for (
const SCEV *AddOp :
Add->operands()) {
2985 if (!isa<SCEVMulExpr>(Mul)) AnyFolded =
true;
2990 }
else if (
const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2993 for (
const SCEV *AddRecOp : AddRec->operands())
2997 return getAddRecExpr(Operands, AddRec->getLoop(),
3003 if (Ops.
size() == 1)
3008 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
3012 if (Idx < Ops.
size()) {
3013 bool DeletedMul =
false;
3014 while (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3020 Ops.
append(Mul->op_begin(), Mul->op_end());
3038 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3044 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
3045 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3052 if (!LIOps.
empty()) {
3067 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3070 if (Ops.
size() == 1)
return NewRec;
3073 for (
unsigned i = 0;; ++i)
3074 if (Ops[i] == AddRec) {
3095 bool OpsModified =
false;
3096 for (
unsigned OtherIdx = Idx+1;
3097 OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3101 if (!OtherAddRec || OtherAddRec->
getLoop() != AddRecLoop)
3111 bool Overflow =
false;
3113 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3118 for (
int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3119 uint64_t Coeff1 =
Choose(x, 2*x - y, Overflow);
3122 z < ze && !Overflow; ++z) {
3123 uint64_t Coeff2 =
Choose(2*x - y, x-z, Overflow);
3125 if (LargerThan64Bits)
3126 Coeff =
umul_ov(Coeff1, Coeff2, Overflow);
3128 Coeff = Coeff1*Coeff2;
3129 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3132 SumOps.
push_back(getMulExpr(CoeffTerm, Term1, Term2,
3141 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3143 if (Ops.
size() == 2)
return NewAddRec;
3144 Ops[Idx] = NewAddRec;
3145 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
3161 return getOrCreateMulExpr(Ops, Flags);
3168 getEffectiveSCEVType(RHS->
getType()) &&
3169 "SCEVURemExpr operand types don't match!");
3172 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3174 if (RHSC->getValue()->isOne())
3175 return getZero(LHS->
getType());
3178 if (RHSC->getAPInt().isPowerOf2()) {
3182 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3187 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3197 getEffectiveSCEVType(RHS->
getType()) &&
3198 "SCEVUDivExpr operand types don't match!");
3200 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3201 if (RHSC->getValue()->isOne())
3206 if (!RHSC->getValue()->isZero()) {
3211 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3212 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3215 if (!RHSC->getAPInt().isPowerOf2())
3221 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*
this))) {
3223 const APInt &StepInt = Step->getAPInt();
3224 const APInt &DivInt = RHSC->getAPInt();
3225 if (!StepInt.
urem(DivInt) &&
3226 getZeroExtendExpr(AR, ExtTy) ==
3227 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3228 getZeroExtendExpr(Step, ExtTy),
3231 for (
const SCEV *
Op : AR->operands())
3233 return getAddRecExpr(Operands, AR->getLoop(),
SCEV::FlagNW);
3239 if (StartC && !DivInt.
urem(StepInt) &&
3240 getZeroExtendExpr(AR, ExtTy) ==
3241 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3242 getZeroExtendExpr(Step, ExtTy),
3244 const APInt &StartInt = StartC->getAPInt();
3245 const APInt &StartRem = StartInt.
urem(StepInt);
3247 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3252 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3254 for (
const SCEV *
Op : M->operands())
3256 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3258 for (
unsigned i = 0,
e = M->getNumOperands(); i !=
e; ++i) {
3259 const SCEV *
Op = M->getOperand(i);
3260 const SCEV *Div = getUDivExpr(Op, RHSC);
3261 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3265 return getMulExpr(Operands);
3271 if (
const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3272 if (
auto *DivisorConstant =
3273 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3274 bool Overflow =
false;
3276 DivisorConstant->getAPInt().
umul_ov(RHSC->getAPInt(), Overflow);
3278 return getConstant(RHSC->getType(), 0,
false);
3280 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3285 if (
const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3287 for (
const SCEV *
Op : A->operands())
3289 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3291 for (
unsigned i = 0,
e = A->getNumOperands(); i !=
e; ++i) {
3292 const SCEV *
Op = getUDivExpr(A->getOperand(i), RHS);
3293 if (isa<SCEVUDivExpr>(Op) ||
3294 getMulExpr(Op, RHS) != A->getOperand(i))
3298 if (Operands.
size() == A->getNumOperands())
3299 return getAddExpr(Operands);
3304 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3305 Constant *LHSCV = LHSC->getValue();
3306 Constant *RHSCV = RHSC->getValue();
3318 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3321 UniqueSCEVs.InsertNode(S, IP);
3322 addToLoopUseLists(S);
3352 return getUDivExpr(LHS, RHS);
3354 if (
const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3357 if (
const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->
getOperand(0))) {
3358 if (LHSCst == RHSCst) {
3361 return getMulExpr(Operands);
3367 APInt Factor =
gcd(LHSCst, RHSCst);
3370 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3372 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3376 LHS = getMulExpr(Operands);
3380 return getUDivExactExpr(LHS, RHS);
3390 return getMulExpr(Operands);
3394 return getUDivExpr(LHS, RHS);
3404 if (
const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3405 if (StepChrec->getLoop() == L) {
3406 Operands.
append(StepChrec->op_begin(), StepChrec->op_end());
3407 return getAddRecExpr(Operands, L, maskFlags(Flags,
SCEV::FlagNW));
3411 return getAddRecExpr(Operands, L, Flags);
3419 if (Operands.
size() == 1)
return Operands[0];
3421 Type *ETy = getEffectiveSCEVType(Operands[0]->
getType());
3422 for (
unsigned i = 1,
e = Operands.
size(); i !=
e; ++i)
3423 assert(getEffectiveSCEVType(Operands[i]->
getType()) == ETy &&
3424 "SCEVAddRecExpr operand types don't match!");
3425 for (
unsigned i = 0,
e = Operands.
size(); i !=
e; ++i)
3426 assert(isLoopInvariant(Operands[i], L) &&
3427 "SCEVAddRecExpr operand is not loop-invariant!");
3430 if (Operands.
back()->isZero()) {
3444 if (
const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3445 const Loop *NestedLoop = NestedAR->getLoop();
3451 NestedAR->op_end());
3452 Operands[0] = NestedAR->getStart();
3456 bool AllInvariant =
all_of(
3457 Operands, [&](
const SCEV *
Op) {
return isLoopInvariant(Op, L); });
3465 maskFlags(Flags,
SCEV::FlagNW | NestedAR->getNoWrapFlags());
3467 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3468 AllInvariant =
all_of(NestedOperands, [&](
const SCEV *Op) {
3469 return isLoopInvariant(Op, NestedLoop);
3478 maskFlags(NestedAR->getNoWrapFlags(),
SCEV::FlagNW | Flags);
3479 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3483 Operands[0] = NestedAR;
3489 return getOrCreateAddRecExpr(Operands, L, Flags);
3498 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->
getType());
3507 const SCEV *TotalOffset = getZero(IntIdxTy);
3511 for (
const SCEV *IndexExpr : IndexExprs) {
3513 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
3517 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3520 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3523 CurTy = STy->getTypeAtIndex(Index);
3526 CurTy = cast<SequentialType>(CurTy)->getElementType();
3528 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3530 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3533 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3536 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3541 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3544 std::tuple<const SCEV *, FoldingSetNodeID, void *>
3545 ScalarEvolution::findExistingSCEVInCache(
int SCEVType,
3550 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
3552 return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3553 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3558 assert(!Ops.
empty() &&
"Cannot get empty (u|s)(min|max)!");
3559 if (Ops.
size() == 1)
return Ops[0];
3561 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
3562 for (
unsigned i = 1,
e = Ops.
size(); i !=
e; ++i)
3564 "Operand types don't match!");
3574 if (
const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3580 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3583 auto FoldOp = [&](
const APInt &LHS,
const APInt &RHS) {
3595 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3598 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3599 Ops[0] = getConstant(Fold);
3601 if (Ops.
size() == 1)
return Ops[0];
3602 LHSC = cast<SCEVConstant>(Ops[0]);
3605 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3606 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3608 if (IsMax ? IsMinV : IsMaxV) {
3612 }
else if (IsMax ? IsMaxV : IsMinV) {
3618 if (Ops.
size() == 1)
return Ops[0];
3622 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
Kind)
3627 if (Idx < Ops.
size()) {
3628 bool DeletedAny =
false;
3637 return getMinMaxExpr(Kind, Ops);
3649 for (
unsigned i = 0,
e = Ops.
size() - 1; i !=
e; ++i) {
3650 if (Ops[i] == Ops[i + 1] ||
3651 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3657 }
else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3666 if (Ops.
size() == 1)
return Ops[0];
3668 assert(!Ops.
empty() &&
"Reduced smax down to nothing!");
3672 const SCEV *ExistingSCEV;
3675 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3677 return ExistingSCEV;
3678 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
3679 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
3683 UniqueSCEVs.InsertNode(S, IP);
3684 addToLoopUseLists(S);
3690 return getSMaxExpr(Ops);
3699 return getUMaxExpr(Ops);
3709 return getSMinExpr(Ops);
3719 return getUMinExpr(Ops);
3730 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3740 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3753 if (
SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3754 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3755 "Stale SCEVUnknown in uniquing map!");
3760 FirstUnknown = cast<SCEVUnknown>(S);
3761 UniqueSCEVs.InsertNode(S, IP);
3781 assert(isSCEVable(Ty) &&
"Type is not SCEVable!");
3783 return getDataLayout().getIndexTypeSizeInBits(Ty);
3784 return getDataLayout().getTypeSizeInBits(Ty);
3791 assert(isSCEVable(Ty) &&
"Type is not SCEVable!");
3798 return getDataLayout().getIndexType(Ty);
3802 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ?
T1 : T2;
3806 return CouldNotCompute.get();
3809 bool ScalarEvolution::checkValidity(
const SCEV *S)
const {
3812 return SU && SU->
getValue() ==
nullptr;
3815 return !ContainsNulls;
3820 if (I != HasRecMap.end())
3824 HasRecMap.insert({S, FoundAddRec});
3834 return {S,
nullptr};
3836 if (
Add->getNumOperands() != 2)
3837 return {S,
nullptr};
3841 return {S,
nullptr};
3843 return {
Add->getOperand(1), ConstOp->getValue()};
3849 ScalarEvolution::getSCEVValues(
const SCEV *S) {
3850 ExprValueMapType::iterator
SI = ExprValueMap.find_as(S);
3851 if (SI == ExprValueMap.end())
3856 for (
const auto &VE : SI->second)
3857 assert(ValueExprMap.count(VE.first));
3868 if (I != ValueExprMap.end()) {
3869 const SCEV *S = I->second;
3872 SV->remove({V, nullptr});
3875 const SCEV *Stripped;
3878 if (Offset !=
nullptr) {
3880 SV->remove({V, Offset});
3882 ValueExprMap.erase(V);
3890 if (
auto *
I = dyn_cast<Instruction>(V)) {
3891 if (isa<OverflowingBinaryOperator>(
I)) {
3892 if (
auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3893 if (
I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3895 if (
I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3898 }
else if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
3907 assert(isSCEVable(V->
getType()) &&
"Value is not SCEVable!");
3909 const SCEV *S = getExistingSCEV(V);
3915 std::pair<ValueExprMapType::iterator, bool> Pair =
3916 ValueExprMap.insert({SCEVCallbackVH(V,
this), S});
3918 ExprValueMap[S].insert({V,
nullptr});
3922 const SCEV *Stripped = S;
3930 if (Offset !=
nullptr && !isa<SCEVUnknown>(Stripped) &&
3931 !isa<GetElementPtrInst>(V))
3932 ExprValueMap[Stripped].insert({V, Offset});
3938 const SCEV *ScalarEvolution::getExistingSCEV(
Value *V) {
3939 assert(isSCEVable(V->
getType()) &&
"Value is not SCEVable!");
3942 if (I != ValueExprMap.end()) {
3943 const SCEV *S = I->second;
3944 if (checkValidity(S))
3946 eraseValueFromMap(V);
3947 forgetMemoizedResults(S);
3960 Ty = getEffectiveSCEVType(Ty);
3990 for (
const SCEV *Operand : MME->operands()) {
3993 return (
const SCEV *)
nullptr;
3996 return getMinMaxExpr(
4000 if (
const SCEV *Replaced = MatchMinMaxNegation(MME))
4005 Ty = getEffectiveSCEVType(Ty);
4006 const SCEV *AllOnes =
4008 return getMinusSCEV(AllOnes, V);
4016 return getZero(LHS->
getType());
4021 const bool RHSIsNotMinSigned =
4022 !getSignedRangeMin(RHS).isMinSignedValue();
4047 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4054 "Cannot truncate or zero extend with non-integer arguments!");
4055 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4057 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4058 return getTruncateExpr(V, Ty, Depth);
4059 return getZeroExtendExpr(V, Ty, Depth);
4066 "Cannot truncate or zero extend with non-integer arguments!");
4067 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4069 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4070 return getTruncateExpr(V, Ty, Depth);
4071 return getSignExtendExpr(V, Ty, Depth);
4078 "Cannot noop or zero extend with non-integer arguments!");
4079 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4080 "getNoopOrZeroExtend cannot truncate!");
4081 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4083 return getZeroExtendExpr(V, Ty);
4090 "Cannot noop or sign extend with non-integer arguments!");
4091 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4092 "getNoopOrSignExtend cannot truncate!");
4093 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4095 return getSignExtendExpr(V, Ty);
4102 "Cannot noop or any extend with non-integer arguments!");
4103 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4104 "getNoopOrAnyExtend cannot truncate!");
4105 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4107 return getAnyExtendExpr(V, Ty);
4114 "Cannot truncate or noop with non-integer arguments!");
4115 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4116 "getTruncateOrNoop cannot extend!");
4117 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4119 return getTruncateExpr(V, Ty);
4124 const SCEV *PromotedLHS = LHS;
4125 const SCEV *PromotedRHS = RHS;
4127 if (getTypeSizeInBits(LHS->
getType()) > getTypeSizeInBits(RHS->
getType()))
4128 PromotedRHS = getZeroExtendExpr(RHS, LHS->
getType());
4130 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->
getType());
4132 return getUMaxExpr(PromotedLHS, PromotedRHS);
4138 return getUMinFromMismatchedTypes(Ops);
4143 assert(!Ops.
empty() &&
"At least one operand must be!");
4145 if (Ops.
size() == 1)
4149 Type *MaxType =
nullptr;
4159 PromotedOps.
push_back(getNoopOrZeroExtend(S, MaxType));
4162 return getUMinExpr(PromotedOps);
4170 if (
const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4171 return getPointerBase(Cast->getOperand());
4172 }
else if (
const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4173 const SCEV *PtrOp =
nullptr;
4174 for (
const SCEV *NAryOp : NAry->operands()) {
4175 if (NAryOp->getType()->isPointerTy()) {
4184 return getPointerBase(PtrOp);
4195 Worklist.
push_back(cast<Instruction>(U));
4198 void ScalarEvolution::forgetSymbolicName(
Instruction *PN,
const SCEV *SymName) {
4204 while (!Worklist.
empty()) {
4206 if (!Visited.
insert(I).second)
4209 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4210 if (It != ValueExprMap.end()) {
4211 const SCEV *Old = It->second;
4215 if (Old != SymName && !hasOperand(Old, SymName))
4225 if (!isa<PHINode>(I) ||
4226 !isa<SCEVUnknown>(Old) ||
4227 (I != PN && Old == SymName)) {
4228 eraseValueFromMap(It->first);
4229 forgetMemoizedResults(Old);
4247 bool IgnoreOtherLoops =
true) {
4249 const SCEV *Result = Rewriter.visit(S);
4250 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4252 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4259 SeenLoopVariantSCEVUnknown =
true;
4267 SeenOtherLoops =
true;
4271 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4273 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4280 bool SeenLoopVariantSCEVUnknown =
false;
4281 bool SeenOtherLoops =
false;
4291 SCEVPostIncRewriter
Rewriter(L, SE);
4292 const SCEV *Result = Rewriter.visit(S);
4293 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4300 SeenLoopVariantSCEVUnknown =
true;
4308 SeenOtherLoops =
true;
4312 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4314 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4321 bool SeenLoopVariantSCEVUnknown =
false;
4322 bool SeenOtherLoops =
false;
4328 class SCEVBackedgeConditionFolder
4333 bool IsPosBECond =
false;
4334 Value *BECond =
nullptr;
4339 "Both outgoing branches should not target same header!");
4346 SCEVBackedgeConditionFolder
Rewriter(L, BECond, IsPosBECond, SE);
4347 return Rewriter.visit(S);
4351 const SCEV *Result = Expr;
4361 if (Res.hasValue()) {
4362 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4379 explicit SCEVBackedgeConditionFolder(
const Loop *L,
Value *BECond,
4382 IsPositiveBECond(IsPosBECond) {}
4388 Value *BackedgeCond =
nullptr;
4390 bool IsPositiveBECond;
4394 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(
Value *IC) {
4399 if (BackedgeCond == IC)
4410 const SCEV *Result = Rewriter.visit(S);
4428 bool isValid() {
return Valid; }
4441 ScalarEvolution::proveNoWrapViaConstantRanges(
const SCEVAddRecExpr *AR) {
4455 if (NSWRegion.contains(AddRecRange))
4465 if (NUWRegion.contains(AddRecRange))
4491 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4492 IsNSW = OBO->hasNoSignedWrap();
4493 IsNUW = OBO->hasNoUnsignedWrap();
4497 explicit BinaryOp(
unsigned Opcode,
Value *LHS,
Value *RHS,
bool IsNSW =
false,
4499 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4514 switch (
Op->getOpcode()) {
4516 case Instruction::Sub:
4517 case Instruction::Mul:
4518 case Instruction::UDiv:
4519 case Instruction::URem:
4520 case Instruction::And:
4521 case Instruction::Or:
4522 case Instruction::AShr:
4523 case Instruction::Shl:
4524 return BinaryOp(
Op);
4526 case Instruction::Xor:
4527 if (
auto *RHSC = dyn_cast<ConstantInt>(
Op->getOperand(1)))
4530 if (RHSC->getValue().isSignMask())
4532 return BinaryOp(
Op);
4534 case Instruction::LShr:
4536 if (
ConstantInt *SA = dyn_cast<ConstantInt>(
Op->getOperand(1))) {
4543 if (SA->getValue().ult(BitWidth)) {
4547 return BinaryOp(Instruction::UDiv,
Op->getOperand(0),
X);
4550 return BinaryOp(
Op);
4552 case Instruction::ExtractValue: {
4553 auto *EVI = cast<ExtractValueInst>(
Op);
4554 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4562 bool Signed = WO->isSigned();
4565 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4570 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4580 if (
auto *II = dyn_cast<IntrinsicInst>(V))
4581 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4582 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4610 if (Op == SymbolicPHI)
4615 if (SourceBits != NewBits)
4624 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4628 if (X != SymbolicPHI)
4630 Signed = SExt !=
nullptr;
4697 ScalarEvolution::createAddRecFromPHIWithCastsImpl(
const SCEVUnknown *SymbolicPHI) {
4703 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4705 assert(L &&
"Expecting an integer loop header phi");
4710 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
4711 for (
unsigned i = 0,
e = PN->getNumIncomingValues(); i !=
e; ++i) {
4712 Value *V = PN->getIncomingValue(i);
4713 if (L->contains(PN->getIncomingBlock(i))) {
4716 }
else if (BEValueV != V) {
4720 }
else if (!StartValueV) {
4722 }
else if (StartValueV != V) {
4723 StartValueV =
nullptr;
4727 if (!BEValueV || !StartValueV)
4730 const SCEV *BEValue = getSCEV(BEValueV);
4741 unsigned FoundIndex =
Add->getNumOperands();
4742 Type *TruncTy =
nullptr;
4744 for (
unsigned i = 0,
e =
Add->getNumOperands(); i !=
e; ++i)
4747 if (FoundIndex ==
e) {
4752 if (FoundIndex ==
Add->getNumOperands())
4757 for (
unsigned i = 0,
e =
Add->getNumOperands(); i !=
e; ++i)
4758 if (i != FoundIndex)
4760 const SCEV *Accum = getAddExpr(Ops);
4764 if (!isLoopInvariant(Accum, L))
4818 const SCEV *StartVal = getSCEV(StartValueV);
4819 const SCEV *PHISCEV =
4820 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4829 if (
const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4833 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4846 auto getExtendedExpr = [&](
const SCEV *Expr,
4847 bool CreateSignExtend) ->
const SCEV * {
4848 assert(isLoopInvariant(Expr, L) &&
"Expr is expected to be invariant");
4849 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4850 const SCEV *ExtendedExpr =
4851 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->
getType())
4852 : getZeroExtendExpr(TruncatedExpr, Expr->
getType());
4853 return ExtendedExpr;
4861 auto PredIsKnownFalse = [&](
const SCEV *Expr,
4862 const SCEV *ExtendedExpr) ->
bool {
4863 return Expr != ExtendedExpr &&
4867 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4868 if (PredIsKnownFalse(StartVal, StartExtended)) {
4875 const SCEV *AccumExtended = getExtendedExpr(Accum,
true);
4876 if (PredIsKnownFalse(Accum, AccumExtended)) {
4881 auto AppendPredicate = [&](
const SCEV *Expr,
4882 const SCEV *ExtendedExpr) ->
void {
4883 if (Expr != ExtendedExpr &&
4885 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4891 AppendPredicate(StartVal, StartExtended);
4892 AppendPredicate(Accum, AccumExtended);
4900 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4901 std::make_pair(NewAR, Predicates);
4903 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4909 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4915 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4916 if (
I != PredicatedSCEVRewrites.end()) {
4917 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4920 if (Rewrite.first == SymbolicPHI)
4924 assert(isa<SCEVAddRecExpr>(Rewrite.first) &&
"Expected an AddRec");
4925 assert(!(Rewrite.second).empty() &&
"Expected to find Predicates");
4930 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4935 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4953 auto areExprsEqual = [&](
const SCEV *Expr1,
const SCEV *Expr2) ->
bool {
4954 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4955 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4972 const SCEV *ScalarEvolution::createSimpleAffineAddRec(
PHINode *PN,
4974 Value *StartValueV) {
4977 assert(BEValueV && StartValueV);
4986 const SCEV *Accum =
nullptr;
4988 Accum = getSCEV(BO->RHS);
4990 Accum = getSCEV(BO->LHS);
5001 const SCEV *StartVal = getSCEV(StartValueV);
5002 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5004 ValueExprMap[SCEVCallbackVH(PN,
this)] = PHISCEV;
5009 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
5010 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5011 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5016 const SCEV *ScalarEvolution::createAddRecFromPHI(
PHINode *PN) {
5024 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
5030 }
else if (BEValueV != V) {
5034 }
else if (!StartValueV) {
5036 }
else if (StartValueV != V) {
5037 StartValueV =
nullptr;
5041 if (!BEValueV || !StartValueV)
5044 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5045 "PHI node already processed?");
5049 if (
auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5053 const SCEV *SymbolicName = getUnknown(PN);
5054 ValueExprMap.insert({SCEVCallbackVH(PN,
this), SymbolicName});
5058 const SCEV *BEValue = getSCEV(BEValueV);
5068 unsigned FoundIndex =
Add->getNumOperands();
5069 for (
unsigned i = 0,
e =
Add->getNumOperands(); i !=
e; ++i)
5070 if (
Add->getOperand(i) == SymbolicName)
5071 if (FoundIndex ==
e) {
5076 if (FoundIndex !=
Add->getNumOperands()) {
5079 for (
unsigned i = 0,
e =
Add->getNumOperands(); i !=
e; ++i)
5080 if (i != FoundIndex)
5083 const SCEV *Accum = getAddExpr(Ops);
5087 if (isLoopInvariant(Accum, L) ||
5088 (isa<SCEVAddRecExpr>(Accum) &&
5089 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5106 if (
GEP->isInBounds() &&
GEP->getOperand(0) == PN) {
5109 const SCEV *Ptr = getSCEV(
GEP->getPointerOperand());
5119 const SCEV *StartVal = getSCEV(StartValueV);
5120 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5125 forgetSymbolicName(PN, SymbolicName);
5126 ValueExprMap[SCEVCallbackVH(PN,
this)] = PHISCEV;
5131 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
5132 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5133 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5150 if (Shifted != getCouldNotCompute() &&
5151 Start != getCouldNotCompute()) {
5152 const SCEV *StartVal = getSCEV(StartValueV);
5153 if (Start == StartVal) {
5157 forgetSymbolicName(PN, SymbolicName);
5158 ValueExprMap[SCEVCallbackVH(PN,
this)] = Shifted;
5168 eraseValueFromMap(PN);
5177 struct CheckAvailable {
5178 bool TraversalDone =
false;
5179 bool Available =
true;
5181 const Loop *L =
nullptr;
5186 : L(L), BB(BB), DT(DT) {}
5188 bool setUnavailable() {
5189 TraversalDone =
true;
5194 bool follow(
const SCEV *S) {
5209 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5210 if (L && (ARLoop == L || ARLoop->
contains(L)))
5213 return setUnavailable();
5218 const auto *SU = cast<SCEVUnknown>(S);
5219 Value *V = SU->getValue();
5221 if (isa<Argument>(V))
5224 if (isa<Instruction>(V) && DT.
dominates(cast<Instruction>(V), BB))
5227 return setUnavailable();
5233 return setUnavailable();
5238 bool isDone() {
return TraversalDone; }
5241 CheckAvailable CA(L, BB, DT);
5245 return CA.Available;
5258 if (!LeftEdge.isSingleEdge())
5261 assert(RightEdge.isSingleEdge() &&
"Follows from LeftEdge.isSingleEdge()");
5281 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(
PHINode *PN) {
5283 [&](
BasicBlock *BB) {
return DT.isReachableFromEntry(BB); };
5305 assert(IDom &&
"At least the entry block should dominate PN");
5308 Value *Cond =
nullptr, *LHS =
nullptr, *RHS =
nullptr;
5310 if (BI && BI->isConditional() &&
5314 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5320 const SCEV *ScalarEvolution::createNodeForPHI(
PHINode *PN) {
5321 if (
const SCEV *S = createAddRecFromPHI(PN))
5324 if (
const SCEV *S = createNodeFromSelectLikePHI(PN))
5332 if (LI.replacementPreservesLCSSAForm(PN, V))
5336 return getUnknown(PN);
5345 if (
auto *CI = dyn_cast<ConstantInt>(Cond))
5346 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5351 return getUnknown(I);
5353 Value *LHS = ICI->getOperand(0);
5354 Value *RHS = ICI->getOperand(1);
5356 switch (ICI->getPredicate()) {
5365 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType())) {
5366 const SCEV *
LS = getNoopOrSignExtend(getSCEV(LHS), I->
getType());
5367 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->
getType());
5368 const SCEV *LA = getSCEV(TrueVal);
5369 const SCEV *
RA = getSCEV(FalseVal);
5370 const SCEV *LDiff = getMinusSCEV(LA, LS);
5371 const SCEV *RDiff = getMinusSCEV(RA, RS);
5373 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5374 LDiff = getMinusSCEV(LA, RS);
5375 RDiff = getMinusSCEV(RA, LS);
5377 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5388 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType())) {
5389 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5390 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->
getType());
5391 const SCEV *LA = getSCEV(TrueVal);
5392 const SCEV *
RA = getSCEV(FalseVal);
5393 const SCEV *LDiff = getMinusSCEV(LA, LS);
5394 const SCEV *RDiff = getMinusSCEV(RA, RS);
5396 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5397 LDiff = getMinusSCEV(LA, RS);
5398 RDiff = getMinusSCEV(RA, LS);
5400 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5405 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType()) &&
5406 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
5408 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5409 const SCEV *LA = getSCEV(TrueVal);
5410 const SCEV *
RA = getSCEV(FalseVal);
5411 const SCEV *LDiff = getMinusSCEV(LA, LS);
5412 const SCEV *RDiff = getMinusSCEV(RA, One);
5414 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5419 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType()) &&
5420 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
5422 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5423 const SCEV *LA = getSCEV(TrueVal);
5424 const SCEV *
RA = getSCEV(FalseVal);
5425 const SCEV *LDiff = getMinusSCEV(LA, One);
5426 const SCEV *RDiff = getMinusSCEV(RA, LS);
5428 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5435 return getUnknown(I);
5443 return getUnknown(GEP);
5448 return getGEPExpr(GEP, IndexExprs);
5451 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(
const SCEV *S) {
5453 return C->getAPInt().countTrailingZeros();
5456 return std::min(GetMinTrailingZeros(
T->getOperand()),
5457 (
uint32_t)getTypeSizeInBits(
T->getType()));
5460 uint32_t OpRes = GetMinTrailingZeros(
E->getOperand());
5461 return OpRes == getTypeSizeInBits(
E->getOperand()->getType())
5462 ? getTypeSizeInBits(
E->getType())
5467 uint32_t OpRes = GetMinTrailingZeros(
E->getOperand());
5468 return OpRes == getTypeSizeInBits(
E->getOperand()->getType())
5469 ? getTypeSizeInBits(
E->getType())
5473 if (
const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5475 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5476 for (
unsigned i = 1,
e = A->getNumOperands(); MinOpRes && i !=
e; ++i)
5477 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5481 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5483 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5484 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5485 for (
unsigned i = 1,
e = M->getNumOperands();
5486 SumOpRes != BitWidth && i !=
e; ++i)
5488 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5494 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5495 for (
unsigned i = 1,
e = A->getNumOperands(); MinOpRes && i !=
e; ++i)
5496 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5500 if (
const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5502 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5503 for (
unsigned i = 1,
e = M->getNumOperands(); MinOpRes && i !=
e; ++i)
5504 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5508 if (
const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5510 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5511 for (
unsigned i = 1,
e = M->getNumOperands(); MinOpRes && i !=
e; ++i)
5512 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5516 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5527 auto I = MinTrailingZerosCache.find(S);
5528 if (I != MinTrailingZerosCache.end())
5531 uint32_t Result = GetMinTrailingZerosImpl(S);
5532 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5533 assert(InsertPair.second &&
"Should insert a new key");
5534 return InsertPair.first->second;
5550 ScalarEvolution::getRangeRef(
const SCEV *S,
5551 ScalarEvolution::RangeSignHint SignHint) {
5553 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5556 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5561 if (I != Cache.
end())
5567 unsigned BitWidth = getTypeSizeInBits(S->
getType());
5573 uint32_t TZ = GetMinTrailingZeros(S);
5575 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5576 ConservativeResult =
5587 unsigned WrapType = OBO::AnyWrap;
5588 if (
Add->hasNoSignedWrap())
5589 WrapType |= OBO::NoSignedWrap;
5590 if (
Add->hasNoUnsignedWrap())
5591 WrapType |= OBO::NoUnsignedWrap;
5592 for (
unsigned i = 1,
e =
Add->getNumOperands(); i !=
e; ++i)
5594 WrapType, RangeType);
5595 return setRange(
Add, SignHint,
5596 ConservativeResult.intersectWith(X, RangeType));
5599 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5601 for (
unsigned i = 1,
e = Mul->getNumOperands(); i !=
e; ++i)
5602 X = X.
multiply(getRangeRef(Mul->getOperand(i), SignHint));
5603 return setRange(Mul, SignHint,
5604 ConservativeResult.intersectWith(X, RangeType));
5607 if (
const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5609 for (
unsigned i = 1,
e = SMax->getNumOperands(); i !=
e; ++i)
5610 X = X.
smax(getRangeRef(SMax->getOperand(i), SignHint));
5611 return setRange(SMax, SignHint,
5612 ConservativeResult.intersectWith(X, RangeType));
5615 if (
const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5617 for (
unsigned i = 1,
e = UMax->getNumOperands(); i !=
e; ++i)
5618 X = X.
umax(getRangeRef(UMax->getOperand(i), SignHint));
5619 return setRange(UMax, SignHint,
5620 ConservativeResult.intersectWith(X, RangeType));
5623 if (
const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5625 for (
unsigned i = 1,
e = SMin->getNumOperands(); i !=
e; ++i)
5626 X = X.
smin(getRangeRef(SMin->getOperand(i), SignHint));
5627 return setRange(SMin, SignHint,
5628 ConservativeResult.intersectWith(X, RangeType));
5631 if (
const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5633 for (
unsigned i = 1,
e = UMin->getNumOperands(); i !=
e; ++i)
5634 X = X.
umin(getRangeRef(UMin->getOperand(i), SignHint));
5635 return setRange(UMin, SignHint,
5636 ConservativeResult.intersectWith(X, RangeType));
5639 if (
const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5642 return setRange(UDiv, SignHint,
5643 ConservativeResult.intersectWith(X.
udiv(Y), RangeType));
5648 return setRange(ZExt, SignHint,
5649 ConservativeResult.intersectWith(X.
zeroExtend(BitWidth),
5655 return setRange(SExt, SignHint,
5656 ConservativeResult.intersectWith(X.
signExtend(BitWidth),
5662 return setRange(Trunc, SignHint,
5663 ConservativeResult.intersectWith(X.
truncate(BitWidth),
5667 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5670 if (AddRec->hasNoUnsignedWrap()) {
5671 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5673 ConservativeResult = ConservativeResult.intersectWith(
5682 if (AddRec->hasNoSignedWrap()) {
5683 bool AllNonNeg =
true;
5684 bool AllNonPos =
true;
5685 for (
unsigned i = 1,
e = AddRec->getNumOperands(); i !=
e; ++i) {
5688 if (!isKnownNonPositive(AddRec->getOperand(i)))
5692 ConservativeResult = ConservativeResult.intersectWith(
5697 ConservativeResult = ConservativeResult.intersectWith(
5700 getSignedRangeMax(AddRec->getStart()) + 1),
5705 if (AddRec->isAffine()) {
5706 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5707 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5708 getTypeSizeInBits(MaxBECount->
getType()) <= BitWidth) {
5709 auto RangeFromAffine = getRangeForAffineAR(
5710 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5712 if (!RangeFromAffine.isFullSet())
5713 ConservativeResult =
5714 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5716 auto RangeFromFactoring = getRangeViaFactoring(
5717 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5719 if (!RangeFromFactoring.isFullSet())
5720 ConservativeResult =
5721 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5725 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5728 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5732 ConservativeResult = ConservativeResult.intersectWith(MDRange.
getValue(),
5739 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5746 ConservativeResult = ConservativeResult.intersectWith(
5750 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5751 "generalize as needed!");
5755 if (U->getType()->isPointerTy()) {
5757 int ptrIdxDiff = ptrSize - BitWidth;
5758 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (
unsigned)ptrIdxDiff)
5763 ConservativeResult = ConservativeResult.intersectWith(
5770 if (
const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5772 if (PendingPhiRanges.insert(Phi).second) {
5774 for (
auto &
Op : Phi->operands()) {
5775 auto OpRange = getRangeRef(getSCEV(
Op), SignHint);
5776 RangeFromOps = RangeFromOps.
unionWith(OpRange);
5781 ConservativeResult =
5783 bool Erased = PendingPhiRanges.erase(Phi);
5784 assert(Erased &&
"Failed to erase Phi properly?");
5789 return setRange(U, SignHint, std::move(ConservativeResult));
5792 return setRange(S, SignHint, std::move(ConservativeResult));
5801 const APInt &MaxBECount,
5802 unsigned BitWidth,
bool Signed) {
5805 if (Step == 0 || MaxBECount == 0)
5812 return ConstantRange::getFull(BitWidth);
5816 bool Descending = Signed && Step.
isNegative();
5828 return ConstantRange::getFull(BitWidth);
5840 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5841 : (StartUpper + std::move(Offset));
5846 if (StartRange.
contains(MovedBoundary))
5847 return ConstantRange::getFull(BitWidth);
5850 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5852 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5861 const SCEV *MaxBECount,
5862 unsigned BitWidth) {
5863 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5864 getTypeSizeInBits(MaxBECount->
getType()) <= BitWidth &&
5867 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->
getType());
5868 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5878 MaxBECountValue, BitWidth,
true);
5880 StartSRange, MaxBECountValue,
5885 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5886 MaxBECountValue, BitWidth,
false);
5894 const SCEV *MaxBECount,
5895 unsigned BitWidth) {
5899 struct SelectPattern {
5900 Value *Condition =
nullptr;
5913 if (
auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5916 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5919 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5920 S = SA->getOperand(1);
5924 if (
auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5925 CastOp = SCast->getSCEVType();
5926 S = SCast->getOperand();
5932 const APInt *TrueVal, *FalseVal;
5936 Condition =
nullptr;
5940 TrueValue = *TrueVal;
5941 FalseValue = *FalseVal;
5950 TrueValue = TrueValue.
trunc(BitWidth);
5951 FalseValue = FalseValue.
trunc(BitWidth);
5954 TrueValue = TrueValue.
zext(BitWidth);
5955 FalseValue = FalseValue.
zext(BitWidth);
5958 TrueValue = TrueValue.
sext(BitWidth);
5959 FalseValue = FalseValue.
sext(BitWidth);
5968 bool isRecognized() {
return Condition !=
nullptr; }
5971 SelectPattern StartPattern(*
this, BitWidth, Start);
5972 if (!StartPattern.isRecognized())
5973 return ConstantRange::getFull(BitWidth);
5975 SelectPattern StepPattern(*
this, BitWidth, Step);
5976 if (!StepPattern.isRecognized())
5977 return ConstantRange::getFull(BitWidth);
5979 if (StartPattern.Condition != StepPattern.Condition) {
5983 return ConstantRange::getFull(BitWidth);
5994 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5995 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5996 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5997 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6000 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6002 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6023 bool ScalarEvolution::isSCEVExprNeverPoison(
const Instruction *I) {
6029 Loop *InnermostContainingLoop = LI.getLoopFor(I->
getParent());
6030 if (InnermostContainingLoop ==
nullptr ||
6053 for (
unsigned OpIndex = 0; OpIndex < I->
getNumOperands(); ++OpIndex) {
6059 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6060 bool AllOtherOpsLoopInvariant =
true;
6061 for (
unsigned OtherOpIndex = 0; OtherOpIndex < I->
getNumOperands();
6063 if (OtherOpIndex != OpIndex) {
6065 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6066 AllOtherOpsLoopInvariant =
false;
6071 if (AllOtherOpsLoopInvariant &&
6079 bool ScalarEvolution::isAddRecNeverPoison(
const Instruction *I,
const Loop *L) {
6081 if (isSCEVExprNeverPoison(I))
6108 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6120 bool LatchControlDependentOnPoison =
false;
6121 while (!PoisonStack.
empty() && !LatchControlDependentOnPoison) {
6124 for (
auto *PoisonUser : Poison->
users()) {
6126 if (Pushed.
insert(cast<Instruction>(PoisonUser)).second)
6127 PoisonStack.
push_back(cast<Instruction>(PoisonUser));
6128 }
else if (
auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6129 assert(BI->isConditional() &&
"Only possibility!");
6130 if (BI->getParent() == LatchBB) {
6131 LatchControlDependentOnPoison =
true;
6138 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6141 ScalarEvolution::LoopProperties
6142 ScalarEvolution::getLoopProperties(
const Loop *L) {
6143 using LoopProperties = ScalarEvolution::LoopProperties;
6145 auto Itr = LoopPropertiesCache.find(L);
6146 if (Itr == LoopPropertiesCache.end()) {
6148 if (
auto *
SI = dyn_cast<StoreInst>(I))
6149 return !
SI->isSimple();
6154 LoopProperties LP = {
true,
6158 for (
auto &I : *BB) {
6160 LP.HasNoAbnormalExits =
false;
6161 if (HasSideEffects(&I))
6162 LP.HasNoSideEffects =
false;
6163 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6167 auto InsertPair = LoopPropertiesCache.insert({L, LP});
6168 assert(InsertPair.second &&
"We just checked!");
6169 Itr = InsertPair.first;
6175 const SCEV *ScalarEvolution::createSCEV(
Value *V) {
6176 if (!isSCEVable(V->
getType()))
6177 return getUnknown(V);
6184 if (!DT.isReachableFromEntry(I->
getParent()))
6186 }
else if (
ConstantInt *CI = dyn_cast<ConstantInt>(V))
6187 return getConstant(CI);
6188 else if (isa<ConstantPointerNull>(V))
6190 else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6191 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6192 else if (!isa<ConstantExpr>(V))
6193 return getUnknown(V);
6197 switch (BO->Opcode) {
6208 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
6220 const SCEV *RHS = getSCEV(BO->RHS);
6223 const SCEV *LHS = getSCEV(BO->LHS);
6224 if (BO->Opcode == Instruction::Sub)
6225 AddOps.
push_back(getMinusSCEV(LHS, RHS, Flags));
6227 AddOps.
push_back(getAddExpr(LHS, RHS, Flags));
6232 if (BO->Opcode == Instruction::Sub)
6233 AddOps.
push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6239 NewBO->Opcode != Instruction::Sub)) {
6246 return getAddExpr(AddOps);
6249 case Instruction::Mul: {
6253 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
6261 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6268 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6275 return getMulExpr(MulOps);
6277 case Instruction::UDiv:
6278 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6279 case Instruction::URem:
6280 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6281 case Instruction::Sub: {
6284 Flags = getNoWrapFlagsFromUB(BO->Op);
6285 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6287 case Instruction::And:
6290 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6292 return getSCEV(BO->RHS);
6293 if (CI->isMinusOne())
6294 return getSCEV(BO->LHS);
6295 const APInt &A = CI->getValue();
6306 0, &AC,
nullptr, &DT);
6308 APInt EffectiveMask =
6310 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.
Zero) & EffectiveMask)) {
6312 const SCEV *LHS = getSCEV(BO->LHS);
6313 const SCEV *ShiftedLHS =
nullptr;
6314 if (
auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6315 if (
auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6317 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6318 unsigned GCD = std::min(MulZeros, TZ);
6321 MulOps.
push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6322 MulOps.
append(LHSMul->op_begin() + 1, LHSMul->op_end());
6323 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6324 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6328 ShiftedLHS = getUDivExpr(LHS, MulCount);
6331 getTruncateExpr(ShiftedLHS,
6333 BO->LHS->getType()),
6339 case Instruction::Or:
6346 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6347 const SCEV *LHS = getSCEV(BO->LHS);
6348 const APInt &CIVal = CI->getValue();
6349 if (GetMinTrailingZeros(LHS) >=
6352 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6365 case Instruction::Xor:
6366 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6368 if (CI->isMinusOne())
6369 return getNotSCEV(getSCEV(BO->LHS));
6375 if (
auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6376 if (
ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6377 if (LBO->getOpcode() == Instruction::And &&
6378 LCI->getValue() == CI->getValue())
6380 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6381 Type *UTy = BO->LHS->getType();
6382 const SCEV *Z0 =
Z->getOperand();
6384 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6389 if (CI->getValue().isMask(Z0TySize))
6390 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6395 APInt Trunc = CI->getValue().
trunc(Z0TySize);
6396 if (Trunc.
zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6398 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6404 case Instruction::Shl:
6406 if (
ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6413 if (SA->getValue().uge(BitWidth))
6423 if (BO->Op && SA->getValue().ult(BitWidth - 1))
6424 Flags = getNoWrapFlagsFromUB(BO->Op);
6428 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6432 case Instruction::AShr: {
6438 Type *OuterTy = BO->LHS->getType();
6439 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6448 return getSCEV(BO->LHS);
6454 if (L && L->
getOpcode() == Instruction::Shl) {
6463 return getSignExtendExpr(
6464 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6467 if (ShlAmtCI && ShlAmtCI->
getValue().
ult(BitWidth)) {
6469 if (ShlAmt > AShrAmt) {
6476 return getSignExtendExpr(
6477 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6478 getConstant(Mul)), OuterTy);
6488 case Instruction::Trunc:
6491 case Instruction::ZExt:
6494 case Instruction::SExt:
6503 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6505 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6506 auto *
V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6512 case Instruction::BitCast:
6523 case Instruction::GetElementPtr:
6524 return createNodeForGEP(cast<GEPOperator>(U));
6526 case Instruction::PHI:
6527 return createNodeForPHI(cast<PHINode>(U));
6534 if (isa<Instruction>(U))
6535 return createNodeForSelectOrPHI(cast<Instruction>(U), U->
getOperand(0),
6540 case Instruction::Invoke:
6546 return getUnknown(V);
6569 return getSmallConstantTripCount(L, ExitingBB);
6577 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6579 "Exiting block must actually branch out of the loop!");
6586 const auto *MaxExitCount =
6593 return getSmallConstantTripMultiple(L, ExitingBB);
6614 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6616 "Exiting block must actually branch out of the loop!");
6617 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6618 if (ExitCount == getCouldNotCompute())
6622 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6629 return 1U << std::min((
uint32_t)31, GetMinTrailingZeros(TCExpr));
6648 return getBackedgeTakenInfo(L).getExact(ExitingBlock,
this);
6649 case ConstantMaximum:
6650 return getBackedgeTakenInfo(L).getMax(ExitingBlock,
this);
6658 return getPredicatedBackedgeTakenInfo(L).getExact(L,
this, &Preds);
6665 return getBackedgeTakenInfo(L).getExact(L,
this);
6666 case ConstantMaximum:
6667 return getBackedgeTakenInfo(L).getMax(
this);
6673 return getBackedgeTakenInfo(L).isMaxOrZero(
this);
6686 const ScalarEvolution::BackedgeTakenInfo &
6687 ScalarEvolution::getPredicatedBackedgeTakenInfo(
const Loop *L) {
6688 auto &BTI = getBackedgeTakenInfo(L);
6689 if (BTI.hasFullInfo())
6692 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6695 return Pair.first->second;
6697 BackedgeTakenInfo Result =
6698 computeBackedgeTakenCount(L,
true);
6700 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6703 const ScalarEvolution::BackedgeTakenInfo &
6704 ScalarEvolution::getBackedgeTakenInfo(
const Loop *L) {
6710 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator,
bool> Pair =
6711 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6713 return Pair.first->second;
6718 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6721 (void)NumTripCountsComputed;
6722 (void)NumTripCountsNotComputed;
6723 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6724 const SCEV *BEExact = Result.getExact(L,
this);
6725 if (BEExact != getCouldNotCompute()) {
6726 assert(isLoopInvariant(BEExact, L) &&
6727 isLoopInvariant(Result.getMax(
this), L) &&
6728 "Computed backedge-taken count isn't loop invariant for loop!");
6729 ++NumTripCountsComputed;
6731 else if (Result.getMax(
this) == getCouldNotCompute() &&
6734 ++NumTripCountsNotComputed;
6736 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6743 if (Result.hasAnyInfo()) {
6748 while (!Worklist.
empty()) {
6751 ValueExprMapType::iterator It =
6752 ValueExprMap.find_as(static_cast<Value *>(I));
6753 if (It != ValueExprMap.end()) {
6754 const SCEV *Old = It->second;
6762 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6763 eraseValueFromMap(It->first);
6764 forgetMemoizedResults(Old);
6766 if (
PHINode *PN = dyn_cast<PHINode>(I))
6767 ConstantEvolutionLoopExitValue.erase(PN);
6788 for (
auto *U : I->
users())
6789 if (
auto *I = dyn_cast<Instruction>(U)) {
6790 auto *LoopForUser = LI.getLoopFor(I->
getParent());
6791 if (LoopForUser && L->
contains(LoopForUser) &&
6792 Discovered.
insert(I).second)
6803 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6812 BackedgeTakenCounts.clear();
6813 PredicatedBackedgeTakenCounts.clear();
6814 LoopPropertiesCache.clear();
6815 ConstantEvolutionLoopExitValue.clear();
6816 ValueExprMap.clear();
6817 ValuesAtScopes.clear();
6818 LoopDispositions.clear();
6819 BlockDispositions.clear();
6820 UnsignedRanges.clear();
6821 SignedRanges.clear();
6822 ExprValueMap.clear();
6824 MinTrailingZerosCache.clear();
6825 PredicatedSCEVRewrites.clear();
6830 auto RemoveLoopFromBackedgeMap =
6832 auto BTCPos = Map.
find(L);
6833 if (BTCPos != Map.
end()) {
6834 BTCPos->second.clear();
6844 while (!LoopWorklist.
empty()) {
6847 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6848 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6851 for (
auto I = PredicatedSCEVRewrites.begin();
6852 I != PredicatedSCEVRewrites.end();) {
6853 std::pair<const SCEV *, const Loop *>
Entry = I->first;
6854 if (Entry.second == CurrL)
6855 PredicatedSCEVRewrites.erase(I++);
6860 auto LoopUsersItr = LoopUsers.find(CurrL);
6861 if (LoopUsersItr != LoopUsers.end()) {
6862 for (
auto *S : LoopUsersItr->second)
6863 forgetMemoizedResults(S);
6864 LoopUsers.erase(LoopUsersItr);
6870 while (!Worklist.
empty()) {
6872 if (!Visited.
insert(I).second)
6876 ValueExprMap.find_as(static_cast<Value *>(I));
6877 if (It != ValueExprMap.end()) {
6878 eraseValueFromMap(It->first);
6879 forgetMemoizedResults(It->second);
6880 if (
PHINode *PN = dyn_cast<PHINode>(I))
6881 ConstantEvolutionLoopExitValue.erase(PN);
6887 LoopPropertiesCache.erase(CurrL);
6890 LoopWorklist.
append(CurrL->begin(), CurrL->end());
6909 while (!Worklist.
empty()) {
6911 if (!Visited.
insert(I).second)
6915 ValueExprMap.find_as(static_cast<Value *>(I));
6916 if (It != ValueExprMap.end()) {
6917 eraseValueFromMap(It->first);
6918 forgetMemoizedResults(It->second);
6919 if (
PHINode *PN = dyn_cast<PHINode>(I))
6920 ConstantEvolutionLoopExitValue.erase(PN);
6937 if (!isComplete() || ExitNotTaken.empty())
6948 for (
auto &ENT : ExitNotTaken) {
6949 const SCEV *BECount = ENT.ExactNotTaken;
6952 "We should only have known counts for exiting blocks that dominate " 6957 if (Preds && !ENT.hasAlwaysTruePredicate())
6958 Preds->
add(ENT.Predicate.get());
6960 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6961 "Predicate should be always true!");
6969 ScalarEvolution::BackedgeTakenInfo::getExact(
BasicBlock *ExitingBlock,
6971 for (
auto &ENT : ExitNotTaken)
6972 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6973 return ENT.ExactNotTaken;
6979 ScalarEvolution::BackedgeTakenInfo::getMax(
BasicBlock *ExitingBlock,
6981 for (
auto &ENT : ExitNotTaken)
6982 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6983 return ENT.MaxNotTaken;
6990 ScalarEvolution::BackedgeTakenInfo::getMax(
ScalarEvolution *SE)
const {
6991 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
6992 return !ENT.hasAlwaysTruePredicate();
6995 if (
any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6998 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6999 "No point in having a non-constant max backedge taken count!");
7003 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(
ScalarEvolution *SE)
const {
7004 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
7005 return !ENT.hasAlwaysTruePredicate();
7007 return MaxOrZero && !
any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7010 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(
const SCEV *S,
7016 for (
auto &ENT : ExitNotTaken)
7024 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *
E)
7025 : ExactNotTaken(E), MaxNotTaken(E) {
7026 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7027 isa<SCEVConstant>(MaxNotTaken)) &&
7028 "No point in having a non-constant max backedge taken count!");
7031 ScalarEvolution::ExitLimit::ExitLimit(
7032 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
7034 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7035 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7036 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7037 "Exact is not allowed to be less precise than Max");
7038 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7039 isa<SCEVConstant>(MaxNotTaken)) &&
7040 "No point in having a non-constant max backedge taken count!");
7041 for (
auto *PredSet : PredSetList)
7042 for (
auto *
P : *PredSet)
7046 ScalarEvolution::ExitLimit::ExitLimit(
7047 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
7049 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7050 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7051 isa<SCEVConstant>(MaxNotTaken)) &&
7052 "No point in having a non-constant max backedge taken count!");
7055 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *E,
const SCEV *M,
7057 : ExitLimit(E, M, MaxOrZero,
None) {
7058 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7059 isa<SCEVConstant>(MaxNotTaken)) &&
7060 "No point in having a non-constant max backedge taken count!");
7065 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7068 bool Complete,
const SCEV *MaxCount,
bool MaxOrZero)
7069 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
7070 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7072 ExitNotTaken.reserve(ExitCounts.
size());
7074 ExitCounts.
begin(), ExitCounts.
end(), std::back_inserter(ExitNotTaken),
7075 [&](
const EdgeExitInfo &EEI) {
7077 const ExitLimit &EL = EEI.second;
7078 if (EL.Predicates.empty())
7079 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7083 for (
auto *Pred : EL.Predicates)
7084 Predicate->add(Pred);
7086 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7087 std::move(Predicate));
7089 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7090 "No point in having a non-constant max backedge taken count!");
7095 ExitNotTaken.clear();
7099 ScalarEvolution::BackedgeTakenInfo
7100 ScalarEvolution::computeBackedgeTakenCount(
const Loop *L,
7101 bool AllowPredicates) {
7105 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7108 bool CouldComputeBECount =
true;
7110 const SCEV *MustExitMaxBECount =
nullptr;
7111 const SCEV *MayExitMaxBECount =
nullptr;
7112 bool MustExitMaxOrZero =
false;
7117 for (
unsigned i = 0,
e = ExitingBlocks.
size(); i !=
e; ++i) {
7123 if (
auto *BI = dyn_cast<BranchInst>(ExitBB->
getTerminator()))
7124 if (
auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7125 bool ExitIfTrue = !L->
contains(BI->getSuccessor(0));
7126 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7130 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7132 assert((AllowPredicates || EL.Predicates.empty()) &&
7133 "Predicated exit limit when predicates are not allowed!");
7137 if (EL.ExactNotTaken == getCouldNotCompute())
7140 CouldComputeBECount =
false;
7154 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7155 DT.dominates(ExitBB, Latch)) {
7156 if (!MustExitMaxBECount) {
7157 MustExitMaxBECount = EL.MaxNotTaken;
7158 MustExitMaxOrZero = EL.MaxOrZero;
7160 MustExitMaxBECount =
7161 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7163 }
else if (MayExitMaxBECount != getCouldNotCompute()) {
7164 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7165 MayExitMaxBECount = EL.MaxNotTaken;
7168 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7172 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7173 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7176 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.
size() == 1);
7177 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7178 MaxBECount, MaxOrZero);
7181 ScalarEvolution::ExitLimit
7182 ScalarEvolution::computeExitLimit(
const Loop *L,
BasicBlock *ExitingBlock,
7183 bool AllowPredicates) {
7184 assert(L->
contains(ExitingBlock) &&
"Exit count for non-loop block?");
7188 if (!Latch || !DT.dominates(ExitingBlock, Latch))
7189 return getCouldNotCompute();
7193 if (
BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7194 assert(BI->isConditional() &&
"If unconditional, it can't be in loop!");
7195 bool ExitIfTrue = !L->
contains(BI->getSuccessor(0));
7197 "It should have one successor in loop and one exit block!");
7199 return computeExitLimitFromCond(
7200 L, BI->getCondition(), ExitIfTrue,
7201 IsOnlyExit, AllowPredicates);
7210 return getCouldNotCompute();
7213 assert(Exit &&
"Exiting block must have at least one exit");
7214 return computeExitLimitFromSingleExitSwitch(L,
SI, Exit,
7218 return getCouldNotCompute();
7221 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7222 const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7223 bool ControlsExit,
bool AllowPredicates) {
7224 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7225 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7226 ControlsExit, AllowPredicates);
7231 bool ExitIfTrue,
bool ControlsExit,
7232 bool AllowPredicates) {
7234 (void)this->ExitIfTrue;
7235 (void)this->AllowPredicates;
7237 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7238 this->AllowPredicates == AllowPredicates &&
7239 "Variance in assumed invariant key components!");
7240 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7241 if (Itr == TripCountMap.end())
7246 void ScalarEvolution::ExitLimitCache::insert(
const Loop *L,
Value *ExitCond,
7249 bool AllowPredicates,
7250 const ExitLimit &EL) {
7251 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7252 this->AllowPredicates == AllowPredicates &&
7253 "Variance in assumed invariant key components!");
7255 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7256 assert(InsertResult.second &&
"Expected successful insertion!");
7261 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7262 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7263 bool ControlsExit,
bool AllowPredicates) {
7266 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7269 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7270 ControlsExit, AllowPredicates);
7271 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7275 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7276 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7277 bool ControlsExit,
bool AllowPredicates) {
7280 if (BO->getOpcode() == Instruction::And) {
7282 bool EitherMayExit = !ExitIfTrue;
7283 ExitLimit EL0 = computeExitLimitFromCondCached(
7284 Cache, L, BO->getOperand(0), ExitIfTrue,
7285 ControlsExit && !EitherMayExit, AllowPredicates);
7286 ExitLimit EL1 = computeExitLimitFromCondCached(
7287 Cache, L, BO->getOperand(1), ExitIfTrue,
7288 ControlsExit && !EitherMayExit, AllowPredicates);
7290 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7291 return CI->isOne() ? EL0 : EL1;
7292 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7293 return CI->isOne() ? EL1 : EL0;
7294 const SCEV *BECount = getCouldNotCompute();
7295 const SCEV *MaxBECount = getCouldNotCompute();
7296 if (EitherMayExit) {
7299 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7300 EL1.ExactNotTaken == getCouldNotCompute())
7301 BECount = getCouldNotCompute();
7304 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7305 if (EL0.MaxNotTaken == getCouldNotCompute())
7306 MaxBECount = EL1.MaxNotTaken;
7307 else if (EL1.MaxNotTaken == getCouldNotCompute())
7308 MaxBECount = EL0.MaxNotTaken;
7311 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7315 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7316 MaxBECount = EL0.MaxNotTaken;
7317 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7318 BECount = EL0.ExactNotTaken;
7326 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7327 !isa<SCEVCouldNotCompute>(BECount))
7328 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7330 return ExitLimit(BECount, MaxBECount,
false,
7331 {&EL0.Predicates, &EL1.Predicates});
7333 if (BO->getOpcode() == Instruction::Or) {
7335 bool EitherMayExit = ExitIfTrue;
7336 ExitLimit EL0 = computeExitLimitFromCondCached(
7337 Cache, L, BO->getOperand(0), ExitIfTrue,
7338 ControlsExit && !EitherMayExit, AllowPredicates);
7339 ExitLimit EL1 = computeExitLimitFromCondCached(
7340 Cache, L, BO->getOperand(1), ExitIfTrue,
7341 ControlsExit && !EitherMayExit, AllowPredicates);
7343 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7344 return CI->isZero() ? EL0 : EL1;
7345 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7346 return CI->isZero() ? EL1 : EL0;
7347 const SCEV *BECount = getCouldNotCompute();
7348 const SCEV *MaxBECount = getCouldNotCompute();
7349 if (EitherMayExit) {
7352 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7353 EL1.ExactNotTaken == getCouldNotCompute())
7354 BECount = getCouldNotCompute();
7357 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7358 if (EL0.MaxNotTaken == getCouldNotCompute())
7359 MaxBECount = EL1.MaxNotTaken;
7360 else if (EL1.MaxNotTaken == getCouldNotCompute())
7361 MaxBECount = EL0.MaxNotTaken;
7364 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7368 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7369 MaxBECount = EL0.MaxNotTaken;
7370 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7371 BECount = EL0.ExactNotTaken;
7378 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7379 !isa<SCEVCouldNotCompute>(BECount))
7380 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7382 return ExitLimit(BECount, MaxBECount,
false,
7383 {&EL0.Predicates, &EL1.Predicates});
7389 if (
ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7391 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7392 if (EL.hasFullInfo() || !AllowPredicates)
7396 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7404 if (
ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7405 if (ExitIfTrue == !CI->getZExtValue())
7407 return getCouldNotCompute();
7410 return getZero(CI->getType());
7414 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7417 ScalarEvolution::ExitLimit
7418 ScalarEvolution::computeExitLimitFromICmp(
const Loop *L,
7422 bool AllowPredicates) {
7435 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7436 if (ItCnt.hasAnyInfo())
7444 LHS = getSCEVAtScope(LHS, L);
7445 RHS = getSCEVAtScope(RHS, L);
7449 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7456 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7460 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7461 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7462 if (AddRec->getLoop() == L) {
7467 const SCEV *
Ret = AddRec->getNumIterationsInRange(CompRange, *
this);
7468 if (!isa<SCEVCouldNotCompute>(Ret))
return Ret;
7474 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7476 if (EL.hasAnyInfo())
return EL;
7481 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7482 if (EL.hasAnyInfo())
return EL;
7488 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7490 if (EL.hasAnyInfo())
return EL;
7497 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7499 if (EL.hasAnyInfo())
return EL;
7506 auto *ExhaustiveCount =
7507 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7509 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7510 return ExhaustiveCount;
7512 return computeShiftCompareExitLimit(ExitCond->
getOperand(0),
7516 ScalarEvolution::ExitLimit
7517 ScalarEvolution::computeExitLimitFromSingleExitSwitch(
const Loop *L,
7520 bool ControlsExit) {
7525 return getCouldNotCompute();
7528 "Default case must not exit the loop!");
7533 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7534 if (EL.hasAnyInfo())
7537 return getCouldNotCompute();
7545 assert(isa<SCEVConstant>(Val) &&
7546 "Evaluation of SCEV at constant didn't fold correctly?");
7547 return cast<SCEVConstant>(Val)->getValue();
7552 ScalarEvolution::ExitLimit
7553 ScalarEvolution::computeLoadConstantCompareExitLimit(
7558 if (LI->
isVolatile())
return getCouldNotCompute();
7563 if (!GEP)
return getCouldNotCompute();
7570 !cast<Constant>(GEP->
getOperand(1))->isNullValue())
7571 return getCouldNotCompute();
7574 Value *VarIdx =
nullptr;
7575 std::vector<Constant*> Indexes;
7576 unsigned VarIdxNum = 0;
7579 Indexes.push_back(CI);
7580 }
else if (!isa<ConstantInt>(GEP->
getOperand(i))) {
7581 if (VarIdx)
return getCouldNotCompute();
7584 Indexes.push_back(
nullptr);
7589 return getCouldNotCompute();
7593 const SCEV *Idx = getSCEV(VarIdx);
7594 Idx = getSCEVAtScope(Idx, L);
7599 if (!IdxExpr || !IdxExpr->
isAffine() || isLoopInvariant(IdxExpr, L) ||
7600 !isa<SCEVConstant>(IdxExpr->
getOperand(0)) ||
7602 return getCouldNotCompute();
7605 for (
unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7607 cast<IntegerType>(IdxExpr->
getType()), IterationNum);
7611 Indexes[VarIdxNum] = Val;
7619 if (!isa<ConstantInt>(Result))
break;
7620 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7621 ++NumArrayLenItCounts;
7622 return getConstant(ItCst);
7625 return getCouldNotCompute();
7628 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7632 return getCouldNotCompute();
7636 return getCouldNotCompute();
7640 return getCouldNotCompute();
7644 auto MatchPositiveShift =
7651 OutOpCode = Instruction::LShr;
7653 OutOpCode = Instruction::AShr;
7655 OutOpCode = Instruction::Shl;
7670 auto MatchShiftRecurrence =
7687 if (MatchPositiveShift(LHS, V, OpC)) {
7688 PostShiftOpCode = OpC;
7694 if (!PNOut || PNOut->getParent() != L->
getHeader())
7697 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7703 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7710 (!PostShiftOpCode.
hasValue() || *PostShiftOpCode == OpCodeOut);
7715 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7716 return getCouldNotCompute();
7732 case Instruction::AShr: {
7738 auto *
Ty = cast<IntegerType>(RHS->
getType());
7744 return getCouldNotCompute();
7748 case Instruction::LShr:
7749 case Instruction::Shl:
7758 assert(Result->getType()->isIntegerTy(1) &&
7759 "Otherwise cannot be an operand to a branch instruction");
7761 if (Result->isZeroValue()) {
7762 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
7763 const SCEV *UpperBound =
7764 getConstant(getEffectiveSCEVType(RHS->
getType()), BitWidth);
7765 return ExitLimit(getCouldNotCompute(), UpperBound,
false);
7768 return getCouldNotCompute();
7774 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7775 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7776 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7779 if (
const CallInst *CI = dyn_cast<CallInst>(I))
7780 if (
const Function *
F = CI->getCalledFunction())
7791 if (isa<PHINode>(I)) {
7815 if (isa<Constant>(
Op))
continue;
7825 P = PHIMap.
lookup(OpInst);
7834 if (PHI && PHI != P)
7851 if (
PHINode *PN = dyn_cast<PHINode>(I))
7868 if (
Constant *
C = dyn_cast<Constant>(V))
return C;
7870 if (!I)
return nullptr;
7881 if (isa<PHINode>(I))
return nullptr;
7894 if (!C)
return nullptr;
7898 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
7901 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
7922 if (IncomingVal != CurrentVal) {
7925 IncomingVal = CurrentVal;
7937 ScalarEvolution::getConstantEvolutionLoopExitValue(
PHINode *PN,
7940 auto I = ConstantEvolutionLoopExitValue.find(PN);
7941 if (I != ConstantEvolutionLoopExitValue.end())
7945 return ConstantEvolutionLoopExitValue[PN] =
nullptr;
7947 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7951 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
7959 CurrentIterVals[&PHI] = StartCST;
7961 if (!CurrentIterVals.
count(PN))
7962 return RetVal =
nullptr;
7968 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7971 unsigned IterationNum = 0;
7973 for (; ; ++IterationNum) {
7974 if (IterationNum == NumIterations)
7975 return RetVal = CurrentIterVals[PN];
7984 NextIterVals[PN] = NextPHI;
7986 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7992 for (
const auto &I : CurrentIterVals) {
7994 if (!PHI || PHI == PN || PHI->
getParent() != Header)
continue;
7999 for (
const auto &I : PHIsToCompute) {
8001 Constant *&NextPHI = NextIterVals[PHI];
8006 if (NextPHI != I.second)
8007 StoppedEvolving =
false;
8012 if (StoppedEvolving)
8013 return RetVal = CurrentIterVals[PN];
8015 CurrentIterVals.swap(NextIterVals);
8019 const SCEV *ScalarEvolution::computeExitCountExhaustively(
const Loop *L,
8023 if (!PN)
return getCouldNotCompute();
8031 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
8034 assert(Latch &&
"Should follow from NumIncomingValues == 2!");
8038 CurrentIterVals[&PHI] = StartCST;
8040 if (!CurrentIterVals.
count(PN))
8041 return getCouldNotCompute();
8048 for (
unsigned IterationNum = 0; IterationNum !=
MaxIterations;++IterationNum){
8049 auto *CondVal = dyn_cast_or_null<ConstantInt>(
8053 if (!CondVal)
return getCouldNotCompute();
8055 if (CondVal->getValue() == uint64_t(ExitWhen)) {
8056 ++NumBruteForceTripCountsComputed;
8067 for (
const auto &I : CurrentIterVals) {
8069 if (!PHI || PHI->
getParent() != Header)
continue;
8072 for (
PHINode *PHI : PHIsToCompute) {
8073 Constant *&NextPHI = NextIterVals[PHI];
8074 if (NextPHI)
continue;
8076 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8079 CurrentIterVals.swap(NextIterVals);
8083 return getCouldNotCompute();
8090 for (
auto &
LS : Values)
8092 return LS.second ?
LS.second : V;
8094 Values.emplace_back(L,
nullptr);
8097 const SCEV *
C = computeSCEVAtScope(V, L);
8098 for (
auto &
LS :
reverse(ValuesAtScopes[V]))
8099 if (
LS.first == L) {
8111 switch (static_cast<SCEVTypes>(V->
getSCEVType())) {
8116 return cast<SCEVConstant>(V)->getValue();
8141 unsigned AS = PTy->getAddressSpace();
8147 if (!C2)
return nullptr;
8165 if (PTy->getElementType()->isStructTy())
8207 const SCEV *ScalarEvolution::computeSCEVAtScope(
const SCEV *V,
const Loop *L) {
8208 if (isa<SCEVConstant>(V))
return V;
8212 if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8213 if (
Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8214 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
8223 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8226 if (BackedgeTakenCount->
isZero()) {
8227 Value *InitValue =
nullptr;
8228 bool MultipleInitValues =
false;
8234 MultipleInitValues =
true;
8239 if (!MultipleInitValues && InitValue)
8240 return getSCEV(InitValue);
8244 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8252 if (
auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8257 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8258 if (RV)
return getSCEV(RV);
8266 const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8269 if (isa<SCEVConstant>(InputAtScope))
return InputAtScope;
8279 bool MadeImprovement =
false;
8292 const SCEV *OrigV = getSCEV(
Op);
8293 const SCEV *OpV = getSCEVAtScope(OrigV, L);
8294 MadeImprovement |= OrigV != OpV;
8307 if (MadeImprovement) {
8310 if (
const CmpInst *CI = dyn_cast<CmpInst>(I))
8312 Operands[1], DL, &TLI);
8313 else if (
const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8331 for (
unsigned i = 0,
e = Comm->getNumOperands(); i !=
e; ++i) {
8332 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8333 if (OpAtScope != Comm->getOperand(i)) {
8337 Comm->op_begin()+i);
8340 for (++i; i !=
e; ++i) {
8341 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8342 NewOps.push_back(OpAtScope);
8344 if (isa<SCEVAddExpr>(Comm))
8345 return getAddExpr(NewOps, Comm->getNoWrapFlags());
8346 if (isa<SCEVMulExpr>(Comm))
8347 return getMulExpr(NewOps, Comm->getNoWrapFlags());
8348 if (isa<SCEVMinMaxExpr>(Comm))
8349 return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8357 if (
const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8358 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8359 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8360 if (LHS == Div->getLHS() && RHS == Div->getRHS())
8362 return getUDivExpr(LHS, RHS);
8367 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8371 for (
unsigned i = 0,
e = AddRec->getNumOperands(); i !=
e; ++i) {
8372 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8373 if (OpAtScope == AddRec->getOperand(i))
8379 AddRec->op_begin()+i);
8381 for (++i; i !=
e; ++i)
8382 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8384 const SCEV *FoldedRec =
8385 getAddRecExpr(NewOps, AddRec->getLoop(),
8398 if (!AddRec->getLoop()->contains(L)) {
8401 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8402 if (BackedgeTakenCount == getCouldNotCompute())
return AddRec;
8405 return AddRec->evaluateAtIteration(BackedgeTakenCount, *
this);
8412 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8413 if (Op == Cast->getOperand())
8415 return getZeroExtendExpr(Op, Cast->
getType());
8419 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8420 if (Op == Cast->getOperand())
8422 return getSignExtendExpr(Op, Cast->
getType());
8426 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8427 if (Op == Cast->getOperand())
8429 return getTruncateExpr(Op, Cast->
getType());
8436 return getSCEVAtScope(getSCEV(V), L);
8439 const SCEV *ScalarEvolution::stripInjectiveFunctions(
const SCEV *S)
const {
8441 return stripInjectiveFunctions(ZExt->getOperand());
8443 return stripInjectiveFunctions(SExt->getOperand());
8459 assert(A != 0 &&
"A must be non-zero.");
8509 LLVM_DEBUG(
dbgs() << __func__ <<
": analyzing quadratic addrec: " 8510 << *AddRec <<
'\n');
8513 if (!LC || !MC || !NC) {
8514 LLVM_DEBUG(
dbgs() << __func__ <<
": coefficients are not constant\n");
8518 APInt L = LC->getAPInt();
8519 APInt M = MC->getAPInt();
8520 APInt N = NC->getAPInt();
8523 unsigned BitWidth = LC->getAPInt().getBitWidth();
8524 unsigned NewWidth = BitWidth + 1;
8526 << BitWidth <<
'\n');
8529 N = N.
sext(NewWidth);
8530 M = M.
sext(NewWidth);
8531 L = L.
sext(NewWidth);
8547 LLVM_DEBUG(
dbgs() << __func__ <<
": equation " << A <<
"x^2 + " << B
8548 <<
"x + " << C <<
", coeff bw: " << NewWidth
8549 <<
", multiplied by " << T <<
'\n');
8550 return std::make_tuple(A, B, C, T, BitWidth);
8562 return XW.
slt(YW) ? *
X : *
Y;
8584 if (BitWidth > 1 && BitWidth < W && X->
isIntN(BitWidth))
8585 return X->
trunc(BitWidth);
8611 std::tie(A, B, C, M, BitWidth) = *
T;
8612 LLVM_DEBUG(
dbgs() << __func__ <<
": solving for unsigned overflow\n");
8639 "Starting value of addrec should be 0");
8640 LLVM_DEBUG(
dbgs() << __func__ <<
": solving boundary crossing for range " 8641 << Range <<
", addrec " << *AddRec <<
'\n');
8645 "Addrec's initial value should be in range");
8664 LLVM_DEBUG(
dbgs() <<
"SolveQuadraticAddRecRange: checking boundary " 8665 << Bound <<
" (before multiplying by " << M <<
")\n");
8671 "signed overflow\n");
8675 "unsigned overflow\n");
8679 auto LeavesRange = [&] (
const APInt &
X) {
8682 if (Range.
contains(V0->getValue()))
8687 if (Range.
contains(V1->getValue()))
8696 return {
None,
false };
8701 if (LeavesRange(*Min))
8702 return { Min,
true };
8704 if (LeavesRange(*Max))
8705 return { Max,
true };
8708 return {
None,
true };
8711 std::tie(A, B, C, M, BitWidth) = *
T;
8715 auto SL = SolveForBoundary(Lower);
8716 auto SU = SolveForBoundary(Upper);
8719 if (!SL.second || !SU.second)
8763 ScalarEvolution::ExitLimit
8764 ScalarEvolution::howFarToZero(
const SCEV *V,
const Loop *L,
bool ControlsExit,
8765 bool AllowPredicates) {
8776 if (
C->getValue()->isZero())
return C;
8777 return getCouldNotCompute();
8783 if (!AddRec && AllowPredicates)
8787 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8789 if (!AddRec || AddRec->
getLoop() != L)
8790 return getCouldNotCompute();
8799 const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8800 return ExitLimit(R, R,
false, Predicates);
8802 return getCouldNotCompute();
8807 return getCouldNotCompute();
8831 if (!StepC || StepC->getValue()->isZero())
8832 return getCouldNotCompute();
8840 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8845 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8846 APInt MaxBECount = getUnsignedRangeMax(Distance);
8857 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8864 return ExitLimit(Distance, getConstant(MaxBECount),
false, Predicates);
8873 loopHasNoAbnormalExits(AddRec->
getLoop())) {
8875 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8877 Exact == getCouldNotCompute()
8879 : getConstant(getUnsignedRangeMax(Exact));
8880 return ExitLimit(Exact, Max,
false, Predicates);
8885 getNegativeSCEV(Start), *
this);
8886 const SCEV *M = E == getCouldNotCompute()
8888 : getConstant(getUnsignedRangeMax(E));
8889 return ExitLimit(E, M,
false, Predicates);
8892 ScalarEvolution::ExitLimit
8893 ScalarEvolution::howFarToNonZero(
const SCEV *V,
const Loop *L) {
8901 if (!
C->getValue()->isZero())
8903 return getCouldNotCompute();
8908 return getCouldNotCompute();
8911 std::pair<BasicBlock *, BasicBlock *>
8912 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(
BasicBlock *BB) {
8922 if (
Loop *L = LI.getLoopFor(BB))
8925 return {
nullptr,
nullptr};
8934 if (A == B)
return true;
8940 return A->
isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8945 if (
const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8946 if (
const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8947 if (
const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8948 if (
const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8949 if (ComputesEqualValues(AI, BI))
8957 const SCEV *&LHS,
const SCEV *&RHS,
8959 bool Changed =
false;
8962 auto TrivialCase = [&](
bool TriviallyTrue) {
8972 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8974 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8977 RHSC->getValue())->isNullValue())
8978 return TrivialCase(
false);
8980 return TrivialCase(
true);
8993 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->
getHeader())) {
9002 if (
const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9003 const APInt &
RA = RC->getAPInt();
9005 bool SimplifiedByConstantRange =
false;
9010 return TrivialCase(
true);
9012 return TrivialCase(
false);
9020 RHS = getConstant(NewRHS);
9021 Changed = SimplifiedByConstantRange =
true;
9025 if (!SimplifiedByConstantRange) {
9033 if (
const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9035 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9036 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9037 ME->getOperand(0)->isAllOnesValue()) {
9038 RHS = AE->getOperand(1);
9039 LHS = ME->getOperand(1);
9053 RHS = getConstant(RA - 1);
9059 RHS = getConstant(RA + 1);
9065 RHS = getConstant(RA - 1);
9071 RHS = getConstant(RA + 1);
9081 return TrivialCase(
true);
9083 return TrivialCase(
false);
9090 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9091 RHS = getAddExpr(getConstant(RHS->
getType(), 1,
true), RHS,
9095 }
else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9096 LHS = getAddExpr(getConstant(RHS->
getType(), (uint64_t)-1,
true), LHS,
9103 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9104 RHS = getAddExpr(getConstant(RHS->
getType(), (uint64_t)-1,
true), RHS,
9108 }
else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9109 LHS = getAddExpr(getConstant(RHS->
getType(), 1,
true), LHS,
9116 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9117 RHS = getAddExpr(getConstant(RHS->
getType(), 1,
true), RHS,
9121 }
else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9122 LHS = getAddExpr(getConstant(RHS->
getType(), (uint64_t)-1,
true), LHS);
9128 if (!getUnsignedRangeMin(RHS).isMinValue()) {
9129 RHS = getAddExpr(getConstant(RHS->
getType(), (uint64_t)-1,
true), RHS);
9132 }
else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9133 LHS = getAddExpr(getConstant(RHS->
getType(), 1,
true), LHS,
9148 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9154 return getSignedRangeMax(S).isNegative();
9158 return getSignedRangeMin(S).isStrictlyPositive();
9162 return !getSignedRangeMin(S).isNegative();
9166 return !getSignedRangeMax(S).isStrictlyPositive();
9173 std::pair<const SCEV *, const SCEV *>
9177 if (Start == getCouldNotCompute())
9178 return { Start, Start };
9181 assert(PostInc != getCouldNotCompute() &&
"Unexpected could not compute");
9182 return { Start, PostInc };
9186 const SCEV *LHS,
const SCEV *RHS) {
9189 getUsedLoops(LHS, LoopsUsed);
9190 getUsedLoops(RHS, LoopsUsed);
9192 if (LoopsUsed.
empty())
9197 for (
auto *L1 : LoopsUsed)
9198 for (
auto *L2 : LoopsUsed)
9199 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9200 DT.dominates(L2->getHeader(), L1->getHeader())) &&
9201 "Domination relationship is not a linear order");
9205 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9206 [&](
const Loop *L1,
const Loop *L2) {
9207 return DT.properlyDominates(L1->
getHeader(), L2->getHeader());
9211 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9213 if (SplitLHS.first == getCouldNotCompute())
9215 assert (SplitLHS.second != getCouldNotCompute() &&
"Unexpected CNC");
9217 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9219 if (SplitRHS.first == getCouldNotCompute())
9221 assert (SplitRHS.second != getCouldNotCompute() &&
"Unexpected CNC");
9225 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9226 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9229 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9230 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9235 const SCEV *LHS,
const SCEV *RHS) {
9237 (void)SimplifyICmpOperands(Pred, LHS, RHS);
9239 if (isKnownViaInduction(Pred, LHS, RHS))
9242 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9246 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9253 return isLoopEntryGuardedByCond(L, Pred, LHS->
getStart(), RHS) &&
9254 isLoopBackedgeGuardedByCond(L, Pred, LHS->
getPostIncExpr(*
this), RHS);
9260 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9265 bool IncreasingSwapped;
9266 bool ResultSwapped = isMonotonicPredicateImpl(
9269 assert(Result == ResultSwapped &&
"should be able to analyze both!");
9271 assert(Increasing == !IncreasingSwapped &&
9272 "monotonicity should flip as we flip the predicate");
9278 bool ScalarEvolution::isMonotonicPredicateImpl(
const SCEVAddRecExpr *LHS,
9320 if (isKnownNonPositive(Step)) {
9336 const SCEV *&InvariantRHS) {
9339 if (!isLoopInvariant(RHS, L)) {
9340 if (!isLoopInvariant(LHS, L))
9348 if (!ArLHS || ArLHS->
getLoop() != L)
9352 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9375 if (!isLoopBackedgeGuardedByCond(L,
P, LHS, RHS))
9378 InvariantPred = Pred;
9384 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9404 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9405 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9409 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9411 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9419 auto MatchBinaryAddToConst =
9422 const SCEV *NonConstOp, *ConstOp;
9425 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9426 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9429 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9430 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9493 bool ScalarEvolution::isImpliedViaGuard(
BasicBlock *BB,
9495 const SCEV *LHS,
const SCEV *RHS) {
9504 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9506 isImpliedCond(Pred, LHS, RHS, Condition,
false);
9516 const SCEV *LHS,
const SCEV *RHS) {
9519 if (!L)
return true;
9523 "This cannot be done on broken IR!");
9526 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9535 if (LoopContinuePredicate && LoopContinuePredicate->
isConditional() &&
9536 isImpliedCond(Pred, LHS, RHS,
9543 if (WalkingBEDominatingConds)
9549 const auto &BETakenInfo = getBackedgeTakenInfo(L);
9550 const SCEV *LatchBECount = BETakenInfo.getExact(Latch,
this);
9551 if (LatchBECount != getCouldNotCompute()) {
9557 const SCEV *LoopCounter =
9558 getAddRecExpr(getZero(Ty), getOne(Ty), L,
NoWrapFlags);
9565 for (
auto &AssumeVH : AC.assumptions()) {
9568 auto *CI = cast<CallInst>(AssumeVH);
9572 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0),
false))
9579 if (!DT.isReachableFromEntry(L->
getHeader()))
9582 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9586 DTN != HeaderDTN; DTN = DTN->
getIDom()) {
9587 assert(DTN &&
"should reach the loop header before reaching the root!");
9590 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9598 if (!ContinuePredicate || !ContinuePredicate->
isConditional())
9612 assert(DT.dominates(DominatingEdge, Latch) &&
"should be!");
9614 if (isImpliedCond(Pred, LHS, RHS, Condition,
9626 const SCEV *LHS,
const SCEV *RHS) {
9629 if (!L)
return false;
9633 "This cannot be done on broken IR!");
9636 assert(isAvailableAtLoopEntry(LHS, L) &&
9637 "LHS is not available at Loop Entry");
9638 assert(isAvailableAtLoopEntry(RHS, L) &&
9639 "RHS is not available at Loop Entry");
9641 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9650 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9651 bool ProvedNonStrictComparison =
false;
9652 bool ProvedNonEquality =
false;
9654 if (ProvingStrictComparison) {
9655 ProvedNonStrictComparison =
9656 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9659 if (ProvedNonStrictComparison && ProvedNonEquality)
9664 auto ProveViaGuard = [&](
BasicBlock *Block) {
9665 if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9667 if (ProvingStrictComparison) {
9668 if (!ProvedNonStrictComparison)
9669 ProvedNonStrictComparison =
9670 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9671 if (!ProvedNonEquality)
9674 if (ProvedNonStrictComparison && ProvedNonEquality)
9681 auto ProveViaCond = [&](
Value *Condition,
bool Inverse) {
9682 if (isImpliedCond(Pred, LHS, RHS, Condition,
Inverse))
9684 if (ProvingStrictComparison) {
9685 if (!ProvedNonStrictComparison)
9686 ProvedNonStrictComparison =
9687 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition,
Inverse);
9688 if (!ProvedNonEquality)
9691 if (ProvedNonStrictComparison && ProvedNonEquality)
9700 for (std::pair<BasicBlock *, BasicBlock *>
9703 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9705 if (ProveViaGuard(Pair.first))
9710 if (!LoopEntryPredicate ||
9720 for (
auto &AssumeVH : AC.assumptions()) {
9723 auto *CI = cast<CallInst>(AssumeVH);
9727 if (ProveViaCond(CI->getArgOperand(0),
false))
9736 Value *FoundCondValue,
9738 if (!PendingLoopPredicates.insert(FoundCondValue).second)
9742 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9745 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9746 if (BO->getOpcode() == Instruction::And) {
9748 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9749 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9750 }
else if (BO->getOpcode() == Instruction::Or) {
9752 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9753 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9758 if (!ICI)
return false;
9766 FoundPred = ICI->getPredicate();
9768 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9769 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9771 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9777 const SCEV *FoundLHS,
9778 const SCEV *FoundRHS) {
9780 if (getTypeSizeInBits(LHS->
getType()) <
9781 getTypeSizeInBits(FoundLHS->
getType())) {
9783 LHS = getSignExtendExpr(LHS, FoundLHS->
getType());
9784 RHS = getSignExtendExpr(RHS, FoundLHS->
getType());
9786 LHS = getZeroExtendExpr(LHS, FoundLHS->
getType());
9787 RHS = getZeroExtendExpr(RHS, FoundLHS->
getType());
9789 }
else if (getTypeSizeInBits(LHS->
getType()) >
9790 getTypeSizeInBits(FoundLHS->
getType())) {
9792 FoundLHS = getSignExtendExpr(FoundLHS, LHS->
getType());
9793 FoundRHS = getSignExtendExpr(FoundRHS, LHS->
getType());
9795 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->
getType());
9796 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->
getType());
9802 if (SimplifyICmpOperands(Pred, LHS, RHS))
9805 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9806 if (FoundLHS == FoundRHS)
9810 if (LHS == FoundRHS || RHS == FoundLHS) {
9811 if (isa<SCEVConstant>(RHS)) {
9821 if (FoundPred == Pred)
9827 if (isa<SCEVConstant>(RHS))
9831 RHS, LHS, FoundLHS, FoundRHS);
9843 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9846 const SCEV *V =
nullptr;
9848 if (isa<SCEVConstant>(FoundLHS)) {
9849 C = cast<SCEVConstant>(FoundLHS);
9852 C = cast<SCEVConstant>(FoundRHS);
9862 getSignedRangeMin(V) : getUnsignedRangeMin(V);
9869 APInt SharperMin = Min + 1;
9877 getConstant(SharperMin)))
9917 bool ScalarEvolution::splitBinaryAdd(
const SCEV *Expr,
9921 if (!AE || AE->getNumOperands() != 2)
9924 L = AE->getOperand(0);
9925 R = AE->getOperand(1);
9926 Flags = AE->getNoWrapFlags();
9939 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9940 const auto *LAR = cast<SCEVAddRecExpr>(
Less);
9941 const auto *MAR = cast<SCEVAddRecExpr>(More);
9943 if (LAR->getLoop() != MAR->getLoop())
9948 if (!LAR->isAffine() || !MAR->isAffine())
9951 if (LAR->getStepRecurrence(*
this) != MAR->getStepRecurrence(*
this))
9954 Less = LAR->getStart();
9955 More = MAR->getStart();
9960 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9961 const auto &M = cast<SCEVConstant>(More)->getAPInt();
9962 const auto &L = cast<SCEVConstant>(
Less)->getAPInt();
9967 const SCEV *LLess =
nullptr, *RLess =
nullptr;
9968 const SCEV *LMore =
nullptr, *RMore =
nullptr;
9971 if (splitBinaryAdd(Less, LLess, RLess, Flags))
9972 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9977 if (splitBinaryAdd(More, LMore, RMore, Flags))
9978 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9983 if (C1 && C2 && RLess == RMore)
9984 return C2->getAPInt() - C1->
getAPInt();
9989 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9991 const SCEV *FoundLHS,
const SCEV *FoundRHS) {
10000 if (!AddRecFoundLHS)
10007 const Loop *L = AddRecFoundLHS->getLoop();
10008 if (L != AddRecLHS->getLoop())
10045 if (!LDiff || !RDiff || *LDiff != *RDiff)
10051 APInt FoundRHSLimit;
10054 FoundRHSLimit = -(*RDiff);
10061 return isAvailableAtLoopEntry(FoundRHS, L) &&
10062 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10063 getConstant(FoundRHSLimit));
10068 const SCEV *FoundLHS,
10069 const SCEV *FoundRHS,
unsigned Depth) {
10070 const PHINode *LPhi =
nullptr, *RPhi =
nullptr;
10074 bool Erased = PendingMerges.erase(LPhi);
10075 assert(Erased &&
"Failed to erase LPhi!");
10079 bool Erased = PendingMerges.erase(RPhi);
10080 assert(Erased &&
"Failed to erase RPhi!");
10086 if (
const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10087 if (
auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10088 if (!PendingMerges.insert(Phi).second)
10092 if (
const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10093 if (
auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10102 if (!PendingMerges.insert(Phi).second)
10108 if (!LPhi && !RPhi)
10119 assert(LPhi &&
"LPhi should definitely be a SCEVUnknown Phi!");
10123 auto ProvedEasily = [&](
const SCEV *S1,
const SCEV *S2) {
10124 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10125 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10126 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10129 if (RPhi && RPhi->getParent() == LBB) {
10136 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10137 if (!ProvedEasily(L, R))
10148 auto *RLoop = RAR->
getLoop();
10150 assert(Predecessor &&
"Loop with AddRec with no predecessor?");
10152 if (!ProvedEasily(L1, RAR->
getStart()))
10154 auto *Latch = RLoop->getLoopLatch();
10155 assert(Latch &&
"Loop with AddRec with no latch?");
10166 if (!dominates(RHS, IncBB))
10169 if (!ProvedEasily(L, RHS))
10178 const SCEV *FoundLHS,
10179 const SCEV *FoundRHS) {
10180 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10183 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10186 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10187 FoundLHS, FoundRHS) ||
10189 isImpliedCondOperandsHelper(Pred, LHS, RHS,
10190 getNotSCEV(FoundRHS),
10191 getNotSCEV(FoundLHS));
10195 template <
typename MinMaxExprType>
10197 const SCEV *Candidate) {
10198 const MinMaxExprType *MinMaxExpr =
dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10202 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10207 const SCEV *LHS,
const SCEV *RHS) {
10241 const SCEV *LHS,
const SCEV *RHS) {
10252 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10254 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10262 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10264 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10272 const SCEV *FoundLHS,
10273 const SCEV *FoundRHS,
10276 getTypeSizeInBits(RHS->
getType()) &&
10277 "LHS and RHS have different sizes?");
10279 getTypeSizeInBits(FoundRHS->
getType()) &&
10280 "FoundLHS and FoundRHS have different sizes?");
10294 auto GetOpFromSExt = [&](
const SCEV *S) {
10295 if (
auto *
Ext = dyn_cast<SCEVSignExtendExpr>(S))
10296 return Ext->getOperand();
10303 auto *OrigLHS = LHS;
10304 auto *OrigFoundLHS = FoundLHS;
10305 LHS = GetOpFromSExt(LHS);
10306 FoundLHS = GetOpFromSExt(FoundLHS);
10309 auto IsSGTViaContext = [&](
const SCEV *S1,
const SCEV *S2) {
10312 FoundRHS, Depth + 1);
10315 if (
auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10321 if (getTypeSizeInBits(LHS->
getType()) != getTypeSizeInBits(RHS->
getType()))
10325 if (!LHSAddExpr->hasNoSignedWrap())
10328 auto *LL = LHSAddExpr->getOperand(0);
10329 auto *LR = LHSAddExpr->getOperand(1);
10330 auto *MinusOne = getNegativeSCEV(getOne(RHS->
getType()));
10333 auto IsSumGreaterThanRHS = [&](
const SCEV *S1,
const SCEV *S2) {
10334 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10339 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10341 }
else if (
auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10356 if (!isa<ConstantInt>(LR))
10359 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10363 auto *Numerator = getExistingSCEV(LL);
10364 if (!Numerator || Numerator->getType() != FoundLHS->
getType())
10372 auto *DTy = Denominator->getType();
10373 auto *FRHSTy = FoundRHS->
getType();
10374 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10384 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10385 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10391 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10392 if (isKnownNonPositive(RHS) &&
10393 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10403 auto *MinusOne = getNegativeSCEV(getOne(WTy));
10404 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10406 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10414 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10421 const SCEV *LHS,
const SCEV *RHS) {
10431 if (SExt && ZExt && SExt->
getOperand() == ZExt->getOperand())
10454 const SCEV *LHS,
const SCEV *RHS) {
10456 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10459 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10465 const SCEV *FoundLHS,
10466 const SCEV *FoundRHS) {
10501 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10510 const SCEV *FoundLHS,
10511 const SCEV *FoundRHS) {
10512 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10521 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10533 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10539 return SatisfyingLHSRange.
contains(LHSRange);
10542 bool ScalarEvolution::doesIVOverflowOnLT(
const SCEV *RHS,
const SCEV *Stride,
10543 bool IsSigned,
bool NoWrap) {
10546 if (NoWrap)
return false;
10548 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
10552 APInt MaxRHS = getSignedRangeMax(RHS);
10554 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10557 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10560 APInt MaxRHS = getUnsignedRangeMax(RHS);
10562 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10565 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10568 bool ScalarEvolution::doesIVOverflowOnGT(
const SCEV *RHS,
const SCEV *Stride,
10569 bool IsSigned,
bool NoWrap) {
10570 if (NoWrap)
return false;
10572 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
10576 APInt MinRHS = getSignedRangeMin(RHS);
10578 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10581 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10584 APInt MinRHS = getUnsignedRangeMin(RHS);
10586 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10589 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10592 const SCEV *ScalarEvolution::computeBECount(
const SCEV *Delta,
const SCEV *Step,
10595 Delta = Equality ? getAddExpr(Delta, Step)
10596 : getAddExpr(Delta, getMinusSCEV(Step, One));
10597 return getUDivExpr(Delta, Step);
10600 const SCEV *ScalarEvolution::computeMaxBECountForLT(
const SCEV *Start,
10601 const SCEV *Stride,
10606 assert(!isKnownNonPositive(Stride) &&
10607 "Stride is expected strictly positive!");
10610 const SCEV *MaxBECount;
10612 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10614 APInt StrideForMaxBECount =
10615 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10622 APInt One(BitWidth, 1, IsSigned);
10627 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10636 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) ,
10637 getConstant(StrideForMaxBECount) ,
10643 ScalarEvolution::ExitLimit
10644 ScalarEvolution::howManyLessThans(
const SCEV *LHS,
const SCEV *RHS,
10645 const Loop *L,
bool IsSigned,
10646 bool ControlsExit,
bool AllowPredicates) {
10650 bool PredicatedIV =
false;
10652 if (!IV && AllowPredicates) {
10656 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10657 PredicatedIV =
true;
10662 return getCouldNotCompute();
10664 bool NoWrap = ControlsExit &&
10672 if (!PositiveStride) {
10715 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10716 !loopHasNoSideEffects(L))
10717 return getCouldNotCompute();
10718 }
else if (!Stride->
isOne() &&
10719 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10724 return getCouldNotCompute();
10729 const SCEV *End = RHS;
10735 if (!isLoopInvariant(RHS, L)) {
10736 const SCEV *MaxBECount = computeMaxBECountForLT(
10737 Start, Stride, RHS, getTypeSizeInBits(LHS->
getType()), IsSigned);
10738 return ExitLimit(getCouldNotCompute() , MaxBECount,
10739 false , Predicates);
10745 const SCEV *BECountIfBackedgeTaken =
10746 computeBECount(getMinusSCEV(End, Start), Stride,
false);
10754 const SCEV *BECount;
10755 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10756 BECount = BECountIfBackedgeTaken;
10758 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10759 BECount = computeBECount(getMinusSCEV(End, Start), Stride,
false);
10762 const SCEV *MaxBECount;
10763 bool MaxOrZero =
false;
10764 if (isa<SCEVConstant>(BECount))
10765 MaxBECount = BECount;
10766 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10770 MaxBECount = BECountIfBackedgeTaken;
10773 MaxBECount = computeMaxBECountForLT(
10774 Start, Stride, RHS, getTypeSizeInBits(LHS->
getType()), IsSigned);
10777 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10778 !isa<SCEVCouldNotCompute>(BECount))
10779 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10781 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10784 ScalarEvolution::ExitLimit
10785 ScalarEvolution::howManyGreaterThans(
const SCEV *LHS,
const SCEV *RHS,
10786 const Loop *L,
bool IsSigned,
10787 bool ControlsExit,
bool AllowPredicates) {
10790 if (!isLoopInvariant(RHS, L))
10791 return getCouldNotCompute();
10794 if (!IV && AllowPredicates)
10798 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10802 return getCouldNotCompute();
10804 bool NoWrap = ControlsExit &&
10811 return getCouldNotCompute();
10817 if (!Stride->
isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10818 return getCouldNotCompute();
10824 const SCEV *End = RHS;
10825 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10826 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10828 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride,
false);
10830 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10831 : getUnsignedRangeMax(Start);
10833 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10834 : getUnsignedRangeMin(Stride);
10836 unsigned BitWidth = getTypeSizeInBits(LHS->
getType());
10847 const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
10849 : computeBECount(getConstant(MaxStart - MinEnd),
10850 getConstant(MinStride),
false);
10852 if (isa<SCEVCouldNotCompute>(MaxBECount))
10853 MaxBECount = BECount;
10855 return ExitLimit(BECount, MaxBECount,
false, Predicates);
10864 if (
const SCEVConstant *
SC = dyn_cast<SCEVConstant>(getStart()))
10865 if (!
SC->getValue()->isZero()) {
10867 Operands[0] = SE.
getZero(
SC->getType());
10869 getNoWrapFlags(
FlagNW));
10870 if (
const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10871 return ShiftedAddRec->getNumIterationsInRange(
10879 if (
any_of(operands(), [](
const SCEV *
Op) {
return !isa<SCEVConstant>(
Op); }))
10903 APInt ExitVal = (End + A).udiv(A);
10910 if (Range.
contains(Val->getValue()))
10917 "Linear scev computation is off in a bad way!");
10921 if (isQuadratic()) {
10931 assert(getNumOperands() > 1 &&
"AddRec with zero step?");
10941 for (
unsigned i = 0,
e = getNumOperands() - 1; i <
e; ++i)
10948 assert(!Last->
isZero() &&
"Recurrency with zero step?");
10950 return cast<SCEVAddRecExpr>(SE.
getAddRecExpr(Ops, getLoop(),
10957 if (
const auto *SU = dyn_cast<SCEVUnknown>(S))
10958 return isa<UndefValue>(SU->getValue());
10966 struct SCEVCollectStrides {
10971 : SE(SE), Strides(S) {}
10973 bool follow(
const SCEV *S) {
10979 bool isDone()
const {
return false; }
10983 struct SCEVCollectTerms {
10988 bool follow(
const SCEV *S) {
10989 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10990 isa<SCEVSignExtendExpr>(S)) {
11002 bool isDone()
const {
return false; }
11006 struct SCEVHasAddRec {
11007 bool &ContainsAddRec;
11009 SCEVHasAddRec(
bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11010 ContainsAddRec =
false;
11013 bool follow(
const SCEV *S) {
11014 if (isa<SCEVAddRecExpr>(S)) {
11015 ContainsAddRec =
true;
11025 bool isDone()
const {
return false; }
11040 struct SCEVCollectAddRecMultiplies {
11045 : Terms(T), SE(SE) {}
11047 bool follow(
const SCEV *S) {
11048 if (
auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11049 bool HasAddRec =
false;
11051 for (
auto Op : Mul->operands()) {
11053 if (Unknown && !isa<CallInst>(Unknown->
getValue())) {
11055 }
else if (Unknown) {
11058 bool ContainsAddRec =
false;
11059 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11061 HasAddRec |= ContainsAddRec;
11064 if (Operands.
size() == 0)
11079 bool isDone()
const {
return false; }
11091 SCEVCollectStrides StrideCollector(*
this, Strides);
11095 dbgs() <<
"Strides:\n";
11096 for (
const SCEV *S : Strides)
11097 dbgs() << *S <<
"\n";
11100 for (
const SCEV *S : Strides) {
11101 SCEVCollectTerms TermCollector(Terms);
11106 dbgs() <<
"Terms:\n";
11107 for (
const SCEV *
T : Terms)
11108 dbgs() << *
T <<
"\n";
11111 SCEVCollectAddRecMultiplies MulCollector(Terms, *
this);
11118 int Last = Terms.
size() - 1;
11119 const SCEV *Step = Terms[Last];
11123 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11125 for (
const SCEV *
Op : M->operands())
11126 if (!isa<SCEVConstant>(
Op))
11136 for (
const SCEV *&Term : Terms) {
11139 SCEVDivision::divide(SE, Term, Step, &Q, &R);
11150 remove_if(Terms, [](
const SCEV *E) {
return isa<SCEVConstant>(
E); }),
11153 if (Terms.size() > 0)
11163 for (
const SCEV *
T : Terms)
11171 if (
const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11172 return Expr->getNumOperands();
11177 if (isa<SCEVConstant>(T))
11180 if (isa<SCEVUnknown>(T))
11183 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11185 for (
const SCEV *
Op : M->operands())
11186 if (!isa<SCEVConstant>(
Op))
11199 Ty =
Store->getValueOperand()->getType();
11201 Ty =
Load->getType();
11206 return getSizeOfExpr(ETy, Ty);
11211 const SCEV *ElementSize) {
11212 if (Terms.
size() < 1 || !ElementSize)
11221 dbgs() <<
"Terms:\n";
11222 for (
const SCEV *
T : Terms)
11223 dbgs() << *
T <<
"\n";
11237 for (
const SCEV *&Term : Terms) {
11239 SCEVDivision::divide(*
this, Term, ElementSize, &Q, &R);
11247 for (
const SCEV *
T : Terms)
11252 dbgs() <<
"Terms after sorting:\n";
11253 for (
const SCEV *
T : NewTerms)
11254 dbgs() << *
T <<
"\n";
11266 dbgs() <<
"Sizes:\n";
11267 for (
const SCEV *S : Sizes)
11268 dbgs() << *S <<
"\n";
11279 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11283 const SCEV *Res = Expr;
11284 int Last = Sizes.
size() - 1;
11285 for (
int i = Last; i >= 0; i--) {
11287 SCEVDivision::divide(*
this, Res, Sizes[i], &Q, &R);
11290 dbgs() <<
"Res: " << *Res <<
"\n";
11291 dbgs() <<
"Sizes[i]: " << *Sizes[i] <<
"\n";
11292 dbgs() <<
"Res divided by Sizes[i]:\n";
11293 dbgs() <<
"Quotient: " << *Q <<
"\n";
11294 dbgs() <<
"Remainder: " << *R <<
"\n";
11304 if (isa<SCEVAddRecExpr>(R)) {
11305 Subscripts.
clear();
11324 dbgs() <<
"Subscripts:\n";
11325 for (
const SCEV *S : Subscripts)
11326 dbgs() << *S <<
"\n";
11381 const SCEV *ElementSize) {
11384 collectParametricTerms(Expr, Terms);
11390 findArrayDimensions(Terms, Sizes, ElementSize);
11396 computeAccessFunctions(Expr, Subscripts, Sizes);
11398 if (Subscripts.
empty())
11402 dbgs() <<
"succeeded to delinearize " << *Expr <<
"\n";
11403 dbgs() <<
"ArrayDecl[UnknownSize]";
11404 for (
const SCEV *S : Sizes)
11405 dbgs() <<
"[" << *S <<
"]";
11407 dbgs() <<
"\nArrayRef";
11408 for (
const SCEV *S : Subscripts)
11409 dbgs() <<
"[" << *S <<
"]";
11418 void ScalarEvolution::SCEVCallbackVH::deleted() {
11419 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
11420 if (
PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11421 SE->ConstantEvolutionLoopExitValue.erase(PN);
11426 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(
Value *V) {
11427 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
11432 Value *Old = getValPtr();
11435 while (!Worklist.empty()) {
11436 User *U = Worklist.pop_back_val();
11441 if (!Visited.
insert(U).second)
11443 if (
PHINode *PN = dyn_cast<PHINode>(U))
11444 SE->ConstantEvolutionLoopExitValue.erase(PN);
11449 if (
PHINode *PN = dyn_cast<PHINode>(Old))
11450 SE->ConstantEvolutionLoopExitValue.erase(PN);
11465 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11467 LoopDispositions(64), BlockDispositions(64) {
11480 HasGuards = GuardDecl && !GuardDecl->use_empty();
11484 : F(
Arg.F), HasGuards(
Arg.HasGuards), TLI(
Arg.TLI), AC(
Arg.AC), DT(
Arg.DT),
11485 LI(
Arg.LI), CouldNotCompute(
std::move(
Arg.CouldNotCompute)),
11486 ValueExprMap(
std::move(
Arg.ValueExprMap)),
11487 PendingLoopPredicates(
std::move(
Arg.PendingLoopPredicates)),
11488 PendingPhiRanges(
std::move(
Arg.PendingPhiRanges)),
11489 PendingMerges(
std::move(
Arg.PendingMerges)),
11490 MinTrailingZerosCache(
std::move(
Arg.MinTrailingZerosCache)),
11491 BackedgeTakenCounts(
std::move(
Arg.BackedgeTakenCounts)),
11492 PredicatedBackedgeTakenCounts(
11493 std::move(
Arg.PredicatedBackedgeTakenCounts)),
11494 ConstantEvolutionLoopExitValue(
11495 std::move(
Arg.ConstantEvolutionLoopExitValue)),
11496 ValuesAtScopes(
std::move(
Arg.ValuesAtScopes)),
11497 LoopDispositions(
std::move(
Arg.LoopDispositions)),
11498 LoopPropertiesCache(
std::move(
Arg.LoopPropertiesCache)),
11499 BlockDispositions(
std::move(
Arg.BlockDispositions)),
11500 UnsignedRanges(
std::move(
Arg.UnsignedRanges)),
11501 SignedRanges(
std::move(
Arg.SignedRanges)),
11502 UniqueSCEVs(
std::move(
Arg.UniqueSCEVs)),
11503 UniquePreds(
std::move(
Arg.UniquePreds)),
11504 SCEVAllocator(
std::move(
Arg.SCEVAllocator)),
11505 LoopUsers(
std::move(
Arg.LoopUsers)),
11506 PredicatedSCEVRewrites(
std::move(
Arg.PredicatedSCEVRewrites)),
11507 FirstUnknown(
Arg.FirstUnknown) {
11508 Arg.FirstUnknown =
nullptr;
11517 Tmp->~SCEVUnknown();
11519 FirstUnknown =
nullptr;
11521 ExprValueMap.
clear();
11522 ValueExprMap.
clear();
11527 for (
auto &BTCI : BackedgeTakenCounts)
11528 BTCI.second.clear();
11529 for (
auto &BTCI : PredicatedBackedgeTakenCounts)
11530 BTCI.second.clear();
11532 assert(PendingLoopPredicates.empty() &&
"isImpliedCond garbage");
11533 assert(PendingPhiRanges.empty() &&
"getRangeRef garbage");
11534 assert(PendingMerges.empty() &&
"isImpliedViaMerge garbage");
11535 assert(!WalkingBEDominatingConds &&
"isLoopBackedgeGuardedByCond garbage!");
11536 assert(!ProvingSplitPredicate &&
"ProvingSplitPredicate garbage!");
11550 L->getHeader()->printAsOperand(OS,
false);
11554 L->getExitingBlocks(ExitingBlocks);
11555 if (ExitingBlocks.
size() != 1)
11556 OS <<
"<multiple exits> ";
11561 OS <<
"Unpredictable backedge-taken count.\n";
11563 if (ExitingBlocks.
size() > 1)
11564 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
11565 OS <<
" exit count for " << ExitingBlock->
getName() <<
": " 11570 L->getHeader()->printAsOperand(OS,
false);
11576 OS <<
", actual taken count either this or zero.";
11578 OS <<
"Unpredictable max backedge-taken count. ";
11583 L->getHeader()->printAsOperand(OS,
false);
11588 if (!isa<SCEVCouldNotCompute>(PBT)) {
11589 OS <<
"Predicated backedge-taken count is " << *PBT <<
"\n";
11590 OS <<
" Predicates:\n";
11593 OS <<
"Unpredictable predicated backedge-taken count. ";
11599 L->getHeader()->printAsOperand(OS,
false);
11610 return "Invariant";
11612 return "Computable";
11627 OS <<
"Classifying expressions for: ";
11636 if (!isa<SCEVCouldNotCompute>(SV)) {
11643 const Loop *L = LI.getLoopFor(I.getParent());
11649 if (!isa<SCEVCouldNotCompute>(AtUse)) {
11658 OS <<
"\t\t" "Exits: ";
11661 OS <<
"<<Unknown>>";
11669 OS <<
"\t\t" "LoopDispositions: { ";
11675 Iter->getHeader()->printAsOperand(OS,
false);
11683 OS <<
"\t\t" "LoopDispositions: { ";
11689 InnerL->getHeader()->printAsOperand(OS,
false);
11700 OS <<
"Determining loop execution counts for: ";
11709 auto &Values = LoopDispositions[S];
11710 for (
auto &V : Values) {
11711 if (V.getPointer() == L)
11716 auto &Values2 = LoopDispositions[S];
11717 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
11718 if (V.getPointer() == L) {
11727 ScalarEvolution::computeLoopDisposition(
const SCEV *S,
const Loop *L) {
11728 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
11750 " dominate the contained loop's header?");
11771 bool HasVarying =
false;
11772 for (
auto *
Op : cast<SCEVNAryExpr>(S)->operands()) {
11797 if (
auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11816 auto &Values = BlockDispositions[S];
11817 for (
auto &V : Values) {
11818 if (V.getPointer() == BB)
11823 auto &Values2 = BlockDispositions[S];
11824 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
11825 if (V.getPointer() == BB) {
11834 ScalarEvolution::computeBlockDisposition(
const SCEV *S,
const BasicBlock *BB) {
11835 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
11861 bool Proper =
true;
11885 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11911 bool ScalarEvolution::ExitLimit::hasOperand(
const SCEV *S)
const {
11912 auto IsS = [&](
const SCEV *
X) {
return S ==
X; };
11913 auto ContainsS = [&](
const SCEV *
X) {
11916 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11920 ScalarEvolution::forgetMemoizedResults(
const SCEV *S) {
11921 ValuesAtScopes.erase(S);
11922 LoopDispositions.erase(S);
11923 BlockDispositions.erase(S);
11924 UnsignedRanges.erase(S);
11925 SignedRanges.erase(S);
11926 ExprValueMap.
erase(S);
11927 HasRecMap.
erase(S);
11928 MinTrailingZerosCache.erase(S);
11930 for (
auto I = PredicatedSCEVRewrites.begin();
11931 I != PredicatedSCEVRewrites.end();) {
11932 std::pair<const SCEV *, const Loop *>
Entry = I->first;
11933 if (Entry.first == S)
11934 PredicatedSCEVRewrites.erase(I++);
11939 auto RemoveSCEVFromBackedgeMap =
11941 for (
auto I = Map.begin(), E = Map.end(); I !=
E;) {
11942 BackedgeTakenInfo &BEInfo = I->second;
11943 if (BEInfo.hasOperand(S,
this)) {
11951 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11952 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11956 ScalarEvolution::getUsedLoops(
const SCEV *S,
11958 struct FindUsedLoops {
11960 : LoopsUsed(LoopsUsed) {}
11962 bool follow(
const SCEV *S) {
11963 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11968 bool isDone()
const {
return false; }
11971 FindUsedLoops
F(LoopsUsed);
11975 void ScalarEvolution::addToLoopUseLists(
const SCEV *S) {
11977 getUsedLoops(S, LoopsUsed);
11978 for (
auto *L : LoopsUsed)
11979 LoopUsers[L].push_back(S);
12005 SCEVMapper SCM(SE2);
12007 while (!LoopStack.empty()) {
12008 auto *L = LoopStack.pop_back_val();
12009 LoopStack.insert(LoopStack.end(), L->
begin(), L->
end());
12011 auto *CurBECount = SCM.visit(
12046 dbgs() <<
"Trip Count for " << *L <<
" Changed!\n";
12047 dbgs() <<
"Old: " << *CurBECount <<
"\n";
12048 dbgs() <<
"New: " << *NewBECount <<
"\n";
12049 dbgs() <<
"Delta: " << *Delta <<
"\n";
12090 "Scalar Evolution Analysis",
false,
true)
12098 char ScalarEvolutionWrapperPass::ID = 0;
12106 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12107 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12108 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12109 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12138 "Type mismatch between LHS and RHS");
12143 void *IP =
nullptr;
12144 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12148 UniquePreds.InsertNode(Eq, IP);
12160 void *IP =
nullptr;
12161 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12163 auto *OF =
new (SCEVAllocator)
12165 UniquePreds.InsertNode(OF, IP);
12185 SCEVPredicateRewriter
Rewriter(L, SE, NewPreds, Pred);
12186 return Rewriter.visit(S);
12192 for (
auto *Pred : ExprPreds)
12193 if (
const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12194 if (IPred->getLHS() == Expr)
12195 return IPred->getRHS();
12197 return convertToAddRecWithPreds(Expr);
12203 if (AR && AR->getLoop() == L && AR->isAffine()) {
12206 const SCEV *Step = AR->getStepRecurrence(SE);
12211 AR->getNoWrapFlags());
12219 if (AR && AR->getLoop() == L && AR->isAffine()) {
12222 const SCEV *Step = AR->getStepRecurrence(SE);
12227 AR->getNoWrapFlags());
12241 return Pred && Pred->
implies(P);
12250 return addOverflowAssumption(A);
12260 if (!isa<PHINode>(Expr->
getValue()))
12264 if (!PredicatedRewrite)
12266 for (
auto *P : PredicatedRewrite->second){
12268 if (
auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12269 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12273 if (!addOverflowAssumption(P))
12276 return PredicatedRewrite->first;
12303 for (
auto *
P : TransformPreds)
12312 : FastID(ID), Kind(Kind) {}
12318 assert(LHS != RHS &&
"LHS and RHS are the same SCEV");
12327 return Op->LHS == LHS &&
Op->RHS == RHS;
12335 OS.
indent(Depth) <<
"Equal predicate: " << *LHS <<
" == " << *RHS <<
"\n";
12348 return Op &&
Op->AR == AR &&
setFlags(Flags,
Op->Flags) == Flags;
12384 if (Step->getValue()->getValue().isNonNegative())
12388 return ImpliedFlags;
12402 auto I = SCEVToPreds.
find(Expr);
12403 if (
I == SCEVToPreds.
end())
12409 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12410 return all_of(Set->Preds,
12413 auto ScevPredsIt = SCEVToPreds.
find(N->
getExpr());
12414 if (ScevPredsIt == SCEVToPreds.
end())
12416 auto &SCEVPreds = ScevPredsIt->second;
12418 return any_of(SCEVPreds,
12425 for (
auto Pred : Preds)
12426 Pred->print(OS, Depth);
12430 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12431 for (
auto Pred : Set->Preds)
12440 assert(Key &&
"Only SCEVUnionPredicate doesn't have an " 12441 " associated expression!");
12443 SCEVToPreds[
Key].push_back(N);
12444 Preds.push_back(N);
12453 RewriteEntry &
Entry = RewriteMap[Expr];
12456 if (Entry.second && Generation == Entry.first)
12457 return Entry.second;
12462 Expr = Entry.second;
12465 Entry = {Generation, NewSCEV};
12471 if (!BackedgeCount) {
12476 return BackedgeCount;
12483 updateGeneration();
12490 void PredicatedScalarEvolution::updateGeneration() {
12492 if (++Generation == 0) {
12493 for (
auto &II : RewriteMap) {
12494 const SCEV *Rewritten = II.second.second;
12503 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12511 auto II = FlagsMap.insert({V, Flags});
12519 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12524 auto II = FlagsMap.find(V);
12526 if (II != FlagsMap.end())
12540 for (
auto *
P : NewPreds)
12543 updateGeneration();
12544 RewriteMap[SE.
getSCEV(V)] = {Generation, New};
12550 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12551 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12552 for (
auto I : Init.FlagsMap)
12553 FlagsMap.insert(
I);
12559 for (
auto &
I : *BB) {
12564 auto II = RewriteMap.find(Expr);
12566 if (II == RewriteMap.end())
12570 if (II->second.second == Expr)
12573 OS.
indent(Depth) <<
"[PSE]" <<
I <<
":\n";
12574 OS.
indent(Depth + 2) << *Expr <<
"\n";
12575 OS.
indent(Depth + 2) <<
"--> " << *II->second.second <<
"\n";
12583 bool ScalarEvolution::matchURem(
const SCEV *Expr,
const SCEV *&LHS,
12584 const SCEV *&RHS) {
12586 if (
Add ==
nullptr ||
Add->getNumOperands() != 2)
12589 const SCEV *A =
Add->getOperand(1);
12592 if (Mul ==
nullptr)
12595 const auto MatchURemWithDivisor = [&](
const SCEV *
B) {
12597 if (Expr == getURemExpr(A,
B)) {
12606 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12607 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12608 MatchURemWithDivisor(Mul->getOperand(2));
12611 if (Mul->getNumOperands() == 2)
12612 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12613 MatchURemWithDivisor(Mul->getOperand(0)) ||
12614 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12615 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
APInt abs() const
Get the absolute value;.
static Optional< APInt > MinOptional(Optional< APInt > X, Optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X, Y), (b) if neither X nor Y exist, return None, (c) if exactly one of X and Y exists, return that value.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be positive (i.e.
virtual const SCEV * getExpr() const =0
Returns the SCEV to which this predicate applies, or nullptr if this is a SCEVUnionPredicate.
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, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
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...
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
ValTy * getReturnedArgOperand() const
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
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 enum SCEVTypes negate(enum SCEVTypes T)
static ConstantInt * getFalse(LLVMContext &Context)
reference emplace_back(ArgTypes &&... Args)
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.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
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...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static IntegerType * getInt1Ty(LLVMContext &C)
static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
APInt sext(unsigned width) const
Sign extend to a new width.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
static Optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
SCEVCastExpr(const FoldingSetNodeIDRef ID, unsigned SCEVTy, const SCEV *op, Type *ty)
unsigned getValueID() const
Return an ID for the concrete type of this object.
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
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...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const SCEV * getConstant(ConstantInt *V)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
const APInt & getUpper() const
Return the upper value for this range.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
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...
static const SCEV * removeConstantFactors(ScalarEvolution &SE, const SCEV *T)
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...
Represents an op.with.overflow intrinsic.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
void dump() const
This method is used for debugging.
SCEVUnionPredicate()
Union predicates don't get cached so create a dummy set ID for it.
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.
size_t getNumOperands() const
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
unsigned getLoopDepth() const
Return the nesting level of this loop.
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
void push_back(const T &Elt)
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.
APInt zext(unsigned width) const
Zero extend to a new width.
bool slt(const APInt &RHS) const
Signed less than comparison.
bool isZero() const
Return true if the expression is a constant zero.
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. ...
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
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.
const Value * getTrueValue() const
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
ConstantRange truncate(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const
Intern - Copy this node's data to a memory region allocated from the given allocator and return a Fol...
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.
A cache of @llvm.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...
uint32_t GetMinTrailingZeros(const SCEV *S)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration)...
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
LLVMContext & getContext() const
All values hold a context through their type.
This class represents a truncation of an integer value to a smaller integer value.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
const Use & getOperandUse(unsigned i) const
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)
BasicBlock * getSuccessor(unsigned i) const
APInt trunc(unsigned width) const
Truncate to new width.
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 properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
STATISTIC(NumFunctions, "Total number of functions")
ConstantRange udiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned division of a value in...
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.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
block Block Frequency true
An instruction for reading from memory.
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
union - Merge the two equivalence sets for the specified values, inserting them if they do not alread...
static std::pair< const SCEV *, ConstantInt * > splitAddExpr(const SCEV *S)
Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
const SCEV * getOperand() const
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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 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.
static cl::opt< bool > VerifySCEVMap("verify-scev-maps", cl::Hidden, cl::desc("Verify no dangling value in ScalarEvolution's " "ExprValueMap (slow)"))
This defines the Use class.
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...
bool hasNoSignedWrap() const
bool isKnownOnEveryIteration(ICmpInst::Predicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
void print(raw_ostream &OS) const
Print out the bounds to a stream.
INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", "Scalar Evolution Analysis", false, true) INITIALIZE_PASS_END(ScalarEvolutionWrapperPass
unsigned getBitWidth() const
Get the bit width of this value.
APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
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.
const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead...
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.
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...
unsigned getBitWidth() const
Return the number of bits in the APInt.
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.
bool isOffsetOf(Type *&STy, Constant *&FieldNo) const
static Optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation...
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
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.
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
bool isSingleEdge() const
Check if this is the only edge between Start and End.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
bool isKnownViaInduction(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
The SCEV is loop-invariant.
SI optimize exec mask operations pre RA
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static cl::opt< bool > VerifySCEV("verify-scev", cl::Hidden, cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
bool match(Val *V, const Pattern &P)
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
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.
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)
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
void collectParametricTerms(const SCEV *Expr, SmallVectorImpl< const SCEV *> &Terms)
Collect parametric terms occurring in step expressions (first step of delinearization).
void setBit(unsigned BitPosition)
Set a given bit to 1.
bool isAlignOf(Type *&AllocTy) const
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
APInt shl(unsigned shiftAmt) const
Left-shift function.
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...
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 isSizeOf(Type *&AllocTy) const
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction *> &Worklist)
Push users of the given Instruction onto the given Worklist.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVMContext & getContext() const
static Constant * AddOne(Constant *C)
Add one to a Constant.
const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
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.
ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
Analysis pass that exposes the LoopInfo for a function.
mir Rename Register Operands
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
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:
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
This file implements a class to represent arbitrary precision integral constant values and operations...
KnownBits zextOrTrunc(unsigned BitWidth, bool ExtendedBitsAreKnownZero) const
Extends or truncates the underlying known Zero and One bits.
const APInt & getAPInt() const
BlockT * getHeader() const
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.
std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
ConstantInt * getValue() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
unsigned getActiveBits() const
Compute the number of active bits in the value.
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 ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
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...
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
static bool isPrivateLinkage(LinkageTypes Linkage)
A constant value that is initialized with an expression using other constant values.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
op_range operands() const
const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
Type * getType() const
All values are typed, get the type of this value.
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.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
bool implies(const SCEVPredicate *N) const override
Implementation of the SCEVPredicate interface.
const T & getValue() const LLVM_LVALUE_FUNCTION
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
static bool containsParameters(SmallVectorImpl< const SCEV *> &Terms)
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...
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
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.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
op_iterator op_begin() const
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
This class represents a signed minimum selection.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
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.
Value * getOperand(unsigned i) const
Class to represent pointers.
bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
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))
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
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.
iterator find(const_arg_type_t< KeyT > Val)
bool isNegative() const
Returns true if this value is known to be negative.
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)
unsigned short getExpressionSize() const
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
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.
bool isNegative() const
Determine sign of this APInt.
const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
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)
const SCEV * getOperand(unsigned i) const
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)
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...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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...
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
This class defines a simple visitor class that may be used for various SCEV analysis purposes...
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
static unsigned short computeExpressionSize(ArrayRef< const SCEV *> Args)
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM Basic Block Representation.
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 binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
This node is the base class min/max selections.
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.
ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
size_t size() const
size - Get the array size.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
This class represents an unsigned minimum selection.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
APInt multiplicativeInverse(const APInt &modulo) const
Computes the multiplicative inverse of this APInt for a given modulo.
const SCEV * getExpr() const override
Implementation of the SCEVPredicate interface.
SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEV *LHS, const SCEV *RHS)
APInt getMinValue() const
Return the minimal value possible given these KnownBits.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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.
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void add(const SCEVPredicate *N)
Adds a predicate to this union.
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...
const SCEV * getLHS() const
const SCEV * getGEPExpr(GEPOperator *GEP, const SmallVectorImpl< const SCEV *> &IndexExprs)
Returns an expression for a GEP.
void visitAll(const SCEV *Root)
BasicBlock * getDefaultDest() const
const SCEV * getSMaxExpr(const SCEV *LHS, const SCEV *RHS)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
ConstantRange addWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from an addition with wrap type NoWrapK...
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
op_iterator op_end() const
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.
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()
bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
FunctionPass class - This class is used to implement most global optimizations.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static 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()
const SCEV * getStart() const
Class to represent integer types.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
static int CompareValueComplexity(EquivalenceClasses< const Value *> &EqCacheValue, 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 ...
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
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...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
const Value * getCondition() const
static Constant * getAllOnesValue(Type *Ty)
void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
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)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
Constant * ConstantFoldLoadThroughGEPIndices(Constant *C, ArrayRef< Constant *> Indices)
ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr indices (with an implied zero ...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
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...
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.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const SCEV * getUDivExactExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
The SCEV is loop-variant (unknown).
This class represents an assumption made using SCEV expressions which can be checked at run-time...
void sort(IteratorTy Start, IteratorTy End)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static 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.
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
const SCEV * getSMinExpr(const SCEV *LHS, const SCEV *RHS)
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
bool isEmptySet() const
Return true if this set contains no members.
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)
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
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))
unsigned getSCEVType() const
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::ZeroOrMore, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
unsigned getNumOperands() const
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...
bool isMaxSignedValue() const
Determine if this is the largest signed value.
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 isAllOnesValue() const
Return true if the expression is a constant all-ones value.
const SCEVUnionPredicate & getUnionPredicate() const
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
Type * getType() const
Return the LLVM type of this SCEV expression.
Align max(MaybeAlign Lhs, Align Rhs)
void initializeScalarEvolutionWrapperPassPass(PassRegistry &)
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
bool hasNoSelfWrap() const
const SCEV *const * op_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
This is a utility class that provides an abstraction for the common functionality between Instruction...
Provides information about what library functions are available for the current target.
The SCEV dominates the block.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
This class represents a range of values.
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.
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 isMaxValue() const
Determine if this is the largest unsigned value.
ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
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 GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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.
bool isConditional() const
iterator_range< detail::value_sequence_iterator< ValueT > > seq(ValueT Begin, ValueT End)
pred_range predecessors(BasicBlock *BB)
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)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
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.
The access may modify the value stored in memory.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
bool isTrueWhenEqual() const
This is just a convenience.
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.
bool isFalseWhenEqual() const
This is just a convenience.
static bool isHugeExpression(const SCEV *S)
Returns true if the subtree of S contains at least HugeExprThreshold nodes.
Type * getWiderType(Type *Ty1, Type *Ty2) const
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
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)
iterator insert(iterator I, T &&Elt)
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
const Value * getFalseValue() const
A utility class that uses RAII to save and restore the value of a variable.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
SCEVPredicate(const SCEVPredicate &)=default
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static Optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
Analysis pass that exposes the ScalarEvolution for a function.
ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
This class represents a zero extension of a small integer value to a larger integer value...
LoopT * getParentLoop() const
Virtual Register Rewriter
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
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.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
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 hasNoUnsignedWrap() const
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be negative (i.e.
LLVM_NODISCARD bool empty() const
unsigned greater or equal
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
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...
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...
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool hasHugeExpression(ArrayRef< const SCEV *> Ops)
Returns true of Ops contains a huge SCEV (see definition above).
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.
const APInt & getLower() const
Return the lower value for this range.
Optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V)
Check whether value has nuw/nsw/exact set but SCEV does not.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction *> &Worklist)
Push PHI nodes in the header of the given loop onto the given Worklist.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
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.
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 ...
static int CompareSCEVComplexity(EquivalenceClasses< const SCEV *> &EqCacheSCEV, EquivalenceClasses< const Value *> &EqCacheValue, const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
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 findArrayDimensionsRec(ScalarEvolution &SE, SmallVectorImpl< const SCEV *> &Terms, SmallVectorImpl< const SCEV *> &Sizes)
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...
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const SCEV * getURemExpr(const SCEV *LHS, const SCEV *RHS)
Represents an unsigned remainder expression based on unsigned division.
static bool rewrite(Function &F)
AnalysisUsage & addRequiredTransitive()
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
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 ...
bool isUnconditional() const
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void print(raw_ostream &OS) const
const SCEV * getRHS() const
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...
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...
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
bool isMinValue() const
Determine if this is the smallest unsigned value.
static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD)
API to communicate dependencies between analyses during invalidation.
APInt umul_ov(const APInt &RHS, bool &Overflow) const
ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
Analysis pass providing the TargetLibraryInfo.
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)...
iterator_range< df_iterator< T > > depth_first(const T &G)
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
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...
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
bool isOne() const
Return true if the expression is a constant one.
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS)
void stable_sort(R &&Range)
static Optional< BinaryOp > MatchBinaryOp(Value *V, DominatorTree &DT)
Try to map V into a BinaryOp, and return None on failure.
static Optional< APInt > TruncIfPossible(Optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
ConstantRange multiply(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
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.
ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
void eraseValueFromMap(Value *V)
Erase Value from ValueExprMap and ExprValueMap.
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
succ_range successors(Instruction *I)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
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))
const SCEV * getMinMaxExpr(unsigned Kind, SmallVectorImpl< const SCEV *> &Operands)
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 getConstantMaxBackedgeTakenCo...
const SCEV * getUDivExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getUnknown(Value *V)
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.
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block...
Value handle with callbacks on RAUW and destruction.
static int sizeOfSCEV(const SCEV *S)
StringRef - Represent a constant reference to a string, i.e.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Type * getSourceElementType() const
inst_range instructions(Function *F)
bool isNonNegative() const
Returns true if this value is known to be non-negative.
A container for analyses that lazily runs them and caches their results.
APInt getMaxValue() const
Return the maximal value possible given these KnownBits.
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, const ArrayRef< const SCEV *> Ops, SCEV::NoWrapFlags Flags)
static Optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS, const DataLayout &DL, unsigned Depth)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred ALHS ARHS" is true.
Legacy analysis pass which computes a DominatorTree.
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
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 ...
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...
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)
bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const
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.
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
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...
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...
APInt sextOrSelf(unsigned width) const
Sign extend or truncate to width.
static bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
This visitor recursively visits a SCEV expression and re-writes it.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isNullValue() const
Determine if all bits are clear.
bool isStructTy() const
True if this is an instance of StructType.
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool isArrayTy() const
True if this is an instance of ArrayType.
const BasicBlock * getParent() const
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...
void forgetTopmostLoop(const Loop *L)
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode *> &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
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?