31#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
32#define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
34#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
41 cl::desc(
"When performing SCEV expansion only if it is cheap to do, this "
42 "controls the budget that is considered cheap (default = 4)"));
44using namespace PatternMatch;
52 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I)) {
53 NUW = OBO->hasNoUnsignedWrap();
54 NSW = OBO->hasNoSignedWrap();
56 if (
auto *PEO = dyn_cast<PossiblyExactOperator>(
I))
57 Exact = PEO->isExact();
58 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
60 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
61 NNeg = PNI->hasNonNeg();
62 if (
auto *TI = dyn_cast<TruncInst>(
I)) {
63 NUW = TI->hasNoUnsignedWrap();
64 NSW = TI->hasNoSignedWrap();
69 if (isa<OverflowingBinaryOperator>(
I)) {
70 I->setHasNoUnsignedWrap(
NUW);
71 I->setHasNoSignedWrap(
NSW);
73 if (isa<PossiblyExactOperator>(
I))
75 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
77 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
79 if (isa<TruncInst>(
I)) {
80 I->setHasNoUnsignedWrap(
NUW);
81 I->setHasNoSignedWrap(
NSW);
102 Value *Ret =
nullptr;
105 for (
User *U : V->users()) {
106 if (U->getType() != Ty)
108 CastInst *CI = dyn_cast<CastInst>(U);
114 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
123 SCEVInsertPointGuard Guard(Builder,
this);
131 assert(!isa<Instruction>(Ret) ||
132 SE.DT.
dominates(cast<Instruction>(Ret), &*BIP));
141 if (
auto *
II = dyn_cast<InvokeInst>(
I))
142 IP =
II->getNormalDest()->begin();
144 while (isa<PHINode>(IP))
147 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
149 }
else if (isa<CatchSwitchInst>(IP)) {
150 IP = MustDominate->
getParent()->getFirstInsertionPt();
152 assert(!IP->isEHPad() &&
"unexpected eh pad!");
165SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
168 if (
Argument *
A = dyn_cast<Argument>(V)) {
170 while ((isa<BitCastInst>(IP) &&
171 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
172 cast<BitCastInst>(IP)->getOperand(0) !=
A) ||
173 isa<DbgInfoIntrinsic>(IP))
184 assert(isa<Constant>(V) &&
185 "Expected the cast argument to be a global/constant");
197 assert((
Op == Instruction::BitCast ||
198 Op == Instruction::PtrToInt ||
199 Op == Instruction::IntToPtr) &&
200 "InsertNoopCastOfTo cannot perform non-noop casts!");
202 "InsertNoopCastOfTo cannot change sizes!");
209 if (
Op == Instruction::IntToPtr) {
210 auto *PtrTy = cast<PointerType>(Ty);
215 if (
Op == Instruction::BitCast) {
216 if (
V->getType() == Ty)
218 if (
CastInst *CI = dyn_cast<CastInst>(V)) {
224 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
226 if (
CastInst *CI = dyn_cast<CastInst>(V))
227 if ((CI->
getOpcode() == Instruction::PtrToInt ||
228 CI->
getOpcode() == Instruction::IntToPtr) &&
233 if ((
CE->getOpcode() == Instruction::PtrToInt ||
234 CE->getOpcode() == Instruction::IntToPtr) &&
237 return CE->getOperand(0);
245 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
255 if (
Constant *CLHS = dyn_cast<Constant>(LHS))
256 if (
Constant *CRHS = dyn_cast<Constant>(RHS))
261 unsigned ScanLimit = 6;
265 if (IP != BlockBegin) {
267 for (; ScanLimit; --IP, --ScanLimit) {
270 if (isa<DbgInfoIntrinsic>(IP))
275 if (isa<OverflowingBinaryOperator>(
I)) {
283 if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
287 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) ==
LHS &&
288 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
290 if (IP == BlockBegin)
break;
296 SCEVInsertPointGuard Guard(Builder,
this);
301 if (!
L->isLoopInvariant(LHS) || !
L->isLoopInvariant(RHS))
break;
303 if (!Preheader)
break;
351 assert(!isa<Instruction>(V) ||
357 if (
Constant *CLHS = dyn_cast<Constant>(V))
362 unsigned ScanLimit = 6;
366 if (IP != BlockBegin) {
368 for (; ScanLimit; --IP, --ScanLimit) {
371 if (isa<DbgInfoIntrinsic>(IP))
373 if (IP->getOpcode() == Instruction::GetElementPtr &&
374 IP->getOperand(0) == V && IP->getOperand(1) ==
Idx &&
375 cast<GEPOperator>(&*IP)->getSourceElementType() ==
378 if (IP == BlockBegin)
break;
383 SCEVInsertPointGuard Guard(Builder,
this);
387 if (!
L->isLoopInvariant(V) || !
L->isLoopInvariant(
Idx))
break;
389 if (!Preheader)
break;
406 if (
A->contains(
B))
return B;
407 if (
B->contains(
A))
return A;
408 if (DT.
dominates(
A->getHeader(),
B->getHeader()))
return B;
409 if (DT.
dominates(
B->getHeader(),
A->getHeader()))
return A;
415const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
417 auto Pair = RelevantLoops.insert(std::make_pair(S,
nullptr));
419 return Pair.first->second;
438 const Loop *
L =
nullptr;
443 return RelevantLoops[S] =
L;
447 if (
const Instruction *
I = dyn_cast<Instruction>(
U->getValue()))
448 return Pair.first->second = SE.LI.
getLoopFor(
I->getParent());
466 bool operator()(std::pair<const Loop *, const SCEV *>
LHS,
467 std::pair<const Loop *, const SCEV *>
RHS)
const {
474 if (
LHS.first !=
RHS.first)
480 if (
LHS.second->isNonConstantNegative()) {
481 if (!
RHS.second->isNonConstantNegative())
483 }
else if (
RHS.second->isNonConstantNegative())
495 const SCEV *URemLHS =
nullptr;
496 const SCEV *URemRHS =
nullptr;
497 if (SE.matchURem(S, URemLHS, URemRHS)) {
510 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
518 Value *Sum =
nullptr;
519 for (
auto I = OpsAndLoops.
begin(), E = OpsAndLoops.
end();
I != E;) {
520 const Loop *CurLoop =
I->first;
529 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
530 if (isa<PointerType>(Sum->
getType())) {
534 for (;
I != E &&
I->first == CurLoop; ++
I) {
537 const SCEV *
X =
I->second;
539 if (!isa<Instruction>(
U->getValue()))
543 Sum = expandAddToGEP(SE.
getAddExpr(NewOps), Sum);
544 }
else if (
Op->isNonConstantNegative()) {
554 if (isa<Constant>(Sum))
572 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
579 Value *Prod =
nullptr;
580 auto I = OpsAndLoops.
begin();
585 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
595 while (E != OpsAndLoops.
end() && *
I == *E &&
Exponent != MaxExponent) {
599 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
618 assert(Result &&
"Nothing was expanded?");
622 while (
I != OpsAndLoops.
end()) {
625 Prod = ExpandOpBinPowN();
626 }
else if (
I->second->isAllOnesValue()) {
633 Value *
W = ExpandOpBinPowN();
635 if (isa<Constant>(Prod))
std::swap(Prod, W);
642 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
644 Prod = InsertBinop(Instruction::Shl, Prod,
645 ConstantInt::get(Ty,
RHS->logBase2()), NWFlags,
648 Prod = InsertBinop(Instruction::Mul, Prod, W, S->
getNoWrapFlags(),
661 if (
RHS.isPowerOf2())
662 return InsertBinop(Instruction::LShr, LHS,
663 ConstantInt::get(
SC->getType(),
RHS.logBase2()),
677 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
682 if (L == IVIncInsertLoop) {
685 if (!SE.DT.
dominates(OInst, IVIncInsertPos))
689 IncV = dyn_cast<Instruction>(IncV->
getOperand(0));
699 return isNormalAddRecExprPHI(PN, IncV, L);
714 if (IncV == InsertPos)
721 case Instruction::Add:
722 case Instruction::Sub: {
724 if (!OInst || SE.DT.
dominates(OInst, InsertPos))
725 return dyn_cast<Instruction>(IncV->
getOperand(0));
728 case Instruction::BitCast:
729 return dyn_cast<Instruction>(IncV->
getOperand(0));
730 case Instruction::GetElementPtr:
732 if (isa<Constant>(U))
734 if (
Instruction *OInst = dyn_cast<Instruction>(U)) {
743 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
747 return dyn_cast<Instruction>(IncV->
getOperand(0));
763 for (
auto *InsertPtGuard : InsertPointGuards)
764 if (InsertPtGuard->GetInsertPoint() == It)
765 InsertPtGuard->SetInsertPoint(NewInsertPt);
772 bool RecomputePoisonFlags) {
777 I->dropPoisonGeneratingFlags();
778 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
780 auto *BO = cast<BinaryOperator>(
I);
789 if (RecomputePoisonFlags)
790 FixupPoisonFlags(IncV);
796 if (isa<PHINode>(InsertPos) ||
816 fixupInsertPoints(
I);
817 I->moveBefore(InsertPos);
818 if (RecomputePoisonFlags)
841 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
874 Type *PhiTy = Phi->getType();
888 if (Phi == Requested) {
903 if (!isa<IntegerType>(AR->
getType()))
911 const SCEV *ExtendAfterOp =
913 return ExtendAfterOp == OpAfterExtend;
917 if (!isa<IntegerType>(AR->
getType()))
925 const SCEV *ExtendAfterOp =
927 return ExtendAfterOp == OpAfterExtend;
934SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
937 assert((!IVIncInsertLoop || IVIncInsertPos) &&
938 "Uninitialized insert position");
943 PHINode *AddRecPhiMatch =
nullptr;
950 bool TryNonMatchingSCEV =
954 for (
PHINode &PN :
L->getHeader()->phis()) {
962 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
970 bool IsMatchingSCEV = PhiSCEV == Normalized;
974 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
985 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
988 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
993 if (IsMatchingSCEV) {
997 AddRecPhiMatch = &PN;
1003 if ((!TruncTy || InvertStep) &&
1007 AddRecPhiMatch = &PN;
1009 TruncTy = Normalized->
getType();
1013 if (AddRecPhiMatch) {
1016 InsertedValues.insert(AddRecPhiMatch);
1018 rememberInstruction(IncV);
1020 ReusedValues.
insert(AddRecPhiMatch);
1021 ReusedValues.
insert(IncV);
1022 return AddRecPhiMatch;
1027 SCEVInsertPointGuard Guard(Builder,
this);
1037 PostIncLoops.
clear();
1040 assert(
L->getLoopPreheader() &&
1041 "Can't expand add recurrences without a loop preheader!");
1043 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
1047 assert(!isa<Instruction>(StartV) ||
1062 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1067 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1068 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1079 if (!
L->contains(Pred)) {
1088 IVIncInsertPos : Pred->getTerminator();
1090 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1092 if (isa<OverflowingBinaryOperator>(IncV)) {
1094 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1096 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1103 PostIncLoops = SavedPostIncLoops;
1107 InsertedValues.insert(PN);
1108 InsertedIVs.push_back(PN);
1118 if (PostIncLoops.
count(L)) {
1121 Normalized = cast<SCEVAddRecExpr>(
1125 [[maybe_unused]]
const SCEV *Start = Normalized->
getStart();
1128 "Start does not properly dominate loop header");
1129 assert(SE.
dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1133 Type *TruncTy =
nullptr;
1134 bool InvertStep =
false;
1135 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1139 if (!PostIncLoops.
count(L))
1144 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1150 if (isa<OverflowingBinaryOperator>(Result)) {
1151 auto *
I = cast<Instruction>(Result);
1153 I->setHasNoUnsignedWrap(
false);
1155 I->setHasNoSignedWrap(
false);
1161 if (isa<Instruction>(Result) &&
1162 !SE.DT.
dominates(cast<Instruction>(Result),
1180 SCEVInsertPointGuard Guard(Builder,
this);
1181 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1183 Result = expandIVInc(PN, StepV, L, useSubtract);
1191 if (TruncTy !=
Result->getType())
1214 return expandAddRecExprLiterally(S);
1220 PHINode *CanonicalIV =
nullptr;
1221 if (
PHINode *PN =
L->getCanonicalInductionVariable())
1243 if (isa<PointerType>(S->
getType())) {
1259 return expand(SE.
getAddExpr(AddExprLHS, AddExprRHS));
1270 rememberInstruction(CanonicalIV);
1273 Constant *One = ConstantInt::get(Ty, 1);
1276 if (!PredSeen.
insert(HP).second) {
1283 if (
L->contains(HP)) {
1290 rememberInstruction(
Add);
1301 "IVs with types different from the canonical IV should "
1302 "already have been handled!");
1324 const SCEV *NewS = S;
1326 if (isa<SCEVAddRecExpr>(Ext))
1329 const SCEV *
V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1338 return ReuseOrCreateCast(V, S->
getType(), CastInst::PtrToInt,
1339 GetOptimalInsertionPointForCastOf(V));
1360 bool IsSequential) {
1367 if (IsSequential && i != 0)
1384 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1388 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1392 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1396 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1400 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
true);
1416 Value *V = expand(SH);
1420 "non-trivial casts should be done with the SCEVs directly!");
1421 V = InsertNoopCastOfTo(V, Ty);
1426Value *SCEVExpander::FindValueInExprValueMap(
1435 if (isa<SCEVConstant>(S))
1438 for (
Value *V : SE.getSCEVValues(S)) {
1455 DropPoisonGeneratingInsts.
clear();
1466Value *SCEVExpander::expand(
const SCEV *S) {
1473 auto SafeToHoist = [](
const SCEV *S) {
1475 if (
const auto *
D = dyn_cast<SCEVUDivExpr>(S)) {
1476 if (
const auto *SC = dyn_cast<SCEVConstant>(
D->getRHS()))
1478 return SC->getValue()->isZero();
1488 if (SafeToHoist(S)) {
1490 L =
L->getParentLoop()) {
1493 if (
BasicBlock *Preheader =
L->getLoopPreheader()) {
1499 InsertPt =
L->getHeader()->getFirstInsertionPt();
1506 InsertPt =
L->getHeader()->getFirstInsertionPt();
1510 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1511 InsertPt = std::next(InsertPt);
1519 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1520 if (
I != InsertedExpressions.end())
1523 SCEVInsertPointGuard Guard(Builder,
this);
1528 Value *
V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1531 V = fixupLCSSAFormFor(V);
1535 I->dropPoisonGeneratingAnnotations();
1538 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
1540 auto *BO = cast<BinaryOperator>(
I);
1546 if (
auto *NNI = dyn_cast<PossiblyNonNegInst>(
I)) {
1547 auto *Src = NNI->getOperand(0);
1550 DL).value_or(
false))
1551 NNI->setNonNeg(
true);
1561 InsertedExpressions[std::make_pair(S, &*InsertPt)] =
V;
1565void SCEVExpander::rememberInstruction(
Value *
I) {
1566 auto DoInsert = [
this](
Value *
V) {
1567 if (!PostIncLoops.
empty())
1568 InsertedPostIncValues.insert(V);
1570 InsertedValues.insert(V);
1580void SCEVExpander::replaceCongruentIVInc(
1590 dyn_cast<Instruction>(
Phi->getIncomingValueForBlock(LatchBlock));
1591 if (!OrigInc || !IsomorphicInc)
1598 !(ChainedPhis.count(Phi) ||
1599 isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1600 (ChainedPhis.count(Phi) ||
1601 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1615 const SCEV *TruncExpr =
1617 if (OrigInc == IsomorphicInc || TruncExpr != SE.
getSCEV(IsomorphicInc) ||
1621 bool BothHaveNUW =
false;
1622 bool BothHaveNSW =
false;
1623 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1624 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1625 if (OBOIncV && OBOIsomorphic) {
1627 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1629 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1642 "Should only replace an increment with a wider one.");
1643 if (BothHaveNUW || BothHaveNSW) {
1649 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1650 << *IsomorphicInc <<
'\n');
1651 Value *NewInc = OrigInc;
1654 if (
PHINode *PN = dyn_cast<PHINode>(OrigInc))
1655 IP = PN->
getParent()->getFirstInsertionPt();
1680 for (
PHINode &PN : L->getHeader()->phis())
1694 unsigned NumElim = 0;
1704 auto *Const = dyn_cast<SCEVConstant>(SE.
getSCEV(PN));
1707 return Const->getValue();
1712 if (
Value *V = SimplifyPHINode(Phi)) {
1713 if (V->getType() != Phi->getType())
1716 Phi->replaceAllUsesWith(V);
1720 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1731 if (Phi->getType()->isIntegerTy() &&
TTI &&
1737 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1740 const SCEV *TruncExpr =
1742 ExprToIVMap[TruncExpr] = Phi;
1753 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1755 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1758 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1760 Value *NewIV = OrigPhiRef;
1761 if (OrigPhiRef->
getType() != Phi->getType()) {
1763 L->getHeader()->getFirstInsertionPt());
1767 Phi->replaceAllUsesWith(NewIV);
1779 L->getExitingBlocks(ExitingBlocks);
1786 if (!
match(BB->getTerminator(),
1803 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
1814 struct OperationIndices {
1815 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
1816 Opcode(Opc), MinIdx(min), MaxIdx(
max) { }
1830 S->getOperand(0)->getType(),
1834 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
1835 unsigned MinIdx = 0,
1838 return NumRequired *
1842 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
1845 Type *OpType = S->getType();
1851 switch (S->getSCEVType()) {
1859 Cost = CastCost(Instruction::PtrToInt);
1862 Cost = CastCost(Instruction::Trunc);
1865 Cost = CastCost(Instruction::ZExt);
1868 Cost = CastCost(Instruction::SExt);
1871 unsigned Opcode = Instruction::UDiv;
1872 if (
auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1873 if (SC->getAPInt().isPowerOf2())
1874 Opcode = Instruction::LShr;
1875 Cost = ArithCost(Opcode, 1);
1879 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1885 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1894 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1895 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1896 switch (S->getSCEVType()) {
1900 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1901 Cost += ArithCost(Instruction::Or,
1902 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1903 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1907 assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1908 "Unhandled SCEV expression type?");
1917 return !Op->isZero();
1920 assert(NumTerms >= 1 &&
"Polynominal should have at least one term.");
1921 assert(!(*std::prev(S->operands().end()))->isZero() &&
1922 "Last operand should not be zero");
1925 int NumNonZeroDegreeNonOneTerms =
1927 auto *SConst = dyn_cast<SCEVConstant>(Op);
1928 return !SConst || SConst->getAPInt().ugt(1);
1937 ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
1938 Cost = AddCost + MulCost;
1941 int PolyDegree = S->getNumOperands() - 1;
1942 assert(PolyDegree >= 1 &&
"Should be at least affine.");
1950 Cost += MulCost * (PolyDegree - 1);
1955 for (
auto &CostOp : Operations) {
1956 for (
auto SCEVOp :
enumerate(S->operands())) {
1958 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1959 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1960 Worklist.
emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1966bool SCEVExpander::isHighCostExpansionHelper(
1976 if (!isa<SCEVConstant>(S) && !Processed.
insert(S).second)
1985 L->getHeader()->getParent()->hasMinSize()
2000 const APInt &
Imm = cast<SCEVConstant>(S)->getAPInt();
2004 return Cost > Budget;
2038 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2039 "Nary expr should have more than 1 operand.");
2044 return Cost > Budget;
2047 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2048 "Polynomial should be at least linear");
2049 Cost += costAndCollectOperands<SCEVAddRecExpr>(
2051 return Cost > Budget;
2066 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2080 auto *
I = Builder.
CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2087 "non-affine expression");
2091 const SCEV *ExitCount =
2094 assert(!isa<SCEVCouldNotCompute>(ExitCount) &&
"Invalid loop count");
2109 Value *TripCountVal = expand(ExitCount, Loc);
2114 Value *StepValue = expand(Step, Loc);
2116 Value *StartValue = expand(Start, Loc);
2134 auto ComputeEndCheck = [&]() ->
Value * {
2142 Value *MulV, *OfMul;
2143 if (Step->
isOne()) {
2147 MulV = TruncTripCount;
2151 Intrinsic::umul_with_overflow, Ty);
2153 Builder.
CreateCall(MulF, {AbsStep, TruncTripCount},
"mul");
2158 Value *
Add =
nullptr, *Sub =
nullptr;
2162 if (isa<PointerType>(ARTy)) {
2172 Sub = Builder.
CreateSub(StartValue, MulV);
2175 Value *EndCompareLT =
nullptr;
2176 Value *EndCompareGT =
nullptr;
2177 Value *EndCheck =
nullptr;
2179 EndCheck = EndCompareLT = Builder.
CreateICmp(
2182 EndCheck = EndCompareGT = Builder.
CreateICmp(
2184 if (NeedPosCheck && NeedNegCheck) {
2186 EndCheck = Builder.
CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2188 return Builder.
CreateOr(EndCheck, OfMul);
2190 Value *EndCheck = ComputeEndCheck();
2195 if (SrcBits > DstBits) {
2197 auto *BackedgeCheck =
2199 ConstantInt::get(Loc->
getContext(), MaxVal));
2203 EndCheck = Builder.
CreateOr(EndCheck, BackedgeCheck);
2211 const auto *
A = cast<SCEVAddRecExpr>(Pred->
getExpr());
2212 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2222 if (NUSWCheck && NSSWCheck)
2223 return Builder.
CreateOr(NUSWCheck, NSSWCheck);
2238 for (
const auto *Pred : Union->getPredicates()) {
2248Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2249 auto *DefI = dyn_cast<Instruction>(V);
2250 if (!PreserveLCSSA || !DefI)
2256 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2267 if (DefI->getType()->isIntegerTy())
2273 auto RemoveUserOnExit =
2282 for (
PHINode *PN : InsertedPHIs)
2283 rememberInstruction(PN);
2284 for (
PHINode *PN : PHIsToRemove) {
2287 InsertedValues.erase(PN);
2288 InsertedPostIncValues.erase(PN);
2314struct SCEVFindUnsafe {
2317 bool IsUnsafe =
false;
2320 : SE(SE), CanonicalMode(CanonicalMode) {}
2322 bool follow(
const SCEV *S) {
2332 if (!AR->getLoop()->getLoopPreheader() &&
2333 (!CanonicalMode || !AR->isAffine())) {
2340 bool isDone()
const {
return IsUnsafe; }
2345 SCEVFindUnsafe Search(SE, CanonicalMode);
2347 return !Search.IsUnsafe;
2363 if (InsertionPoint->
getParent()->getTerminator() == InsertionPoint)
2365 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2378 for (
auto [
I, Flags] : Expander.OrigFlags)
2384 InsertedInstructions.end());
2394 [&InsertedSet](
Value *U) {
2395 return InsertedSet.contains(cast<Instruction>(U));
2397 "removed instruction should only be used by instructions inserted "
2398 "during expansion");
2400 assert(!
I->getType()->isVoidTy() &&
2401 "inserted instruction should have non-void types");
2403 I->eraseFromParent();
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
uint64_t IntrinsicInst * II
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that's most relevant for SCEV expansion.
static InstructionCost costAndCollectOperands(const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, SmallVectorImpl< SCEVOperand > &Worklist)
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static bool canBeCheaplyTransformed(ScalarEvolution &SE, const SCEVAddRecExpr *Phi, const SCEVAddRecExpr *Requested, bool &InvertStep)
Check whether we can cheaply express the requested SCEV in terms of the available PHI SCEV by truncat...
#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallSet class.
Class for arbitrary precision integers.
APInt zext(unsigned width) const
Zero extend to a new width.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
This class represents an incoming formal argument to a Function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
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.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
A constant value that is initialized with an expression using other constant values.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
This is the shared class of boolean and integer constants.
static ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This class represents an Operation in the Expression.
bool isNonIntegralPointerType(PointerType *PT) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
Value * CreateVScale(Constant *Scaling, const Twine &Name="")
Create a call to llvm.vscale, multiplied by Scaling.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFreeze(Value *V, const Twine &Name="")
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
BasicBlock * GetInsertBlock() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Class to represent integer types.
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.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Represents a single loop in the control flow graph.
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStart() const
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
const SCEV * getOperand() const
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
const SCEV * getRHS() const
Returns the right hand side of the predicate.
ICmpInst::Predicate getPredicate() const
const SCEV * getLHS() const
Returns the left hand side of the predicate.
This class represents a constant integer value.
Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
bool hasRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Determine whether there is an existing expansion of S that can be reused.
SmallVector< Instruction *, 32 > getAllInsertedInstructions() const
Return a vector containing all instructions inserted during expansion.
bool isSafeToExpand(const SCEV *S) const
Return true if the given expression is safe to expand in the sense that all materialized values are s...
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos, bool RecomputePoisonFlags=false)
Utility for hoisting IncV (with all subexpressions requried for its computation) before InsertPos.
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
static bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
BasicBlock::iterator findInsertPointAfter(Instruction *I, Instruction *MustDominate) const
Returns a suitable insert point after I, that dominates MustDominate.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
bool hasNoUnsignedWrap() const
size_t getNumOperands() const
bool hasNoSignedWrap() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getOperand(unsigned i) const
ArrayRef< const SCEV * > operands() const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicateKind getKind() const
This class represents a cast from a pointer to a pointer-sized integer value.
This class represents a signed maximum selection.
This class represents a signed minimum selection.
This class represents a sequential/in-order unsigned minimum selection.
This class represents a sign extension of a small integer value to a larger integer value.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
const SCEV * getLHS() const
const SCEV * getRHS() const
This class represents an unsigned maximum selection.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
ArrayRef< const SCEV * > operands() const
Return operands of this SCEV expression.
bool isOne() const
Return true if the expression is a constant one.
bool isZero() const
Return true if the expression is a constant zero.
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
SCEVTypes getSCEVType() const
Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
The main scalar evolution driver.
bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
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...
const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEV * getUnknown(Value *V)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask)
Convenient NoWrapFlags manipulation that hides enum casts and is visible in the ScalarEvolution name ...
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
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 * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVector< const SCEVPredicate *, 4 > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
iterator_range< value_op_iterator > operand_values()
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
constexpr ScalarTy getFixedValue() const
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
NodeAddr< PhiNode * > Phi
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
pred_iterator pred_end(BasicBlock *BB)
void stable_sort(R &&Range)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
pred_iterator pred_begin(BasicBlock *BB)
auto reverse(ContainerTy &&C)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
cl::opt< unsigned > SCEVCheapExpansionBudget
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE, bool CheckInvertible=true)
Normalize S to be post-increment for all loops present in Loops.
@ Mul
Product of integers.
constexpr unsigned BitWidth
bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
unsigned pred_size(const MachineBasicBlock *BB)
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
void apply(Instruction *I)
PoisonFlags(const Instruction *I)
struct for holding enough information to help calculate the cost of the given SCEV when expanded into...
Value * visit(const SCEV *S)