86 #include "llvm/Config/llvm-config.h" 136 using namespace llvm;
138 #define DEBUG_TYPE "scalar-evolution" 141 "Number of trip counts computed with array length");
143 "Number of loops with predictable loop counts");
145 "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147 "Number of loops with trip counts computed by force");
151 cl::desc(
"Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 159 cl::desc(
"Verify ScalarEvolution's backedge taken counts (slow)"));
162 cl::desc(
"Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)"));
167 cl::desc(
"Threshold for inlining multiplication operands into a SCEV"),
172 cl::desc(
"Threshold for inlining addition operands into a SCEV"),
176 "scalar-evolution-max-scev-compare-depth",
cl::Hidden,
177 cl::desc(
"Maximum depth of recursive SCEV complexity comparisons"),
181 "scalar-evolution-max-scev-operations-implication-depth",
cl::Hidden,
182 cl::desc(
"Maximum depth of recursive SCEV operations implication analysis"),
186 "scalar-evolution-max-value-compare-depth",
cl::Hidden,
187 cl::desc(
"Maximum depth of recursive value complexity comparisons"),
192 cl::desc(
"Maximum depth of recursive arithmetics"),
196 "scalar-evolution-max-constant-evolving-depth",
cl::Hidden,
201 cl::desc(
"Maximum depth of recursive SExt/ZExt"),
206 cl::desc(
"Max coefficients in AddRec during evolving"),
217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 227 cast<SCEVConstant>(
this)->getValue()->printAsOperand(OS,
false);
232 OS <<
"(trunc " << *Op->getType() <<
" " << *Op <<
" to " 239 OS <<
"(zext " << *Op->getType() <<
" " << *Op <<
" to " 246 OS <<
"(sext " << *Op->getType() <<
" " << *Op <<
" to " 272 const char *OpStr =
nullptr;
283 if (std::next(I) !=
E)
299 OS <<
"(" << *UDiv->
getLHS() <<
" /u " << *UDiv->
getRHS() <<
")";
306 OS <<
"sizeof(" << *AllocTy <<
")";
310 OS <<
"alignof(" << *AllocTy <<
")";
317 OS <<
"offsetof(" << *CTy <<
", ";
328 OS <<
"***COULDNOTCOMPUTE***";
337 return cast<SCEVConstant>(
this)->
getType();
341 return cast<SCEVCastExpr>(
this)->
getType();
346 return cast<SCEVNAryExpr>(
this)->
getType();
348 return cast<SCEVAddExpr>(
this)->
getType();
350 return cast<SCEVUDivExpr>(
this)->
getType();
352 return cast<SCEVUnknown>(
this)->
getType();
361 return SC->getValue()->isZero();
367 return SC->getValue()->isOne();
373 return SC->getValue()->isMinusOne();
379 if (!Mul)
return false;
383 if (!SC)
return false;
401 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
403 UniqueSCEVs.InsertNode(S, IP);
413 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
419 :
SCEV(ID, SCEVTy),
Op(op), Ty(ty) {}
425 "Cannot truncate non-integer value!");
432 "Cannot zero extend non-integer value!");
439 "Cannot sign extend non-integer value!");
442 void SCEVUnknown::deleted() {
444 SE->forgetMemoizedResults(
this);
447 SE->UniqueSCEVs.RemoveNode(
this);
453 void SCEVUnknown::allUsesReplacedWith(
Value *New) {
455 SE->UniqueSCEVs.RemoveNode(
this);
464 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
465 if (VCE->getOpcode() == Instruction::PtrToInt)
466 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
467 if (CE->getOpcode() == Instruction::GetElementPtr &&
468 CE->getOperand(0)->isNullValue() &&
469 CE->getNumOperands() == 2)
470 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
472 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
481 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
482 if (VCE->getOpcode() == Instruction::PtrToInt)
483 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
484 if (CE->getOpcode() == Instruction::GetElementPtr &&
485 CE->getOperand(0)->isNullValue()) {
487 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
488 if (
StructType *STy = dyn_cast<StructType>(Ty))
489 if (!STy->isPacked() &&
490 CE->getNumOperands() == 3 &&
491 CE->getOperand(1)->isNullValue()) {
492 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
494 STy->getNumElements() == 2 &&
495 STy->getElementType(0)->isIntegerTy(1)) {
496 AllocTy = STy->getElementType(1);
506 if (
ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
507 if (VCE->getOpcode() == Instruction::PtrToInt)
508 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
509 if (CE->getOpcode() == Instruction::GetElementPtr &&
510 CE->getNumOperands() == 3 &&
511 CE->getOperand(0)->isNullValue() &&
512 CE->getOperand(1)->isNullValue()) {
514 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
519 FieldNo = CE->getOperand(2);
560 if (LIsPointer != RIsPointer)
561 return (
int)LIsPointer - (int)RIsPointer;
566 return (
int)LID - (int)RID;
569 if (
const auto *LA = dyn_cast<Argument>(LV)) {
570 const auto *
RA = cast<Argument>(RV);
571 unsigned LArgNo = LA->getArgNo(), RArgNo =
RA->getArgNo();
572 return (
int)LArgNo - (int)RArgNo;
575 if (
const auto *LGV = dyn_cast<GlobalValue>(LV)) {
576 const auto *RGV = cast<GlobalValue>(RV);
578 const auto IsGVNameSemantic = [&](
const GlobalValue *GV) {
579 auto LT = GV->getLinkage();
586 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
587 return LGV->getName().compare(RGV->getName());
592 if (
const auto *LInst = dyn_cast<Instruction>(LV)) {
593 const auto *RInst = cast<Instruction>(RV);
598 if (LParent != RParent) {
601 if (LDepth != RDepth)
602 return (
int)LDepth - (int)RDepth;
606 unsigned LNumOps = LInst->getNumOperands(),
607 RNumOps = RInst->getNumOperands();
608 if (LNumOps != RNumOps)
609 return (
int)LNumOps - (int)RNumOps;
611 for (
unsigned Idx :
seq(0u, LNumOps)) {
614 RInst->getOperand(Idx), Depth + 1);
639 return (
int)LType - (int)RType;
646 switch (static_cast<SCEVTypes>(LType)) {
652 RU->getValue(),
Depth + 1);
664 const APInt &
RA = RC->getAPInt();
665 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.
getBitWidth();
666 if (LBitWidth != RBitWidth)
667 return (
int)LBitWidth - (int)RBitWidth;
668 return LA.ult(RA) ? -1 : 1;
678 const Loop *LLoop = LA->
getLoop(), *RLoop = RA->getLoop();
679 if (LLoop != RLoop) {
680 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
681 assert(LHead != RHead &&
"Two loops share the same header?");
686 "No dominance between recurrences used by one SCEV?");
691 unsigned LNumOps = LA->
getNumOperands(), RNumOps = RA->getNumOperands();
692 if (LNumOps != RNumOps)
693 return (
int)LNumOps - (int)RNumOps;
700 for (
unsigned i = 0; i != LNumOps; ++i) {
719 unsigned LNumOps = LC->
getNumOperands(), RNumOps = RC->getNumOperands();
720 if (LNumOps != RNumOps)
721 return (
int)LNumOps - (int)RNumOps;
727 for (
unsigned i = 0; i != LNumOps; ++i) {
744 RC->getLHS(), DT,
Depth + 1);
748 RC->getRHS(), DT,
Depth + 1);
786 if (Ops.
size() < 2)
return;
790 if (Ops.
size() == 2) {
793 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
800 std::stable_sort(Ops.
begin(), Ops.
end(),
801 [&](
const SCEV *LHS,
const SCEV *RHS) {
810 for (
unsigned i = 0, e = Ops.
size(); i != e-2; ++i) {
811 const SCEV *S = Ops[i];
816 for (
unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
821 if (i == e-2)
return;
829 struct FindSCEVSize {
832 FindSCEVSize() =
default;
834 bool follow(
const SCEV *S) {
840 bool isDone()
const {
853 struct SCEVDivision :
public SCEVVisitor<SCEVDivision, void> {
858 const SCEV *Denominator,
const SCEV **Quotient,
859 const SCEV **Remainder) {
860 assert(Numerator && Denominator &&
"Uninitialized SCEV");
862 SCEVDivision
D(SE, Numerator, Denominator);
866 if (Numerator == Denominator) {
872 if (Numerator->
isZero()) {
879 if (Denominator->
isOne()) {
880 *Quotient = Numerator;
886 if (
const SCEVMulExpr *
T = dyn_cast<SCEVMulExpr>(Denominator)) {
888 *Quotient = Numerator;
889 for (
const SCEV *
Op :
T->operands()) {
890 divide(SE, *Quotient,
Op, &Q, &R);
897 *Remainder = Numerator;
906 *Quotient = D.Quotient;
907 *Remainder = D.Remainder;
922 if (
const SCEVConstant *
D = dyn_cast<SCEVConstant>(Denominator)) {
924 APInt DenominatorVal =
D->getAPInt();
928 if (NumeratorBW > DenominatorBW)
929 DenominatorVal = DenominatorVal.
sext(NumeratorBW);
930 else if (NumeratorBW < DenominatorBW)
931 NumeratorVal = NumeratorVal.
sext(DenominatorBW);
935 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
943 const SCEV *StartQ, *StartR, *StepQ, *StepR;
945 return cannotDivide(Numerator);
946 divide(SE, Numerator->
getStart(), Denominator, &StartQ, &StartR);
950 if (Ty != StartQ->getType() || Ty != StartR->
getType() ||
951 Ty != StepQ->getType() || Ty != StepR->
getType())
952 return cannotDivide(Numerator);
965 divide(SE,
Op, Denominator, &Q, &R);
969 return cannotDivide(Numerator);
975 if (Qs.
size() == 1) {
989 bool FoundDenominatorTerm =
false;
993 return cannotDivide(Numerator);
995 if (FoundDenominatorTerm) {
1002 divide(SE,
Op, Denominator, &Q, &R);
1010 return cannotDivide(Numerator);
1012 FoundDenominatorTerm =
true;
1016 if (FoundDenominatorTerm) {
1025 if (!isa<SCEVUnknown>(Denominator))
1026 return cannotDivide(Numerator);
1030 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1031 cast<SCEVConstant>(Zero)->getValue();
1034 if (Remainder->
isZero()) {
1036 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1037 cast<SCEVConstant>(One)->getValue();
1048 return cannotDivide(Numerator);
1049 divide(SE, Diff, Denominator, &Q, &R);
1051 return cannotDivide(Numerator);
1057 const SCEV *Denominator)
1058 : SE(S), Denominator(Denominator) {
1065 cannotDivide(Numerator);
1070 void cannotDivide(
const SCEV *Numerator) {
1072 Remainder = Numerator;
1076 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1153 APInt OddFactorial(W, 1);
1155 for (
unsigned i = 3; i <= K; ++i) {
1160 OddFactorial *=
Mult;
1164 unsigned CalculationBits = W +
T;
1173 APInt MultiplyFactor = OddFactorial.
zext(W+1);
1175 MultiplyFactor = MultiplyFactor.
trunc(W);
1181 for (
unsigned i = 1; i != K; ++i) {
1207 for (
unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1212 if (isa<SCEVCouldNotCompute>(Coeff))
1226 assert(getTypeSizeInBits(Op->
getType()) > getTypeSizeInBits(Ty) &&
1227 "This is not a truncating conversion!");
1229 "This is not a conversion to a SCEVable type!");
1230 Ty = getEffectiveSCEVType(Ty);
1237 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1246 return getTruncateExpr(
ST->getOperand(),
Ty);
1250 return getTruncateOrSignExtend(SS->getOperand(),
Ty);
1254 return getTruncateOrZeroExtend(SZ->getOperand(),
Ty);
1260 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(
Op)) {
1261 auto *CommOp = cast<SCEVCommutativeExpr>(
Op);
1263 unsigned numTruncs = 0;
1264 for (
unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1266 const SCEV *S = getTruncateExpr(CommOp->getOperand(i),
Ty);
1267 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1269 Operands.push_back(S);
1271 if (numTruncs < 2) {
1272 if (isa<SCEVAddExpr>(Op))
1273 return getAddExpr(Operands);
1274 else if (isa<SCEVMulExpr>(Op))
1275 return getMulExpr(Operands);
1282 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1287 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1289 for (
const SCEV *Op : AddRec->operands())
1290 Operands.
push_back(getTruncateExpr(Op, Ty));
1299 UniqueSCEVs.InsertNode(S, IP);
1300 addToLoopUseLists(S);
1339 struct ExtendOpTraitsBase {
1345 template <
typename ExtendOp>
struct ExtendOpTraits {
1358 struct ExtendOpTraits<SCEVSignExtendExpr> :
public ExtendOpTraitsBase {
1361 static const GetExtendExprTy GetExtendExpr;
1363 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1370 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1374 struct ExtendOpTraits<SCEVZeroExtendExpr> :
public ExtendOpTraitsBase {
1377 static const GetExtendExprTy GetExtendExpr;
1379 static const SCEV *getOverflowLimitForStep(
const SCEV *Step,
1386 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1398 template <
typename ExtendOpTy>
1401 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1402 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1428 auto PreStartFlags =
1446 const SCEV *OperandExtendedStart =
1447 SE->
getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1448 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1449 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1461 const SCEV *OverflowLimit =
1462 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1464 if (OverflowLimit &&
1472 template <
typename ExtendOpTy>
1476 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1478 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR,
Ty, SE,
Depth);
1480 return (SE->*GetExtendExpr)(AR->getStart(),
Ty,
Depth);
1482 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE),
Ty,
1484 (SE->*GetExtendExpr)(PreStart,
Ty,
Depth));
1519 template <
typename ExtendOpTy>
1520 bool ScalarEvolution::proveNoWrapByVaryingStart(
const SCEV *Start,
1523 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1535 for (
unsigned Delta : {-2, -1, 1, 2}) {
1545 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1549 if (PreAR && PreAR->getNoWrapFlags(WrapType)) {
1552 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1553 DeltaS, &Pred,
this);
1554 if (Limit && isKnownPredicate(Pred, PreAR, Limit))
1579 return TZ < BitWidth ? C.
trunc(TZ).
zext(BitWidth) :
C;
1581 return APInt(BitWidth, 0);
1589 const APInt &ConstantStart,
1591 const unsigned BitWidth = ConstantStart.
getBitWidth();
1594 return TZ < BitWidth ? ConstantStart.
trunc(TZ).
zext(BitWidth)
1596 return APInt(BitWidth, 0);
1601 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
1602 "This is not an extending conversion!");
1604 "This is not a conversion to a SCEVable type!");
1605 Ty = getEffectiveSCEVType(Ty);
1614 return getZeroExtendExpr(SZ->getOperand(),
Ty, Depth + 1);
1623 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1627 UniqueSCEVs.InsertNode(S, IP);
1628 addToLoopUseLists(S);
1636 const SCEV *
X =
ST->getOperand();
1638 unsigned TruncBits = getTypeSizeInBits(
ST->getType());
1639 unsigned NewBits = getTypeSizeInBits(Ty);
1642 return getTruncateOrZeroExtend(X, Ty);
1650 if (AR->isAffine()) {
1651 const SCEV *Start = AR->getStart();
1652 const SCEV *Step = AR->getStepRecurrence(*
this);
1653 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1654 const Loop *L = AR->getLoop();
1656 if (!AR->hasNoUnsignedWrap()) {
1657 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1663 if (AR->hasNoUnsignedWrap())
1664 return getAddRecExpr(
1665 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1666 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1676 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1677 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1683 const SCEV *CastedMaxBECount =
1684 getTruncateOrZeroExtend(MaxBECount, Start->
getType());
1685 const SCEV *RecastedMaxBECount =
1686 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->
getType());
1687 if (MaxBECount == RecastedMaxBECount) {
1690 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1692 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1696 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1697 const SCEV *WideMaxBECount =
1698 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1699 const SCEV *OperandExtendedAdd =
1700 getAddExpr(WideStart,
1701 getMulExpr(WideMaxBECount,
1702 getZeroExtendExpr(Step, WideTy, Depth + 1),
1705 if (ZAdd == OperandExtendedAdd) {
1709 return getAddRecExpr(
1710 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1712 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1713 AR->getNoWrapFlags());
1717 OperandExtendedAdd =
1718 getAddExpr(WideStart,
1719 getMulExpr(WideMaxBECount,
1720 getSignExtendExpr(Step, WideTy, Depth + 1),
1723 if (ZAdd == OperandExtendedAdd) {
1728 return getAddRecExpr(
1729 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1731 getSignExtendExpr(Step, Ty, Depth + 1), L,
1732 AR->getNoWrapFlags());
1744 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1745 !AC.assumptions().empty()) {
1753 getUnsignedRangeMax(Step));
1760 return getAddRecExpr(
1761 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1763 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1764 AR->getNoWrapFlags());
1768 getSignedRangeMin(Step));
1776 return getAddRecExpr(
1777 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this,
1779 getSignExtendExpr(Step, Ty, Depth + 1), L,
1780 AR->getNoWrapFlags());
1788 if (
const auto *
SC = dyn_cast<SCEVConstant>(Start)) {
1793 const SCEV *SResidual =
1794 getAddRecExpr(
getConstant(C - D), Step, L, AR->getNoWrapFlags());
1795 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1796 return getAddExpr(SZExtD, SZExtR,
1802 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1804 return getAddRecExpr(
1805 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty,
this, Depth + 1),
1806 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1814 if (matchURem(Op, LHS, RHS))
1815 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1816 getZeroExtendExpr(RHS, Ty, Depth + 1));
1820 if (
auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1821 return getUDivExpr(getZeroExtendExpr(Div->getLHS(),
Ty, Depth + 1),
1822 getZeroExtendExpr(Div->getRHS(),
Ty, Depth + 1));
1824 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1826 if (SA->hasNoUnsignedWrap()) {
1830 for (
const auto *Op : SA->operands())
1831 Ops.
push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1843 if (
const auto *
SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1847 const SCEV *SResidual =
1849 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1850 return getAddExpr(SZExtD, SZExtR,
1857 if (
auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1859 if (SM->hasNoUnsignedWrap()) {
1863 for (
const auto *Op : SM->operands())
1864 Ops.
push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1880 if (SM->getNumOperands() == 2)
1881 if (
auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1882 if (MulLHS->getAPInt().isPowerOf2())
1883 if (
auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1884 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1885 MulLHS->getAPInt().logBase2();
1888 getZeroExtendExpr(MulLHS, Ty),
1890 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1897 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1900 UniqueSCEVs.InsertNode(S, IP);
1901 addToLoopUseLists(S);
1907 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
1908 "This is not an extending conversion!");
1910 "This is not a conversion to a SCEVable type!");
1911 Ty = getEffectiveSCEVType(Ty);
1920 return getSignExtendExpr(SS->getOperand(),
Ty, Depth + 1);
1924 return getZeroExtendExpr(SZ->getOperand(),
Ty, Depth + 1);
1933 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
1938 UniqueSCEVs.InsertNode(S, IP);
1939 addToLoopUseLists(S);
1947 const SCEV *
X =
ST->getOperand();
1949 unsigned TruncBits = getTypeSizeInBits(
ST->getType());
1950 unsigned NewBits = getTypeSizeInBits(Ty);
1953 return getTruncateOrSignExtend(X, Ty);
1956 if (
auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1958 if (SA->hasNoSignedWrap()) {
1962 for (
const auto *Op : SA->operands())
1963 Ops.
push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1976 if (
const auto *
SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1980 const SCEV *SResidual =
1982 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1983 return getAddExpr(SSExtD, SSExtR,
1994 if (AR->isAffine()) {
1995 const SCEV *Start = AR->getStart();
1996 const SCEV *Step = AR->getStepRecurrence(*
this);
1997 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1998 const Loop *L = AR->getLoop();
2000 if (!AR->hasNoSignedWrap()) {
2001 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2007 if (AR->hasNoSignedWrap())
2008 return getAddRecExpr(
2009 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2020 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2021 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2027 const SCEV *CastedMaxBECount =
2028 getTruncateOrZeroExtend(MaxBECount, Start->
getType());
2029 const SCEV *RecastedMaxBECount =
2030 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->
getType());
2031 if (MaxBECount == RecastedMaxBECount) {
2034 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2036 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2040 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2041 const SCEV *WideMaxBECount =
2042 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2043 const SCEV *OperandExtendedAdd =
2044 getAddExpr(WideStart,
2045 getMulExpr(WideMaxBECount,
2046 getSignExtendExpr(Step, WideTy, Depth + 1),
2049 if (SAdd == OperandExtendedAdd) {
2053 return getAddRecExpr(
2054 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2056 getSignExtendExpr(Step, Ty, Depth + 1), L,
2057 AR->getNoWrapFlags());
2061 OperandExtendedAdd =
2062 getAddExpr(WideStart,
2063 getMulExpr(WideMaxBECount,
2064 getZeroExtendExpr(Step, WideTy, Depth + 1),
2067 if (SAdd == OperandExtendedAdd) {
2079 return getAddRecExpr(
2080 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this,
2082 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2083 AR->getNoWrapFlags());
2096 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2097 !AC.assumptions().empty()) {
2104 const SCEV *OverflowLimit =
2106 if (OverflowLimit &&
2107 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2108 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2111 return getAddRecExpr(
2112 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2113 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2120 if (
const auto *
SC = dyn_cast<SCEVConstant>(Start)) {
2125 const SCEV *SResidual =
2126 getAddRecExpr(
getConstant(C - D), Step, L, AR->getNoWrapFlags());
2127 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2128 return getAddExpr(SSExtD, SSExtR,
2134 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2136 return getAddRecExpr(
2137 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty,
this, Depth + 1),
2138 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2145 return getZeroExtendExpr(Op, Ty, Depth + 1);
2149 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
2152 UniqueSCEVs.InsertNode(S, IP);
2153 addToLoopUseLists(S);
2161 assert(getTypeSizeInBits(Op->
getType()) < getTypeSizeInBits(Ty) &&
2162 "This is not an extending conversion!");
2164 "This is not a conversion to a SCEVable type!");
2165 Ty = getEffectiveSCEVType(Ty);
2169 if (
SC->getAPInt().isNegative())
2170 return getSignExtendExpr(Op, Ty);
2174 const SCEV *NewOp =
T->getOperand();
2175 if (getTypeSizeInBits(NewOp->
getType()) < getTypeSizeInBits(Ty))
2176 return getAnyExtendExpr(NewOp, Ty);
2177 return getTruncateOrNoop(NewOp, Ty);
2181 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2182 if (!isa<SCEVZeroExtendExpr>(ZExt))
2186 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2187 if (!isa<SCEVSignExtendExpr>(SExt))
2193 for (
const SCEV *Op : AR->operands())
2194 Ops.
push_back(getAnyExtendExpr(Op, Ty));
2195 return getAddRecExpr(Ops, AR->getLoop(),
SCEV::FlagNW);
2199 if (isa<SCEVSMaxExpr>(Op))
2232 APInt &AccumulatedConstant,
2233 const SCEV *
const *Ops,
size_t NumOperands,
2236 bool Interesting =
false;
2240 while (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2243 if (Scale != 1 || AccumulatedConstant != 0 ||
C->getValue()->isZero())
2245 AccumulatedConstant += Scale *
C->getAPInt();
2250 for (; i != NumOperands; ++i) {
2252 if (Mul && isa<SCEVConstant>(Mul->
getOperand(0))) {
2254 Scale * cast<SCEVConstant>(Mul->
getOperand(0))->getAPInt();
2271 Pair.first->second += NewScale;
2279 std::pair<DenseMap<const SCEV *, APInt>::iterator,
bool> Pair =
2280 M.
insert({Ops[i], Scale});
2284 Pair.first->second += Scale;
2302 using namespace std::placeholders;
2309 assert(CanAnalyze &&
"don't call from other places!");
2316 auto IsKnownNonNegative = [&](
const SCEV *S) {
2326 if (SignOrUnsignWrap != SignOrUnsignMask &&
2328 isa<SCEVConstant>(Ops[0])) {
2335 return Instruction::Mul;
2341 const APInt &
C = cast<SCEVConstant>(Ops[0])->getAPInt();
2346 Opcode, C, OBO::NoSignedWrap);
2354 Opcode, C, OBO::NoUnsignedWrap);
2372 "only nuw or nsw allowed");
2374 if (Ops.
size() == 1)
return Ops[0];
2376 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
2377 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
2379 "SCEVAddExpr operand types don't match!");
2389 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2392 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2394 Ops[0] =
getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2395 if (Ops.
size() == 2)
return Ops[0];
2397 LHSC = cast<SCEVConstant>(Ops[0]);
2401 if (LHSC->getValue()->isZero()) {
2406 if (Ops.
size() == 1)
return Ops[0];
2411 return getOrCreateAddExpr(Ops, Flags);
2416 Type *
Ty = Ops[0]->getType();
2417 bool FoundMatch =
false;
2418 for (
unsigned i = 0, e = Ops.
size(); i != e-1; ++i)
2419 if (Ops[i] == Ops[i+1]) {
2422 while (i+Count != e && Ops[i+Count] == Ops[i])
2427 if (Ops.
size() == Count)
2431 --i; e -= Count - 1;
2435 return getAddExpr(Ops, Flags, Depth + 1);
2441 auto FindTruncSrcType = [&]() ->
Type * {
2446 if (
auto *
T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2447 return T->getOperand()->getType();
2448 if (
const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2449 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2450 if (
const auto *
T = dyn_cast<SCEVTruncateExpr>(LastOp))
2451 return T->getOperand()->getType();
2455 if (
auto *SrcType = FindTruncSrcType()) {
2460 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
2462 if (
T->getOperand()->getType() != SrcType) {
2467 }
else if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(Ops[i])) {
2468 LargeOps.
push_back(getAnyExtendExpr(
C, SrcType));
2469 }
else if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2471 for (
unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2473 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2474 if (
T->getOperand()->getType() != SrcType) {
2479 }
else if (
const auto *
C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2480 LargeMulOps.
push_back(getAnyExtendExpr(
C, SrcType));
2497 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2498 return getTruncateExpr(Fold, Ty);
2503 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scAddExpr)
2507 if (Idx < Ops.
size()) {
2508 bool DeletedAdd =
false;
2509 while (
const SCEVAddExpr *
Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2528 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
2533 if (Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx])) {
2534 uint64_t BitWidth = getTypeSizeInBits(Ty);
2537 APInt AccumulatedConstant(BitWidth, 0);
2540 APInt(BitWidth, 1), *
this)) {
2541 struct APIntCompare {
2542 bool operator()(
const APInt &LHS,
const APInt &RHS)
const {
2543 return LHS.
ult(RHS);
2550 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2551 for (
const SCEV *NewOp : NewOps)
2552 MulOpLists[M.
find(NewOp)->second].push_back(NewOp);
2555 if (AccumulatedConstant != 0)
2557 for (
auto &MulOp : MulOpLists)
2558 if (MulOp.first != 0)
2565 if (Ops.
size() == 1)
2574 for (; Idx < Ops.
size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2575 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2576 for (
unsigned MulOp = 0, e = Mul->
getNumOperands(); MulOp != e; ++MulOp) {
2578 if (isa<SCEVConstant>(MulOpSCEV))
2580 for (
unsigned AddOp = 0, e = Ops.
size(); AddOp != e; ++AddOp)
2581 if (MulOpSCEV == Ops[AddOp]) {
2594 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2596 if (Ops.
size() == 2)
return OuterMul;
2609 for (
unsigned OtherMulIdx = Idx+1;
2610 OtherMulIdx < Ops.
size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2612 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2616 OMulOp != e; ++OMulOp)
2617 if (OtherMul->
getOperand(OMulOp) == MulOpSCEV) {
2634 const SCEV *InnerMulSum =
2636 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2638 if (Ops.
size() == 2)
return OuterMul;
2655 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2661 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2662 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2669 if (!LIOps.
empty()) {
2678 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2684 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2687 if (Ops.
size() == 1)
return NewRec;
2690 for (
unsigned i = 0;; ++i)
2691 if (Ops[i] == AddRec) {
2701 for (
unsigned OtherIdx = Idx+1;
2702 OtherIdx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2707 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2709 "AddRecExprs are not sorted in reverse dominance order?");
2710 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2714 for (; OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2716 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2717 if (OtherAddRec->getLoop() == AddRecLoop) {
2718 for (
unsigned i = 0, e = OtherAddRec->getNumOperands();
2720 if (i >= AddRecOps.size()) {
2721 AddRecOps.
append(OtherAddRec->op_begin()+i,
2722 OtherAddRec->op_end());
2726 AddRecOps[i], OtherAddRec->getOperand(i)};
2729 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
2744 return getOrCreateAddExpr(Ops, Flags);
2752 for (
const SCEV *
Op : Ops)
2756 static_cast<SCEVAddExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2758 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.size());
2759 std::uninitialized_copy(Ops.begin(), Ops.end(),
O);
2760 S =
new (SCEVAllocator)
2762 UniqueSCEVs.InsertNode(S, IP);
2763 addToLoopUseLists(S);
2774 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2778 static_cast<SCEVMulExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2780 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
2781 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
2784 UniqueSCEVs.InsertNode(S, IP);
2785 addToLoopUseLists(S);
2791 static uint64_t
umul_ov(uint64_t i, uint64_t j,
bool &Overflow) {
2793 if (j > 1 && k / j != i) Overflow =
true;
2800 static uint64_t
Choose(uint64_t n, uint64_t k,
bool &Overflow) {
2809 if (n == 0 || n == k)
return 1;
2810 if (k > n)
return 0;
2816 for (uint64_t i = 1; i <= k; ++i) {
2817 r =
umul_ov(r, n-(i-1), Overflow);
2826 struct FindConstantInAddMulChain {
2827 bool FoundConstant =
false;
2829 bool follow(
const SCEV *S) {
2830 FoundConstant |= isa<SCEVConstant>(S);
2831 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2834 bool isDone()
const {
2835 return FoundConstant;
2839 FindConstantInAddMulChain
F;
2842 return F.FoundConstant;
2850 "only nuw or nsw allowed");
2852 if (Ops.
size() == 1)
return Ops[0];
2854 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
2855 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
2857 "SCEVMulExpr operand types don't match!");
2867 return getOrCreateMulExpr(Ops, Flags);
2871 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2873 if (Ops.
size() == 2)
2883 return getAddExpr(getMulExpr(LHSC,
Add->getOperand(0),
2885 getMulExpr(LHSC,
Add->getOperand(1),
2890 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2895 Ops.erase(Ops.begin()+1);
2896 if (Ops.size() == 1)
return Ops[0];
2897 LHSC = cast<SCEVConstant>(Ops[0]);
2901 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2904 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2910 if (Ops.
size() == 2) {
2913 bool AnyFolded =
false;
2914 for (
const SCEV *AddOp :
Add->operands()) {
2917 if (!isa<SCEVMulExpr>(Mul)) AnyFolded =
true;
2922 }
else if (
const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2925 for (
const SCEV *AddRecOp : AddRec->operands())
2929 return getAddRecExpr(Operands, AddRec->getLoop(),
2935 if (Ops.
size() == 1)
2940 while (Idx < Ops.
size() && Ops[Idx]->getSCEVType() <
scMulExpr)
2944 if (Idx < Ops.
size()) {
2945 bool DeletedMul =
false;
2946 while (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2952 Ops.
append(Mul->op_begin(), Mul->op_end());
2970 for (; Idx < Ops.
size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2976 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
2977 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2984 if (!LIOps.
empty()) {
2999 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3002 if (Ops.
size() == 1)
return NewRec;
3005 for (
unsigned i = 0;; ++i)
3006 if (Ops[i] == AddRec) {
3027 bool OpsModified =
false;
3028 for (
unsigned OtherIdx = Idx+1;
3029 OtherIdx != Ops.
size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3033 if (!OtherAddRec || OtherAddRec->
getLoop() != AddRecLoop)
3042 bool Overflow =
false;
3044 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3048 const SCEV *Term = getZero(Ty);
3049 for (
int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3050 uint64_t Coeff1 =
Choose(x, 2*x - y, Overflow);
3053 z < ze && !Overflow; ++z) {
3054 uint64_t Coeff2 =
Choose(2*x - y, x-z, Overflow);
3056 if (LargerThan64Bits)
3057 Coeff =
umul_ov(Coeff1, Coeff2, Overflow);
3059 Coeff = Coeff1*Coeff2;
3063 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
3071 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->
getLoop(),
3073 if (Ops.
size() == 2)
return NewAddRec;
3074 Ops[Idx] = NewAddRec;
3075 Ops.
erase(Ops.
begin() + OtherIdx); --OtherIdx;
3091 return getOrCreateMulExpr(Ops, Flags);
3098 getEffectiveSCEVType(RHS->
getType()) &&
3099 "SCEVURemExpr operand types don't match!");
3102 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3104 if (RHSC->getValue()->isOne())
3105 return getZero(LHS->
getType());
3108 if (RHSC->getAPInt().isPowerOf2()) {
3112 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3117 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3127 getEffectiveSCEVType(RHS->
getType()) &&
3128 "SCEVUDivExpr operand types don't match!");
3130 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3131 if (RHSC->getValue()->isOne())
3136 if (!RHSC->getValue()->isZero()) {
3141 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3142 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3145 if (!RHSC->getAPInt().isPowerOf2())
3151 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*
this))) {
3153 const APInt &StepInt = Step->getAPInt();
3154 const APInt &DivInt = RHSC->getAPInt();
3155 if (!StepInt.
urem(DivInt) &&
3156 getZeroExtendExpr(AR, ExtTy) ==
3157 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3158 getZeroExtendExpr(Step, ExtTy),
3161 for (
const SCEV *
Op : AR->operands())
3163 return getAddRecExpr(Operands, AR->getLoop(),
SCEV::FlagNW);
3169 if (StartC && !DivInt.
urem(StepInt) &&
3170 getZeroExtendExpr(AR, ExtTy) ==
3171 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3172 getZeroExtendExpr(Step, ExtTy),
3174 const APInt &StartInt = StartC->getAPInt();
3175 const APInt &StartRem = StartInt.
urem(StepInt);
3177 LHS = getAddRecExpr(
getConstant(StartInt - StartRem), Step,
3182 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3184 for (
const SCEV *
Op : M->operands())
3186 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3188 for (
unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3189 const SCEV *
Op = M->getOperand(i);
3190 const SCEV *Div = getUDivExpr(Op, RHSC);
3191 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3195 return getMulExpr(Operands);
3201 if (
const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3202 if (
auto *DivisorConstant =
3203 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3204 bool Overflow =
false;
3206 DivisorConstant->getAPInt().
umul_ov(RHSC->getAPInt(), Overflow);
3210 return getUDivExpr(OtherDiv->getLHS(),
getConstant(NewRHS));
3215 if (
const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3217 for (
const SCEV *
Op : A->operands())
3219 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3221 for (
unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3222 const SCEV *
Op = getUDivExpr(A->getOperand(i), RHS);
3223 if (isa<SCEVUDivExpr>(Op) ||
3224 getMulExpr(Op, RHS) != A->getOperand(i))
3228 if (Operands.
size() == A->getNumOperands())
3229 return getAddExpr(Operands);
3234 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3235 Constant *LHSCV = LHSC->getValue();
3236 Constant *RHSCV = RHSC->getValue();
3248 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3251 UniqueSCEVs.InsertNode(S, IP);
3252 addToLoopUseLists(S);
3282 return getUDivExpr(LHS, RHS);
3284 if (
const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3287 if (
const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->
getOperand(0))) {
3288 if (LHSCst == RHSCst) {
3291 return getMulExpr(Operands);
3297 APInt Factor =
gcd(LHSCst, RHSCst);
3300 cast<SCEVConstant>(
getConstant(LHSCst->getAPInt().udiv(Factor)));
3302 cast<SCEVConstant>(
getConstant(RHSCst->getAPInt().udiv(Factor)));
3306 LHS = getMulExpr(Operands);
3310 return getUDivExactExpr(LHS, RHS);
3320 return getMulExpr(Operands);
3324 return getUDivExpr(LHS, RHS);
3334 if (
const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3335 if (StepChrec->getLoop() == L) {
3336 Operands.
append(StepChrec->op_begin(), StepChrec->op_end());
3337 return getAddRecExpr(Operands, L, maskFlags(Flags,
SCEV::FlagNW));
3341 return getAddRecExpr(Operands, L, Flags);
3349 if (Operands.
size() == 1)
return Operands[0];
3351 Type *ETy = getEffectiveSCEVType(Operands[0]->
getType());
3352 for (
unsigned i = 1, e = Operands.
size(); i != e; ++i)
3353 assert(getEffectiveSCEVType(Operands[i]->
getType()) == ETy &&
3354 "SCEVAddRecExpr operand types don't match!");
3355 for (
unsigned i = 0, e = Operands.
size(); i != e; ++i)
3357 "SCEVAddRecExpr operand is not loop-invariant!");
3374 if (
const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3375 const Loop *NestedLoop = NestedAR->getLoop();
3381 NestedAR->op_end());
3382 Operands[0] = NestedAR->getStart();
3386 bool AllInvariant =
all_of(
3395 maskFlags(Flags,
SCEV::FlagNW | NestedAR->getNoWrapFlags());
3397 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3398 AllInvariant =
all_of(NestedOperands, [&](
const SCEV *Op) {
3408 maskFlags(NestedAR->getNoWrapFlags(),
SCEV::FlagNW | Flags);
3409 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3413 Operands[0] = NestedAR;
3421 for (
unsigned i = 0, e = Operands.
size(); i != e; ++i)
3426 static_cast<SCEVAddRecExpr *
>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3428 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Operands.
size());
3429 std::uninitialized_copy(Operands.
begin(), Operands.
end(),
O);
3431 O, Operands.
size(), L);
3432 UniqueSCEVs.InsertNode(S, IP);
3433 addToLoopUseLists(S);
3445 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->
getType());
3454 const SCEV *TotalOffset = getZero(IntPtrTy);
3458 for (
const SCEV *IndexExpr : IndexExprs) {
3460 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
3464 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3467 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3470 CurTy = STy->getTypeAtIndex(Index);
3473 CurTy = cast<SequentialType>(CurTy)->getElementType();
3475 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3477 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3480 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3483 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3488 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3494 return getSMaxExpr(Ops);
3500 if (Ops.
size() == 1)
return Ops[0];
3502 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
3503 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
3505 "SCEVSMaxExpr operand types don't match!");
3513 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3516 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3519 getContext(),
APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3522 if (Ops.
size() == 1)
return Ops[0];
3523 LHSC = cast<SCEVConstant>(Ops[0]);
3527 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(
true)) {
3530 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(
true)) {
3536 if (Ops.
size() == 1)
return Ops[0];
3545 if (Idx < Ops.
size()) {
3546 bool DeletedSMax =
false;
3547 while (
const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3549 Ops.
append(SMax->op_begin(), SMax->op_end());
3554 return getSMaxExpr(Ops);
3560 for (
unsigned i = 0, e = Ops.
size()-1; i != e; ++i)
3563 if (Ops[i] == Ops[i+1] ||
3572 if (Ops.
size() == 1)
return Ops[0];
3574 assert(!Ops.
empty() &&
"Reduced smax down to nothing!");
3580 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
3581 ID.AddPointer(Ops[i]);
3583 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3584 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
3585 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
3588 UniqueSCEVs.InsertNode(S, IP);
3589 addToLoopUseLists(S);
3596 return getUMaxExpr(Ops);
3602 if (Ops.
size() == 1)
return Ops[0];
3604 Type *ETy = getEffectiveSCEVType(Ops[0]->
getType());
3605 for (
unsigned i = 1, e = Ops.
size(); i != e; ++i)
3607 "SCEVUMaxExpr operand types don't match!");
3615 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3618 while (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3621 getContext(),
APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3624 if (Ops.
size() == 1)
return Ops[0];
3625 LHSC = cast<SCEVConstant>(Ops[0]);
3629 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(
false)) {
3632 }
else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(
false)) {
3638 if (Ops.
size() == 1)
return Ops[0];
3647 if (Idx < Ops.
size()) {
3648 bool DeletedUMax =
false;
3649 while (
const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3651 Ops.
append(UMax->op_begin(), UMax->op_end());
3656 return getUMaxExpr(Ops);
3662 for (
unsigned i = 0, e = Ops.
size()-1; i != e; ++i)
3665 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3675 if (Ops.
size() == 1)
return Ops[0];
3677 assert(!Ops.
empty() &&
"Reduced umax down to nothing!");
3683 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
3684 ID.AddPointer(Ops[i]);
3686 if (
const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
return S;
3687 const SCEV **
O = SCEVAllocator.Allocate<
const SCEV *>(Ops.
size());
3688 std::uninitialized_copy(Ops.
begin(), Ops.
end(),
O);
3691 UniqueSCEVs.InsertNode(S, IP);
3692 addToLoopUseLists(S);
3699 return getSMinExpr(Ops);
3707 return getNotSCEV(getSMaxExpr(NotOps));
3713 return getUMinExpr(Ops);
3717 assert(!Ops.
empty() &&
"At least one operand must be!");
3719 if (Ops.
size() == 1)
3726 return getNotSCEV(getUMaxExpr(NotOps));
3733 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3743 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3756 if (
SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3757 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3758 "Stale SCEVUnknown in uniquing map!");
3763 FirstUnknown = cast<SCEVUnknown>(S);
3764 UniqueSCEVs.InsertNode(S, IP);
3784 assert(isSCEVable(Ty) &&
"Type is not SCEVable!");
3786 return getDataLayout().getIndexTypeSizeInBits(Ty);
3787 return getDataLayout().getTypeSizeInBits(Ty);
3794 assert(isSCEVable(Ty) &&
"Type is not SCEVable!");
3801 return getDataLayout().getIntPtrType(Ty);
3805 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ?
T1 : T2;
3809 return CouldNotCompute.get();
3812 bool ScalarEvolution::checkValidity(
const SCEV *S)
const {
3815 return SU && SU->
getValue() ==
nullptr;
3818 return !ContainsNulls;
3823 if (I != HasRecMap.end())
3827 HasRecMap.insert({S, FoundAddRec});
3837 return {S,
nullptr};
3839 if (
Add->getNumOperands() != 2)
3840 return {S,
nullptr};
3844 return {S,
nullptr};
3846 return {
Add->getOperand(1), ConstOp->getValue()};
3852 ScalarEvolution::getSCEVValues(
const SCEV *S) {
3853 ExprValueMapType::iterator
SI = ExprValueMap.find_as(S);
3854 if (SI == ExprValueMap.end())
3859 for (
const auto &VE : SI->second)
3860 assert(ValueExprMap.count(VE.first));
3871 if (I != ValueExprMap.end()) {
3872 const SCEV *S = I->second;
3875 SV->remove({V, nullptr});
3878 const SCEV *Stripped;
3881 if (Offset !=
nullptr) {
3883 SV->remove({V, Offset});
3885 ValueExprMap.erase(V);
3893 if (
auto *
I = dyn_cast<Instruction>(V)) {
3894 if (isa<OverflowingBinaryOperator>(
I)) {
3895 if (
auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3896 if (
I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3898 if (
I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3901 }
else if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
3910 assert(isSCEVable(V->
getType()) &&
"Value is not SCEVable!");
3912 const SCEV *S = getExistingSCEV(V);
3918 std::pair<ValueExprMapType::iterator, bool> Pair =
3919 ValueExprMap.insert({SCEVCallbackVH(V,
this), S});
3921 ExprValueMap[S].insert({V,
nullptr});
3925 const SCEV *Stripped = S;
3933 if (Offset !=
nullptr && !isa<SCEVUnknown>(Stripped) &&
3934 !isa<GetElementPtrInst>(V))
3935 ExprValueMap[Stripped].insert({V, Offset});
3941 const SCEV *ScalarEvolution::getExistingSCEV(
Value *V) {
3942 assert(isSCEVable(V->
getType()) &&
"Value is not SCEVable!");
3945 if (I != ValueExprMap.end()) {
3946 const SCEV *S = I->second;
3947 if (checkValidity(S))
3949 eraseValueFromMap(V);
3950 forgetMemoizedResults(S);
3963 Ty = getEffectiveSCEVType(Ty);
3975 Ty = getEffectiveSCEVType(Ty);
3976 const SCEV *AllOnes =
3978 return getMinusSCEV(AllOnes, V);
3986 return getZero(LHS->
getType());
3991 const bool RHSIsNotMinSigned =
3992 !getSignedRangeMin(RHS).isMinSignedValue();
4017 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4024 "Cannot truncate or zero extend with non-integer arguments!");
4025 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4027 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4028 return getTruncateExpr(V, Ty);
4029 return getZeroExtendExpr(V, Ty);
4037 "Cannot truncate or zero extend with non-integer arguments!");
4038 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4040 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4041 return getTruncateExpr(V, Ty);
4042 return getSignExtendExpr(V, Ty);
4049 "Cannot noop or zero extend with non-integer arguments!");
4050 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4051 "getNoopOrZeroExtend cannot truncate!");
4052 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4054 return getZeroExtendExpr(V, Ty);
4061 "Cannot noop or sign extend with non-integer arguments!");
4062 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4063 "getNoopOrSignExtend cannot truncate!");
4064 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4066 return getSignExtendExpr(V, Ty);
4073 "Cannot noop or any extend with non-integer arguments!");
4074 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4075 "getNoopOrAnyExtend cannot truncate!");
4076 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4078 return getAnyExtendExpr(V, Ty);
4085 "Cannot truncate or noop with non-integer arguments!");
4086 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4087 "getTruncateOrNoop cannot extend!");
4088 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4090 return getTruncateExpr(V, Ty);
4095 const SCEV *PromotedLHS = LHS;
4096 const SCEV *PromotedRHS = RHS;
4098 if (getTypeSizeInBits(LHS->
getType()) > getTypeSizeInBits(RHS->
getType()))
4099 PromotedRHS = getZeroExtendExpr(RHS, LHS->
getType());
4101 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->
getType());
4103 return getUMaxExpr(PromotedLHS, PromotedRHS);
4109 return getUMinFromMismatchedTypes(Ops);
4114 assert(!Ops.
empty() &&
"At least one operand must be!");
4116 if (Ops.
size() == 1)
4120 Type *MaxType =
nullptr;
4130 PromotedOps.
push_back(getNoopOrZeroExtend(S, MaxType));
4133 return getUMinExpr(PromotedOps);
4141 if (
const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4142 return getPointerBase(Cast->getOperand());
4143 }
else if (
const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4144 const SCEV *PtrOp =
nullptr;
4145 for (
const SCEV *NAryOp : NAry->operands()) {
4146 if (NAryOp->getType()->isPointerTy()) {
4155 return getPointerBase(PtrOp);
4166 Worklist.
push_back(cast<Instruction>(U));
4169 void ScalarEvolution::forgetSymbolicName(
Instruction *PN,
const SCEV *SymName) {
4175 while (!Worklist.
empty()) {
4177 if (!Visited.
insert(I).second)
4180 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4181 if (It != ValueExprMap.end()) {
4182 const SCEV *Old = It->second;
4186 if (Old != SymName && !hasOperand(Old, SymName))
4196 if (!isa<PHINode>(I) ||
4197 !isa<SCEVUnknown>(Old) ||
4198 (I != PN && Old == SymName)) {
4199 eraseValueFromMap(It->first);
4200 forgetMemoizedResults(Old);
4218 bool IgnoreOtherLoops =
true) {
4221 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4223 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4230 SeenLoopVariantSCEVUnknown =
true;
4238 SeenOtherLoops =
true;
4242 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4244 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4251 bool SeenLoopVariantSCEVUnknown =
false;
4252 bool SeenOtherLoops =
false;
4262 SCEVPostIncRewriter
Rewriter(L, SE);
4264 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4271 SeenLoopVariantSCEVUnknown =
true;
4279 SeenOtherLoops =
true;
4283 bool hasSeenLoopVariantSCEVUnknown() {
return SeenLoopVariantSCEVUnknown; }
4285 bool hasSeenOtherLoops() {
return SeenOtherLoops; }
4292 bool SeenLoopVariantSCEVUnknown =
false;
4293 bool SeenOtherLoops =
false;
4299 class SCEVBackedgeConditionFolder
4302 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
4304 bool IsPosBECond =
false;
4305 Value *BECond =
nullptr;
4310 "Both outgoing branches should not target same header!");
4317 SCEVBackedgeConditionFolder
Rewriter(L, BECond, IsPosBECond, SE);
4318 return Rewriter.visit(S);
4332 if (Res.hasValue()) {
4333 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4350 explicit SCEVBackedgeConditionFolder(
const Loop *L,
Value *BECond,
4353 IsPositiveBECond(IsPosBECond) {}
4359 Value *BackedgeCond =
nullptr;
4361 bool IsPositiveBECond;
4365 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(
Value *IC) {
4370 if (BackedgeCond == IC)
4378 static const SCEV *rewrite(
const SCEV *S,
const Loop *L,
4399 bool isValid() {
return Valid; }
4412 ScalarEvolution::proveNoWrapViaConstantRanges(
const SCEVAddRecExpr *AR) {
4426 if (NSWRegion.contains(AddRecRange))
4436 if (NUWRegion.contains(AddRecRange))
4462 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4463 IsNSW = OBO->hasNoSignedWrap();
4464 IsNUW = OBO->hasNoUnsignedWrap();
4468 explicit BinaryOp(
unsigned Opcode,
Value *LHS,
Value *RHS,
bool IsNSW =
false,
4470 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4485 switch (
Op->getOpcode()) {
4487 case Instruction::Sub:
4488 case Instruction::Mul:
4489 case Instruction::UDiv:
4490 case Instruction::URem:
4491 case Instruction::And:
4492 case Instruction::Or:
4493 case Instruction::AShr:
4494 case Instruction::Shl:
4495 return BinaryOp(
Op);
4497 case Instruction::Xor:
4498 if (
auto *RHSC = dyn_cast<ConstantInt>(
Op->getOperand(1)))
4501 if (RHSC->getValue().isSignMask())
4503 return BinaryOp(
Op);
4505 case Instruction::LShr:
4507 if (
ConstantInt *SA = dyn_cast<ConstantInt>(
Op->getOperand(1))) {
4514 if (SA->getValue().ult(BitWidth)) {
4518 return BinaryOp(Instruction::UDiv,
Op->getOperand(0),
X);
4521 return BinaryOp(
Op);
4523 case Instruction::ExtractValue: {
4524 auto *EVI = cast<ExtractValueInst>(
Op);
4525 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4532 if (
auto *
F = CI->getCalledFunction())
4533 switch (
F->getIntrinsicID()) {
4534 case Intrinsic::sadd_with_overflow:
4535 case Intrinsic::uadd_with_overflow:
4538 CI->getArgOperand(1));
4543 if (
F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4545 CI->getArgOperand(1),
true,
4549 CI->getArgOperand(1),
false,
4551 case Intrinsic::ssub_with_overflow:
4552 case Intrinsic::usub_with_overflow:
4554 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4555 CI->getArgOperand(1));
4558 if (
F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4559 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4560 CI->getArgOperand(1),
true,
4563 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4564 CI->getArgOperand(1),
false,
4566 case Intrinsic::smul_with_overflow:
4567 case Intrinsic::umul_with_overflow:
4568 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4569 CI->getArgOperand(1));
4606 if (Op == SymbolicPHI)
4611 if (SourceBits != NewBits)
4620 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4624 if (X != SymbolicPHI)
4626 Signed = SExt !=
nullptr;
4693 ScalarEvolution::createAddRecFromPHIWithCastsImpl(
const SCEVUnknown *SymbolicPHI) {
4699 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4701 assert(L &&
"Expecting an integer loop header phi");
4706 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
4707 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4708 Value *V = PN->getIncomingValue(i);
4709 if (L->contains(PN->getIncomingBlock(i))) {
4712 }
else if (BEValueV != V) {
4716 }
else if (!StartValueV) {
4718 }
else if (StartValueV != V) {
4719 StartValueV =
nullptr;
4723 if (!BEValueV || !StartValueV)
4726 const SCEV *BEValue = getSCEV(BEValueV);
4737 unsigned FoundIndex =
Add->getNumOperands();
4738 Type *TruncTy =
nullptr;
4740 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4743 if (FoundIndex == e) {
4748 if (FoundIndex ==
Add->getNumOperands())
4753 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
4754 if (i != FoundIndex)
4756 const SCEV *Accum = getAddExpr(Ops);
4814 const SCEV *StartVal = getSCEV(StartValueV);
4815 const SCEV *PHISCEV =
4816 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4825 if (
const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4829 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4842 auto getExtendedExpr = [&](
const SCEV *Expr,
4843 bool CreateSignExtend) ->
const SCEV * {
4845 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4846 const SCEV *ExtendedExpr =
4847 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->
getType())
4848 : getZeroExtendExpr(TruncatedExpr, Expr->
getType());
4849 return ExtendedExpr;
4857 auto PredIsKnownFalse = [&](
const SCEV *Expr,
4858 const SCEV *ExtendedExpr) ->
bool {
4859 return Expr != ExtendedExpr &&
4863 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4864 if (PredIsKnownFalse(StartVal, StartExtended)) {
4871 const SCEV *AccumExtended = getExtendedExpr(Accum,
true);
4872 if (PredIsKnownFalse(Accum, AccumExtended)) {
4877 auto AppendPredicate = [&](
const SCEV *Expr,
4878 const SCEV *ExtendedExpr) ->
void {
4879 if (Expr != ExtendedExpr &&
4881 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4887 AppendPredicate(StartVal, StartExtended);
4888 AppendPredicate(Accum, AccumExtended);
4896 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4897 std::make_pair(NewAR, Predicates);
4899 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4905 auto *PN = cast<PHINode>(SymbolicPHI->
getValue());
4911 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4912 if (
I != PredicatedSCEVRewrites.end()) {
4913 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4916 if (Rewrite.first == SymbolicPHI)
4920 assert(isa<SCEVAddRecExpr>(Rewrite.first) &&
"Expected an AddRec");
4921 assert(!(Rewrite.second).empty() &&
"Expected to find Predicates");
4926 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4931 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4949 auto areExprsEqual = [&](
const SCEV *Expr1,
const SCEV *Expr2) ->
bool {
4950 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4951 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4968 const SCEV *ScalarEvolution::createSimpleAffineAddRec(
PHINode *PN,
4970 Value *StartValueV) {
4973 assert(BEValueV && StartValueV);
4982 const SCEV *Accum =
nullptr;
4984 Accum = getSCEV(BO->RHS);
4986 Accum = getSCEV(BO->LHS);
4997 const SCEV *StartVal = getSCEV(StartValueV);
4998 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5000 ValueExprMap[SCEVCallbackVH(PN,
this)] = PHISCEV;
5005 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
5007 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5012 const SCEV *ScalarEvolution::createAddRecFromPHI(
PHINode *PN) {
5020 Value *BEValueV =
nullptr, *StartValueV =
nullptr;
5026 }
else if (BEValueV != V) {
5030 }
else if (!StartValueV) {
5032 }
else if (StartValueV != V) {
5033 StartValueV =
nullptr;
5037 if (!BEValueV || !StartValueV)
5040 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5041 "PHI node already processed?");
5045 if (
auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5049 const SCEV *SymbolicName = getUnknown(PN);
5050 ValueExprMap.insert({SCEVCallbackVH(PN,
this), SymbolicName});
5054 const SCEV *BEValue = getSCEV(BEValueV);
5064 unsigned FoundIndex =
Add->getNumOperands();
5065 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5066 if (
Add->getOperand(i) == SymbolicName)
5067 if (FoundIndex == e) {
5072 if (FoundIndex !=
Add->getNumOperands()) {
5075 for (
unsigned i = 0, e =
Add->getNumOperands(); i != e; ++i)
5076 if (i != FoundIndex)
5077 Ops.
push_back(SCEVBackedgeConditionFolder::rewrite(
Add->getOperand(i),
5079 const SCEV *Accum = getAddExpr(Ops);
5084 (isa<SCEVAddRecExpr>(Accum) &&
5085 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5102 if (
GEP->isInBounds() &&
GEP->getOperand(0) == PN) {
5105 const SCEV *
Ptr = getSCEV(
GEP->getPointerOperand());
5115 const SCEV *StartVal = getSCEV(StartValueV);
5116 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5121 forgetSymbolicName(PN, SymbolicName);
5122 ValueExprMap[SCEVCallbackVH(PN,
this)] = PHISCEV;
5127 if (
auto *BEInst = dyn_cast<Instruction>(BEValueV))
5129 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5144 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *
this);
5145 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *
this,
false);
5146 if (Shifted != getCouldNotCompute() &&
5147 Start != getCouldNotCompute()) {
5148 const SCEV *StartVal = getSCEV(StartValueV);
5149 if (Start == StartVal) {
5153 forgetSymbolicName(PN, SymbolicName);
5154 ValueExprMap[SCEVCallbackVH(PN,
this)] = Shifted;
5164 eraseValueFromMap(PN);
5173 struct CheckAvailable {
5174 bool TraversalDone =
false;
5175 bool Available =
true;
5177 const Loop *L =
nullptr;
5182 : L(L), BB(BB), DT(DT) {}
5184 bool setUnavailable() {
5185 TraversalDone =
true;
5190 bool follow(
const SCEV *S) {
5203 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5204 if (L && (ARLoop == L || ARLoop->
contains(L)))
5207 return setUnavailable();
5212 const auto *SU = cast<SCEVUnknown>(S);
5213 Value *V = SU->getValue();
5215 if (isa<Argument>(V))
5218 if (isa<Instruction>(V) && DT.
dominates(cast<Instruction>(V), BB))
5221 return setUnavailable();
5227 return setUnavailable();
5232 bool isDone() {
return TraversalDone; }
5235 CheckAvailable CA(L, BB, DT);
5239 return CA.Available;
5252 if (!LeftEdge.isSingleEdge())
5255 assert(RightEdge.isSingleEdge() &&
"Follows from LeftEdge.isSingleEdge()");
5275 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(
PHINode *PN) {
5277 [&](
BasicBlock *BB) {
return DT.isReachableFromEntry(BB); };
5299 assert(IDom &&
"At least the entry block should dominate PN");
5302 Value *Cond =
nullptr, *LHS =
nullptr, *RHS =
nullptr;
5304 if (BI && BI->isConditional() &&
5308 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5314 const SCEV *ScalarEvolution::createNodeForPHI(
PHINode *PN) {
5315 if (
const SCEV *S = createAddRecFromPHI(PN))
5318 if (
const SCEV *S = createNodeFromSelectLikePHI(PN))
5326 if (LI.replacementPreservesLCSSAForm(PN, V))
5330 return getUnknown(PN);
5339 if (
auto *CI = dyn_cast<ConstantInt>(Cond))
5340 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5345 return getUnknown(I);
5347 Value *LHS = ICI->getOperand(0);
5348 Value *RHS = ICI->getOperand(1);
5350 switch (ICI->getPredicate()) {
5359 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType())) {
5360 const SCEV *
LS = getNoopOrSignExtend(getSCEV(LHS), I->
getType());
5361 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->
getType());
5362 const SCEV *LA = getSCEV(TrueVal);
5363 const SCEV *
RA = getSCEV(FalseVal);
5364 const SCEV *LDiff = getMinusSCEV(LA, LS);
5365 const SCEV *RDiff = getMinusSCEV(RA, RS);
5367 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5368 LDiff = getMinusSCEV(LA, RS);
5369 RDiff = getMinusSCEV(RA, LS);
5371 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5382 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType())) {
5383 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5384 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->
getType());
5385 const SCEV *LA = getSCEV(TrueVal);
5386 const SCEV *
RA = getSCEV(FalseVal);
5387 const SCEV *LDiff = getMinusSCEV(LA, LS);
5388 const SCEV *RDiff = getMinusSCEV(RA, RS);
5390 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5391 LDiff = getMinusSCEV(LA, RS);
5392 RDiff = getMinusSCEV(RA, LS);
5394 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5399 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType()) &&
5400 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
5402 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5403 const SCEV *LA = getSCEV(TrueVal);
5404 const SCEV *
RA = getSCEV(FalseVal);
5405 const SCEV *LDiff = getMinusSCEV(LA, LS);
5406 const SCEV *RDiff = getMinusSCEV(RA, One);
5408 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5413 if (getTypeSizeInBits(LHS->
getType()) <= getTypeSizeInBits(I->
getType()) &&
5414 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->
isZero()) {
5416 const SCEV *
LS = getNoopOrZeroExtend(getSCEV(LHS), I->
getType());
5417 const SCEV *LA = getSCEV(TrueVal);
5418 const SCEV *
RA = getSCEV(FalseVal);
5419 const SCEV *LDiff = getMinusSCEV(LA, One);
5420 const SCEV *RDiff = getMinusSCEV(RA, LS);
5422 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5429 return getUnknown(I);
5437 return getUnknown(GEP);
5442 return getGEPExpr(GEP, IndexExprs);
5445 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(
const SCEV *S) {
5447 return C->getAPInt().countTrailingZeros();
5450 return std::min(GetMinTrailingZeros(
T->getOperand()),
5451 (
uint32_t)getTypeSizeInBits(
T->getType()));
5454 uint32_t OpRes = GetMinTrailingZeros(
E->getOperand());
5455 return OpRes == getTypeSizeInBits(
E->getOperand()->getType())
5456 ? getTypeSizeInBits(
E->getType())
5461 uint32_t OpRes = GetMinTrailingZeros(
E->getOperand());
5462 return OpRes == getTypeSizeInBits(
E->getOperand()->getType())
5463 ? getTypeSizeInBits(
E->getType())
5467 if (
const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5469 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5470 for (
unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5475 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5477 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5478 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5479 for (
unsigned i = 1, e = M->getNumOperands();
5480 SumOpRes != BitWidth && i != e; ++i)
5482 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5488 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5489 for (
unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5494 if (
const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5496 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5497 for (
unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5502 if (
const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5504 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5505 for (
unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5506 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5510 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5521 auto I = MinTrailingZerosCache.find(S);
5522 if (I != MinTrailingZerosCache.end())
5526 auto InsertPair = MinTrailingZerosCache.insert({S,
Result});
5527 assert(InsertPair.second &&
"Should insert a new key");
5528 return InsertPair.first->second;
5544 ScalarEvolution::getRangeRef(
const SCEV *S,
5545 ScalarEvolution::RangeSignHint SignHint) {
5547 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5552 if (I != Cache.
end())
5558 unsigned BitWidth = getTypeSizeInBits(S->
getType());
5563 uint32_t TZ = GetMinTrailingZeros(S);
5565 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5566 ConservativeResult =
5577 for (
unsigned i = 1, e =
Add->getNumOperands(); i != e; ++i)
5578 X = X.
add(getRangeRef(
Add->getOperand(i), SignHint));
5579 return setRange(
Add, SignHint, ConservativeResult.intersectWith(X));
5582 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5584 for (
unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5585 X = X.
multiply(getRangeRef(Mul->getOperand(i), SignHint));
5586 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5589 if (
const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5591 for (
unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5592 X = X.
smax(getRangeRef(SMax->getOperand(i), SignHint));
5593 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5596 if (
const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5598 for (
unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5599 X = X.
umax(getRangeRef(UMax->getOperand(i), SignHint));
5600 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5603 if (
const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5606 return setRange(UDiv, SignHint,
5607 ConservativeResult.intersectWith(X.
udiv(Y)));
5612 return setRange(ZExt, SignHint,
5613 ConservativeResult.intersectWith(X.
zeroExtend(BitWidth)));
5618 return setRange(SExt, SignHint,
5619 ConservativeResult.intersectWith(X.
signExtend(BitWidth)));
5624 return setRange(Trunc, SignHint,
5625 ConservativeResult.intersectWith(X.
truncate(BitWidth)));
5628 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5631 if (AddRec->hasNoUnsignedWrap())
5632 if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5633 if (!
C->getValue()->isZero())
5634 ConservativeResult = ConservativeResult.intersectWith(
5639 if (AddRec->hasNoSignedWrap()) {
5640 bool AllNonNeg =
true;
5641 bool AllNonPos =
true;
5642 for (
unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5644 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos =
false;
5647 ConservativeResult = ConservativeResult.intersectWith(
5651 ConservativeResult = ConservativeResult.intersectWith(
5653 APInt(BitWidth, 1)));
5657 if (AddRec->isAffine()) {
5658 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5659 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5660 getTypeSizeInBits(MaxBECount->
getType()) <= BitWidth) {
5661 auto RangeFromAffine = getRangeForAffineAR(
5662 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5664 if (!RangeFromAffine.isFullSet())
5665 ConservativeResult =
5666 ConservativeResult.intersectWith(RangeFromAffine);
5668 auto RangeFromFactoring = getRangeViaFactoring(
5669 AddRec->getStart(), AddRec->getStepRecurrence(*
this), MaxBECount,
5671 if (!RangeFromFactoring.isFullSet())
5672 ConservativeResult =
5673 ConservativeResult.intersectWith(RangeFromFactoring);
5677 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5680 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5684 ConservativeResult = ConservativeResult.intersectWith(MDRange.
getValue());
5690 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5693 if (Known.
One != ~Known.
Zero + 1)
5694 ConservativeResult =
5698 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5699 "generalize as needed!");
5702 ConservativeResult = ConservativeResult.intersectWith(
5708 if (
const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5710 if (PendingPhiRanges.insert(Phi).second) {
5712 for (
auto &
Op : Phi->operands()) {
5713 auto OpRange = getRangeRef(getSCEV(
Op), SignHint);
5714 RangeFromOps = RangeFromOps.
unionWith(OpRange);
5719 ConservativeResult = ConservativeResult.
intersectWith(RangeFromOps);
5720 bool Erased = PendingPhiRanges.erase(Phi);
5721 assert(Erased &&
"Failed to erase Phi properly?");
5726 return setRange(U, SignHint, std::move(ConservativeResult));
5729 return setRange(S, SignHint, std::move(ConservativeResult));
5738 const APInt &MaxBECount,
5739 unsigned BitWidth,
bool Signed) {
5742 if (Step == 0 || MaxBECount == 0)
5753 bool Descending = Signed && Step.
isNegative();
5777 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5778 : (StartUpper + std::move(Offset));
5783 if (StartRange.
contains(MovedBoundary))
5787 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5789 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5793 if (NewLower == NewUpper)
5797 return ConstantRange(std::move(NewLower), std::move(NewUpper));
5802 const SCEV *MaxBECount,
5803 unsigned BitWidth) {
5804 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5805 getTypeSizeInBits(MaxBECount->
getType()) <= BitWidth &&
5808 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->
getType());
5809 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5819 MaxBECountValue, BitWidth,
true);
5821 StartSRange, MaxBECountValue,
5826 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5827 MaxBECountValue, BitWidth,
false);
5830 return SR.intersectWith(UR);
5835 const SCEV *MaxBECount,
5836 unsigned BitWidth) {
5840 struct SelectPattern {
5841 Value *Condition =
nullptr;
5854 if (
auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5857 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5860 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5861 S = SA->getOperand(1);
5865 if (
auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5866 CastOp = SCast->getSCEVType();
5867 S = SCast->getOperand();
5873 const APInt *TrueVal, *FalseVal;
5877 Condition =
nullptr;
5881 TrueValue = *TrueVal;
5882 FalseValue = *FalseVal;
5891 TrueValue = TrueValue.
trunc(BitWidth);
5892 FalseValue = FalseValue.
trunc(BitWidth);
5895 TrueValue = TrueValue.
zext(BitWidth);
5896 FalseValue = FalseValue.
zext(BitWidth);
5899 TrueValue = TrueValue.
sext(BitWidth);
5900 FalseValue = FalseValue.
sext(BitWidth);
5909 bool isRecognized() {
return Condition !=
nullptr; }
5912 SelectPattern StartPattern(*
this, BitWidth, Start);
5913 if (!StartPattern.isRecognized())
5916 SelectPattern StepPattern(*
this, BitWidth, Step);
5917 if (!StepPattern.isRecognized())
5920 if (StartPattern.Condition != StepPattern.Condition) {
5941 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5943 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5964 bool ScalarEvolution::isSCEVExprNeverPoison(
const Instruction *I) {
5970 Loop *InnermostContainingLoop = LI.getLoopFor(I->
getParent());
5971 if (InnermostContainingLoop ==
nullptr ||
5994 for (
unsigned OpIndex = 0; OpIndex < I->
getNumOperands(); ++OpIndex) {
6000 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6001 bool AllOtherOpsLoopInvariant =
true;
6002 for (
unsigned OtherOpIndex = 0; OtherOpIndex < I->
getNumOperands();
6004 if (OtherOpIndex != OpIndex) {
6007 AllOtherOpsLoopInvariant =
false;
6012 if (AllOtherOpsLoopInvariant &&
6020 bool ScalarEvolution::isAddRecNeverPoison(
const Instruction *I,
const Loop *L) {
6022 if (isSCEVExprNeverPoison(I))
6049 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6061 bool LatchControlDependentOnPoison =
false;
6062 while (!PoisonStack.
empty() && !LatchControlDependentOnPoison) {
6065 for (
auto *PoisonUser : Poison->
users()) {
6067 if (Pushed.
insert(cast<Instruction>(PoisonUser)).second)
6068 PoisonStack.
push_back(cast<Instruction>(PoisonUser));
6069 }
else if (
auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6070 assert(BI->isConditional() &&
"Only possibility!");
6071 if (BI->getParent() == LatchBB) {
6072 LatchControlDependentOnPoison =
true;
6079 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6082 ScalarEvolution::LoopProperties
6083 ScalarEvolution::getLoopProperties(
const Loop *L) {
6084 using LoopProperties = ScalarEvolution::LoopProperties;
6086 auto Itr = LoopPropertiesCache.find(L);
6087 if (Itr == LoopPropertiesCache.end()) {
6089 if (
auto *
SI = dyn_cast<StoreInst>(I))
6090 return !
SI->isSimple();
6095 LoopProperties LP = {
true,
6099 for (
auto &I : *BB) {
6101 LP.HasNoAbnormalExits =
false;
6102 if (HasSideEffects(&I))
6103 LP.HasNoSideEffects =
false;
6104 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6108 auto InsertPair = LoopPropertiesCache.insert({L, LP});
6109 assert(InsertPair.second &&
"We just checked!");
6110 Itr = InsertPair.first;
6116 const SCEV *ScalarEvolution::createSCEV(
Value *V) {
6117 if (!isSCEVable(V->
getType()))
6118 return getUnknown(V);
6125 if (!DT.isReachableFromEntry(I->
getParent()))
6126 return getUnknown(V);
6127 }
else if (
ConstantInt *CI = dyn_cast<ConstantInt>(V))
6129 else if (isa<ConstantPointerNull>(V))
6131 else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6132 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6133 else if (!isa<ConstantExpr>(V))
6134 return getUnknown(V);
6138 switch (BO->Opcode) {
6149 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
6161 const SCEV *RHS = getSCEV(BO->RHS);
6164 const SCEV *LHS = getSCEV(BO->LHS);
6165 if (BO->Opcode == Instruction::Sub)
6166 AddOps.
push_back(getMinusSCEV(LHS, RHS, Flags));
6168 AddOps.
push_back(getAddExpr(LHS, RHS, Flags));
6173 if (BO->Opcode == Instruction::Sub)
6174 AddOps.
push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6180 NewBO->Opcode != Instruction::Sub)) {
6187 return getAddExpr(AddOps);
6190 case Instruction::Mul: {
6194 if (
auto *OpSCEV = getExistingSCEV(BO->Op)) {
6202 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6209 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6216 return getMulExpr(MulOps);
6218 case Instruction::UDiv:
6219 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6220 case Instruction::URem:
6221 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6222 case Instruction::Sub: {
6225 Flags = getNoWrapFlagsFromUB(BO->Op);
6226 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6228 case Instruction::And:
6231 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6233 return getSCEV(BO->RHS);
6234 if (CI->isMinusOne())
6235 return getSCEV(BO->LHS);
6236 const APInt &A = CI->getValue();
6247 0, &AC,
nullptr, &DT);
6249 APInt EffectiveMask =
6251 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.
Zero) & EffectiveMask)) {
6253 const SCEV *LHS = getSCEV(BO->LHS);
6254 const SCEV *ShiftedLHS =
nullptr;
6255 if (
auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6256 if (
auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6258 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6259 unsigned GCD = std::min(MulZeros, TZ);
6263 MulOps.
append(LHSMul->op_begin() + 1, LHSMul->op_end());
6264 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6265 ShiftedLHS = getUDivExpr(NewMul,
getConstant(DivAmt));
6269 ShiftedLHS = getUDivExpr(LHS, MulCount);
6272 getTruncateExpr(ShiftedLHS,
6274 BO->LHS->getType()),
6280 case Instruction::Or:
6287 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6288 const SCEV *LHS = getSCEV(BO->LHS);
6289 const APInt &CIVal = CI->getValue();
6290 if (GetMinTrailingZeros(LHS) >=
6293 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6306 case Instruction::Xor:
6307 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6309 if (CI->isMinusOne())
6310 return getNotSCEV(getSCEV(BO->LHS));
6316 if (
auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6317 if (
ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6318 if (LBO->getOpcode() == Instruction::And &&
6319 LCI->getValue() == CI->getValue())
6321 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6322 Type *UTy = BO->LHS->getType();
6323 const SCEV *Z0 =
Z->getOperand();
6325 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6330 if (CI->getValue().isMask(Z0TySize))
6331 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6336 APInt Trunc = CI->getValue().
trunc(Z0TySize);
6337 if (Trunc.
zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6339 return getZeroExtendExpr(getAddExpr(Z0,
getConstant(Trunc)),
6345 case Instruction::Shl:
6347 if (
ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6354 if (SA->getValue().uge(BitWidth))
6364 if (BO->Op && SA->getValue().ult(BitWidth - 1))
6365 Flags = getNoWrapFlagsFromUB(BO->Op);
6369 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6373 case Instruction::AShr: {
6379 Type *OuterTy = BO->LHS->getType();
6380 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6389 return getSCEV(BO->LHS);
6395 if (L && L->
getOpcode() == Instruction::Shl) {
6404 return getSignExtendExpr(
6405 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6408 if (ShlAmtCI && ShlAmtCI->
getValue().
ult(BitWidth)) {
6410 if (ShlAmt > AShrAmt) {
6417 return getSignExtendExpr(
6418 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6429 case Instruction::Trunc:
6432 case Instruction::ZExt:
6435 case Instruction::SExt:
6444 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6446 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6447 auto *
V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6453 case Instruction::BitCast:
6464 case Instruction::GetElementPtr:
6465 return createNodeForGEP(cast<GEPOperator>(U));
6467 case Instruction::PHI:
6468 return createNodeForPHI(cast<PHINode>(U));
6475 if (isa<Instruction>(U))
6476 return createNodeForSelectOrPHI(cast<Instruction>(U), U->
getOperand(0),
6481 case Instruction::Invoke:
6487 return getUnknown(V);
6510 return getSmallConstantTripCount(L, ExitingBB);
6518 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6520 "Exiting block must actually branch out of the loop!");
6527 const auto *MaxExitCount =
6534 return getSmallConstantTripMultiple(L, ExitingBB);
6555 assert(ExitingBlock &&
"Must pass a non-null exiting block!");
6557 "Exiting block must actually branch out of the loop!");
6558 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6559 if (ExitCount == getCouldNotCompute())
6563 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6570 return 1U << std::min((
uint32_t)31, GetMinTrailingZeros(TCExpr));
6589 return getBackedgeTakenInfo(L).getExact(ExitingBlock,
this);
6595 return getPredicatedBackedgeTakenInfo(L).getExact(L,
this, &Preds);
6599 return getBackedgeTakenInfo(L).getExact(L,
this);
6605 return getBackedgeTakenInfo(L).getMax(
this);
6609 return getBackedgeTakenInfo(L).isMaxOrZero(
this);
6622 const ScalarEvolution::BackedgeTakenInfo &
6623 ScalarEvolution::getPredicatedBackedgeTakenInfo(
const Loop *L) {
6624 auto &BTI = getBackedgeTakenInfo(L);
6625 if (BTI.hasFullInfo())
6628 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6631 return Pair.first->second;
6633 BackedgeTakenInfo
Result =
6634 computeBackedgeTakenCount(L,
true);
6636 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6639 const ScalarEvolution::BackedgeTakenInfo &
6640 ScalarEvolution::getBackedgeTakenInfo(
const Loop *L) {
6646 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator,
bool> Pair =
6647 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6649 return Pair.first->second;
6654 BackedgeTakenInfo
Result = computeBackedgeTakenCount(L);
6657 (void)NumTripCountsComputed;
6658 (void)NumTripCountsNotComputed;
6659 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6660 const SCEV *BEExact = Result.getExact(L,
this);
6661 if (BEExact != getCouldNotCompute()) {
6664 "Computed backedge-taken count isn't loop invariant for loop!");
6665 ++NumTripCountsComputed;
6667 else if (Result.getMax(
this) == getCouldNotCompute() &&
6670 ++NumTripCountsNotComputed;
6672 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6679 if (Result.hasAnyInfo()) {
6684 while (!Worklist.
empty()) {
6687 ValueExprMapType::iterator It =
6688 ValueExprMap.find_as(static_cast<Value *>(I));
6689 if (It != ValueExprMap.end()) {
6690 const SCEV *Old = It->second;
6698 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6699 eraseValueFromMap(It->first);
6700 forgetMemoizedResults(Old);
6702 if (
PHINode *PN = dyn_cast<PHINode>(I))
6703 ConstantEvolutionLoopExitValue.erase(PN);
6724 for (
auto *U : I->
users())
6725 if (
auto *I = dyn_cast<Instruction>(U)) {
6726 auto *LoopForUser = LI.getLoopFor(I->
getParent());
6727 if (LoopForUser && L->
contains(LoopForUser) &&
6728 Discovered.
insert(I).second)
6739 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6744 auto RemoveLoopFromBackedgeMap =
6746 auto BTCPos = Map.
find(L);
6747 if (BTCPos != Map.
end()) {
6748 BTCPos->second.clear();
6758 while (!LoopWorklist.
empty()) {
6761 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6762 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6765 for (
auto I = PredicatedSCEVRewrites.begin();
6766 I != PredicatedSCEVRewrites.end();) {
6767 std::pair<const SCEV *, const Loop *> Entry = I->first;
6768 if (Entry.second == CurrL)
6769 PredicatedSCEVRewrites.erase(I++);
6774 auto LoopUsersItr = LoopUsers.find(CurrL);
6775 if (LoopUsersItr != LoopUsers.end()) {
6776 for (
auto *S : LoopUsersItr->second)
6777 forgetMemoizedResults(S);
6778 LoopUsers.erase(LoopUsersItr);
6784 while (!Worklist.
empty()) {
6786 if (!Visited.
insert(I).second)
6790 ValueExprMap.find_as(static_cast<Value *>(I));
6791 if (It != ValueExprMap.end()) {
6792 eraseValueFromMap(It->first);
6793 forgetMemoizedResults(It->second);
6794 if (
PHINode *PN = dyn_cast<PHINode>(I))
6795 ConstantEvolutionLoopExitValue.erase(PN);
6801 LoopPropertiesCache.erase(CurrL);
6804 LoopWorklist.
append(CurrL->begin(), CurrL->end());
6823 while (!Worklist.
empty()) {
6825 if (!Visited.
insert(I).second)
6829 ValueExprMap.find_as(static_cast<Value *>(I));
6830 if (It != ValueExprMap.end()) {
6831 eraseValueFromMap(It->first);
6832 forgetMemoizedResults(It->second);
6833 if (
PHINode *PN = dyn_cast<PHINode>(I))
6834 ConstantEvolutionLoopExitValue.erase(PN);
6851 if (!isComplete() || ExitNotTaken.empty())
6862 for (
auto &ENT : ExitNotTaken) {
6863 const SCEV *BECount = ENT.ExactNotTaken;
6866 "We should only have known counts for exiting blocks that dominate " 6871 if (Preds && !ENT.hasAlwaysTruePredicate())
6872 Preds->
add(ENT.Predicate.get());
6874 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6875 "Predicate should be always true!");
6883 ScalarEvolution::BackedgeTakenInfo::getExact(
BasicBlock *ExitingBlock,
6885 for (
auto &ENT : ExitNotTaken)
6886 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6887 return ENT.ExactNotTaken;
6894 ScalarEvolution::BackedgeTakenInfo::getMax(
ScalarEvolution *SE)
const {
6895 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
6896 return !ENT.hasAlwaysTruePredicate();
6899 if (
any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6902 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6903 "No point in having a non-constant max backedge taken count!");
6907 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(
ScalarEvolution *SE)
const {
6908 auto PredicateNotAlwaysTrue = [](
const ExitNotTakenInfo &ENT) {
6909 return !ENT.hasAlwaysTruePredicate();
6911 return MaxOrZero && !
any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6914 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(
const SCEV *S,
6920 for (
auto &ENT : ExitNotTaken)
6928 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *
E)
6929 : ExactNotTaken(E), MaxNotTaken(E) {
6930 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6931 isa<SCEVConstant>(MaxNotTaken)) &&
6932 "No point in having a non-constant max backedge taken count!");
6935 ScalarEvolution::ExitLimit::ExitLimit(
6936 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
6938 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6939 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6940 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6941 "Exact is not allowed to be less precise than Max");
6942 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6943 isa<SCEVConstant>(MaxNotTaken)) &&
6944 "No point in having a non-constant max backedge taken count!");
6945 for (
auto *PredSet : PredSetList)
6946 for (
auto *
P : *PredSet)
6950 ScalarEvolution::ExitLimit::ExitLimit(
6951 const SCEV *E,
const SCEV *M,
bool MaxOrZero,
6953 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6954 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6955 isa<SCEVConstant>(MaxNotTaken)) &&
6956 "No point in having a non-constant max backedge taken count!");
6959 ScalarEvolution::ExitLimit::ExitLimit(
const SCEV *E,
const SCEV *M,
6961 : ExitLimit(E, M, MaxOrZero,
None) {
6962 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6963 isa<SCEVConstant>(MaxNotTaken)) &&
6964 "No point in having a non-constant max backedge taken count!");
6969 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6972 bool Complete,
const SCEV *MaxCount,
bool MaxOrZero)
6973 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6974 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6976 ExitNotTaken.reserve(ExitCounts.size());
6978 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6979 [&](
const EdgeExitInfo &EEI) {
6981 const ExitLimit &EL = EEI.second;
6982 if (EL.Predicates.empty())
6983 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
nullptr);
6986 for (
auto *Pred : EL.Predicates)
6987 Predicate->add(Pred);
6989 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6991 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6992 "No point in having a non-constant max backedge taken count!");
6997 ExitNotTaken.clear();
7001 ScalarEvolution::BackedgeTakenInfo
7002 ScalarEvolution::computeBackedgeTakenCount(
const Loop *L,
7003 bool AllowPredicates) {
7007 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7010 bool CouldComputeBECount =
true;
7012 const SCEV *MustExitMaxBECount =
nullptr;
7013 const SCEV *MayExitMaxBECount =
nullptr;
7014 bool MustExitMaxOrZero =
false;
7019 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
7021 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7023 assert((AllowPredicates || EL.Predicates.empty()) &&
7024 "Predicated exit limit when predicates are not allowed!");
7028 if (EL.ExactNotTaken == getCouldNotCompute())
7031 CouldComputeBECount =
false;
7045 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7046 DT.dominates(ExitBB, Latch)) {
7047 if (!MustExitMaxBECount) {
7048 MustExitMaxBECount = EL.MaxNotTaken;
7049 MustExitMaxOrZero = EL.MaxOrZero;
7051 MustExitMaxBECount =
7052 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7054 }
else if (MayExitMaxBECount != getCouldNotCompute()) {
7055 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7056 MayExitMaxBECount = EL.MaxNotTaken;
7059 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7063 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7064 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7067 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.
size() == 1);
7068 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7069 MaxBECount, MaxOrZero);
7072 ScalarEvolution::ExitLimit
7073 ScalarEvolution::computeExitLimit(
const Loop *L,
BasicBlock *ExitingBlock,
7074 bool AllowPredicates) {
7075 assert(L->
contains(ExitingBlock) &&
"Exit count for non-loop block?");
7079 if (!Latch || !DT.dominates(ExitingBlock, Latch))
7080 return getCouldNotCompute();
7084 if (
BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7085 assert(BI->isConditional() &&
"If unconditional, it can't be in loop!");
7086 bool ExitIfTrue = !L->
contains(BI->getSuccessor(0));
7088 "It should have one successor in loop and one exit block!");
7090 return computeExitLimitFromCond(
7091 L, BI->getCondition(), ExitIfTrue,
7092 IsOnlyExit, AllowPredicates);
7101 return getCouldNotCompute();
7104 assert(Exit &&
"Exiting block must have at least one exit");
7105 return computeExitLimitFromSingleExitSwitch(L,
SI, Exit,
7109 return getCouldNotCompute();
7112 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7113 const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7114 bool ControlsExit,
bool AllowPredicates) {
7115 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7116 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7117 ControlsExit, AllowPredicates);
7122 bool ExitIfTrue,
bool ControlsExit,
7123 bool AllowPredicates) {
7125 (void)this->ExitIfTrue;
7126 (void)this->AllowPredicates;
7128 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7129 this->AllowPredicates == AllowPredicates &&
7130 "Variance in assumed invariant key components!");
7131 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7132 if (Itr == TripCountMap.end())
7137 void ScalarEvolution::ExitLimitCache::insert(
const Loop *L,
Value *ExitCond,
7140 bool AllowPredicates,
7141 const ExitLimit &EL) {
7142 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7143 this->AllowPredicates == AllowPredicates &&
7144 "Variance in assumed invariant key components!");
7146 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7147 assert(InsertResult.second &&
"Expected successful insertion!");
7152 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7153 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7154 bool ControlsExit,
bool AllowPredicates) {
7157 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7160 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7161 ControlsExit, AllowPredicates);
7162 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7166 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7167 ExitLimitCacheTy &Cache,
const Loop *L,
Value *ExitCond,
bool ExitIfTrue,
7168 bool ControlsExit,
bool AllowPredicates) {
7171 if (BO->getOpcode() == Instruction::And) {
7173 bool EitherMayExit = !ExitIfTrue;
7174 ExitLimit EL0 = computeExitLimitFromCondCached(
7175 Cache, L, BO->getOperand(0), ExitIfTrue,
7176 ControlsExit && !EitherMayExit, AllowPredicates);
7177 ExitLimit EL1 = computeExitLimitFromCondCached(
7178 Cache, L, BO->getOperand(1), ExitIfTrue,
7179 ControlsExit && !EitherMayExit, AllowPredicates);
7180 const SCEV *BECount = getCouldNotCompute();
7181 const SCEV *MaxBECount = getCouldNotCompute();
7182 if (EitherMayExit) {
7185 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7186 EL1.ExactNotTaken == getCouldNotCompute())
7187 BECount = getCouldNotCompute();
7190 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7191 if (EL0.MaxNotTaken == getCouldNotCompute())
7192 MaxBECount = EL1.MaxNotTaken;
7193 else if (EL1.MaxNotTaken == getCouldNotCompute())
7194 MaxBECount = EL0.MaxNotTaken;
7197 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7201 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7202 MaxBECount = EL0.MaxNotTaken;
7203 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7204 BECount = EL0.ExactNotTaken;
7212 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7213 !isa<SCEVCouldNotCompute>(BECount))
7214 MaxBECount =
getConstant(getUnsignedRangeMax(BECount));
7216 return ExitLimit(BECount, MaxBECount,
false,
7217 {&EL0.Predicates, &EL1.Predicates});
7219 if (BO->getOpcode() == Instruction::Or) {
7221 bool EitherMayExit = ExitIfTrue;
7222 ExitLimit EL0 = computeExitLimitFromCondCached(
7223 Cache, L, BO->getOperand(0), ExitIfTrue,
7224 ControlsExit && !EitherMayExit, AllowPredicates);
7225 ExitLimit EL1 = computeExitLimitFromCondCached(
7226 Cache, L, BO->getOperand(1), ExitIfTrue,
7227 ControlsExit && !EitherMayExit, AllowPredicates);
7228 const SCEV *BECount = getCouldNotCompute();
7229 const SCEV *MaxBECount = getCouldNotCompute();
7230 if (EitherMayExit) {
7233 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7234 EL1.ExactNotTaken == getCouldNotCompute())
7235 BECount = getCouldNotCompute();
7238 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7239 if (EL0.MaxNotTaken == getCouldNotCompute())
7240 MaxBECount = EL1.MaxNotTaken;
7241 else if (EL1.MaxNotTaken == getCouldNotCompute())
7242 MaxBECount = EL0.MaxNotTaken;
7245 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7249 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7250 MaxBECount = EL0.MaxNotTaken;
7251 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7252 BECount = EL0.ExactNotTaken;
7255 return ExitLimit(BECount, MaxBECount,
false,
7256 {&EL0.Predicates, &EL1.Predicates});
7262 if (
ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7264 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7265 if (EL.hasFullInfo() || !AllowPredicates)
7269 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7277 if (
ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7278 if (ExitIfTrue == !CI->getZExtValue())
7280 return getCouldNotCompute();
7283 return getZero(CI->getType());
7287 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7290 ScalarEvolution::ExitLimit
7291 ScalarEvolution::computeExitLimitFromICmp(
const Loop *L,
7295 bool AllowPredicates) {
7308 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7309 if (ItCnt.hasAnyInfo())
7317 LHS = getSCEVAtScope(LHS, L);
7318 RHS = getSCEVAtScope(RHS, L);
7329 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7333 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7334 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7335 if (AddRec->getLoop() == L) {
7340 const SCEV *
Ret = AddRec->getNumIterationsInRange(CompRange, *
this);
7341 if (!isa<SCEVCouldNotCompute>(Ret))
return Ret;
7347 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7349 if (EL.hasAnyInfo())
return EL;
7354 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7355 if (EL.hasAnyInfo())
return EL;
7361 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7363 if (EL.hasAnyInfo())
return EL;
7370 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7372 if (EL.hasAnyInfo())
return EL;
7379 auto *ExhaustiveCount =
7380 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7382 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7383 return ExhaustiveCount;
7385 return computeShiftCompareExitLimit(ExitCond->
getOperand(0),
7389 ScalarEvolution::ExitLimit
7390 ScalarEvolution::computeExitLimitFromSingleExitSwitch(
const Loop *L,
7393 bool ControlsExit) {
7398 return getCouldNotCompute();
7401 "Default case must not exit the loop!");
7406 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7407 if (EL.hasAnyInfo())
7410 return getCouldNotCompute();
7418 assert(isa<SCEVConstant>(Val) &&
7419 "Evaluation of SCEV at constant didn't fold correctly?");
7420 return cast<SCEVConstant>(Val)->getValue();
7425 ScalarEvolution::ExitLimit
7426 ScalarEvolution::computeLoadConstantCompareExitLimit(
7431 if (LI->
isVolatile())
return getCouldNotCompute();
7436 if (!GEP)
return getCouldNotCompute();
7443 !cast<Constant>(GEP->
getOperand(1))->isNullValue())
7444 return getCouldNotCompute();
7447 Value *VarIdx =
nullptr;
7448 std::vector<Constant*> Indexes;
7449 unsigned VarIdxNum = 0;
7452 Indexes.push_back(CI);
7453 }
else if (!isa<ConstantInt>(GEP->
getOperand(i))) {
7454 if (VarIdx)
return getCouldNotCompute();
7457 Indexes.push_back(
nullptr);
7462 return getCouldNotCompute();
7466 const SCEV *Idx = getSCEV(VarIdx);
7467 Idx = getSCEVAtScope(Idx, L);
7473 !isa<SCEVConstant>(IdxExpr->
getOperand(0)) ||
7475 return getCouldNotCompute();
7478 for (
unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7480 cast<IntegerType>(IdxExpr->
getType()), IterationNum);
7484 Indexes[VarIdxNum] = Val;
7492 if (!isa<ConstantInt>(Result))
break;
7493 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7494 ++NumArrayLenItCounts;
7498 return getCouldNotCompute();
7501 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7505 return getCouldNotCompute();
7509 return getCouldNotCompute();
7513 return getCouldNotCompute();
7517 auto MatchPositiveShift =
7524 OutOpCode = Instruction::LShr;
7526 OutOpCode = Instruction::AShr;
7528 OutOpCode = Instruction::Shl;
7543 auto MatchShiftRecurrence =
7560 if (MatchPositiveShift(LHS, V, OpC)) {
7561 PostShiftOpCode = OpC;
7567 if (!PNOut || PNOut->getParent() != L->
getHeader())
7570 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7576 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7583 (!PostShiftOpCode.
hasValue() || *PostShiftOpCode == OpCodeOut);
7588 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7589 return getCouldNotCompute();
7605 case Instruction::AShr: {
7611 auto *
Ty = cast<IntegerType>(RHS->
getType());
7617 return getCouldNotCompute();
7621 case Instruction::LShr:
7622 case Instruction::Shl:
7632 "Otherwise cannot be an operand to a branch instruction");
7634 if (
Result->isZeroValue()) {
7635 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
7636 const SCEV *UpperBound =
7638 return ExitLimit(getCouldNotCompute(), UpperBound,
false);
7641 return getCouldNotCompute();
7647 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7648 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7652 if (
const CallInst *CI = dyn_cast<CallInst>(I))
7653 if (
const Function *
F = CI->getCalledFunction())
7664 if (isa<PHINode>(I)) {
7688 if (isa<Constant>(
Op))
continue;
7698 P = PHIMap.
lookup(OpInst);
7707 if (PHI && PHI != P)
7724 if (
PHINode *PN = dyn_cast<PHINode>(I))
7741 if (
Constant *
C = dyn_cast<Constant>(V))
return C;
7743 if (!I)
return nullptr;
7754 if (isa<PHINode>(I))
return nullptr;
7762 if (!Operands[i])
return nullptr;
7767 if (!C)
return nullptr;
7771 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
7773 Operands[1], DL, TLI);
7774 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
7795 if (IncomingVal != CurrentVal) {
7798 IncomingVal = CurrentVal;
7810 ScalarEvolution::getConstantEvolutionLoopExitValue(
PHINode *PN,
7813 auto I = ConstantEvolutionLoopExitValue.find(PN);
7814 if (I != ConstantEvolutionLoopExitValue.end())
7818 return ConstantEvolutionLoopExitValue[PN] =
nullptr;
7820 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7824 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
7832 CurrentIterVals[&PHI] = StartCST;
7834 if (!CurrentIterVals.
count(PN))
7835 return RetVal =
nullptr;
7841 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7844 unsigned IterationNum = 0;
7846 for (; ; ++IterationNum) {
7847 if (IterationNum == NumIterations)
7848 return RetVal = CurrentIterVals[PN];
7857 NextIterVals[PN] = NextPHI;
7859 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7865 for (
const auto &I : CurrentIterVals) {
7867 if (!PHI || PHI == PN || PHI->
getParent() != Header)
continue;
7872 for (
const auto &I : PHIsToCompute) {
7874 Constant *&NextPHI = NextIterVals[PHI];
7879 if (NextPHI != I.second)
7880 StoppedEvolving =
false;
7885 if (StoppedEvolving)
7886 return RetVal = CurrentIterVals[PN];
7888 CurrentIterVals.swap(NextIterVals);
7892 const SCEV *ScalarEvolution::computeExitCountExhaustively(
const Loop *L,
7896 if (!PN)
return getCouldNotCompute();
7904 assert(PN->
getParent() == Header &&
"Can't evaluate PHI not in loop header!");
7907 assert(Latch &&
"Should follow from NumIncomingValues == 2!");
7911 CurrentIterVals[&PHI] = StartCST;
7913 if (!CurrentIterVals.
count(PN))
7914 return getCouldNotCompute();
7921 for (
unsigned IterationNum = 0; IterationNum !=
MaxIterations;++IterationNum){
7922 auto *CondVal = dyn_cast_or_null<ConstantInt>(
7926 if (!CondVal)
return getCouldNotCompute();
7928 if (CondVal->getValue() == uint64_t(ExitWhen)) {
7929 ++NumBruteForceTripCountsComputed;
7940 for (
const auto &I : CurrentIterVals) {
7942 if (!PHI || PHI->
getParent() != Header)
continue;
7945 for (
PHINode *PHI : PHIsToCompute) {
7946 Constant *&NextPHI = NextIterVals[PHI];
7947 if (NextPHI)
continue;
7949 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7952 CurrentIterVals.swap(NextIterVals);
7956 return getCouldNotCompute();
7963 for (
auto &
LS : Values)
7965 return LS.second ?
LS.second : V;
7967 Values.emplace_back(L,
nullptr);
7970 const SCEV *
C = computeSCEVAtScope(V, L);
7971 for (
auto &
LS :
reverse(ValuesAtScopes[V]))
7972 if (
LS.first == L) {
7984 switch (static_cast<SCEVTypes>(V->
getSCEVType())) {
7989 return cast<SCEVConstant>(V)->getValue();
8014 unsigned AS = PTy->getAddressSpace();
8020 if (!C2)
return nullptr;
8038 if (PTy->getElementType()->isStructTy())
8078 const SCEV *ScalarEvolution::computeSCEVAtScope(
const SCEV *V,
const Loop *L) {
8079 if (isa<SCEVConstant>(V))
return V;
8083 if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8084 if (
Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8087 if (
PHINode *PN = dyn_cast<PHINode>(I))
8093 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8095 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8099 if (BTCC->getValue()->isZero()) {
8100 Value *InitValue =
nullptr;
8101 bool MultipleInitValues =
false;
8107 MultipleInitValues =
true;
8111 if (!MultipleInitValues && InitValue)
8112 return getSCEV(InitValue);
8119 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8120 if (RV)
return getSCEV(RV);
8130 bool MadeImprovement =
false;
8143 const SCEV *OrigV = getSCEV(
Op);
8144 const SCEV *OpV = getSCEVAtScope(OrigV, L);
8145 MadeImprovement |= OrigV != OpV;
8158 if (MadeImprovement) {
8161 if (
const CmpInst *CI = dyn_cast<CmpInst>(I))
8163 Operands[1], DL, &TLI);
8164 else if (
const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8165 if (!LI->isVolatile())
8182 for (
unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8183 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8184 if (OpAtScope != Comm->getOperand(i)) {
8188 Comm->op_begin()+i);
8191 for (++i; i != e; ++i) {
8192 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8193 NewOps.push_back(OpAtScope);
8195 if (isa<SCEVAddExpr>(Comm))
8196 return getAddExpr(NewOps);
8197 if (isa<SCEVMulExpr>(Comm))
8198 return getMulExpr(NewOps);
8199 if (isa<SCEVSMaxExpr>(Comm))
8200 return getSMaxExpr(NewOps);
8201 if (isa<SCEVUMaxExpr>(Comm))
8202 return getUMaxExpr(NewOps);
8210 if (
const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8211 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8212 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8213 if (LHS == Div->getLHS() && RHS == Div->getRHS())
8215 return getUDivExpr(LHS, RHS);
8220 if (
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8224 for (
unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8225 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8226 if (OpAtScope == AddRec->getOperand(i))
8232 AddRec->op_begin()+i);
8234 for (++i; i != e; ++i)
8235 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8237 const SCEV *FoldedRec =
8238 getAddRecExpr(NewOps, AddRec->getLoop(),
8251 if (!AddRec->getLoop()->contains(L)) {
8254 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8255 if (BackedgeTakenCount == getCouldNotCompute())
return AddRec;
8258 return AddRec->evaluateAtIteration(BackedgeTakenCount, *
this);
8265 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8266 if (Op == Cast->getOperand())
8268 return getZeroExtendExpr(Op, Cast->
getType());
8272 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8273 if (Op == Cast->getOperand())
8275 return getSignExtendExpr(Op, Cast->
getType());
8279 const SCEV *
Op = getSCEVAtScope(Cast->getOperand(), L);
8280 if (Op == Cast->getOperand())
8282 return getTruncateExpr(Op, Cast->
getType());
8289 return getSCEVAtScope(getSCEV(V), L);
8292 const SCEV *ScalarEvolution::stripInjectiveFunctions(
const SCEV *S)
const {
8294 return stripInjectiveFunctions(ZExt->getOperand());
8296 return stripInjectiveFunctions(SExt->getOperand());
8312 assert(A != 0 &&
"A must be non-zero.");
8358 if (!LC || !MC || !NC)
8361 uint32_t BitWidth = LC->getAPInt().getBitWidth();
8362 const APInt &L = LC->getAPInt();
8363 const APInt &M = MC->getAPInt();
8364 const APInt &
N = NC->getAPInt();
8365 APInt Two(BitWidth, 2);
8382 SqrtTerm -= 4 * (A *
C);
8395 APInt NegB = -std::move(B);
8396 APInt TwoA = std::move(A);
8408 return std::make_pair(cast<SCEVConstant>(SE.
getConstant(Solution1)),
8412 ScalarEvolution::ExitLimit
8413 ScalarEvolution::howFarToZero(
const SCEV *V,
const Loop *L,
bool ControlsExit,
8414 bool AllowPredicates) {
8425 if (
C->getValue()->isZero())
return C;
8426 return getCouldNotCompute();
8432 if (!AddRec && AllowPredicates)
8436 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8438 if (!AddRec || AddRec->
getLoop() != L)
8439 return getCouldNotCompute();
8450 if (!CB->getZExtValue())
8459 return ExitLimit(R1, R1,
false, Predicates);
8462 return getCouldNotCompute();
8467 return getCouldNotCompute();
8491 if (!StepC || StepC->getValue()->isZero())
8492 return getCouldNotCompute();
8500 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8505 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8506 APInt MaxBECount = getUnsignedRangeMax(Distance);
8517 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8524 return ExitLimit(Distance,
getConstant(MaxBECount),
false, Predicates);
8533 loopHasNoAbnormalExits(AddRec->
getLoop())) {
8535 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8537 Exact == getCouldNotCompute()
8540 return ExitLimit(Exact, Max,
false, Predicates);
8545 getNegativeSCEV(Start), *
this);
8546 const SCEV *M = E == getCouldNotCompute()
8549 return ExitLimit(E, M,
false, Predicates);
8552 ScalarEvolution::ExitLimit
8553 ScalarEvolution::howFarToNonZero(
const SCEV *V,
const Loop *L) {
8561 if (!
C->getValue()->isZero())
8563 return getCouldNotCompute();
8568 return getCouldNotCompute();
8571 std::pair<BasicBlock *, BasicBlock *>
8572 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(
BasicBlock *BB) {
8582 if (
Loop *L = LI.getLoopFor(BB))
8585 return {
nullptr,
nullptr};
8594 if (A == B)
return true;
8600 return A->
isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8605 if (
const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8606 if (
const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8607 if (
const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8608 if (
const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8609 if (ComputesEqualValues(AI, BI))
8617 const SCEV *&LHS,
const SCEV *&RHS,
8619 bool Changed =
false;
8626 if (
const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8628 if (
const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8631 RHSC->getValue())->isNullValue())
8632 goto trivially_false;
8634 goto trivially_true;
8656 if (
const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8657 const APInt &
RA = RC->getAPInt();
8659 bool SimplifiedByConstantRange =
false;
8664 goto trivially_true;
8666 goto trivially_false;
8675 Changed = SimplifiedByConstantRange =
true;
8679 if (!SimplifiedByConstantRange) {
8687 if (
const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8689 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8690 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8691 ME->getOperand(0)->isAllOnesValue()) {
8692 RHS = AE->getOperand(1);
8693 LHS = ME->getOperand(1);
8735 goto trivially_true;
8737 goto trivially_false;
8744 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8749 }
else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8757 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8762 }
else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8770 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8775 }
else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8782 if (!getUnsignedRangeMin(RHS).isMinValue()) {
8786 }
else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8802 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8820 return getSignedRangeMax(S).isNegative();
8824 return getSignedRangeMin(S).isStrictlyPositive();
8828 return !getSignedRangeMin(S).isNegative();
8832 return !getSignedRangeMax(S).isStrictlyPositive();
8839 std::pair<const SCEV *, const SCEV *>
8842 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *
this);
8843 if (Start == getCouldNotCompute())
8844 return { Start, Start };
8846 const SCEV *
PostInc = SCEVPostIncRewriter::rewrite(S, L, *
this);
8847 assert(PostInc != getCouldNotCompute() &&
"Unexpected could not compute");
8848 return { Start, PostInc };
8852 const SCEV *LHS,
const SCEV *RHS) {
8855 getUsedLoops(LHS, LoopsUsed);
8856 getUsedLoops(RHS, LoopsUsed);
8858 if (LoopsUsed.
empty())
8863 for (
auto *L1 : LoopsUsed)
8864 for (
auto *L2 : LoopsUsed)
8865 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
8866 DT.dominates(L2->getHeader(), L1->getHeader())) &&
8867 "Domination relationship is not a linear order");
8871 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
8872 [&](
const Loop *L1,
const Loop *L2) {
8873 return DT.properlyDominates(L1->
getHeader(), L2->getHeader());
8877 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
8879 if (SplitLHS.first == getCouldNotCompute())
8881 assert (SplitLHS.second != getCouldNotCompute() &&
"Unexpected CNC");
8883 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
8885 if (SplitRHS.first == getCouldNotCompute())
8887 assert (SplitRHS.second != getCouldNotCompute() &&
"Unexpected CNC");
8891 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
8892 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
8895 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
8896 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
8901 const SCEV *LHS,
const SCEV *RHS) {
8903 (void)SimplifyICmpOperands(Pred, LHS, RHS);
8905 if (isKnownViaInduction(Pred, LHS, RHS))
8908 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8912 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8919 return isLoopEntryGuardedByCond(L, Pred, LHS->
getStart(), RHS) &&
8920 isLoopBackedgeGuardedByCond(L, Pred, LHS->
getPostIncExpr(*
this), RHS);
8926 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8931 bool IncreasingSwapped;
8932 bool ResultSwapped = isMonotonicPredicateImpl(
8935 assert(Result == ResultSwapped &&
"should be able to analyze both!");
8937 assert(Increasing == !IncreasingSwapped &&
8938 "monotonicity should flip as we flip the predicate");
8944 bool ScalarEvolution::isMonotonicPredicateImpl(
const SCEVAddRecExpr *LHS,
8986 if (isKnownNonPositive(Step)) {
9002 const SCEV *&InvariantRHS) {
9014 if (!ArLHS || ArLHS->
getLoop() != L)
9018 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9041 if (!isLoopBackedgeGuardedByCond(L,
P, LHS, RHS))
9044 InvariantPred = Pred;
9050 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9070 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9071 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9075 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9077 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9085 auto MatchBinaryAddToConst =
9088 const SCEV *NonConstOp, *ConstOp;
9091 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9092 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9095 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9096 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9159 bool ScalarEvolution::isImpliedViaGuard(
BasicBlock *BB,
9161 const SCEV *LHS,
const SCEV *RHS) {
9170 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9172 isImpliedCond(Pred, LHS, RHS, Condition,
false);
9182 const SCEV *LHS,
const SCEV *RHS) {
9185 if (!L)
return true;
9187 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9196 if (LoopContinuePredicate && LoopContinuePredicate->
isConditional() &&
9197 isImpliedCond(Pred, LHS, RHS,
9204 if (WalkingBEDominatingConds)
9210 const auto &BETakenInfo = getBackedgeTakenInfo(L);
9211 const SCEV *LatchBECount = BETakenInfo.getExact(Latch,
this);
9212 if (LatchBECount != getCouldNotCompute()) {
9218 const SCEV *LoopCounter =
9219 getAddRecExpr(getZero(Ty), getOne(Ty), L,
NoWrapFlags);
9226 for (
auto &AssumeVH : AC.assumptions()) {
9229 auto *CI = cast<CallInst>(AssumeVH);
9233 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0),
false))
9240 if (!DT.isReachableFromEntry(L->
getHeader()))
9243 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9247 DTN != HeaderDTN; DTN = DTN->
getIDom()) {
9248 assert(DTN &&
"should reach the loop header before reaching the root!");
9251 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9259 if (!ContinuePredicate || !ContinuePredicate->
isConditional())
9273 assert(DT.dominates(DominatingEdge, Latch) &&
"should be!");
9275 if (isImpliedCond(Pred, LHS, RHS, Condition,
9287 const SCEV *LHS,
const SCEV *RHS) {
9290 if (!L)
return false;
9293 assert(isAvailableAtLoopEntry(LHS, L) &&
9294 "LHS is not available at Loop Entry");
9295 assert(isAvailableAtLoopEntry(RHS, L) &&
9296 "RHS is not available at Loop Entry");
9298 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9307 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9308 bool ProvedNonStrictComparison =
false;
9309 bool ProvedNonEquality =
false;
9311 if (ProvingStrictComparison) {
9312 ProvedNonStrictComparison =
9313 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9316 if (ProvedNonStrictComparison && ProvedNonEquality)
9321 auto ProveViaGuard = [&](
BasicBlock *Block) {
9322 if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9324 if (ProvingStrictComparison) {
9325 if (!ProvedNonStrictComparison)
9326 ProvedNonStrictComparison =
9327 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9328 if (!ProvedNonEquality)
9331 if (ProvedNonStrictComparison && ProvedNonEquality)
9338 auto ProveViaCond = [&](
Value *Condition,
bool Inverse) {
9339 if (isImpliedCond(Pred, LHS, RHS, Condition,
Inverse))
9341 if (ProvingStrictComparison) {
9342 if (!ProvedNonStrictComparison)
9343 ProvedNonStrictComparison =
9344 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition,
Inverse);
9345 if (!ProvedNonEquality)
9348 if (ProvedNonStrictComparison && ProvedNonEquality)
9357 for (std::pair<BasicBlock *, BasicBlock *>
9360 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9362 if (ProveViaGuard(Pair.first))
9367 if (!LoopEntryPredicate ||
9377 for (
auto &AssumeVH : AC.assumptions()) {
9380 auto *CI = cast<CallInst>(AssumeVH);
9384 if (ProveViaCond(CI->getArgOperand(0),
false))
9393 Value *FoundCondValue,
9395 if (!PendingLoopPredicates.insert(FoundCondValue).second)
9399 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9402 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9403 if (BO->getOpcode() == Instruction::And) {
9405 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9406 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9407 }
else if (BO->getOpcode() == Instruction::Or) {
9409 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9410 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9415 if (!ICI)
return false;
9423 FoundPred = ICI->getPredicate();
9425 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9426 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9428 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9434 const SCEV *FoundLHS,
9435 const SCEV *FoundRHS) {
9437 if (getTypeSizeInBits(LHS->
getType()) <
9438 getTypeSizeInBits(FoundLHS->
getType())) {
9440 LHS = getSignExtendExpr(LHS, FoundLHS->
getType());
9441 RHS = getSignExtendExpr(RHS, FoundLHS->
getType());
9443 LHS = getZeroExtendExpr(LHS, FoundLHS->
getType());
9444 RHS = getZeroExtendExpr(RHS, FoundLHS->
getType());
9446 }
else if (getTypeSizeInBits(LHS->
getType()) >
9447 getTypeSizeInBits(FoundLHS->
getType())) {
9449 FoundLHS = getSignExtendExpr(FoundLHS, LHS->
getType());
9450 FoundRHS = getSignExtendExpr(FoundRHS, LHS->
getType());
9452 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->
getType());
9453 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->
getType());
9459 if (SimplifyICmpOperands(Pred, LHS, RHS))
9462 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9463 if (FoundLHS == FoundRHS)
9467 if (LHS == FoundRHS || RHS == FoundLHS) {
9468 if (isa<SCEVConstant>(RHS)) {
9478 if (FoundPred == Pred)
9484 if (isa<SCEVConstant>(RHS))
9488 RHS, LHS, FoundLHS, FoundRHS);
9500 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9503 const SCEV *V =
nullptr;
9505 if (isa<SCEVConstant>(FoundLHS)) {
9506 C = cast<SCEVConstant>(FoundLHS);
9509 C = cast<SCEVConstant>(FoundRHS);
9519 getSignedRangeMin(V) : getUnsignedRangeMin(V);
9526 APInt SharperMin = Min + 1;
9574 bool ScalarEvolution::splitBinaryAdd(
const SCEV *Expr,
9578 if (!AE || AE->getNumOperands() != 2)
9581 L = AE->getOperand(0);
9582 R = AE->getOperand(1);
9583 Flags = AE->getNoWrapFlags();
9592 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9593 const auto *LAR = cast<SCEVAddRecExpr>(
Less);
9594 const auto *MAR = cast<SCEVAddRecExpr>(More);
9596 if (LAR->getLoop() != MAR->getLoop())
9601 if (!LAR->isAffine() || !MAR->isAffine())
9604 if (LAR->getStepRecurrence(*
this) != MAR->getStepRecurrence(*
this))
9607 Less = LAR->getStart();
9608 More = MAR->getStart();
9613 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9614 const auto &M = cast<SCEVConstant>(More)->getAPInt();
9615 const auto &L = cast<SCEVConstant>(
Less)->getAPInt();
9620 const SCEV *LLess =
nullptr, *RLess =
nullptr;
9621 const SCEV *LMore =
nullptr, *RMore =
nullptr;
9624 if (splitBinaryAdd(Less, LLess, RLess, Flags))
9625 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9630 if (splitBinaryAdd(More, LMore, RMore, Flags))
9631 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9636 if (C1 && C2 && RLess == RMore)
9637 return C2->getAPInt() - C1->
getAPInt();
9642 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9644 const SCEV *FoundLHS,
const SCEV *FoundRHS) {
9653 if (!AddRecFoundLHS)
9660 const Loop *L = AddRecFoundLHS->getLoop();
9661 if (L != AddRecLHS->getLoop())
9698 if (!LDiff || !RDiff || *LDiff != *RDiff)
9704 APInt FoundRHSLimit;
9707 FoundRHSLimit = -(*RDiff);
9714 return isAvailableAtLoopEntry(FoundRHS, L) &&
9715 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9721 const SCEV *FoundLHS,
9723 const PHINode *LPhi =
nullptr, *RPhi =
nullptr;
9727 bool Erased = PendingMerges.erase(LPhi);
9728 assert(Erased &&
"Failed to erase LPhi!");
9732 bool Erased = PendingMerges.erase(RPhi);
9733 assert(Erased &&
"Failed to erase RPhi!");
9739 if (
const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9740 if (
auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9741 if (!PendingMerges.insert(Phi).second)
9745 if (
const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9746 if (
auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9755 if (!PendingMerges.insert(Phi).second)
9772 assert(LPhi &&
"LPhi should definitely be a SCEVUnknown Phi!");
9776 auto ProvedEasily = [&](
const SCEV *S1,
const SCEV *S2) {
9777 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9778 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9779 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9782 if (RPhi && RPhi->getParent() == LBB) {
9789 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9790 if (!ProvedEasily(L, R))
9803 assert(Predecessor &&
"Loop with AddRec with no predecessor?");
9805 if (!ProvedEasily(L1, RAR->
getStart()))
9807 auto *Latch = RLoop->getLoopLatch();
9808 assert(Latch &&
"Loop with AddRec with no latch?");
9819 if (!dominates(RHS, IncBB))
9822 if (!ProvedEasily(L, RHS))
9831 const SCEV *FoundLHS,
9832 const SCEV *FoundRHS) {
9833 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9836 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9839 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9840 FoundLHS, FoundRHS) ||
9842 isImpliedCondOperandsHelper(Pred, LHS, RHS,
9843 getNotSCEV(FoundRHS),
9844 getNotSCEV(FoundLHS));
9863 template<
typename MaxExprType>
9865 const SCEV *Candidate) {
9866 const MaxExprType *MaxExpr =
dyn_cast<MaxExprType>(MaybeMaxExpr);
9867 if (!MaxExpr)
return false;
9869 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9873 template<
typename MaxExprType>
9875 const SCEV *MaybeMinExpr,
9876 const SCEV *Candidate) {
9881 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.
getNotSCEV(Candidate));
9886 const SCEV *LHS,
const SCEV *RHS) {
9920 const SCEV *LHS,
const SCEV *RHS) {
9931 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9933 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9941 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9943 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9951 const SCEV *FoundLHS,
9952 const SCEV *FoundRHS,
9955 getTypeSizeInBits(RHS->
getType()) &&
9956 "LHS and RHS have different sizes?");
9958 getTypeSizeInBits(FoundRHS->
getType()) &&
9959 "FoundLHS and FoundRHS have different sizes?");
9973 auto GetOpFromSExt = [&](
const SCEV *S) {
9974 if (
auto *
Ext = dyn_cast<SCEVSignExtendExpr>(S))
9975 return Ext->getOperand();
9982 auto *OrigLHS = LHS;
9983 auto *OrigFoundLHS = FoundLHS;
9984 LHS = GetOpFromSExt(LHS);
9985 FoundLHS = GetOpFromSExt(FoundLHS);
9988 auto IsSGTViaContext = [&](
const SCEV *S1,
const SCEV *S2) {
9991 FoundRHS, Depth + 1);
9994 if (
auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10000 if (getTypeSizeInBits(LHS->
getType()) != getTypeSizeInBits(RHS->
getType()))
10004 if (!LHSAddExpr->hasNoSignedWrap())
10007 auto *LL = LHSAddExpr->getOperand(0);
10008 auto *LR = LHSAddExpr->getOperand(1);
10009 auto *MinusOne = getNegativeSCEV(getOne(RHS->
getType()));
10012 auto IsSumGreaterThanRHS = [&](
const SCEV *S1,
const SCEV *S2) {
10013 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10018 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10020 }
else if (
auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10035 if (!isa<ConstantInt>(LR))
10038 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10042 auto *Numerator = getExistingSCEV(LL);
10043 if (!Numerator || Numerator->getType() != FoundLHS->
getType())
10051 auto *DTy = Denominator->getType();
10052 auto *FRHSTy = FoundRHS->
getType();
10053 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10063 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10064 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10070 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt,
getConstant(WTy, 2));
10071 if (isKnownNonPositive(RHS) &&
10072 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10082 auto *MinusOne = getNegativeSCEV(getOne(WTy));
10083 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10085 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10093 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10101 const SCEV *LHS,
const SCEV *RHS) {
10102 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10105 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10111 const SCEV *FoundLHS,
10112 const SCEV *FoundRHS) {
10147 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10156 const SCEV *FoundLHS,
10157 const SCEV *FoundRHS) {
10158 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10167 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10179 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10185 return SatisfyingLHSRange.
contains(LHSRange);
10188 bool ScalarEvolution::doesIVOverflowOnLT(
const SCEV *RHS,
const SCEV *Stride,
10189 bool IsSigned,
bool NoWrap) {
10192 if (NoWrap)
return false;
10194 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
10198 APInt MaxRHS = getSignedRangeMax(RHS);
10200 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10203 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10206 APInt MaxRHS = getUnsignedRangeMax(RHS);
10208 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10211 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10214 bool ScalarEvolution::doesIVOverflowOnGT(
const SCEV *RHS,
const SCEV *Stride,
10215 bool IsSigned,
bool NoWrap) {
10216 if (NoWrap)
return false;
10218 unsigned BitWidth = getTypeSizeInBits(RHS->
getType());
10222 APInt MinRHS = getSignedRangeMin(RHS);
10224 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10227 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10230 APInt MinRHS = getUnsignedRangeMin(RHS);
10232 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10235 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10238 const SCEV *ScalarEvolution::computeBECount(
const SCEV *Delta,
const SCEV *Step,
10241 Delta = Equality ? getAddExpr(Delta, Step)
10242 : getAddExpr(Delta, getMinusSCEV(Step, One));
10243 return getUDivExpr(Delta, Step);
10246 const SCEV *ScalarEvolution::computeMaxBECountForLT(
const SCEV *Start,
10247 const SCEV *Stride,
10252 assert(!isKnownNonPositive(Stride) &&
10253 "Stride is expected strictly positive!");
10256 const SCEV *MaxBECount;
10258 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10260 APInt StrideForMaxBECount =
10261 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10268 APInt One(BitWidth, 1, IsSigned);
10273 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10282 MaxBECount = computeBECount(
getConstant(MaxEnd - MinStart) ,
10289 ScalarEvolution::ExitLimit
10290 ScalarEvolution::howManyLessThans(
const SCEV *LHS,
const SCEV *RHS,
10291 const Loop *L,
bool IsSigned,
10292 bool ControlsExit,
bool AllowPredicates) {
10296 bool PredicatedIV =
false;
10298 if (!IV && AllowPredicates) {
10302 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10303 PredicatedIV =
true;
10308 return getCouldNotCompute();
10310 bool NoWrap = ControlsExit &&
10318 if (!PositiveStride) {
10361 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10362 !loopHasNoSideEffects(L))
10363 return getCouldNotCompute();
10364 }
else if (!Stride->
isOne() &&
10365 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10370 return getCouldNotCompute();
10375 const SCEV *End = RHS;
10382 const SCEV *MaxBECount = computeMaxBECountForLT(
10383 Start, Stride, RHS, getTypeSizeInBits(LHS->
getType()), IsSigned);
10384 return ExitLimit(getCouldNotCompute() , MaxBECount,
10385 false , Predicates);
10391 const SCEV *BECountIfBackedgeTaken =
10392 computeBECount(getMinusSCEV(End, Start), Stride,
false);
10400 const SCEV *BECount;
10401 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10402 BECount = BECountIfBackedgeTaken;
10404 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10405 BECount = computeBECount(getMinusSCEV(End, Start), Stride,
false);
10408 const SCEV *MaxBECount;
10409 bool MaxOrZero =
false;
10410 if (isa<SCEVConstant>(BECount))
10411 MaxBECount = BECount;
10412 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10416 MaxBECount = BECountIfBackedgeTaken;
10419 MaxBECount = computeMaxBECountForLT(
10420 Start, Stride, RHS, getTypeSizeInBits(LHS->
getType()), IsSigned);
10423 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10424 !isa<SCEVCouldNotCompute>(BECount))
10425 MaxBECount =
getConstant(getUnsignedRangeMax(BECount));
10427 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10430 ScalarEvolution::ExitLimit
10431 ScalarEvolution::howManyGreaterThans(
const SCEV *LHS,
const SCEV *RHS,
10432 const Loop *L,
bool IsSigned,
10433 bool ControlsExit,
bool AllowPredicates) {
10437 return getCouldNotCompute();
10440 if (!IV && AllowPredicates)
10444 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10448 return getCouldNotCompute();
10450 bool NoWrap = ControlsExit &&
10457 return getCouldNotCompute();
10463 if (!Stride->
isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10464 return getCouldNotCompute();
10470 const SCEV *End = RHS;
10471 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10472 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10474 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride,
false);
10476 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10477 : getUnsignedRangeMax(Start);
10479 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10480 : getUnsignedRangeMin(Stride);
10482 unsigned BitWidth = getTypeSizeInBits(LHS->
getType());
10494 const SCEV *MaxBECount = getCouldNotCompute();
10495 if (isa<SCEVConstant>(BECount))
10496 MaxBECount = BECount;
10498 MaxBECount = computeBECount(
getConstant(MaxStart - MinEnd),
10501 if (isa<SCEVCouldNotCompute>(MaxBECount))
10502 MaxBECount = BECount;
10504 return ExitLimit(BECount, MaxBECount,
false, Predicates);
10513 if (
const SCEVConstant *
SC = dyn_cast<SCEVConstant>(getStart()))
10514 if (!
SC->getValue()->isZero()) {
10516 Operands[0] = SE.
getZero(
SC->getType());
10518 getNoWrapFlags(
FlagNW));
10519 if (
const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10520 return ShiftedAddRec->getNumIterationsInRange(
10528 if (
any_of(operands(), [](
const SCEV *
Op) {
return !isa<SCEVConstant>(
Op); }))
10552 APInt ExitVal = (End + A).udiv(A);
10559 if (Range.
contains(Val->getValue()))
10566 "Linear scev computation is off in a bad way!");
10568 }
else if (isQuadratic()) {
10585 if (!CB->getZExtValue())
10599 if (!Range.
contains(R1Val->getValue()))
10609 if (Range.
contains(R1Val->getValue()))
10621 assert(getNumOperands() > 1 &&
"AddRec with zero step?");
10631 for (
unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10638 assert(!Last->
isZero() &&
"Recurrency with zero step?");
10640 return cast<SCEVAddRecExpr>(SE.
getAddRecExpr(Ops, getLoop(),
10647 if (
const auto *SU = dyn_cast<SCEVUnknown>(S))
10648 return isa<UndefValue>(SU->getValue());
10649 else if (
const auto *
SC = dyn_cast<SCEVConstant>(S))
10650 return isa<UndefValue>(
SC->getValue());
10658 struct SCEVCollectStrides {
10663 : SE(SE), Strides(S) {}
10665 bool follow(
const SCEV *S) {
10671 bool isDone()
const {
return false; }
10675 struct SCEVCollectTerms {
10680 bool follow(
const SCEV *S) {
10681 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10682 isa<SCEVSignExtendExpr>(S)) {
10694 bool isDone()
const {
return false; }
10698 struct SCEVHasAddRec {
10699 bool &ContainsAddRec;
10701 SCEVHasAddRec(
bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10702 ContainsAddRec =
false;
10705 bool follow(
const SCEV *S) {
10706 if (isa<SCEVAddRecExpr>(S)) {
10707 ContainsAddRec =
true;
10717 bool isDone()
const {
return false; }
10732 struct SCEVCollectAddRecMultiplies {
10737 : Terms(T), SE(SE) {}
10739 bool follow(
const SCEV *S) {
10740 if (
auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10741 bool HasAddRec =
false;
10743 for (
auto Op : Mul->operands()) {
10745 if (Unknown && !isa<CallInst>(Unknown->
getValue())) {
10747 }
else if (Unknown) {
10750 bool ContainsAddRec;
10751 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10753 HasAddRec |= ContainsAddRec;
10756 if (Operands.
size() == 0)
10771 bool isDone()
const {
return false; }
10783 SCEVCollectStrides StrideCollector(*
this, Strides);
10787 dbgs() <<
"Strides:\n";
10788 for (
const SCEV *S : Strides)
10789 dbgs() << *S <<
"\n";
10792 for (
const SCEV *S : Strides) {
10793 SCEVCollectTerms TermCollector(Terms);
10798 dbgs() <<
"Terms:\n";
10799 for (
const SCEV *
T : Terms)
10800 dbgs() << *
T <<
"\n";
10803 SCEVCollectAddRecMultiplies MulCollector(Terms, *
this);
10810 int Last = Terms.
size() - 1;
10811 const SCEV *Step = Terms[Last];
10815 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10817 for (
const SCEV *
Op : M->operands())
10818 if (!isa<SCEVConstant>(
Op))
10828 for (
const SCEV *&Term : Terms) {
10831 SCEVDivision::divide(SE, Term, Step, &Q, &R);
10842 remove_if(Terms, [](
const SCEV *E) {
return isa<SCEVConstant>(
E); }),
10845 if (Terms.size() > 0)
10855 for (
const SCEV *
T : Terms)
10863 if (
const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10864 return Expr->getNumOperands();
10869 if (isa<SCEVConstant>(T))
10872 if (isa<SCEVUnknown>(T))
10875 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10877 for (
const SCEV *
Op : M->operands())
10878 if (!isa<SCEVConstant>(
Op))
10891 Ty =
Store->getValueOperand()->getType();
10893 Ty =
Load->getType();
10898 return getSizeOfExpr(ETy, Ty);
10903 const SCEV *ElementSize) {
10904 if (Terms.
size() < 1 || !ElementSize)
10913 dbgs() <<
"Terms:\n";
10914 for (
const SCEV *
T : Terms)
10915 dbgs() << *
T <<
"\n";
10929 for (
const SCEV *&Term : Terms) {
10931 SCEVDivision::divide(*
this, Term, ElementSize, &Q, &R);
10939 for (
const SCEV *
T : Terms)
10944 dbgs() <<
"Terms after sorting:\n";
10945 for (
const SCEV *
T : NewTerms)
10946 dbgs() << *
T <<
"\n";
10958 dbgs() <<
"Sizes:\n";
10959 for (
const SCEV *S : Sizes)
10960 dbgs() << *S <<
"\n";
10971 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10975 const SCEV *Res = Expr;
10976 int Last = Sizes.
size() - 1;
10977 for (
int i = Last; i >= 0; i--) {
10979 SCEVDivision::divide(*
this, Res, Sizes[i], &Q, &R);
10982 dbgs() <<
"Res: " << *Res <<
"\n";
10983 dbgs() <<
"Sizes[i]: " << *Sizes[i] <<
"\n";
10984 dbgs() <<
"Res divided by Sizes[i]:\n";
10985 dbgs() <<
"Quotient: " << *Q <<
"\n";
10986 dbgs() <<
"Remainder: " << *R <<
"\n";
10996 if (isa<SCEVAddRecExpr>(R)) {
10997 Subscripts.
clear();
11016 dbgs() <<
"Subscripts:\n";
11017 for (
const SCEV *S : Subscripts)
11018 dbgs() << *S <<
"\n";
11073 const SCEV *ElementSize) {
11076 collectParametricTerms(Expr, Terms);
11082 findArrayDimensions(Terms, Sizes, ElementSize);
11088 computeAccessFunctions(Expr, Subscripts, Sizes);
11090 if (Subscripts.
empty())
11094 dbgs() <<
"succeeded to delinearize " << *Expr <<
"\n";
11095 dbgs() <<
"ArrayDecl[UnknownSize]";
11096 for (
const SCEV *S : Sizes)
11097 dbgs() <<
"[" << *S <<
"]";
11099 dbgs() <<
"\nArrayRef";
11100 for (
const SCEV *S : Subscripts)
11101 dbgs() <<
"[" << *S <<
"]";
11110 void ScalarEvolution::SCEVCallbackVH::deleted() {
11111 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
11112 if (
PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11113 SE->ConstantEvolutionLoopExitValue.erase(PN);
11118 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(
Value *V) {
11119 assert(SE &&
"SCEVCallbackVH called with a null ScalarEvolution!");
11124 Value *Old = getValPtr();
11127 while (!Worklist.empty()) {
11128 User *U = Worklist.pop_back_val();
11133 if (!Visited.
insert(U).second)
11135 if (
PHINode *PN = dyn_cast<PHINode>(U))
11136 SE->ConstantEvolutionLoopExitValue.erase(PN);
11141 if (
PHINode *PN = dyn_cast<PHINode>(Old))
11142 SE->ConstantEvolutionLoopExitValue.erase(PN);
11157 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11159 LoopDispositions(64), BlockDispositions(64) {
11172 HasGuards = GuardDecl && !GuardDecl->use_empty();
11176 : F(
Arg.F), HasGuards(
Arg.HasGuards), TLI(
Arg.TLI), AC(
Arg.AC), DT(
Arg.DT),
11177 LI(
Arg.LI), CouldNotCompute(
std::move(
Arg.CouldNotCompute)),
11178 ValueExprMap(
std::move(
Arg.ValueExprMap)),
11179 PendingLoopPredicates(
std::move(
Arg.PendingLoopPredicates)),
11180 PendingPhiRanges(
std::move(
Arg.PendingPhiRanges)),
11181 PendingMerges(
std::move(
Arg.PendingMerges)),
11182 MinTrailingZerosCache(
std::move(
Arg.MinTrailingZerosCache)),
11183 BackedgeTakenCounts(
std::move(
Arg.BackedgeTakenCounts)),
11184 PredicatedBackedgeTakenCounts(
11185 std::move(
Arg.PredicatedBackedgeTakenCounts)),
11186 ConstantEvolutionLoopExitValue(
11187 std::move(
Arg.ConstantEvolutionLoopExitValue)),
11188 ValuesAtScopes(
std::move(
Arg.ValuesAtScopes)),
11189 LoopDispositions(
std::move(
Arg.LoopDispositions)),
11190 LoopPropertiesCache(
std::move(
Arg.LoopPropertiesCache)),
11191 BlockDispositions(
std::move(
Arg.BlockDispositions)),
11192 UnsignedRanges(
std::move(
Arg.UnsignedRanges)),
11193 SignedRanges(
std::move(
Arg.SignedRanges)),
11194 UniqueSCEVs(
std::move(
Arg.UniqueSCEVs)),
11195 UniquePreds(
std::move(
Arg.UniquePreds)),
11196 SCEVAllocator(
std::move(
Arg.SCEVAllocator)),
11197 LoopUsers(
std::move(
Arg.LoopUsers)),
11198 PredicatedSCEVRewrites(
std::move(
Arg.PredicatedSCEVRewrites)),
11199 FirstUnknown(
Arg.FirstUnknown) {
11200 Arg.FirstUnknown =
nullptr;
11209 Tmp->~SCEVUnknown();
11211 FirstUnknown =
nullptr;
11213 ExprValueMap.
clear();
11214 ValueExprMap.
clear();
11219 for (
auto &BTCI : BackedgeTakenCounts)
11220 BTCI.second.clear();
11221 for (
auto &BTCI : PredicatedBackedgeTakenCounts)
11222 BTCI.second.clear();
11224 assert(PendingLoopPredicates.empty() &&
"isImpliedCond garbage");
11225 assert(PendingPhiRanges.empty() &&
"getRangeRef garbage");
11226 assert(PendingMerges.empty() &&
"isImpliedViaMerge garbage");
11227 assert(!WalkingBEDominatingConds &&
"isLoopBackedgeGuardedByCond garbage!");
11228 assert(!ProvingSplitPredicate &&
"ProvingSplitPredicate garbage!");
11242 L->getHeader()->printAsOperand(OS,
false);
11246 L->getExitBlocks(ExitBlocks);
11247 if (ExitBlocks.
size() != 1)
11248 OS <<
"<multiple exits> ";
11253 OS <<
"Unpredictable backedge-taken count. ";
11258 L->getHeader()->printAsOperand(OS,
false);
11264 OS <<
", actual taken count either this or zero.";
11266 OS <<
"Unpredictable max backedge-taken count. ";
11271 L->getHeader()->printAsOperand(OS,
false);
11276 if (!isa<SCEVCouldNotCompute>(PBT)) {
11277 OS <<
"Predicated backedge-taken count is " << *PBT <<
"\n";
11278 OS <<
" Predicates:\n";
11281 OS <<
"Unpredictable predicated backedge-taken count. ";
11287 L->getHeader()->printAsOperand(OS,
false);
11298 return "Invariant";
11300 return "Computable";
11314 OS <<
"Classifying expressions for: ";
11323 if (!isa<SCEVCouldNotCompute>(SV)) {
11330 const Loop *L = LI.getLoopFor(I.getParent());
11336 if (!isa<SCEVCouldNotCompute>(AtUse)) {
11345 OS <<
"\t\t" "Exits: ";
11348 OS <<
"<<Unknown>>";
11356 OS <<
"\t\t" "LoopDispositions: { ";
11362 Iter->getHeader()->printAsOperand(OS,
false);
11370 OS <<
"\t\t" "LoopDispositions: { ";
11376 InnerL->getHeader()->printAsOperand(OS,
false);
11386 OS <<
"Determining loop execution counts for: ";
11395 auto &Values = LoopDispositions[S];
11396 for (
auto &V : Values) {
11397 if (V.getPointer() == L)
11402 auto &Values2 = LoopDispositions[S];
11403 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
11404 if (V.getPointer() == L) {
11413 ScalarEvolution::computeLoopDisposition(
const SCEV *S,
const Loop *L) {
11414 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
11436 " dominate the contained loop's header?");
11455 bool HasVarying =
false;
11456 for (
auto *
Op : cast<SCEVNAryExpr>(S)->operands()) {
11481 if (
auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11500 auto &Values = BlockDispositions[S];
11501 for (
auto &V : Values) {
11502 if (V.getPointer() == BB)
11507 auto &Values2 = BlockDispositions[S];
11508 for (
auto &V :
make_range(Values2.rbegin(), Values2.rend())) {
11509 if (V.getPointer() == BB) {
11518 ScalarEvolution::computeBlockDisposition(
const SCEV *S,
const BasicBlock *BB) {
11519 switch (static_cast<SCEVTypes>(S->
getSCEVType())) {
11543 bool Proper =
true;
11567 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11593 bool ScalarEvolution::ExitLimit::hasOperand(
const SCEV *S)
const {
11594 auto IsS = [&](
const SCEV *
X) {
return S ==
X; };
11595 auto ContainsS = [&](
const SCEV *
X) {
11598 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11602 ScalarEvolution::forgetMemoizedResults(
const SCEV *S) {
11603 ValuesAtScopes.erase(S);
11604 LoopDispositions.erase(S);
11605 BlockDispositions.erase(S);
11606 UnsignedRanges.erase(S);
11607 SignedRanges.erase(S);
11608 ExprValueMap.
erase(S);
11609 HasRecMap.
erase(S);
11610 MinTrailingZerosCache.erase(S);
11612 for (
auto I = PredicatedSCEVRewrites.begin();
11613 I != PredicatedSCEVRewrites.end();) {
11614 std::pair<const SCEV *, const Loop *> Entry = I->first;
11615 if (Entry.first == S)
11616 PredicatedSCEVRewrites.erase(I++);
11621 auto RemoveSCEVFromBackedgeMap =
11623 for (
auto I = Map.begin(), E = Map.end(); I !=
E;) {
11624 BackedgeTakenInfo &BEInfo = I->second;
11625 if (BEInfo.hasOperand(S,
this)) {
11633 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11634 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11638 ScalarEvolution::getUsedLoops(
const SCEV *S,
11640 struct FindUsedLoops {
11642 : LoopsUsed(LoopsUsed) {}
11644 bool follow(
const SCEV *S) {
11645 if (
auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11650 bool isDone()
const {
return false; }
11653 FindUsedLoops
F(LoopsUsed);
11657 void ScalarEvolution::addToLoopUseLists(
const SCEV *S) {
11659 getUsedLoops(S, LoopsUsed);
11660 for (
auto *L : LoopsUsed)
11661 LoopUsers[L].push_back(S);
11687 SCEVMapper SCM(SE2);
11689 while (!LoopStack.empty()) {
11690 auto *L = LoopStack.pop_back_val();
11691 LoopStack.insert(LoopStack.end(), L->
begin(), L->
end());
11693 auto *CurBECount = SCM.visit(
11724 auto *ConstantDelta =
11727 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11728 dbgs() <<
"Trip Count Changed!\n";
11729 dbgs() <<
"Old: " << *CurBECount <<
"\n";
11730 dbgs() <<
"New: " << *NewBECount <<
"\n";
11731 dbgs() <<
"Delta: " << *ConstantDelta <<
"\n";
11766 "Scalar Evolution Analysis",
false,
true)
11774 char ScalarEvolutionWrapperPass::ID = 0;
11782 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11783 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11784 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11785 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11814 "Type mismatch between LHS and RHS");
11819 void *IP =
nullptr;
11820 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11824 UniquePreds.InsertNode(Eq, IP);
11836 void *IP =
nullptr;
11837 if (
const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11839 auto *OF =
new (SCEVAllocator)
11841 UniquePreds.InsertNode(OF, IP);
11861 SCEVPredicateRewriter
Rewriter(L, SE, NewPreds, Pred);
11862 return Rewriter.visit(S);
11868 for (
auto *Pred : ExprPreds)
11869 if (
const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11870 if (IPred->getLHS() == Expr)
11871 return IPred->getRHS();
11873 return convertToAddRecWithPreds(Expr);
11879 if (AR && AR->getLoop() == L && AR->isAffine()) {
11882 const SCEV *Step = AR->getStepRecurrence(SE);
11887 AR->getNoWrapFlags());
11895 if (AR && AR->getLoop() == L && AR->isAffine()) {
11898 const SCEV *Step = AR->getStepRecurrence(SE);
11903 AR->getNoWrapFlags());
11917 return Pred && Pred->
implies(P);
11926 return addOverflowAssumption(A);
11936 if (!isa<PHINode>(Expr->
getValue()))
11940 if (!PredicatedRewrite)
11942 for (
auto *P : PredicatedRewrite->second){
11944 if (
auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11945 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11949 if (!addOverflowAssumption(P))
11952 return PredicatedRewrite->first;
11964 return SCEVPredicateRewriter::rewrite(S, L, *
this,
nullptr, &Preds);
11971 S = SCEVPredicateRewriter::rewrite(S, L, *
this, &TransformPreds,
nullptr);
11979 for (
auto *
P : TransformPreds)
11988 : FastID(ID), Kind(Kind) {}
11994 assert(LHS != RHS &&
"LHS and RHS are the same SCEV");
12003 return Op->LHS == LHS &&
Op->RHS == RHS;
12011 OS.
indent(Depth) <<
"Equal predicate: " << *LHS <<
" == " << *RHS <<
"\n";
12024 return Op &&
Op->AR == AR &&
setFlags(Flags,
Op->Flags) == Flags;
12060 if (Step->getValue()->getValue().isNonNegative())
12064 return ImpliedFlags;
12078 auto I = SCEVToPreds.
find(Expr);
12079 if (
I == SCEVToPreds.
end())
12085 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12086 return all_of(Set->Preds,
12089 auto ScevPredsIt = SCEVToPreds.
find(N->
getExpr());
12090 if (ScevPredsIt == SCEVToPreds.
end())
12092 auto &SCEVPreds = ScevPredsIt->second;
12094 return any_of(SCEVPreds,
12101 for (
auto Pred : Preds)
12102 Pred->print(OS, Depth);
12106 if (
const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12107 for (
auto Pred : Set->Preds)
12116 assert(Key &&
"Only SCEVUnionPredicate doesn't have an " 12117 " associated expression!");
12119 SCEVToPreds[
Key].push_back(N);
12120 Preds.push_back(N);
12129 RewriteEntry &Entry = RewriteMap[Expr];
12132 if (Entry.second && Generation == Entry.first)
12133 return Entry.second;
12138 Expr = Entry.second;
12141 Entry = {Generation, NewSCEV};
12147 if (!BackedgeCount) {
12152 return BackedgeCount;
12159 updateGeneration();
12166 void PredicatedScalarEvolution::updateGeneration() {
12168 if (++Generation == 0) {
12169 for (
auto &II : RewriteMap) {
12170 const SCEV *Rewritten = II.second.second;
12179 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12187 auto II = FlagsMap.insert({V, Flags});
12195 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12200 auto II = FlagsMap.find(V);
12202 if (II != FlagsMap.end())
12216 for (
auto *
P : NewPreds)
12219 updateGeneration();
12220 RewriteMap[SE.
getSCEV(V)] = {Generation, New};
12226 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12227 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12228 for (
const auto &
I : Init.FlagsMap)
12229 FlagsMap.insert(
I);
12235 for (
auto &
I : *BB) {
12240 auto II = RewriteMap.find(Expr);
12242 if (II == RewriteMap.end())
12246 if (II->second.second == Expr)
12249 OS.
indent(Depth) <<
"[PSE]" <<
I <<
":\n";
12250 OS.
indent(Depth + 2) << *Expr <<
"\n";
12251 OS.
indent(Depth + 2) <<
"--> " << *II->second.second <<
"\n";
12259 bool ScalarEvolution::matchURem(
const SCEV *Expr,
const SCEV *&LHS,
12260 const SCEV *&RHS) {
12262 if (
Add ==
nullptr ||
Add->getNumOperands() != 2)
12265 const SCEV *A =
Add->getOperand(1);
12268 if (Mul ==
nullptr)
12271 const auto MatchURemWithDivisor = [&](
const SCEV *
B) {
12273 if (Expr == getURemExpr(A,
B)) {
12282 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12283 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12284 MatchURemWithDivisor(Mul->getOperand(2));
12287 if (Mul->getNumOperands() == 2)
12288 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12289 MatchURemWithDivisor(Mul->getOperand(0)) ||
12290 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12291 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;.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
virtual const SCEV * getExpr() const =0
Returns the SCEV to which this predicate applies, or nullptr if this is a SCEVUnionPredicate.
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.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
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 ConstantInt * getFalse(LLVMContext &Context)
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)
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.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
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 Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
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...
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT)
Perform a quick domtree based check for loop invariance assuming that V is used within the loop...
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.
Compute iterated dominance frontiers using a linear time algorithm.
const APInt & getUpper() const
Return the upper value for this range.
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...
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.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
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.
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 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.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
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
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
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
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)
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.
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.
zlib-gnu style compression
This file implements a class to represent arbitrary precision integral constant values and operations...
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 int64_t getConstant(const MachineInstr *MI)
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 Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS...
static bool isPrivateLinkage(LinkageTypes Linkage)
A constant value that is initialized with an expression using other constant values.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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.
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.
bool implies(const SCEVPredicate *N) const override
Implementation of the SCEVPredicate interface.
const T & getValue() const LLVM_LVALUE_FUNCTION
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.
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
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)...
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
SelectClass_match< Cond, LHS, RHS > m_Select(const Cond &C, const LHS &L, const RHS &R)
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
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...
APInt sqrt() const
Compute the square root.
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)
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.
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")
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
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...
static cl::opt< unsigned > MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt"), cl::init(8))
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
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 is an important class for using LLVM in a threaded context.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
Conditional or Unconditional Branch instruction.
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the give value is known to be non-negative.
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
static bool IsMinConsistingOf(ScalarEvolution &SE, const SCEV *MaybeMinExpr, const SCEV *Candidate)
Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
bool ult(const APInt &RHS) const
Unsigned less than comparison.
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
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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)
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)
bool isOverflowIntrinsicNoWrap(const IntrinsicInst *II, const DominatorTree &DT)
Returns true if the arithmetic part of the II 's result is used only along the paths control dependen...
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
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.
const SCEV * getMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer 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...
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 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.
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)
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)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, const SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags)
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.
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.
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
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.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return the number of times the sign bit of the register is replicated into the other bits...
void initializeScalarEvolutionWrapperPassPass(PassRegistry &)
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty)
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
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)
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.
scalar Scalar Evolution Analysis
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.
Type * getWiderType(Type *Ty1, Type *Ty2) const
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
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(16))
A utility class that uses RAII to save and restore the value of a variable.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
SCEVPredicate(const SCEVPredicate &)=default
amdgpu Simplify well known AMD library false Value Value * Arg
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.
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...
bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the given value is known be negative (i.e.
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)
static Optional< std::pair< const SCEVConstant *, const SCEVConstant * > > SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Find the roots of the quadratic equation for the given quadratic chrec {L,+,M,+,N}.
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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.
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().
void emplace_back(ArgTypes &&... Args)
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
bool hasNoUnsignedWrap() const
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.
static bool isSigned(Value *V)
Can the given value generate sign bits.
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 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.
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.
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.
AnalysisUsage & addRequiredTransitive()
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
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...
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.
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Return the largest range containing all X such that "X BinOpC Y" is guaranteed not to wrap (overflow)...
bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS, const SCEV *&RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
user_iterator user_begin()
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
bool isOne() const
Return true if the expression is a constant one.
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS)
static Optional< BinaryOp > MatchBinaryOp(Value *V, DominatorTree &DT)
Try to map V into a BinaryOp, and return None on failure.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
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)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
bool canConstantFoldCallTo(ImmutableCallSite CS, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the given value is known be positive (i.e.
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))
This class implements an extremely fast bulk output stream that can only output to a stream...
bool implies(const SCEVPredicate *N) const override
Returns true if this predicate implies N.
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getMaxBackedgeTakenCount or z...
const SCEV * getUDivExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getUnknown(Value *V)
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if the given value is known to be non-zero when defined.
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...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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.
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock)
Get the expression for the number of loop iterations for which this loop is guaranteed not to exit vi...
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.
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, const SCEV *Candidate)
Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
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...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static bool containsUndefs(const SCEV *S)
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop. ...
This node is a base class providing common functionality for n'ary operators.
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
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.
ValTy * getReturnedArgOperand() const
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...
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
A special type used by analysis passes to provide an address that identifies that particular analysis...
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.
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?