36#define DEBUG_TYPE "vplan"
43class PlainCFGBuilder {
54 std::unique_ptr<VPlan> Plan;
75 bool isExternalDef(
Value *Val);
82 : TheLoop(Lp), LI(LI), LVer(LVer), Plan(std::make_unique<VPlan>(Lp)) {}
85 std::unique_ptr<VPlan> buildPlainCFG();
95 VPBBPreds.
push_back(getOrCreateVPBB(Pred));
100 return L && BB == L->getHeader();
104void PlainCFGBuilder::fixHeaderPhis() {
105 for (
auto *Phi : PhisToFix) {
106 assert(IRDef2VPValue.count(Phi) &&
"Missing VPInstruction for PHINode.");
107 VPValue *VPVal = IRDef2VPValue[
Phi];
110 assert(PhiR->getNumOperands() == 0 &&
"Expected VPPhi with no operands.");
112 "Expected Phi in header block.");
114 "header phi must have exactly 2 operands");
117 getOrCreateVPOperand(
Phi->getIncomingValueForBlock(Pred)));
123VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
124 if (
auto *VPBB = BB2VPBB.lookup(BB)) {
131 LLVM_DEBUG(
dbgs() <<
"Creating VPBasicBlock for " << Name <<
"\n");
132 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
143bool PlainCFGBuilder::isExternalDef(
Value *Val) {
159VPValue *PlainCFGBuilder::getOrCreateVPOperand(
Value *IRVal) {
160 auto VPValIt = IRDef2VPValue.find(IRVal);
161 if (VPValIt != IRDef2VPValue.end())
164 return VPValIt->second;
173 assert(isExternalDef(IRVal) &&
"Expected external definition as operand.");
177 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
178 IRDef2VPValue[IRVal] = NewVPVal;
185void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
189 for (Instruction &InstRef : *BB) {
194 assert(!IRDef2VPValue.count(Inst) &&
195 "Instruction shouldn't have been visited.");
204 VPValue *
Cond = getOrCreateVPOperand(Br->getCondition());
212 if (
SI->getNumCases() == 0)
215 for (
auto Case :
SI->cases())
216 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
222 VPSingleDefRecipe *NewR;
233 PhisToFix.push_back(Phi);
237 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
238 for (
unsigned I = 0;
I !=
Phi->getNumOperands(); ++
I) {
239 VPPredToIncomingValue[BB2VPBB[
Phi->getIncomingBlock(
I)]] =
240 getOrCreateVPOperand(
Phi->getIncomingValue(
I));
244 VPPredToIncomingValue.
lookup(Pred->getExitingBasicBlock()));
249 VPIRMetadata MD(*Inst);
251 const auto &[AliasScopeMD, NoAliasMD] =
254 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
256 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
267 CI->getType(), CI->getDebugLoc(),
272 LI->getDebugLoc(), MD);
283 IRDef2VPValue[Inst] = NewR;
288std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
291 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
292 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
305 "Unexpected loop preheader");
306 for (
auto &
I : *ThePreheaderBB) {
307 if (
I.getType()->isVoidTy())
309 IRDef2VPValue[&
I] = Plan->getOrAddLiveIn(&
I);
312 LoopBlocksRPO RPO(TheLoop);
315 for (BasicBlock *BB : RPO) {
317 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
319 setVPBBPredsFromBB(VPBB, BB);
322 createVPInstructionsForVPBB(VPBB, BB);
329 getOrCreateVPBB(
SI->getDefaultDest())};
330 for (
auto Case :
SI->cases())
331 Succs.
push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
342 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
343 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
347 for (
auto *EB : Plan->getExitBlocks())
348 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
355 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->
getHeader()));
356 Plan->getEntry()->setPlan(&*Plan);
363 for (
auto *EB : Plan->getExitBlocks()) {
364 for (VPRecipeBase &R : EB->phis()) {
366 PHINode &
Phi = PhiR->getIRPhi();
367 assert(PhiR->getNumOperands() == 0 &&
368 "no phi operands should be added yet");
369 for (BasicBlock *Pred :
predecessors(EB->getIRBasicBlock()))
371 getOrCreateVPOperand(
Phi.getIncomingValueForBlock(Pred)));
376 return std::move(Plan);
389 if (Preds.
size() != 2)
392 auto *PreheaderVPBB = Preds[0];
393 auto *LatchVPBB = Preds[1];
394 if (!VPDT.
dominates(PreheaderVPBB, HeaderVPB) ||
398 if (!VPDT.
dominates(PreheaderVPBB, HeaderVPB) ||
415 if (LatchVPBB->getSingleSuccessor() ||
416 LatchVPBB->getSuccessors()[0] != HeaderVPB)
419 assert(LatchVPBB->getNumSuccessors() == 2 &&
"Must have 2 successors");
423 "terminator must be a BranchOnCond");
425 Not->insertBefore(Term);
426 Term->setOperand(0, Not);
427 LatchVPBB->swapSuccessors();
438 Type *CanIVTy =
nullptr;
442 VPPhi *OutermostVPPhi =
nullptr;
443 if (HeaderVPB == OutermostHeaderVPBB) {
444 OutermostVPPhi =
cast<VPPhi>(&OutermostHeaderVPBB->front());
466 R->setEntry(HeaderVPB);
467 R->setExiting(LatchVPBB);
470 if (OutermostVPPhi) {
487 HeaderVPBB->
insert(CanonicalIVPHI, HeaderVPBB->
begin());
501 auto *CanonicalIVIncrement = Builder.createAdd(
502 CanonicalIVPHI, &Plan.
getVFxUF(),
DL,
"index.next", {true, false});
503 CanonicalIVPHI->addOperand(CanonicalIVIncrement);
521 VPValue *Exiting = ExitIRI->getIncomingValueForBlock(MiddleVPBB);
526 ExitIRI->setIncomingValueForBlock(MiddleVPBB, Exiting);
554 if (LatchVPBB->getNumSuccessors() == 2) {
559 LatchVPBB->swapSuccessors();
569 "Invalid backedge-taken count");
572 InductionTy, TheLoop);
596 "unexpected predecessor order of scalar ph");
597 for (
const auto &[PhiR, ScalarPhiR] :
600 VPValue *BackedgeVal = VectorPhiR->getOperand(1);
601 VPValue *ResumeFromVectorLoop =
608 {ResumeFromVectorLoop, VectorPhiR->getOperand(0)},
609 VectorPhiR->getDebugLoc());
618 auto GetSimplifiedLiveInViaSCEV = [&](
VPValue *VPV) ->
VPValue * {
626 if (
VPValue *SimplifiedLiveIn = GetSimplifiedLiveInViaSCEV(LiveIn))
627 LiveIn->replaceAllUsesWith(SimplifiedLiveIn);
634std::unique_ptr<VPlan>
638 PlainCFGBuilder Builder(TheLoop, &LI, LVer);
639 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
656 "step must be loop invariant");
661 "Start VPValue must match IndDesc's start value");
675 VPUser *ExtractLastPartUser = ExtractLastPart->getSingleUser();
676 assert(ExtractLastPartUser &&
"must have a single user");
682 "last lane must be extracted in the middle block");
684 ExtractLastLane->replaceAllUsesWith(
686 ExtractLastLane->eraseFromParent();
687 ExtractLastPart->eraseFromParent();
693 Phi, Start, Step, &Plan.
getVFxUF(), IndDesc,
DL);
694 ReplaceExtractsWithExitingIVValue(WideIV);
700 "must have an integer or float induction at this point");
714 Phi, Start, Step, &Plan.
getVF(), IndDesc, Flags,
DL);
716 ReplaceExtractsWithExitingIVValue(WideIV);
730 auto TryToPushSinkCandidate = [&](
VPRecipeBase *SinkCandidate) {
733 if (SinkCandidate == Previous)
737 !Seen.
insert(SinkCandidate).second ||
750 for (
unsigned I = 0;
I != WorkList.
size(); ++
I) {
753 "only recipes with a single defined value expected");
768 if (SinkCandidate == FOR)
771 SinkCandidate->moveAfter(Previous);
772 Previous = SinkCandidate;
798 [&VPDT, HoistPoint](
VPUser *U) {
799 auto *R = cast<VPRecipeBase>(U);
800 return HoistPoint == R ||
801 VPDT.properlyDominates(HoistPoint, R);
803 "HoistPoint must dominate all users of FOR");
805 auto NeedsHoisting = [HoistPoint, &VPDT,
807 VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
811 if (!Visited.
insert(HoistCandidate).second)
817 return HoistCandidate;
827 for (
unsigned I = 0;
I != HoistCandidates.
size(); ++
I) {
830 "only recipes with a single defined value expected");
842 if (
auto *R = NeedsHoisting(
Op)) {
845 if (R->getNumDefinedValues() != 1)
859 HoistCandidate->moveBefore(*HoistPoint->
getParent(),
881 VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
882 while (
auto *PrevPhi =
884 assert(PrevPhi->getParent() == FOR->getParent() &&
885 "PrevPhi must be in same block as FOR");
887 "PrevPhi must not be visited multiple times");
888 Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
891 assert(Previous &&
"Previous must be a recipe");
902 VPBuilder LoopBuilder(InsertBlock, InsertPt);
905 {FOR, FOR->getBackedgeValue()});
907 return &U != RecurSplice;
925 "header must dominate its latch");
931 assert(PhiR->getNumOperands() == 2 &&
932 "Must have 2 operands for header phis");
936 VPValue *BackedgeValue = PhiR->getOperand(1);
938 if (FixedOrderRecurrences.
contains(Phi)) {
946 auto InductionIt = Inductions.
find(Phi);
947 if (InductionIt != Inductions.
end())
950 PhiR->getDebugLoc());
956 "incoming value must match start value");
958 unsigned ScaleFactor = 1;
959 bool UseOrderedReductions = !AllowReordering && RdxDesc.
isOrdered();
973 PhiR->replaceAllUsesWith(HeaderPhiR);
974 PhiR->eraseFromParent();
980 for (
const auto &[HeaderPhiR, ScalarPhiR] :
984 ResumePhiR->setName(
"scalar.recur.init");
986 ExtractLastLane->setName(
"vector.recur.extract");
1005 if (!PhiR || !PhiR->isInLoop() || (MinVF.
isScalar() && !PhiR->isOrdered()))
1008 RecurKind Kind = PhiR->getRecurrenceKind();
1012 "AnyOf and Find reductions are not allowed for in-loop reductions");
1014 bool IsFPRecurrence =
1022 for (
unsigned I = 0;
I != Worklist.
size(); ++
I) {
1026 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
1029 "U must be either in the loop region, the middle block or the "
1030 "scalar preheader.");
1037 Worklist.
insert(UserRecipe);
1051 assert(Blend->getNumIncomingValues() == 2 &&
1052 "Blend must have 2 incoming values");
1053 unsigned PhiRIdx = Blend->getIncomingValue(0) == PhiR ? 0 : 1;
1054 assert(Blend->getIncomingValue(PhiRIdx) == PhiR &&
1055 "PhiR must be an operand of the blend");
1056 Blend->replaceAllUsesWith(Blend->getIncomingValue(1 - PhiRIdx));
1060 if (IsFPRecurrence) {
1065 ->getFastMathFlags();
1069 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
1077 "Expected current VPInstruction to be a call to the "
1078 "llvm.fmuladd intrinsic");
1079 assert(CurrentLink->getOperand(2) == PreviousLink &&
1080 "expected a call where the previous link is the added operand");
1088 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
1090 LinkVPBB->
insert(FMulRecipe, CurrentLink->getIterator());
1096 VPBuilder Builder(LinkVPBB, CurrentLink->getIterator());
1097 auto *
Sub = Builder.createSub(Zero, CurrentLink->getOperand(1),
1099 Sub->setUnderlyingValue(CurrentLinkI);
1103 unsigned IndexOfFirstOperand = 0;
1109 "must be a select recipe");
1110 IndexOfFirstOperand = 1;
1115 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
1116 ? IndexOfFirstOperand + 1
1117 : IndexOfFirstOperand;
1118 VecOp = CurrentLink->getOperand(VecOpId);
1120 VecOp != PreviousLink &&
1123 1 - (VecOpId - IndexOfFirstOperand)) == PreviousLink &&
1124 "PreviousLink must be the operand other than VecOp");
1132 assert(PhiR->getVFScaleFactor() == 1 &&
1133 "inloop reductions must be unscaled");
1135 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
1143 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->
end())));
1147 CurrentLink->replaceAllUsesWith(RedRecipe);
1152 if (!UserR || UserR->getParent() != LinkVPBB)
1156 UserR->moveAfter(RedRecipe);
1159 PreviousLink = RedRecipe;
1164 R->eraseFromParent();
1183 if (!VPI || VPI->getOpcode() != Instruction::Load) {
1184 assert(!R.mayReadFromMemory() &&
"unexpected recipe reading memory");
1189 VPValue *Ptr = VPI->getOperand(0);
1192 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Found non-dereferenceable "
1193 "load with SCEVCouldNotCompute pointer\n");
1198 Type *LoadTy = VPI->getResultType();
1199 const SCEV *SizeSCEV =
1204 TheLoop, SE, DT, AC, &Preds))
1208 dbgs() <<
"LV: Not vectorizing: Auto-vectorization of loops with "
1209 "potentially faulting load is not supported.\n");
1242 if (Pred == MiddleVPBB)
1249 EarlyExitingVPBB->getTerminator()->eraseFromParent();
1262 if (MiddleVPBB->getNumSuccessors() == 1) {
1264 "must have ScalarPH as single successor");
1268 assert(MiddleVPBB->getNumSuccessors() == 2 &&
"must have 2 successors");
1286 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
1306 TopRegion->
setName(
"vector loop");
1312 "only a single-exit block is supported currently");
1315 "the exit block must have middle block as single predecessor");
1319 "The vector loop region must have the middle block as its single "
1320 "successor for now");
1323 Header->
splitAt(Header->getFirstNonPhi());
1328 VPBuilder Builder(Header, Header->getFirstNonPhi());
1336 [[maybe_unused]]
bool TermBranchOnCount =
1340 assert(TermBranchOnCount &&
1343 std::next(IVInc->getDefiningRecipe()->getIterator()) ==
1345 "Unexpected canonical iv increment");
1349 OrigLatch->
splitAt(IVInc->getDefiningRecipe()->getIterator());
1350 Latch->
setName(
"vector.latch");
1364 NeedsPhi[V].push_back(&R);
1367 Builder.setInsertPoint(Latch, Latch->
begin());
1369 for (
const auto &[V,
Users] : NeedsPhi) {
1379 U->replaceUsesOfWith(V, Phi);
1396 R.getVPSingleValue()->replaceAllUsesWith(Ext);
1411 unsigned NumPreds = ScalarPH->getNumPredecessors();
1414 assert(Phi->getNumIncoming() == NumPreds - 1 &&
1415 "must have incoming values for all predecessors");
1416 Phi->addOperand(Phi->getOperand(NumPreds - 2));
1431 if (AddBranchWeights) {
1435 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1441 bool AddBranchWeights) {
1451 auto InsertPt = EntryVPBB->
begin();
1452 while (InsertPt != EntryVPBB->
end() &&
1460 ElementCount MinProfitableTripCount,
bool RequiresScalarEpilogue,
1475 auto GetMinTripCount = [&]() ->
const SCEV * {
1484 const SCEV *MinProfitableTripCountSCEV =
1486 return SE.
getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1491 VPBasicBlock *CheckVPBB = CheckBlock ? CheckBlock : EntryVPBB;
1494 const SCEV *Step = GetMinTripCount();
1505 TripCountCheck = Plan.
getTrue();
1513 TripCountCheck = Builder.createICmp(
1514 CmpPred, TripCountVPV, MinTripCountVPV,
DL,
"min.iters.check");
1523 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1534 RequiresScalarEpilogue,
false,
1540 VPlan &Plan,
Value *VectorTripCount,
bool RequiresScalarEpilogue,
1541 ElementCount EpilogueVF,
unsigned EpilogueUF,
unsigned MainLoopStep,
1555 auto *CheckMinIters = Builder.createICmp(
1566 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1567 const uint32_t Weights[] = {EstimatedSkipCount,
1568 MainLoopStep - EstimatedSkipCount};
1572 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1589 auto GetMinOrMaxCompareValue =
1603 if (MinOrMaxR->getOperand(0) == RedPhiR)
1604 return MinOrMaxR->getOperand(1);
1606 assert(MinOrMaxR->getOperand(1) == RedPhiR &&
1607 "Reduction phi operand expected");
1608 return MinOrMaxR->getOperand(0);
1613 MinOrMaxNumReductionsToHandle;
1614 bool HasUnsupportedPhi =
false;
1621 HasUnsupportedPhi =
true;
1625 Cur->getRecurrenceKind())) {
1626 HasUnsupportedPhi =
true;
1630 VPValue *MinOrMaxOp = GetMinOrMaxCompareValue(Cur);
1634 MinOrMaxNumReductionsToHandle.
emplace_back(Cur, MinOrMaxOp);
1637 if (MinOrMaxNumReductionsToHandle.
empty())
1655 for (
auto &R : *VPBB) {
1663 VPValue *AllNaNLanes =
nullptr;
1665 for (
const auto &[
_, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1668 AllNaNLanes = AllNaNLanes ? LatchBuilder.
createOr(AllNaNLanes, RedNaNLanes)
1676 for (
const auto &[RedPhiR,
_] : MinOrMaxNumReductionsToHandle) {
1678 RedPhiR->getRecurrenceKind()) &&
1679 "unsupported reduction");
1684 assert(RdxResult &&
"must find a ComputeReductionResult");
1686 auto *NewSel = MiddleBuilder.
createSelect(AnyNaNLane, RedPhiR,
1687 RdxResult->getOperand(0));
1689 assert(!RdxResults.
contains(RdxResult) &&
"RdxResult already used");
1690 RdxResults.
insert(RdxResult);
1695 "Unexpected terminator");
1696 auto *IsLatchExitTaken = LatchBuilder.
createICmp(
1698 LatchExitingBranch->getOperand(1));
1699 auto *AnyExitTaken = LatchBuilder.
createOr(AnyNaNLane, IsLatchExitTaken);
1706 auto IsTC = [&Plan](
VPValue *V) {
1711 VPValue *VecV = ResumeR->getOperand(0);
1715 VPValue *DIVTC = DerivedIV->getOperand(1);
1716 if (DerivedIV->getNumUsers() == 1 && IsTC(DIVTC)) {
1720 DerivedIV->setOperand(1, NewSel);
1727 LLVM_DEBUG(
dbgs() <<
"Found resume phi we cannot update for VPlan with "
1728 "FMaxNum/FMinNum reduction.\n");
1738 VPValue *MiddleCond = MiddleTerm->getOperand(0);
1775 PhiR->getRecurrenceKind()))
1785 VPValue *BackedgeSelect = PhiR->getBackedgeValue();
1786 VPValue *CondSelect = BackedgeSelect;
1790 if (HeaderMask && !
match(BackedgeSelect,
1795 VPValue *
Cond =
nullptr, *Op1 =
nullptr, *Op2 =
nullptr;
1804 assert(!Blend->isNormalized() &&
"must run before blend normalizaion");
1805 unsigned NumIncomingDataValues = 0;
1806 for (
unsigned I = 0;
I < Blend->getNumIncomingValues(); ++
I) {
1807 VPValue *Incoming = Blend->getIncomingValue(
I);
1808 if (Incoming != PhiR) {
1809 ++NumIncomingDataValues;
1810 Cond = Blend->getMask(
I);
1815 return NumIncomingDataValues == 1;
1822 !MatchBlend(SelectR))
1825 assert(
Cond != HeaderMask &&
"Cond must not be HeaderMask");
1832 assert(RdxResult &&
"Could not find reduction result");
1836 auto *MaskPHI = Builder.createWidenPhi(Plan.
getFalse());
1839 Builder.setInsertPoint(SelectR);
1847 assert(Op2 == PhiR &&
"data value must be selected if Cond is true");
1850 Cond = Builder.createLogicalAnd(HeaderMask,
Cond);
1854 MaskPHI->addOperand(MaskSelect);
1860 PhiR->setBackedgeValue(DataSelect);
1863 Builder.setInsertPoint(RdxResult);
1864 auto *ExtractLastActive =
1866 {PhiR->getStartValue(), DataSelect, MaskSelect},
1867 RdxResult->getDebugLoc());
1868 RdxResult->replaceAllUsesWith(ExtractLastActive);
1869 RdxResult->eraseFromParent();
1894 "inloop and ordered reductions not supported");
1896 "FindIV reduction must not be scaled");
1908 "backedge value must be a select");
1909 if (FindIVSelectR->getOperand(1) != WideIV &&
1924 WidenCanIV->insertBefore(WideIV);
1927 FindIVSelectR->setOperand(FindIVSelectR->getOperand(1) == WideIV ? 1 : 2,
1984 auto *FinalMinOrMaxCmp =
1989 auto *FinalIVSelect =
1990 Builder.createSelect(FinalMinOrMaxCmp, LastIVExiting, MaxIV);
1999 auto *DerivedIVRecipe =
2004 DerivedIVRecipe->insertBefore(&*Builder.getInsertPoint());
2005 FinalCanIV = DerivedIVRecipe;
2013 VPValue *FinalIV = Builder.createSelect(
2014 AlwaysFalse, FindIVSelect->
getOperand(2), FinalCanIV);
2031 if (!MinOrMaxPhiR || !MinOrMaxPhiR->hasUsesOutsideReductionChain())
2042 RecurKind RdxKind = MinOrMaxPhiR->getRecurrenceKind();
2045 "only min/max recurrences support users outside the reduction chain");
2060 assert(MinOrMaxOp->getNumUsers() == 2 &&
2061 "MinOrMaxOp must have exactly 2 users");
2062 VPValue *MinOrMaxOpValue = MinOrMaxOp->getOperand(0);
2063 if (MinOrMaxOpValue == MinOrMaxPhiR)
2064 MinOrMaxOpValue = MinOrMaxOp->getOperand(1);
2071 if (!Cmp || Cmp->getNumUsers() != 1 ||
2072 (CmpOpA != MinOrMaxOpValue && CmpOpB != MinOrMaxOpValue))
2075 if (MinOrMaxOpValue != CmpOpB)
2081 if (MinOrMaxPhiR->getNumUsers() != 2)
2087 "one user must be MinOrMaxOp");
2088 assert(MinOrMaxResult &&
"MinOrMaxResult must be a user of MinOrMaxOp");
2105 FindIVPhiR->getRecurrenceKind()))
2108 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
2109 "cannot handle inloop/ordered reductions yet");
2115 FindIVPhiR->getBackedgeValue());
2117 "must be able to retrieve the FindIVResult VPInstruction");
2129 bool IsValidKindPred = [RdxKind, Pred]() {
2143 if (!IsValidKindPred) {
2146 DEBUG_TYPE,
"VectorizationMultiUseReductionPredicate",
2148 <<
"Multi-use reduction with predicate "
2150 <<
" incompatible with reduction kind";
2156 auto *FindIVCmp = FindIVSelect->getOperand(0)->getDefiningRecipe();
2159 "both results must be computed in the same block");
2163 MinOrMaxResult->
moveBefore(*FindIVRdxResult->getParent(),
2164 FindIVRdxResult->getIterator());
2167 if (IsStrictPredicate) {
2170 MinOrMaxResult, FindIVSelect, FindIVCmp,
2201 auto *FinalMinOrMaxCmp =
2204 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2205 auto *FinalIVSelect =
2206 B.createSelect(FinalMinOrMaxCmp, LastIVExiting,
Sentinel);
2207 FindIVRdxResult->setOperand(0, FinalIVSelect);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
iv Induction Variable Users
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static constexpr uint32_t MinItersBypassWeights[]
const SmallVectorImpl< MachineOperand > & Cond
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static bool isHeaderBB(BasicBlock *BB, Loop *L)
static bool handleFirstArgMinOrMax(VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR, VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV, VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect, VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult)
Given a first argmin/argmax pattern with strict predicate consisting of 1) a MinOrMax reduction MinOr...
static VPHeaderPHIRecipe * createWidenInductionRecipe(PHINode *Phi, VPPhi *PhiR, VPIRValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, DebugLoc DL)
Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe for Phi based on IndDesc.
static void insertCheckBlockBeforeVectorLoop(VPlan &Plan, VPBasicBlock *CheckBlockVPBB)
Insert CheckBlockVPBB on the edge leading to the vector preheader, connecting it to both vector and s...
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-in and replace them with constants, if they can be simplified via SCEV.
static bool sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, VPDominatorTree &VPDT)
Try to sink users of FOR after Previous.
static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static bool tryToSinkOrHoistRecurrenceUsers(VPBasicBlock *HeaderVPBB, VPDominatorTree &VPDT)
Sink users of fixed-order recurrences past or hoist before the recipe defining the previous value,...
static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB, VPValue *Cond, bool AddBranchWeights)
Create a BranchOnCond terminator in CheckBlockVPBB.
static void addCanonicalIVRecipes(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, Type *IdxTy, DebugLoc DL)
static bool canonicalHeaderAndLatch(VPBlockBase *HeaderVPB, const VPDominatorTree &VPDT)
Checks if HeaderVPB is a loop header block in the plain CFG; that is, it has exactly 2 predecessors (...
static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, VPDominatorTree &VPDT)
Try to hoist Previous and its operands before all users of FOR.
static VPInstruction * findFindIVSelect(VPValue *BackedgeVal)
Find and return the final select instruction of the FindIV result pattern for the given BackedgeVal: ...
static constexpr uint32_t CheckBypassWeights[]
static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, VPBasicBlock *MiddleVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Check if all loads in the loop are dereferenceable.
static void printAfterInitialConstruction(VPlan &)
To make RUN_VPLAN_PASS print initial VPlan.
static VPBasicBlock::iterator getExpandSCEVInsertPt(VPBasicBlock *EntryVPBB)
Return an insert point in EntryVPBB after existing VPIRPhi, VPIRInstruction and VPExpandSCEVRecipe re...
static auto getMatchingPhisForScalarLoop(VPBasicBlock *Header, VPBasicBlock *ScalarHeader)
Return an iterator range to iterate over pairs of matching phi nodes in Header and ScalarHeader,...
static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB)
Creates extracts for values in Plan defined in a loop region and used outside a loop region.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
A parsed version of the target data layout string in and methods for querying it.
static DebugLoc getUnknown()
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Implements a dense probed hash-table based set.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
static constexpr ElementCount getFixed(ScalarTy MinVal)
constexpr bool isScalar() const
Exactly one element.
Convenience struct for specifying and reasoning about fast-math flags.
static FastMathFlags getFast()
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
A struct for saving information about induction variables.
InductionKind getKind() const
const SCEV * getStep() const
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
Value * getStartValue() const
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
Represents a single loop in the control flow graph.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Post-order traversal of a graph.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
FastMathFlags getFastMathFlags() const
static bool isFPMinMaxNumRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point minnum/maxnum kind.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
TrackingVH< Value > getRecurrenceStartValue() const
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isIntMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer min/max kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
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 isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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.
The instances of the Type class are immutable: once they are created, they are never changed.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
RecipeListTy::iterator iterator
Instruction iterators...
iterator begin()
Recipe iterator methods.
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
const VPRecipeBase & back() const
void insert(VPRecipeBase *Recipe, iterator InsertPt)
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
VPRegionBlock * getParent()
const VPBasicBlock * getExitingBasicBlock() const
void setName(const Twine &newName)
size_t getNumSuccessors() const
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
const VPBlocksTy & getPredecessors() const
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
VPBlockBase * getSinglePredecessor() const
void swapPredecessors()
Swap predecessors of the block.
const VPBasicBlock * getEntryBasicBlock() const
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
void setParent(VPRegionBlock *P)
VPBlockBase * getSingleSuccessor() const
const VPBlocksTy & getSuccessors() const
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPBasicBlock::iterator getInsertPoint() const
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, const VPIRMetadata &Metadata={})
VPInstruction * createFCmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new FCmp VPInstruction with predicate Pred and operands A and B.
VPInstructionWithType * createScalarLoad(Type *ResultTy, VPValue *Addr, DebugLoc DL, const VPIRMetadata &Metadata={})
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
VPExpandSCEVRecipe * createExpandSCEV(const SCEV *Expr)
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B)
A special type of VPBasicBlock that wraps an existing IR basic block.
Class to record and manage LLVM IR flags.
RecurKind getRecurKind() const
This is a concrete Recipe that models a single VPlan-level instruction.
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
@ FirstOrderRecurrenceSplice
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
VPBasicBlock * getParent()
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
A recipe for handling reduction phis.
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
A recipe to represent inloop, ordered or partial reduction operations.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
DebugLoc getDebugLoc() const
Returns the debug location of the VPRegionValue.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
void setOperand(unsigned I, VPValue *New)
VPValue * getOperand(unsigned N) const
void addOperand(VPValue *Operand)
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
void setUnderlyingValue(Value *Val)
void replaceAllUsesWith(VPValue *New)
unsigned getNumUsers() const
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
A Recipe for widening the canonical induction variable of the vector loop.
VPValue * getStepValue()
Returns the step value of the induction.
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
VPIRValue * getStartValue() const
Returns the start value of the induction.
bool isCanonical() const
Returns true if the induction is canonical, i.e.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
LLVMContext & getContext() const
VPBasicBlock * getEntry()
VPValue * getTripCount() const
The trip count of the original loop.
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
VPSymbolicValue & getVectorTripCount()
The vector trip count.
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
VPRegionBlock * createLoopRegion(Type *CanIVTy, DebugLoc DL, const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with a canonical IV using CanIVTy and DL.
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
bool hasScalarVFOnly() const
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
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.
@ BasicBlock
Various leaf nodes.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::ExtractLastLane, VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > > m_ExtractLastLaneOfLastPart(const Op0_t &Op0)
bool matchFindIVResult(VPInstruction *VPI, Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
VPInstruction * findComputeReductionResult(VPReductionPHIRecipe *PhiR)
Find the ComputeReductionResult recipe for PhiR, looking through selects inserted for predicated redu...
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
VPSingleDefRecipe * findHeaderMask(VPlan &Plan)
Collect the header mask with the pattern: (ICMP_ULE, WideCanonicalIV, backedge-taken-count) TODO: Int...
static VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
FunctionAddr VTableAddr Value
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
auto dyn_cast_or_null(const Y &Val)
void sort(IteratorTy Start, IteratorTy End)
UncountableExitStyle
Different methods of handling early exits.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionAddr VTableAddr Count
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A recipe for handling first-order recurrence phis.
A VPValue representing a live-in from the input IR or a constant.