31#if 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;
45using namespace SCEVPatternMatch;
55 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I)) {
56 NUW = OBO->hasNoUnsignedWrap();
57 NSW = OBO->hasNoSignedWrap();
59 if (
auto *PEO = dyn_cast<PossiblyExactOperator>(
I))
60 Exact = PEO->isExact();
61 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
63 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
64 NNeg = PNI->hasNonNeg();
65 if (
auto *TI = dyn_cast<TruncInst>(
I)) {
66 NUW = TI->hasNoUnsignedWrap();
67 NSW = TI->hasNoSignedWrap();
69 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
I))
71 if (
auto *ICmp = dyn_cast<ICmpInst>(
I))
76 if (isa<OverflowingBinaryOperator>(
I)) {
77 I->setHasNoUnsignedWrap(
NUW);
78 I->setHasNoSignedWrap(
NSW);
80 if (isa<PossiblyExactOperator>(
I))
82 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
84 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
86 if (isa<TruncInst>(
I)) {
87 I->setHasNoUnsignedWrap(
NUW);
88 I->setHasNoSignedWrap(
NSW);
90 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
I))
92 if (
auto *ICmp = dyn_cast<ICmpInst>(
I))
113 Value *Ret =
nullptr;
115 if (!isa<Constant>(V)) {
117 for (
User *U : V->users()) {
118 if (U->getType() != Ty)
120 CastInst *CI = dyn_cast<CastInst>(U);
127 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
137 SCEVInsertPointGuard Guard(Builder,
this);
145 assert(!isa<Instruction>(Ret) ||
146 SE.DT.
dominates(cast<Instruction>(Ret), &*BIP));
155 if (
auto *
II = dyn_cast<InvokeInst>(
I))
156 IP =
II->getNormalDest()->begin();
158 while (isa<PHINode>(IP))
161 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
163 }
else if (isa<CatchSwitchInst>(IP)) {
164 IP = MustDominate->
getParent()->getFirstInsertionPt();
166 assert(!IP->isEHPad() &&
"unexpected eh pad!");
179SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
182 if (
Argument *
A = dyn_cast<Argument>(V)) {
184 while ((isa<BitCastInst>(IP) &&
185 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
186 cast<BitCastInst>(IP)->getOperand(0) !=
A))
197 assert(isa<Constant>(V) &&
198 "Expected the cast argument to be a global/constant");
210 assert((
Op == Instruction::BitCast ||
211 Op == Instruction::PtrToInt ||
212 Op == Instruction::IntToPtr) &&
213 "InsertNoopCastOfTo cannot perform non-noop casts!");
215 "InsertNoopCastOfTo cannot change sizes!");
222 if (
Op == Instruction::IntToPtr) {
223 auto *PtrTy = cast<PointerType>(Ty);
228 if (
Op == Instruction::BitCast) {
229 if (
V->getType() == Ty)
231 if (
CastInst *CI = dyn_cast<CastInst>(V)) {
237 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
239 if (
CastInst *CI = dyn_cast<CastInst>(V))
240 if ((CI->
getOpcode() == Instruction::PtrToInt ||
241 CI->
getOpcode() == Instruction::IntToPtr) &&
246 if ((
CE->getOpcode() == Instruction::PtrToInt ||
247 CE->getOpcode() == Instruction::IntToPtr) &&
250 return CE->getOperand(0);
258 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
268 if (
Constant *CLHS = dyn_cast<Constant>(LHS))
269 if (
Constant *CRHS = dyn_cast<Constant>(RHS))
274 unsigned ScanLimit = 6;
278 if (IP != BlockBegin) {
280 for (; ScanLimit; --IP, --ScanLimit) {
283 if (isa<OverflowingBinaryOperator>(
I)) {
291 if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
295 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) ==
LHS &&
296 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
298 if (IP == BlockBegin)
break;
304 SCEVInsertPointGuard Guard(Builder,
this);
309 if (!
L->isLoopInvariant(LHS) || !
L->isLoopInvariant(RHS))
break;
311 if (!Preheader)
break;
360 assert(!isa<Instruction>(V) ||
368 if (
Constant *CLHS = dyn_cast<Constant>(V))
373 unsigned ScanLimit = 6;
377 if (IP != BlockBegin) {
379 for (; ScanLimit; --IP, --ScanLimit) {
380 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(IP)) {
381 if (
GEP->getPointerOperand() == V &&
383 GEP->getOperand(1) ==
Idx) {
385 GEP->setNoWrapFlags(
GEP->getNoWrapFlags() & NW);
389 if (IP == BlockBegin)
break;
394 SCEVInsertPointGuard Guard(Builder,
this);
398 if (!
L->isLoopInvariant(V) || !
L->isLoopInvariant(
Idx))
break;
400 if (!Preheader)
break;
417 if (
A->contains(
B))
return B;
418 if (
B->contains(
A))
return A;
419 if (DT.
dominates(
A->getHeader(),
B->getHeader()))
return B;
420 if (DT.
dominates(
B->getHeader(),
A->getHeader()))
return A;
426const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
428 auto Pair = RelevantLoops.try_emplace(S);
430 return Pair.first->second;
449 const Loop *
L =
nullptr;
454 return RelevantLoops[S] =
L;
458 if (
const Instruction *
I = dyn_cast<Instruction>(
U->getValue()))
459 return Pair.first->second = SE.LI.
getLoopFor(
I->getParent());
477 bool operator()(std::pair<const Loop *, const SCEV *>
LHS,
478 std::pair<const Loop *, const SCEV *>
RHS)
const {
485 if (
LHS.first !=
RHS.first)
491 if (
LHS.second->isNonConstantNegative()) {
492 if (!
RHS.second->isNonConstantNegative())
494 }
else if (
RHS.second->isNonConstantNegative())
506 const SCEV *URemLHS =
nullptr;
507 const SCEV *URemRHS =
nullptr;
508 if (SE.matchURem(S, URemLHS, URemRHS)) {
521 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
529 Value *Sum =
nullptr;
530 for (
auto I = OpsAndLoops.
begin(), E = OpsAndLoops.
end();
I != E;) {
531 const Loop *CurLoop =
I->first;
540 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
541 if (isa<PointerType>(Sum->
getType())) {
545 for (;
I != E &&
I->first == CurLoop; ++
I) {
548 const SCEV *
X =
I->second;
550 if (!isa<Instruction>(
U->getValue()))
555 }
else if (
Op->isNonConstantNegative()) {
565 if (isa<Constant>(Sum))
583 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
590 Value *Prod =
nullptr;
591 auto I = OpsAndLoops.
begin();
596 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
606 while (E != OpsAndLoops.
end() && *
I == *E &&
Exponent != MaxExponent) {
610 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
629 assert(Result &&
"Nothing was expanded?");
633 while (
I != OpsAndLoops.
end()) {
636 Prod = ExpandOpBinPowN();
637 }
else if (
I->second->isAllOnesValue()) {
644 Value *
W = ExpandOpBinPowN();
646 if (isa<Constant>(Prod))
std::swap(Prod, W);
653 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
655 Prod = InsertBinop(Instruction::Shl, Prod,
656 ConstantInt::get(Ty,
RHS->logBase2()), NWFlags,
659 Prod = InsertBinop(Instruction::Mul, Prod, W, S->
getNoWrapFlags(),
672 if (
RHS.isPowerOf2())
673 return InsertBinop(Instruction::LShr, LHS,
674 ConstantInt::get(SC->getType(),
RHS.logBase2()),
681 bool GuaranteedNotPoison =
682 ScalarEvolution::isGuaranteedNotToBePoison(RHSExpr);
683 if (!GuaranteedNotPoison)
691 {RHS, ConstantInt::get(RHS->getType(), 1)});
702 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
707 if (L == IVIncInsertLoop) {
710 if (!SE.DT.
dominates(OInst, IVIncInsertPos))
714 IncV = dyn_cast<Instruction>(IncV->
getOperand(0));
724 return isNormalAddRecExprPHI(PN, IncV, L);
739 if (IncV == InsertPos)
746 case Instruction::Add:
747 case Instruction::Sub: {
749 if (!OInst || SE.DT.
dominates(OInst, InsertPos))
750 return dyn_cast<Instruction>(IncV->
getOperand(0));
753 case Instruction::BitCast:
754 return dyn_cast<Instruction>(IncV->
getOperand(0));
755 case Instruction::GetElementPtr:
757 if (isa<Constant>(U))
759 if (
Instruction *OInst = dyn_cast<Instruction>(U)) {
768 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
772 return dyn_cast<Instruction>(IncV->
getOperand(0));
788 for (
auto *InsertPtGuard : InsertPointGuards)
789 if (InsertPtGuard->GetInsertPoint() == It)
790 InsertPtGuard->SetInsertPoint(NewInsertPt);
797 bool RecomputePoisonFlags) {
802 I->dropPoisonGeneratingFlags();
803 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
805 auto *BO = cast<BinaryOperator>(
I);
814 if (RecomputePoisonFlags)
815 FixupPoisonFlags(IncV);
821 if (isa<PHINode>(InsertPos) ||
841 fixupInsertPoints(
I);
843 if (RecomputePoisonFlags)
866 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
899 Type *PhiTy = Phi->getType();
913 if (Phi == Requested) {
928 if (!isa<IntegerType>(AR->
getType()))
936 const SCEV *ExtendAfterOp =
938 return ExtendAfterOp == OpAfterExtend;
942 if (!isa<IntegerType>(AR->
getType()))
950 const SCEV *ExtendAfterOp =
952 return ExtendAfterOp == OpAfterExtend;
959SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
962 assert((!IVIncInsertLoop || IVIncInsertPos) &&
963 "Uninitialized insert position");
968 PHINode *AddRecPhiMatch =
nullptr;
975 bool TryNonMatchingSCEV =
979 for (
PHINode &PN :
L->getHeader()->phis()) {
987 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
995 bool IsMatchingSCEV = PhiSCEV == Normalized;
999 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1010 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1013 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1018 if (IsMatchingSCEV) {
1022 AddRecPhiMatch = &PN;
1028 if ((!TruncTy || InvertStep) &&
1032 AddRecPhiMatch = &PN;
1034 TruncTy = Normalized->
getType();
1038 if (AddRecPhiMatch) {
1041 InsertedValues.insert(AddRecPhiMatch);
1043 rememberInstruction(IncV);
1045 ReusedValues.
insert(AddRecPhiMatch);
1046 ReusedValues.
insert(IncV);
1047 return AddRecPhiMatch;
1052 SCEVInsertPointGuard Guard(Builder,
this);
1062 PostIncLoops.
clear();
1065 assert(
L->getLoopPreheader() &&
1066 "Can't expand add recurrences without a loop preheader!");
1068 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
1072 assert(!isa<Instruction>(StartV) ||
1087 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1092 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1093 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1104 if (!
L->contains(Pred)) {
1113 IVIncInsertPos : Pred->getTerminator();
1115 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1117 if (isa<OverflowingBinaryOperator>(IncV)) {
1119 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1121 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1128 PostIncLoops = SavedPostIncLoops;
1132 InsertedValues.insert(PN);
1133 InsertedIVs.push_back(PN);
1143 if (PostIncLoops.
count(L)) {
1146 Normalized = cast<SCEVAddRecExpr>(
1150 [[maybe_unused]]
const SCEV *Start = Normalized->
getStart();
1153 "Start does not properly dominate loop header");
1154 assert(SE.
dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1158 Type *TruncTy =
nullptr;
1159 bool InvertStep =
false;
1160 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1164 if (!PostIncLoops.
count(L))
1169 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1175 if (isa<OverflowingBinaryOperator>(Result)) {
1176 auto *
I = cast<Instruction>(Result);
1178 I->setHasNoUnsignedWrap(
false);
1180 I->setHasNoSignedWrap(
false);
1186 if (isa<Instruction>(Result) &&
1187 !SE.DT.
dominates(cast<Instruction>(Result),
1205 SCEVInsertPointGuard Guard(Builder,
this);
1206 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1208 Result = expandIVInc(PN, StepV, L, useSubtract);
1216 if (TruncTy !=
Result->getType())
1235 for (
auto &PN : EB->
phis()) {
1238 auto *ExitSCEV = SE.
getSCEV(&PN);
1239 if (!isa<SCEVAddRecExpr>(ExitSCEV))
1244 if (isa<SCEVCouldNotCompute>(ExitSCEV))
1257 if (!isa<SCEVConstant, SCEVUnknown>(
Op))
1261 "difference must be of integer type");
1262 Value *DiffV = expand(Diff);
1263 Value *BaseV = fixupLCSSAFormFor(&PN);
1287 return expandAddRecExprLiterally(S);
1293 PHINode *CanonicalIV =
nullptr;
1294 if (
PHINode *PN =
L->getCanonicalInductionVariable())
1316 if (
Value *V = tryToReuseLCSSAPhi(S))
1321 if (isa<PointerType>(S->
getType())) {
1338 return expand(SE.
getAddExpr(AddExprLHS, AddExprRHS));
1349 rememberInstruction(CanonicalIV);
1352 Constant *One = ConstantInt::get(Ty, 1);
1355 if (!PredSeen.
insert(HP).second) {
1362 if (
L->contains(HP)) {
1369 rememberInstruction(
Add);
1380 "IVs with types different from the canonical IV should "
1381 "already have been handled!");
1403 const SCEV *NewS = S;
1405 if (isa<SCEVAddRecExpr>(Ext))
1408 const SCEV *
V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1417 return ReuseOrCreateCast(V, S->
getType(), CastInst::PtrToInt,
1418 GetOptimalInsertionPointForCastOf(V));
1439 bool IsSequential) {
1440 bool PrevSafeMode = SafeUDivMode;
1441 SafeUDivMode |= IsSequential;
1447 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1449 if (IsSequential && i != 0)
1462 SafeUDivMode = PrevSafeMode;
1467 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1471 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1475 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1479 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1483 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
true);
1499 Value *V = expand(SH);
1501 if (Ty && Ty != V->getType()) {
1503 "non-trivial casts should be done with the SCEVs directly!");
1504 V = InsertNoopCastOfTo(V, Ty);
1509Value *SCEVExpander::FindValueInExprValueMap(
1518 if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
1521 for (
Value *V : SE.getSCEVValues(S)) {
1538 DropPoisonGeneratingInsts.
clear();
1549Value *SCEVExpander::expand(
const SCEV *S) {
1556 auto SafeToHoist = [](
const SCEV *S) {
1558 if (
const auto *
D = dyn_cast<SCEVUDivExpr>(S)) {
1559 if (
const auto *SC = dyn_cast<SCEVConstant>(
D->getRHS()))
1561 return SC->getValue()->isZero();
1571 if (SafeToHoist(S)) {
1573 L =
L->getParentLoop()) {
1576 if (
BasicBlock *Preheader =
L->getLoopPreheader()) {
1582 InsertPt =
L->getHeader()->getFirstInsertionPt();
1589 InsertPt =
L->getHeader()->getFirstInsertionPt();
1593 InsertPt = std::next(InsertPt);
1601 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1602 if (
I != InsertedExpressions.end())
1605 SCEVInsertPointGuard Guard(Builder,
this);
1610 Value *
V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1613 V = fixupLCSSAFormFor(V);
1617 I->dropPoisonGeneratingAnnotations();
1620 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
1622 auto *BO = cast<BinaryOperator>(
I);
1628 if (
auto *NNI = dyn_cast<PossiblyNonNegInst>(
I)) {
1629 auto *Src = NNI->getOperand(0);
1632 DL).value_or(
false))
1633 NNI->setNonNeg(
true);
1643 InsertedExpressions[std::make_pair(S, &*InsertPt)] =
V;
1647void SCEVExpander::rememberInstruction(
Value *
I) {
1648 auto DoInsert = [
this](
Value *
V) {
1649 if (!PostIncLoops.
empty())
1650 InsertedPostIncValues.insert(V);
1652 InsertedValues.insert(V);
1662void SCEVExpander::replaceCongruentIVInc(
1672 dyn_cast<Instruction>(
Phi->getIncomingValueForBlock(LatchBlock));
1673 if (!OrigInc || !IsomorphicInc)
1680 bool Chained = ChainedPhis.contains(Phi);
1681 if (!(Chained || isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1682 (Chained || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1697 const SCEV *TruncExpr =
1699 if (OrigInc == IsomorphicInc || TruncExpr != SE.
getSCEV(IsomorphicInc) ||
1703 bool BothHaveNUW =
false;
1704 bool BothHaveNSW =
false;
1705 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1706 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1707 if (OBOIncV && OBOIsomorphic) {
1709 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1711 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1724 "Should only replace an increment with a wider one.");
1725 if (BothHaveNUW || BothHaveNSW) {
1731 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1732 << *IsomorphicInc <<
'\n');
1733 Value *NewInc = OrigInc;
1736 if (
PHINode *PN = dyn_cast<PHINode>(OrigInc))
1737 IP = PN->
getParent()->getFirstInsertionPt();
1775 unsigned NumElim = 0;
1785 auto *Const = dyn_cast<SCEVConstant>(SE.
getSCEV(PN));
1788 return Const->getValue();
1793 if (
Value *V = SimplifyPHINode(Phi)) {
1794 if (V->getType() != Phi->getType())
1797 Phi->replaceAllUsesWith(V);
1801 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1812 if (Phi->getType()->isIntegerTy() &&
TTI &&
1818 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1821 const SCEV *TruncExpr =
1823 ExprToIVMap[TruncExpr] = Phi;
1834 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1836 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1839 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1841 Value *NewIV = OrigPhiRef;
1842 if (OrigPhiRef->
getType() != Phi->getType()) {
1844 L->getHeader()->getFirstInsertionPt());
1848 Phi->replaceAllUsesWith(NewIV);
1860 L->getExitingBlocks(ExitingBlocks);
1867 if (!
match(BB->getTerminator(),
1884 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
1895 struct OperationIndices {
1896 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
1897 Opcode(
Opc), MinIdx(min), MaxIdx(
max) { }
1911 S->getOperand(0)->getType(),
1915 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
1916 unsigned MinIdx = 0,
1919 return NumRequired *
1923 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
1926 Type *OpType = S->getType();
1932 switch (S->getSCEVType()) {
1940 Cost = CastCost(Instruction::PtrToInt);
1943 Cost = CastCost(Instruction::Trunc);
1946 Cost = CastCost(Instruction::ZExt);
1949 Cost = CastCost(Instruction::SExt);
1952 unsigned Opcode = Instruction::UDiv;
1953 if (
auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1954 if (SC->getAPInt().isPowerOf2())
1955 Opcode = Instruction::LShr;
1956 Cost = ArithCost(Opcode, 1);
1960 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1966 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1975 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1976 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1977 switch (S->getSCEVType()) {
1981 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1982 Cost += ArithCost(Instruction::Or,
1983 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1984 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1988 assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1989 "Unhandled SCEV expression type?");
1996 unsigned NumRecurrences = S->getNumOperands() - 1;
2002 Worklist.
emplace_back(Instruction::PHI, 0, S->getOperand(0));
2004 for (
const SCEV *
Op : S->operands().drop_front())
2010 for (
auto &CostOp : Operations) {
2011 for (
auto SCEVOp :
enumerate(S->operands())) {
2013 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2014 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2021bool SCEVExpander::isHighCostExpansionHelper(
2031 if (!isa<SCEVConstant>(S) && !Processed.
insert(S).second)
2040 L->getHeader()->getParent()->hasMinSize()
2055 const APInt &
Imm = cast<SCEVConstant>(S)->getAPInt();
2059 return Cost > Budget;
2093 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2094 "Nary expr should have more than 1 operand.");
2099 return Cost > Budget;
2102 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2103 "Polynomial should be at least linear");
2104 Cost += costAndCollectOperands<SCEVAddRecExpr>(
2106 return Cost > Budget;
2121 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2135 auto *
I = Builder.
CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2142 "non-affine expression");
2146 const SCEV *ExitCount =
2149 assert(!isa<SCEVCouldNotCompute>(ExitCount) &&
"Invalid loop count");
2164 Value *TripCountVal = expand(ExitCount, Loc);
2169 Value *StepValue = expand(Step, Loc);
2171 Value *StartValue = expand(Start, Loc);
2189 auto ComputeEndCheck = [&]() ->
Value * {
2197 Value *MulV, *OfMul;
2198 if (Step->
isOne()) {
2202 MulV = TruncTripCount;
2206 {AbsStep, TruncTripCount},
2216 if (isa<PointerType>(ARTy)) {
2229 Value *EndCompareLT =
nullptr;
2230 Value *EndCompareGT =
nullptr;
2231 Value *EndCheck =
nullptr;
2233 EndCheck = EndCompareLT = Builder.
CreateICmp(
2236 EndCheck = EndCompareGT = Builder.
CreateICmp(
2238 if (NeedPosCheck && NeedNegCheck) {
2240 EndCheck = Builder.
CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2242 return Builder.
CreateOr(EndCheck, OfMul);
2244 Value *EndCheck = ComputeEndCheck();
2249 if (SrcBits > DstBits) {
2251 auto *BackedgeCheck =
2253 ConstantInt::get(Loc->
getContext(), MaxVal));
2257 EndCheck = Builder.
CreateOr(EndCheck, BackedgeCheck);
2265 const auto *
A = cast<SCEVAddRecExpr>(Pred->
getExpr());
2266 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2276 if (NUSWCheck && NSSWCheck)
2277 return Builder.
CreateOr(NUSWCheck, NSSWCheck);
2292 for (
const auto *Pred : Union->getPredicates()) {
2302Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2303 auto *DefI = dyn_cast<Instruction>(V);
2304 if (!PreserveLCSSA || !DefI)
2310 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2321 if (DefI->getType()->isIntegerTy())
2327 auto RemoveUserOnExit =
2336 for (
PHINode *PN : InsertedPHIs)
2337 rememberInstruction(PN);
2338 for (
PHINode *PN : PHIsToRemove) {
2341 InsertedValues.erase(PN);
2342 InsertedPostIncValues.erase(PN);
2368struct SCEVFindUnsafe {
2371 bool IsUnsafe =
false;
2374 : SE(SE), CanonicalMode(CanonicalMode) {}
2376 bool follow(
const SCEV *S) {
2386 if (!AR->getLoop()->getLoopPreheader() &&
2387 (!CanonicalMode || !AR->isAffine())) {
2394 bool isDone()
const {
return IsUnsafe; }
2399 SCEVFindUnsafe Search(SE, CanonicalMode);
2401 return !Search.IsUnsafe;
2419 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2432 for (
auto [
I, Flags] : Expander.OrigFlags)
2438 InsertedInstructions);
2448 [&InsertedSet](
Value *U) {
2449 return InsertedSet.contains(cast<Instruction>(U));
2451 "removed instruction should only be used by instructions inserted "
2452 "during expansion");
2454 assert(!
I->getType()->isVoidTy() &&
2455 "inserted instruction should have non-void types");
2457 I->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
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")
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
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...
Class for arbitrary precision integers.
LLVM_ABI 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.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
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 LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI 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.
@ 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,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI 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 LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
static LLVM_ABI 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.
LLVM_ABI 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
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
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="")
LLVM_ABI 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())
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Value * CreateVScale(Type *Ty, const Twine &Name="")
Create a call to llvm.vscale.<Ty>().
BasicBlock * GetInsertBlock() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
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 * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
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...
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
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 LLVM_ABI 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 LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI 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.
LLVM_ABI Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
LLVM_ABI 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.
LLVM_ABI 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...
LLVM_ABI 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...
LLVM_ABI unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
LLVM_ABI Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI 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.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
static LLVM_ABI 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...
LLVM_ABI Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
LLVM_ABI Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
LLVM_ABI 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.
LLVM_ABI ArrayRef< const SCEV * > operands() const
Return operands of this SCEV expression.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
SCEVTypes getSCEVType() const
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
The main scalar evolution driver.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getPtrToIntExpr(const SCEV *Op, Type *Ty)
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI 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)
LLVM_ABI 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...
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI 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,...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
LLVM_ABI 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.
LLVM_ABI 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 ...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI 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.
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI 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.
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.
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.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI unsigned getIntegerBitWidth() const
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
constexpr ScalarTy getFixedValue() const
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
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.
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.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
class_match< const SCEVConstant > m_SCEVConstant()
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t > m_scev_Mul(const Op0_t &Op0, const Op1_t &Op1)
bind_ty< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVUnaryExpr_match< SCEVPtrToIntExpr, Op0_t > m_scev_PtrToInt(const Op0_t &Op0)
class_match< const SCEV > m_SCEV()
@ 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.
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,...
auto pred_end(const MachineBasicBlock *BB)
constexpr from_range_t from_range
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI 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.
@ Sub
Subtraction of integers.
constexpr unsigned BitWidth
LLVM_ABI 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 pred_begin(const MachineBasicBlock *BB)
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI 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...
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.
LLVM_ABI void apply(Instruction *I)
LLVM_ABI 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)