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;
54 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I)) {
55 NUW = OBO->hasNoUnsignedWrap();
56 NSW = OBO->hasNoSignedWrap();
58 if (
auto *PEO = dyn_cast<PossiblyExactOperator>(
I))
59 Exact = PEO->isExact();
60 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
62 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
63 NNeg = PNI->hasNonNeg();
64 if (
auto *TI = dyn_cast<TruncInst>(
I)) {
65 NUW = TI->hasNoUnsignedWrap();
66 NSW = TI->hasNoSignedWrap();
68 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
I))
70 if (
auto *ICmp = dyn_cast<ICmpInst>(
I))
75 if (isa<OverflowingBinaryOperator>(
I)) {
76 I->setHasNoUnsignedWrap(
NUW);
77 I->setHasNoSignedWrap(
NSW);
79 if (isa<PossiblyExactOperator>(
I))
81 if (
auto *PDI = dyn_cast<PossiblyDisjointInst>(
I))
83 if (
auto *PNI = dyn_cast<PossiblyNonNegInst>(
I))
85 if (isa<TruncInst>(
I)) {
86 I->setHasNoUnsignedWrap(
NUW);
87 I->setHasNoSignedWrap(
NSW);
89 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
I))
91 if (
auto *ICmp = dyn_cast<ICmpInst>(
I))
112 Value *Ret =
nullptr;
115 for (
User *U : V->users()) {
116 if (U->getType() != Ty)
118 CastInst *CI = dyn_cast<CastInst>(U);
124 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
133 SCEVInsertPointGuard Guard(Builder,
this);
141 assert(!isa<Instruction>(Ret) ||
142 SE.DT.
dominates(cast<Instruction>(Ret), &*BIP));
151 if (
auto *
II = dyn_cast<InvokeInst>(
I))
152 IP =
II->getNormalDest()->begin();
154 while (isa<PHINode>(IP))
157 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
159 }
else if (isa<CatchSwitchInst>(IP)) {
160 IP = MustDominate->
getParent()->getFirstInsertionPt();
162 assert(!IP->isEHPad() &&
"unexpected eh pad!");
175SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
178 if (
Argument *
A = dyn_cast<Argument>(V)) {
180 while ((isa<BitCastInst>(IP) &&
181 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
182 cast<BitCastInst>(IP)->getOperand(0) !=
A) ||
183 isa<DbgInfoIntrinsic>(IP))
194 assert(isa<Constant>(V) &&
195 "Expected the cast argument to be a global/constant");
207 assert((
Op == Instruction::BitCast ||
208 Op == Instruction::PtrToInt ||
209 Op == Instruction::IntToPtr) &&
210 "InsertNoopCastOfTo cannot perform non-noop casts!");
212 "InsertNoopCastOfTo cannot change sizes!");
219 if (
Op == Instruction::IntToPtr) {
220 auto *PtrTy = cast<PointerType>(Ty);
225 if (
Op == Instruction::BitCast) {
226 if (
V->getType() == Ty)
228 if (
CastInst *CI = dyn_cast<CastInst>(V)) {
234 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
236 if (
CastInst *CI = dyn_cast<CastInst>(V))
237 if ((CI->
getOpcode() == Instruction::PtrToInt ||
238 CI->
getOpcode() == Instruction::IntToPtr) &&
243 if ((
CE->getOpcode() == Instruction::PtrToInt ||
244 CE->getOpcode() == Instruction::IntToPtr) &&
247 return CE->getOperand(0);
255 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
265 if (
Constant *CLHS = dyn_cast<Constant>(LHS))
266 if (
Constant *CRHS = dyn_cast<Constant>(RHS))
271 unsigned ScanLimit = 6;
275 if (IP != BlockBegin) {
277 for (; ScanLimit; --IP, --ScanLimit) {
280 if (isa<DbgInfoIntrinsic>(IP))
285 if (isa<OverflowingBinaryOperator>(
I)) {
293 if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
297 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) ==
LHS &&
298 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
300 if (IP == BlockBegin)
break;
306 SCEVInsertPointGuard Guard(Builder,
this);
311 if (!
L->isLoopInvariant(LHS) || !
L->isLoopInvariant(RHS))
break;
313 if (!Preheader)
break;
362 assert(!isa<Instruction>(V) ||
370 if (
Constant *CLHS = dyn_cast<Constant>(V))
375 unsigned ScanLimit = 6;
379 if (IP != BlockBegin) {
381 for (; ScanLimit; --IP, --ScanLimit) {
384 if (isa<DbgInfoIntrinsic>(IP))
386 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(IP)) {
387 if (
GEP->getPointerOperand() == V &&
389 GEP->getOperand(1) ==
Idx) {
391 GEP->setNoWrapFlags(
GEP->getNoWrapFlags() & NW);
395 if (IP == BlockBegin)
break;
400 SCEVInsertPointGuard Guard(Builder,
this);
404 if (!
L->isLoopInvariant(V) || !
L->isLoopInvariant(
Idx))
break;
406 if (!Preheader)
break;
423 if (
A->contains(
B))
return B;
424 if (
B->contains(
A))
return A;
425 if (DT.
dominates(
A->getHeader(),
B->getHeader()))
return B;
426 if (DT.
dominates(
B->getHeader(),
A->getHeader()))
return A;
432const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
434 auto Pair = RelevantLoops.insert(std::make_pair(S,
nullptr));
436 return Pair.first->second;
455 const Loop *
L =
nullptr;
460 return RelevantLoops[S] =
L;
464 if (
const Instruction *
I = dyn_cast<Instruction>(
U->getValue()))
465 return Pair.first->second = SE.LI.
getLoopFor(
I->getParent());
483 bool operator()(std::pair<const Loop *, const SCEV *>
LHS,
484 std::pair<const Loop *, const SCEV *>
RHS)
const {
491 if (
LHS.first !=
RHS.first)
497 if (
LHS.second->isNonConstantNegative()) {
498 if (!
RHS.second->isNonConstantNegative())
500 }
else if (
RHS.second->isNonConstantNegative())
512 const SCEV *URemLHS =
nullptr;
513 const SCEV *URemRHS =
nullptr;
514 if (SE.matchURem(S, URemLHS, URemRHS)) {
527 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
535 Value *Sum =
nullptr;
536 for (
auto I = OpsAndLoops.
begin(), E = OpsAndLoops.
end();
I != E;) {
537 const Loop *CurLoop =
I->first;
546 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
547 if (isa<PointerType>(Sum->
getType())) {
551 for (;
I != E &&
I->first == CurLoop; ++
I) {
554 const SCEV *
X =
I->second;
556 if (!isa<Instruction>(
U->getValue()))
561 }
else if (
Op->isNonConstantNegative()) {
571 if (isa<Constant>(Sum))
589 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
596 Value *Prod =
nullptr;
597 auto I = OpsAndLoops.
begin();
602 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
612 while (E != OpsAndLoops.
end() && *
I == *E &&
Exponent != MaxExponent) {
616 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
635 assert(Result &&
"Nothing was expanded?");
639 while (
I != OpsAndLoops.
end()) {
642 Prod = ExpandOpBinPowN();
643 }
else if (
I->second->isAllOnesValue()) {
650 Value *
W = ExpandOpBinPowN();
652 if (isa<Constant>(Prod))
std::swap(Prod, W);
659 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
661 Prod = InsertBinop(Instruction::Shl, Prod,
662 ConstantInt::get(Ty,
RHS->logBase2()), NWFlags,
665 Prod = InsertBinop(Instruction::Mul, Prod, W, S->
getNoWrapFlags(),
678 if (
RHS.isPowerOf2())
679 return InsertBinop(Instruction::LShr, LHS,
680 ConstantInt::get(
SC->getType(),
RHS.logBase2()),
687 bool GuaranteedNotPoison =
688 ScalarEvolution::isGuaranteedNotToBePoison(RHSExpr);
689 if (!GuaranteedNotPoison)
697 {RHS, ConstantInt::get(RHS->getType(), 1)});
708 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
713 if (L == IVIncInsertLoop) {
716 if (!SE.DT.
dominates(OInst, IVIncInsertPos))
720 IncV = dyn_cast<Instruction>(IncV->
getOperand(0));
730 return isNormalAddRecExprPHI(PN, IncV, L);
745 if (IncV == InsertPos)
752 case Instruction::Add:
753 case Instruction::Sub: {
755 if (!OInst || SE.DT.
dominates(OInst, InsertPos))
756 return dyn_cast<Instruction>(IncV->
getOperand(0));
759 case Instruction::BitCast:
760 return dyn_cast<Instruction>(IncV->
getOperand(0));
761 case Instruction::GetElementPtr:
763 if (isa<Constant>(U))
765 if (
Instruction *OInst = dyn_cast<Instruction>(U)) {
774 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
778 return dyn_cast<Instruction>(IncV->
getOperand(0));
794 for (
auto *InsertPtGuard : InsertPointGuards)
795 if (InsertPtGuard->GetInsertPoint() == It)
796 InsertPtGuard->SetInsertPoint(NewInsertPt);
803 bool RecomputePoisonFlags) {
808 I->dropPoisonGeneratingFlags();
809 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
811 auto *BO = cast<BinaryOperator>(
I);
820 if (RecomputePoisonFlags)
821 FixupPoisonFlags(IncV);
827 if (isa<PHINode>(InsertPos) ||
847 fixupInsertPoints(
I);
848 I->moveBefore(InsertPos);
849 if (RecomputePoisonFlags)
872 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
905 Type *PhiTy = Phi->getType();
919 if (Phi == Requested) {
934 if (!isa<IntegerType>(AR->
getType()))
942 const SCEV *ExtendAfterOp =
944 return ExtendAfterOp == OpAfterExtend;
948 if (!isa<IntegerType>(AR->
getType()))
956 const SCEV *ExtendAfterOp =
958 return ExtendAfterOp == OpAfterExtend;
965SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
968 assert((!IVIncInsertLoop || IVIncInsertPos) &&
969 "Uninitialized insert position");
974 PHINode *AddRecPhiMatch =
nullptr;
981 bool TryNonMatchingSCEV =
985 for (
PHINode &PN :
L->getHeader()->phis()) {
993 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
1001 bool IsMatchingSCEV = PhiSCEV == Normalized;
1005 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1016 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1019 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1024 if (IsMatchingSCEV) {
1028 AddRecPhiMatch = &PN;
1034 if ((!TruncTy || InvertStep) &&
1038 AddRecPhiMatch = &PN;
1040 TruncTy = Normalized->
getType();
1044 if (AddRecPhiMatch) {
1047 InsertedValues.insert(AddRecPhiMatch);
1049 rememberInstruction(IncV);
1051 ReusedValues.
insert(AddRecPhiMatch);
1052 ReusedValues.
insert(IncV);
1053 return AddRecPhiMatch;
1058 SCEVInsertPointGuard Guard(Builder,
this);
1068 PostIncLoops.
clear();
1071 assert(
L->getLoopPreheader() &&
1072 "Can't expand add recurrences without a loop preheader!");
1074 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
1078 assert(!isa<Instruction>(StartV) ||
1093 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1098 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1099 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1110 if (!
L->contains(Pred)) {
1119 IVIncInsertPos : Pred->getTerminator();
1121 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1123 if (isa<OverflowingBinaryOperator>(IncV)) {
1125 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1127 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1134 PostIncLoops = SavedPostIncLoops;
1138 InsertedValues.insert(PN);
1139 InsertedIVs.push_back(PN);
1149 if (PostIncLoops.
count(L)) {
1152 Normalized = cast<SCEVAddRecExpr>(
1156 [[maybe_unused]]
const SCEV *Start = Normalized->
getStart();
1159 "Start does not properly dominate loop header");
1160 assert(SE.
dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1164 Type *TruncTy =
nullptr;
1165 bool InvertStep =
false;
1166 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1170 if (!PostIncLoops.
count(L))
1175 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1181 if (isa<OverflowingBinaryOperator>(Result)) {
1182 auto *
I = cast<Instruction>(Result);
1184 I->setHasNoUnsignedWrap(
false);
1186 I->setHasNoSignedWrap(
false);
1192 if (isa<Instruction>(Result) &&
1193 !SE.DT.
dominates(cast<Instruction>(Result),
1211 SCEVInsertPointGuard Guard(Builder,
this);
1212 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1214 Result = expandIVInc(PN, StepV, L, useSubtract);
1222 if (TruncTy !=
Result->getType())
1245 return expandAddRecExprLiterally(S);
1251 PHINode *CanonicalIV =
nullptr;
1252 if (
PHINode *PN =
L->getCanonicalInductionVariable())
1274 if (isa<PointerType>(S->
getType())) {
1291 return expand(SE.
getAddExpr(AddExprLHS, AddExprRHS));
1302 rememberInstruction(CanonicalIV);
1305 Constant *One = ConstantInt::get(Ty, 1);
1308 if (!PredSeen.
insert(HP).second) {
1315 if (
L->contains(HP)) {
1322 rememberInstruction(
Add);
1333 "IVs with types different from the canonical IV should "
1334 "already have been handled!");
1356 const SCEV *NewS = S;
1358 if (isa<SCEVAddRecExpr>(Ext))
1361 const SCEV *
V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1370 return ReuseOrCreateCast(V, S->
getType(), CastInst::PtrToInt,
1371 GetOptimalInsertionPointForCastOf(V));
1392 bool IsSequential) {
1393 bool PrevSafeMode = SafeUDivMode;
1394 SafeUDivMode |= IsSequential;
1400 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1402 if (IsSequential && i != 0)
1415 SafeUDivMode = PrevSafeMode;
1420 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1424 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1428 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1432 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1436 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
true);
1452 Value *V = expand(SH);
1456 "non-trivial casts should be done with the SCEVs directly!");
1457 V = InsertNoopCastOfTo(V, Ty);
1462Value *SCEVExpander::FindValueInExprValueMap(
1471 if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
1474 for (
Value *V : SE.getSCEVValues(S)) {
1491 DropPoisonGeneratingInsts.
clear();
1502Value *SCEVExpander::expand(
const SCEV *S) {
1509 auto SafeToHoist = [](
const SCEV *S) {
1511 if (
const auto *
D = dyn_cast<SCEVUDivExpr>(S)) {
1512 if (
const auto *SC = dyn_cast<SCEVConstant>(
D->getRHS()))
1514 return SC->getValue()->isZero();
1524 if (SafeToHoist(S)) {
1526 L =
L->getParentLoop()) {
1529 if (
BasicBlock *Preheader =
L->getLoopPreheader()) {
1535 InsertPt =
L->getHeader()->getFirstInsertionPt();
1542 InsertPt =
L->getHeader()->getFirstInsertionPt();
1546 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1547 InsertPt = std::next(InsertPt);
1555 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1556 if (
I != InsertedExpressions.end())
1559 SCEVInsertPointGuard Guard(Builder,
this);
1564 Value *
V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1567 V = fixupLCSSAFormFor(V);
1571 I->dropPoisonGeneratingAnnotations();
1574 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
1576 auto *BO = cast<BinaryOperator>(
I);
1582 if (
auto *NNI = dyn_cast<PossiblyNonNegInst>(
I)) {
1583 auto *Src = NNI->getOperand(0);
1586 DL).value_or(
false))
1587 NNI->setNonNeg(
true);
1597 InsertedExpressions[std::make_pair(S, &*InsertPt)] =
V;
1601void SCEVExpander::rememberInstruction(
Value *
I) {
1602 auto DoInsert = [
this](
Value *
V) {
1603 if (!PostIncLoops.
empty())
1604 InsertedPostIncValues.insert(V);
1606 InsertedValues.insert(V);
1616void SCEVExpander::replaceCongruentIVInc(
1626 dyn_cast<Instruction>(
Phi->getIncomingValueForBlock(LatchBlock));
1627 if (!OrigInc || !IsomorphicInc)
1634 !(ChainedPhis.count(Phi) ||
1635 isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1636 (ChainedPhis.count(Phi) ||
1637 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1651 const SCEV *TruncExpr =
1653 if (OrigInc == IsomorphicInc || TruncExpr != SE.
getSCEV(IsomorphicInc) ||
1657 bool BothHaveNUW =
false;
1658 bool BothHaveNSW =
false;
1659 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1660 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1661 if (OBOIncV && OBOIsomorphic) {
1663 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1665 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1678 "Should only replace an increment with a wider one.");
1679 if (BothHaveNUW || BothHaveNSW) {
1685 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1686 << *IsomorphicInc <<
'\n');
1687 Value *NewInc = OrigInc;
1690 if (
PHINode *PN = dyn_cast<PHINode>(OrigInc))
1691 IP = PN->
getParent()->getFirstInsertionPt();
1716 for (
PHINode &PN : L->getHeader()->phis())
1730 unsigned NumElim = 0;
1740 auto *Const = dyn_cast<SCEVConstant>(SE.
getSCEV(PN));
1743 return Const->getValue();
1748 if (
Value *V = SimplifyPHINode(Phi)) {
1749 if (V->getType() != Phi->getType())
1752 Phi->replaceAllUsesWith(V);
1756 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1767 if (Phi->getType()->isIntegerTy() &&
TTI &&
1773 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1776 const SCEV *TruncExpr =
1778 ExprToIVMap[TruncExpr] = Phi;
1789 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1791 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1794 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1796 Value *NewIV = OrigPhiRef;
1797 if (OrigPhiRef->
getType() != Phi->getType()) {
1799 L->getHeader()->getFirstInsertionPt());
1803 Phi->replaceAllUsesWith(NewIV);
1815 L->getExitingBlocks(ExitingBlocks);
1822 if (!
match(BB->getTerminator(),
1839 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
1850 struct OperationIndices {
1851 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
1852 Opcode(Opc), MinIdx(min), MaxIdx(
max) { }
1866 S->getOperand(0)->getType(),
1870 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
1871 unsigned MinIdx = 0,
1874 return NumRequired *
1878 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
1881 Type *OpType = S->getType();
1887 switch (S->getSCEVType()) {
1895 Cost = CastCost(Instruction::PtrToInt);
1898 Cost = CastCost(Instruction::Trunc);
1901 Cost = CastCost(Instruction::ZExt);
1904 Cost = CastCost(Instruction::SExt);
1907 unsigned Opcode = Instruction::UDiv;
1908 if (
auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1909 if (SC->getAPInt().isPowerOf2())
1910 Opcode = Instruction::LShr;
1911 Cost = ArithCost(Opcode, 1);
1915 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1921 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1930 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1931 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1932 switch (S->getSCEVType()) {
1936 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1937 Cost += ArithCost(Instruction::Or,
1938 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1939 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1943 assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1944 "Unhandled SCEV expression type?");
1951 unsigned NumRecurrences = S->getNumOperands() - 1;
1957 Worklist.
emplace_back(Instruction::PHI, 0, S->getOperand(0));
1959 for (
const SCEV *
Op : S->operands().drop_front())
1965 for (
auto &CostOp : Operations) {
1966 for (
auto SCEVOp :
enumerate(S->operands())) {
1968 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1969 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1970 Worklist.
emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1976bool SCEVExpander::isHighCostExpansionHelper(
1986 if (!isa<SCEVConstant>(S) && !Processed.
insert(S).second)
1995 L->getHeader()->getParent()->hasMinSize()
2010 const APInt &
Imm = cast<SCEVConstant>(S)->getAPInt();
2014 return Cost > Budget;
2048 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2049 "Nary expr should have more than 1 operand.");
2054 return Cost > Budget;
2057 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2058 "Polynomial should be at least linear");
2059 Cost += costAndCollectOperands<SCEVAddRecExpr>(
2061 return Cost > Budget;
2076 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2090 auto *
I = Builder.
CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2097 "non-affine expression");
2101 const SCEV *ExitCount =
2104 assert(!isa<SCEVCouldNotCompute>(ExitCount) &&
"Invalid loop count");
2119 Value *TripCountVal = expand(ExitCount, Loc);
2124 Value *StepValue = expand(Step, Loc);
2126 Value *StartValue = expand(Start, Loc);
2144 auto ComputeEndCheck = [&]() ->
Value * {
2152 Value *MulV, *OfMul;
2153 if (Step->
isOne()) {
2157 MulV = TruncTripCount;
2161 {AbsStep, TruncTripCount},
2167 Value *
Add =
nullptr, *Sub =
nullptr;
2171 if (isa<PointerType>(ARTy)) {
2181 Sub = Builder.
CreateSub(StartValue, MulV);
2184 Value *EndCompareLT =
nullptr;
2185 Value *EndCompareGT =
nullptr;
2186 Value *EndCheck =
nullptr;
2188 EndCheck = EndCompareLT = Builder.
CreateICmp(
2191 EndCheck = EndCompareGT = Builder.
CreateICmp(
2193 if (NeedPosCheck && NeedNegCheck) {
2195 EndCheck = Builder.
CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2197 return Builder.
CreateOr(EndCheck, OfMul);
2199 Value *EndCheck = ComputeEndCheck();
2204 if (SrcBits > DstBits) {
2206 auto *BackedgeCheck =
2208 ConstantInt::get(Loc->
getContext(), MaxVal));
2212 EndCheck = Builder.
CreateOr(EndCheck, BackedgeCheck);
2220 const auto *
A = cast<SCEVAddRecExpr>(Pred->
getExpr());
2221 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2231 if (NUSWCheck && NSSWCheck)
2232 return Builder.
CreateOr(NUSWCheck, NSSWCheck);
2247 for (
const auto *Pred : Union->getPredicates()) {
2257Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2258 auto *DefI = dyn_cast<Instruction>(V);
2259 if (!PreserveLCSSA || !DefI)
2265 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2276 if (DefI->getType()->isIntegerTy())
2282 auto RemoveUserOnExit =
2291 for (
PHINode *PN : InsertedPHIs)
2292 rememberInstruction(PN);
2293 for (
PHINode *PN : PHIsToRemove) {
2296 InsertedValues.erase(PN);
2297 InsertedPostIncValues.erase(PN);
2323struct SCEVFindUnsafe {
2326 bool IsUnsafe =
false;
2329 : SE(SE), CanonicalMode(CanonicalMode) {}
2331 bool follow(
const SCEV *S) {
2341 if (!AR->getLoop()->getLoopPreheader() &&
2342 (!CanonicalMode || !AR->isAffine())) {
2349 bool isDone()
const {
return IsUnsafe; }
2354 SCEVFindUnsafe Search(SE, CanonicalMode);
2356 return !Search.IsUnsafe;
2374 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2387 for (
auto [
I, Flags] : Expander.OrigFlags)
2393 InsertedInstructions.end());
2403 [&InsertedSet](
Value *U) {
2404 return InsertedSet.contains(cast<Instruction>(U));
2406 "removed instruction should only be used by instructions inserted "
2407 "during expansion");
2409 assert(!
I->getType()->isVoidTy() &&
2410 "inserted instruction should have non-void types");
2412 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.
@ 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 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
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
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 * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
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="")
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="")
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.
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 * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
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.
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
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.
@ 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.
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.
@ 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)
auto pred_size(const MachineBasicBlock *BB)
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
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 pred_begin(const MachineBasicBlock *BB)
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...
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)