162#define LV_NAME "loop-vectorize"
163#define DEBUG_TYPE LV_NAME
169STATISTIC(LoopsVectorized,
"Number of loops vectorized");
170STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
171STATISTIC(LoopsEpilogueVectorized,
"Number of epilogues vectorized");
172STATISTIC(LoopsEarlyExitVectorized,
"Number of early exit loops vectorized");
174 "Number of partial aliasing loops vectorized");
178 cl::desc(
"Enable vectorization of epilogue loops."));
183 cl::desc(
"When epilogue vectorization is enabled, and a value greater than "
184 "1 is specified, forces the given VF for all applicable epilogue "
185 "loops. Note: This allows all scalable VFs >= vscale x 1."));
188 "epilogue-vectorization-minimum-VF",
cl::Hidden,
189 cl::desc(
"Only loops with vectorization factor equal to or larger than "
190 "the specified value are considered for epilogue vectorization."));
196 cl::desc(
"Loops with a constant trip count that is smaller than this "
197 "value are vectorized only if no scalar iteration overheads "
202 cl::desc(
"The maximum allowed number of runtime memory checks"));
206 cl::desc(
"Replace pointer diff checks with alias masks."));
217 cl::desc(
"Tail-folding preferences over creating an epilogue loop."),
220 "Don't tail-fold loops."),
222 "prefer tail-folding, otherwise create an epilogue when "
225 "always tail-fold, don't attempt vectorization if "
226 "tail-folding fails.")));
231 "Epilogue-tail-folding preferences over creating an epilogue loop."),
234 "Don't tail-fold loops."),
236 "prefer tail-folding, otherwise create an epilogue when "
240 "force-tail-folding-style",
cl::desc(
"Force the tail folding style"),
246 "Create lane mask for data only, using active.lane.mask intrinsic"),
248 "data-without-lane-mask",
249 "Create lane mask with compare/stepvector"),
251 "Create lane mask using active.lane.mask intrinsic, and use "
252 "it for both data and control flow"),
254 "Use predicated EVL instructions for tail folding. If EVL "
255 "is unsupported, fallback to data-without-lane-mask.")));
259 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
265 cl::desc(
"Enable vectorization on masked interleaved memory accesses in a loop"));
269 cl::desc(
"A flag that overrides the target's number of scalar registers."));
273 cl::desc(
"A flag that overrides the target's number of vector registers."));
277 cl::desc(
"A flag that overrides the target's max interleave factor for "
282 cl::desc(
"A flag that overrides the target's max interleave factor for "
283 "vectorized loops."));
287 cl::desc(
"A flag that overrides the target's expected cost for "
288 "an instruction to a single constant value. Mostly "
289 "useful for getting consistent testing."));
294 "The cost of a loop that is considered 'small' by the interleaver."));
298 cl::desc(
"Enable the use of the block frequency analysis to access PGO "
299 "heuristics minimizing code growth in cold regions and being more "
300 "aggressive in hot regions."));
306 "Enable runtime interleaving until load/store ports are saturated"));
311 cl::desc(
"Max number of stores to be predicated behind an if."));
317 cl::desc(
"The maximum number of SCEV checks allowed."));
321 cl::desc(
"The maximum number of SCEV checks allowed with a "
322 "vectorize(enable) pragma"));
326 cl::desc(
"Count the induction variable only once when interleaving"));
330 cl::desc(
"The maximum interleave count to use when interleaving a scalar "
331 "reduction in a nested loop."));
335 cl::desc(
"Enable the vectorisation of loops with in-order (strict) "
341 "Prefer predicating a reduction operation over an after loop select."));
345 cl::desc(
"Enable VPlan-native vectorization path with "
346 "support for outer loop vectorization."));
350#ifdef EXPENSIVE_CHECKS
356 cl::desc(
"Verify VPlans after VPlan transforms."));
358#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
361 cl::desc(
"Print VPlans before all VPlan transformations."));
365 cl::desc(
"Print VPlans after all VPlan transformations."));
369 cl::desc(
"Print VPlans before specified VPlan transformations (regexp)."));
373 cl::desc(
"Print VPlans after specified VPlan transformations (regexp)."));
377 cl::desc(
"Limit VPlan printing to vector loop region in "
378 "`-vplan-print-after*` if the plan has one."));
388 "Build VPlan for every supported loop nest in the function and bail "
389 "out right after the build (stress test the VPlan H-CFG construction "
390 "in the VPlan-native vectorization path)."));
394 cl::desc(
"Enable loop interleaving in Loop vectorization passes"));
397 cl::desc(
"Run the Loop vectorization passes"));
401 cl::desc(
"Override cost based masked intrinsic widening "
402 "for div/rem instructions"));
407 "Enable vectorization of early exit loops with uncountable exits."));
410 "enable-early-exit-vectorization-with-side-effects",
cl::init(
false),
412 cl::desc(
"Enable vectorization of early exit loops with uncountable exits "
413 "and side effects"));
481 bool CanExcludeZeroTrips =
false,
bool ComputeUpperBoundOnly =
false) {
495 if (!CanUseConstantMax)
505 if (CanUseConstantMax && CanExcludeZeroTrips)
514class GeneratedRTChecks;
548 Plan.getVectorLoopRegion()->getSinglePredecessor())) {}
636 "A high UF for the epilogue loop is likely not beneficial.");
657 UnrollFactor, Checks,
Plan),
719 if (
I->getDebugLoc() !=
Empty)
720 return I->getDebugLoc();
723 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
724 if (OpInst->getDebugLoc() != Empty)
725 return OpInst->getDebugLoc();
728 return I->getDebugLoc();
735 return B.CreateElementCount(Ty, VF);
787 : Config(Config), EpilogueLoweringStatus(SEL),
TheLoop(L),
PSE(
PSE),
806 void collectValuesToIgnore();
812 "Profitable to scalarize relevant only for VF > 1.");
815 "cost-model should not be used for outer loops (in VPlan-native path)");
817 auto Scalars = InstsToScalarize.find(VF);
818 assert(Scalars != InstsToScalarize.end() &&
819 "VF not yet analyzed for scalarization profitability");
820 return Scalars->second.contains(
I);
827 "cost-model should not be used for outer loops (in VPlan-native path)");
838 auto UniformsPerVF = Uniforms.find(VF);
839 assert(UniformsPerVF != Uniforms.end() &&
840 "VF not yet analyzed for uniformity");
841 return UniformsPerVF->second.count(
I);
848 "cost-model should not be used for outer loops (in VPlan-native path)");
852 auto ScalarsPerVF = Scalars.find(VF);
853 assert(ScalarsPerVF != Scalars.end() &&
854 "Scalar values are not calculated for VF");
855 return ScalarsPerVF->second.count(
I);
861 const auto &MinBWs = Config.getMinimalBitwidths();
864 I->getType()->getScalarSizeInBits() < MinBWs.lookup(
I))
866 return VF.
isVector() && MinBWs.contains(
I) &&
890 WideningDecisions[{
I, VF}] = {W,
Cost};
911 WideningDecisions[{
I, VF}] = {W, InsertPosCost};
913 WideningDecisions[{
I, VF}] = {W, OtherMemberCost};
924 "cost-model should not be used for outer loops (in VPlan-native path)");
926 std::pair<Instruction *, ElementCount> InstOnVF(
I, VF);
927 auto Itr = WideningDecisions.find(InstOnVF);
928 if (Itr == WideningDecisions.end())
930 return Itr->second.first;
937 std::pair<Instruction *, ElementCount> InstOnVF(
I, VF);
938 assert(WideningDecisions.contains(InstOnVF) &&
939 "The cost is not calculated");
940 return WideningDecisions[InstOnVF].second;
961 Value *
Op = Trunc->getOperand(0);
962 if (
Op !=
Legal->getPrimaryInduction() &&
TTI.isTruncateFree(SrcTy, DestTy))
966 return Legal->isInductionPhi(
Op);
982 if (VF.
isScalar() || Uniforms.contains(VF))
985 collectLoopUniforms(VF);
986 collectLoopScalars(VF);
997 return ScalarCost < MaskedCost;
1044 std::pair<InstructionCost, InstructionCost>
1050 std::optional<InstWidening> memoryInstructionCanBeWidened(
Instruction *
I,
1078 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1085 LLVM_DEBUG(
dbgs() <<
"LV: Loop requires scalar epilogue: not exiting "
1086 "from latch block\n");
1091 "interleaved group requires scalar epilogue\n");
1094 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1112 return ChosenTailFoldingStyle;
1120 "Tail folding must not be selected yet.");
1121 if (!
Legal->canFoldTailByMasking()) {
1127 ChosenTailFoldingStyle =
TTI.getPreferredTailFoldingStyle();
1135 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1148 dbgs() <<
"LV: Preference for VP intrinsics indicated. Will "
1149 "not try to generate VP Intrinsics "
1151 ?
"since interleave count specified is greater than 1.\n"
1152 :
"due to non-interleaving reasons.\n"));
1163 "Did not expect to enable alias masking with EVL!");
1172 !
Legal->getFixedOrderRecurrences().empty())
1180 if (!DiffChecks || DiffChecks->empty())
1183 [[maybe_unused]]
auto HasPointerArgs = [](
CallBase *CB) {
1185 return Arg->getType()->isPointerTy();
1194 (!
I.mayReadOrWriteMemory() || (
Call && !HasPointerArgs(
Call))) &&
1195 "Skipped unexpected memory access");
1206 if (
Legal->isConsecutivePtr(ScalarTy, Ptr) == -1)
1252 TTI.preferPredicatedReductionSelect();
1267 WideningDecisions.clear();
1284 std::optional<InstructionCost> getReductionPatternCost(
Instruction *
I,
1286 Type *VectorTy)
const;
1290 bool shouldConsiderInvariant(
Value *
Op);
1294 auto FS = ForcedScalars.find(VF);
1295 return FS != ForcedScalars.end() && FS->second.contains(
I);
1299 unsigned NumPredStores = 0;
1312 "alias-mask status must be decided already");
1313 return Legal->isUniform(V, PartialAliasMaskingStatus ==
1324 "alias-mask status must be decided already");
1325 return Legal->isUniformMemOp(
I, PartialAliasMaskingStatus ==
1335 InstructionCost getMemInstScalarizationCost(Instruction *
I, ElementCount VF);
1338 InstructionCost getInterleaveGroupCost(Instruction *
I, ElementCount VF)
const;
1341 InstructionCost getGatherScatterCost(Instruction *
I, ElementCount VF)
const;
1352 InstructionCost getUniformMemOpCost(Instruction *
I, ElementCount VF)
const;
1357 ElementCount VF)
const;
1362 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1366 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1367 PredicatedBBsAfterVectorization;
1388 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1392 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1396 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1400 DenseMap<ElementCount, SmallSetVector<Instruction *, 4>> ForcedScalars;
1408 ScalarCostsTy &ScalarCosts,
1420 void collectLoopUniforms(ElementCount VF);
1429 void collectLoopScalars(ElementCount VF);
1433 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1434 std::pair<InstWidening, InstructionCost>>;
1436 DecisionList WideningDecisions;
1440 bool needsExtract(
Value *V, ElementCount VF)
const {
1442 if (VF.
isScalar() || !
I || !TheLoop->contains(
I) ||
1443 TheLoop->isLoopInvariant(
I) ||
1444 getWideningDecision(
I, VF) == CM_Scalarize)
1453 return !Scalars.
contains(VF) || !isScalarAfterVectorization(
I, VF);
1457 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range
Ops,
1458 ElementCount VF)
const {
1460 SmallPtrSet<const Value *, 4> UniqueOperands;
1461 SmallVector<Value *, 4> Res;
1464 !needsExtract(
Op, VF))
1531class GeneratedRTChecks {
1537 Value *SCEVCheckCond =
nullptr;
1544 Value *MemRuntimeCheckCond =
nullptr;
1553 bool CostTooHigh =
false;
1555 Loop *OuterLoop =
nullptr;
1563 bool LoopUsesPartialAliasMasking =
false;
1569 bool LoopUsesPartialAliasMasking)
1570 : DT(DT), LI(LI),
TTI(
TTI),
1571 SCEVExp(*PSE.
getSE(),
"scev.check",
false),
1572 MemCheckExp(*PSE.
getSE(),
"scev.check",
false),
1574 LoopUsesPartialAliasMasking(LoopUsesPartialAliasMasking) {}
1581 void create(
Loop *L,
const LoopAccessInfo &LAI,
1582 const SCEVPredicate &UnionPred, ElementCount VF,
unsigned IC,
1583 OptimizationRemarkEmitter &ORE) {
1596 return OptimizationRemarkAnalysisAliasing(
1597 DEBUG_TYPE,
"TooManyMemoryRuntimeChecks",
L->getStartLoc(),
1599 <<
"loop not vectorized: too many memory checks needed";
1614 nullptr,
"vector.scevcheck");
1621 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1622 SCEVCleaner.cleanup();
1630 if (RtPtrChecking.Need && !LoopUsesPartialAliasMasking) {
1631 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1632 MemCheckBlock =
SplitBlock(Pred, Pred->getTerminator(), DT, LI,
nullptr,
1635 auto DiffChecks = RtPtrChecking.getDiffChecks();
1638 MemCheckBlock->
getTerminator(), *DiffChecks, MemCheckExp, VF, IC);
1641 MemCheckBlock->
getTerminator(), L, RtPtrChecking.getChecks(),
1644 assert(MemRuntimeCheckCond &&
1645 "no RT checks generated although RtPtrChecking "
1646 "claimed checks are required");
1651 if (!MemCheckBlock && !SCEVCheckBlock)
1661 if (SCEVCheckBlock) {
1664 auto *UI =
new UnreachableInst(Preheader->
getContext(), SCEVCheckBlock);
1668 if (MemCheckBlock) {
1671 auto *UI =
new UnreachableInst(Preheader->
getContext(), MemCheckBlock);
1677 if (MemCheckBlock) {
1681 if (SCEVCheckBlock) {
1687 OuterLoop =
L->getParentLoop();
1691 if (SCEVCheckBlock || MemCheckBlock)
1703 for (Instruction &
I : *SCEVCheckBlock) {
1704 if (SCEVCheckBlock->getTerminator() == &
I)
1710 if (MemCheckBlock) {
1712 for (Instruction &
I : *MemCheckBlock) {
1713 if (MemCheckBlock->getTerminator() == &
I)
1725 ScalarEvolution *SE = MemCheckExp.
getSE();
1730 const SCEV *
Cond = SE->
getSCEV(MemRuntimeCheckCond);
1735 unsigned BestTripCount = 2;
1739 PSE, OuterLoop,
false))
1740 if (EstimatedTC->isFixed())
1741 BestTripCount = EstimatedTC->getFixedValue();
1746 NewMemCheckCost = std::max(NewMemCheckCost.
getValue(),
1747 (InstructionCost::CostType)1);
1749 if (BestTripCount > 1)
1751 <<
"We expect runtime memory checks to be hoisted "
1752 <<
"out of the outer loop. Cost reduced from "
1753 << MemCheckCost <<
" to " << NewMemCheckCost <<
'\n');
1755 MemCheckCost = NewMemCheckCost;
1759 RTCheckCost += MemCheckCost;
1762 if (SCEVCheckBlock || MemCheckBlock)
1763 LLVM_DEBUG(
dbgs() <<
"Total cost of runtime checks: " << RTCheckCost
1771 ~GeneratedRTChecks() {
1772 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1773 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
1774 bool SCEVChecksUsed = !SCEVCheckBlock || !
pred_empty(SCEVCheckBlock);
1775 bool MemChecksUsed = !MemCheckBlock || !
pred_empty(MemCheckBlock);
1777 SCEVCleaner.markResultUsed();
1779 if (MemChecksUsed) {
1780 MemCheckCleaner.markResultUsed();
1782 auto &SE = *MemCheckExp.
getSE();
1789 I.eraseFromParent();
1792 MemCheckCleaner.cleanup();
1793 SCEVCleaner.cleanup();
1795 if (!SCEVChecksUsed)
1796 SCEVCheckBlock->eraseFromParent();
1798 MemCheckBlock->eraseFromParent();
1803 std::pair<Value *, BasicBlock *> getSCEVChecks()
const {
1804 using namespace llvm::PatternMatch;
1806 return {
nullptr,
nullptr};
1808 return {SCEVCheckCond, SCEVCheckBlock};
1813 std::pair<Value *, BasicBlock *> getMemRuntimeChecks()
const {
1814 using namespace llvm::PatternMatch;
1815 if (MemRuntimeCheckCond &&
match(MemRuntimeCheckCond,
m_ZeroInt()))
1816 return {
nullptr,
nullptr};
1817 return {MemRuntimeCheckCond, MemCheckBlock};
1821 bool hasChecks()
const {
1822 return getSCEVChecks().first || getMemRuntimeChecks().first;
1863 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent outer loop vectorization.\n");
1869 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Interleave is not supported for "
1899 for (
Loop *InnerL : L)
1914 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
1917 : std::max(Cost->TTI.getMaxInterleaveFactor(VF,
false),
1918 Cost->TTI.getMaxInterleaveFactor(VF,
true));
1920 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
1927 Cost->PSE, Cost->TheLoop,
1931 uint64_t MaxTC = TC->getKnownMinValue();
1933 std::optional<unsigned> MaxVScale =
1938 MaxVF *= *MaxVScale;
1939 if (TC->isScalable())
1940 MaxTC *= *MaxVScale;
1945 if (MaxUIntTripCount.
ult(MaxTC))
1949 return (MaxUIntTripCount - MaxTC).ugt(MaxStep);
1963 return TTI.enableMaskedInterleavedAccessVectorization();
1972 VPlan *Plan =
nullptr) {
1976 auto IP = IRVPBB->
begin();
1978 R.moveBefore(*IRVPBB, IP);
1982 R.moveBefore(*IRVPBB, IRVPBB->
end());
1991 assert(VectorPH &&
"Invalid loop structure");
1998 Twine(Prefix) +
"scalar.ph");
2007 auto *Cmp = L->getLatchCmpInst();
2009 InstsToIgnore.
insert(Cmp);
2010 for (
const auto &KV : IL) {
2019 [&](
const User *U) { return U == IV || U == Cmp; }))
2020 InstsToIgnore.
insert(IVInst);
2032struct CSEDenseMapInfo {
2039 assert(canHandle(
I) &&
"Unknown instruction!");
2044 static bool isEqual(
const Instruction *
LHS,
const Instruction *
RHS) {
2045 return LHS->isIdenticalTo(
RHS);
2057 if (!CSEDenseMapInfo::canHandle(&In))
2063 In.replaceAllUsesWith(V);
2064 In.eraseFromParent();
2077 std::optional<unsigned> VScale) {
2081 EstimatedVF *= *VScale;
2082 assert(EstimatedVF >= 1 &&
"Estimated VF shouldn't be less than 1");
2096 if (Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()))
2114 for (
auto &ArgOp : CI->
args())
2135 TTI.getCallInstrCost(
2136 nullptr, Variant->getReturnType(),
2137 Variant->getFunctionType()->params(), Config.CostKind));
2152 assert(ID &&
"Expected intrinsic call!");
2156 FMF = FPMO->getFastMathFlags();
2162 std::back_inserter(ParamTys),
2163 [&](
Type *Ty) { return maybeVectorizeType(Ty, VF); });
2168 return TTI.getIntrinsicInstrCost(CostAttrs, Config.CostKind);
2179 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2185void LoopVectorizationCostModel::collectLoopScalars(
ElementCount VF) {
2190 "This function should not be visited twice for the same VF");
2206 auto *Latch = TheLoop->getLoopLatch();
2213 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2214 assert(WideningDecision != CM_Unknown &&
2215 "Widening decision should be ready at this moment");
2217 if (
Store && Ptr ==
Store->getValueOperand())
2218 return WideningDecision == CM_Scalarize;
2220 "Ptr is neither a value or pointer operand");
2221 return WideningDecision != CM_GatherScatter &&
2227 auto IsLoopVaryingGEP = [&](
Value *
V) {
2238 if (!IsLoopVaryingGEP(Ptr))
2250 if (IsScalarUse(MemAccess, Ptr) &&
2254 PossibleNonScalarPtrs.
insert(
I);
2270 for (
auto *BB : TheLoop->blocks())
2271 for (
auto &
I : *BB) {
2273 EvaluatePtrUse(
Load,
Load->getPointerOperand());
2275 EvaluatePtrUse(
Store,
Store->getPointerOperand());
2276 EvaluatePtrUse(
Store,
Store->getValueOperand());
2279 for (
auto *
I : ScalarPtrs)
2280 if (!PossibleNonScalarPtrs.
count(
I)) {
2288 auto ForcedScalar = ForcedScalars.
find(VF);
2289 if (ForcedScalar != ForcedScalars.
end())
2290 for (
auto *
I : ForcedScalar->second) {
2291 LLVM_DEBUG(
dbgs() <<
"LV: Found (forced) scalar instruction: " << *
I <<
"\n");
2300 while (Idx != Worklist.
size()) {
2302 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2306 auto *J = cast<Instruction>(U);
2307 return !TheLoop->contains(J) || Worklist.count(J) ||
2308 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2309 IsScalarUse(J, Src));
2312 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
2318 for (
const auto &Induction :
Legal->getInductionVars()) {
2319 auto *Ind = Induction.first;
2324 if (Ind ==
Legal->getPrimaryInduction() && foldTailByMasking())
2329 auto IsDirectLoadStoreFromPtrIndvar = [&](
Instruction *Indvar,
2331 return Induction.second.getKind() ==
2339 bool ScalarInd =
all_of(Ind->users(), [&](User *U) ->
bool {
2340 auto *I = cast<Instruction>(U);
2341 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2342 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2351 if (IndUpdatePhi &&
Legal->isFixedOrderRecurrence(IndUpdatePhi))
2356 bool ScalarIndUpdate =
all_of(IndUpdate->users(), [&](User *U) ->
bool {
2357 auto *I = cast<Instruction>(U);
2358 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2359 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2361 if (!ScalarIndUpdate)
2366 Worklist.
insert(IndUpdate);
2367 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
2368 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
2390 switch(
I->getOpcode()) {
2393 case Instruction::Call: {
2401 case Instruction::Load:
2402 case Instruction::Store: {
2406 !Config.isLegalGatherOrScatter(
I, VF);
2408 case Instruction::UDiv:
2409 case Instruction::SDiv:
2410 case Instruction::SRem:
2411 case Instruction::URem: {
2436 if (
Legal->blockNeedsPredication(
I->getParent()))
2449 switch(
I->getOpcode()) {
2452 "instruction should have been considered by earlier checks");
2453 case Instruction::Call:
2457 "should have returned earlier for calls not needing a mask");
2459 case Instruction::Load:
2462 case Instruction::Store: {
2470 case Instruction::UDiv:
2471 case Instruction::URem:
2473 return !
Legal->isInvariant(
I->getOperand(1));
2474 case Instruction::SDiv:
2475 case Instruction::SRem:
2488 if (!
Legal->blockNeedsPredication(BB))
2491 uint64_t HeaderFreq =
2493 uint64_t
BBFreq =
getBFI().getBlockFreq(BB).getFrequency();
2495 "Header has smaller block freq than dominated BB?");
2496 return std::round((
double)HeaderFreq /
BBFreq);
2501 case Instruction::UDiv:
2502 return Intrinsic::masked_udiv;
2503 case Instruction::SDiv:
2504 return Intrinsic::masked_sdiv;
2505 case Instruction::URem:
2506 return Intrinsic::masked_urem;
2507 case Instruction::SRem:
2508 return Intrinsic::masked_srem;
2514std::pair<InstructionCost, InstructionCost>
2517 assert(
I->getOpcode() == Instruction::UDiv ||
2518 I->getOpcode() == Instruction::SDiv ||
2519 I->getOpcode() == Instruction::SRem ||
2520 I->getOpcode() == Instruction::URem);
2529 ScalarizationCost = 0;
2536 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
2539 ScalarizationCost +=
2541 I->getOpcode(),
I->getType(), Config.CostKind);
2558 {VecTy, VecTy, MaskTy});
2560 return {ScalarizationCost, MaskedCost};
2567 "Decision should not be set yet.");
2569 assert(Group &&
"Must have a group.");
2570 unsigned InterleaveFactor = Group->getFactor();
2574 auto &
DL =
I->getDataLayout();
2586 bool ScalarNI =
DL.isNonIntegralPointerType(ScalarTy);
2589 bool MemberNI =
DL.isNonIntegralPointerType(MemberTy);
2591 if (MemberNI != ScalarNI)
2594 if (MemberNI && ScalarNI &&
2595 ScalarTy->getPointerAddressSpace() !=
2596 MemberTy->getPointerAddressSpace())
2605 bool PredicatedAccessRequiresMasking =
2607 bool LoadAccessWithGapsRequiresEpilogMasking =
2610 bool StoreAccessWithGapsRequiresMasking =
2612 if (!PredicatedAccessRequiresMasking &&
2613 !LoadAccessWithGapsRequiresEpilogMasking &&
2614 !StoreAccessWithGapsRequiresMasking)
2621 "Masked interleave-groups for predicated accesses are not enabled.");
2623 if (Group->isReverse())
2627 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
2628 StoreAccessWithGapsRequiresMasking;
2635std::optional<LoopVectorizationCostModel::InstWidening>
2645 int Stride =
Legal->isConsecutivePtr(ScalarTy, Ptr);
2647 return std::nullopt;
2652 return std::nullopt;
2656 auto &
DL =
I->getDataLayout();
2658 return std::nullopt;
2663void LoopVectorizationCostModel::collectLoopUniforms(
ElementCount VF) {
2670 "This function should not be visited twice for the same VF");
2674 Uniforms[VF].
clear();
2682 auto IsOutOfScope = [&](
Value *V) ->
bool {
2684 return (!
I || !TheLoop->contains(
I));
2694 auto AddToWorklistIfAllowed = [&](
Instruction *
I) ->
void {
2695 if (IsOutOfScope(
I)) {
2700 if (isPredicatedInst(
I)) {
2702 dbgs() <<
"LV: Found not uniform due to requiring predication: " << *
I
2706 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *
I <<
"\n");
2715 TheLoop->getExitingBlocks(Exiting);
2716 for (BasicBlock *
E : Exiting) {
2717 if (
Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() !=
E)
2720 if (Cmp && TheLoop->contains(Cmp) &&
Cmp->hasOneUse())
2721 AddToWorklistIfAllowed(Cmp);
2730 if (PrevVF.isVector()) {
2731 auto Iter = Uniforms.
find(PrevVF);
2732 if (Iter != Uniforms.
end() && !Iter->second.contains(
I))
2735 if (!isUniformMemOp(*
I, VF))
2745 auto IsUniformDecision = [&](
Instruction *
I, ElementCount VF) {
2746 InstWidening WideningDecision = getWideningDecision(
I, VF);
2747 assert(WideningDecision != CM_Unknown &&
2748 "Widening decision should be ready at this moment");
2750 if (IsUniformMemOpUse(
I))
2753 return (WideningDecision == CM_Widen ||
2754 WideningDecision == CM_Widen_Reverse ||
2755 WideningDecision == CM_Interleave);
2765 (IsUniformDecision(
I, VF) ||
Legal->isInvariant(Ptr));
2773 SetVector<Value *> HasUniformUse;
2777 for (
auto *BB : TheLoop->blocks())
2778 for (
auto &
I : *BB) {
2780 switch (
II->getIntrinsicID()) {
2781 case Intrinsic::sideeffect:
2782 case Intrinsic::experimental_noalias_scope_decl:
2783 case Intrinsic::assume:
2784 case Intrinsic::lifetime_start:
2785 case Intrinsic::lifetime_end:
2786 if (TheLoop->hasLoopInvariantOperands(&
I))
2787 AddToWorklistIfAllowed(&
I);
2795 if (IsOutOfScope(EVI->getAggregateOperand())) {
2796 AddToWorklistIfAllowed(EVI);
2802 "Expected aggregate value to be call return value");
2815 if (IsUniformMemOpUse(&
I))
2816 AddToWorklistIfAllowed(&
I);
2818 if (IsVectorizedMemAccessUse(&
I, Ptr))
2819 HasUniformUse.
insert(Ptr);
2825 for (
auto *V : HasUniformUse) {
2826 if (IsOutOfScope(V))
2829 bool UsersAreMemAccesses =
all_of(
I->users(), [&](User *U) ->
bool {
2830 auto *UI = cast<Instruction>(U);
2831 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
2833 if (UsersAreMemAccesses)
2834 AddToWorklistIfAllowed(
I);
2841 while (Idx != Worklist.
size()) {
2844 for (
auto *OV :
I->operand_values()) {
2846 if (IsOutOfScope(OV))
2851 if (
OP &&
Legal->isFixedOrderRecurrence(
OP))
2857 auto *J = cast<Instruction>(U);
2858 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
2860 AddToWorklistIfAllowed(OI);
2871 for (
const auto &Induction :
Legal->getInductionVars()) {
2872 auto *Ind = Induction.first;
2877 bool UniformInd =
all_of(Ind->users(), [&](User *U) ->
bool {
2878 auto *I = cast<Instruction>(U);
2879 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2880 IsVectorizedMemAccessUse(I, Ind);
2887 bool UniformIndUpdate =
all_of(IndUpdate->users(), [&](User *U) ->
bool {
2888 auto *I = cast<Instruction>(U);
2889 return I == Ind || Worklist.count(I) ||
2890 IsVectorizedMemAccessUse(I, IndUpdate);
2892 if (!UniformIndUpdate)
2896 AddToWorklistIfAllowed(Ind);
2897 AddToWorklistIfAllowed(IndUpdate);
2906 scope_exit EnsureAliasMaskingStatusIsDecidedOnReturn([
this] {
2913 if (!
TheLoop->isInnermost()) {
2914 return Config.computeVPlanOuterloopVF(UserVF);
2917 if (
Legal->getRuntimePointerChecking()->Need &&
TTI.hasBranchDivergence()) {
2921 "Not inserting runtime ptr check for divergent target",
2922 "runtime pointer checks needed. Not enabled for divergent target",
2923 "CantVersionLoopWithDivergentTarget",
ORE,
TheLoop);
2929 unsigned MaxTC =
PSE.getSmallConstantMaxTripCount();
2934 LLVM_DEBUG(
dbgs() <<
"LV: Found maximum trip count: " << MaxTC <<
'\n');
2937 "Single iteration (non) loop",
2938 "loop trip count is one, irrelevant for vectorization",
2949 Legal->getWidestInductionType()->getScalarSizeInBits() &&
2953 "Trip count computation wrapped",
2954 "backedge-taken count is -1, loop trip count wrapped to 0",
2959 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
2960 "No cost-modeling decisions should have been taken at this point");
2962 switch (EpilogueLoweringStatus) {
2964 return Config.computeFeasibleMaxVF(MaxTC, UserVF, UserIC,
false,
2970 <<
"LV: Not allowing epilogue, creating tail-folded "
2971 <<
"vector loop.\n");
2977 LLVM_DEBUG(
dbgs() <<
"LV: Not allowing epilogue due to -Os/-Oz.\n");
2979 LLVM_DEBUG(
dbgs() <<
"LV: Not allowing epilogue due to low trip "
2984 if (Config.runtimeChecksRequired())
3005 std::optional<unsigned> MaxPowerOf2RuntimeVF =
3010 MaxPowerOf2RuntimeVF = std::max<unsigned>(
3011 *MaxPowerOf2RuntimeVF,
3014 MaxPowerOf2RuntimeVF = std::nullopt;
3017 auto NoScalarEpilogueNeeded = [
this, &UserIC](
unsigned MaxVF) {
3021 !
Legal->hasUncountableEarlyExit())
3023 unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
3028 const SCEV *BackedgeTakenCount =
PSE.getSymbolicMaxBackedgeTakenCount();
3030 BackedgeTakenCount ==
PSE.getBackedgeTakenCount()) &&
3031 "Invalid loop count");
3033 BackedgeTakenCount, SE->
getOne(BackedgeTakenCount->
getType()));
3040 if (MaxPowerOf2RuntimeVF > 0u) {
3042 "MaxFixedVF must be a power of 2");
3043 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3045 LLVM_DEBUG(
dbgs() <<
"LV: No tail will remain for any chosen VF.\n");
3051 if (ExpectedTC && ExpectedTC->isFixed() &&
3052 ExpectedTC->getFixedValue() <=
3053 TTI.getMinTripCountTailFoldingThreshold()) {
3054 if (MaxPowerOf2RuntimeVF > 0u) {
3060 LLVM_DEBUG(
dbgs() <<
"LV: Picking a fixed-width so that no tail will "
3061 "remain for any chosen VF.\n");
3068 "The trip count is below the minial threshold value.",
3069 "loop trip count is too low, avoiding vectorization",
"LowTripCount",
3084 <<
"LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3085 "try to generate VP Intrinsics with scalable vector "
3090 assert(ContainsScalableVF &&
"Expected scalable vector factor.");
3102 LLVM_DEBUG(
dbgs() <<
"LV: Cannot fold tail by masking: vectorize with an "
3103 "epilogue instead.\n");
3109 LLVM_DEBUG(
dbgs() <<
"LV: Can't fold tail by masking: don't vectorize\n");
3115 "unable to calculate the loop count due to complex control flow",
3121 "Cannot optimize for size and vectorize at the same time.",
3122 "cannot optimize for size and vectorize at the same time. "
3123 "Enable vectorization of this loop with '#pragma clang loop "
3124 "vectorize(enable)' when compiling with -Os/-Oz",
3131 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3133 for (
const auto &Plan : VPlans) {
3144 precomputeCosts(*Plan, VF, CostCtx);
3147 for (
auto &R : *VPBB) {
3148 if (!R.cost(VF, CostCtx).isValid())
3154 if (InvalidCosts.
empty())
3162 for (
auto &Pair : InvalidCosts)
3167 sort(InvalidCosts, [&Numbering](RecipeVFPair &
A, RecipeVFPair &
B) {
3168 unsigned NA = Numbering[
A.first];
3169 unsigned NB = Numbering[
B.first];
3184 Subset = Tail.take_front(1);
3194 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
3195 [](
const auto *R) {
return Instruction::Call; })
3198 [](
const auto *R) {
return R->getOpcode(); })
3200 return R->getStoredValues().empty() ? Instruction::Load
3201 : Instruction::Store;
3212 if (Subset == Tail || Tail[Subset.size()].first != R) {
3213 std::string OutString;
3215 assert(!Subset.empty() &&
"Unexpected empty range");
3216 OS <<
"Recipe with invalid costs prevented vectorization at VF=(";
3217 for (
const auto &Pair : Subset)
3218 OS << (Pair.second == Subset.front().second ?
"" :
", ") << Pair.second;
3220 if (Opcode == Instruction::Call) {
3223 Name =
Int->getIntrinsicName();
3227 WidenCall ? WidenCall->getCalledScalarFunction()
3229 ->getLiveInIRValue());
3232 OS <<
" call to " << Name;
3237 Tail = Tail.drop_front(Subset.size());
3241 Subset = Tail.take_front(Subset.size() + 1);
3242 }
while (!Tail.empty());
3263 switch (R.getVPRecipeID()) {
3264 case VPRecipeBase::VPDerivedIVSC:
3265 case VPRecipeBase::VPScalarIVStepsSC:
3266 case VPRecipeBase::VPReplicateSC:
3267 case VPRecipeBase::VPInstructionSC:
3268 case VPRecipeBase::VPCurrentIterationPHISC:
3269 case VPRecipeBase::VPVectorPointerSC:
3270 case VPRecipeBase::VPVectorEndPointerSC:
3271 case VPRecipeBase::VPExpandSCEVSC:
3272 case VPRecipeBase::VPPredInstPHISC:
3273 case VPRecipeBase::VPBranchOnMaskSC:
3275 case VPRecipeBase::VPReductionSC:
3276 case VPRecipeBase::VPActiveLaneMaskPHISC:
3277 case VPRecipeBase::VPWidenCallSC:
3278 case VPRecipeBase::VPWidenCanonicalIVSC:
3279 case VPRecipeBase::VPWidenCastSC:
3280 case VPRecipeBase::VPWidenGEPSC:
3281 case VPRecipeBase::VPWidenIntrinsicSC:
3282 case VPRecipeBase::VPWidenMemIntrinsicSC:
3283 case VPRecipeBase::VPWidenSC:
3284 case VPRecipeBase::VPBlendSC:
3285 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
3286 case VPRecipeBase::VPHistogramSC:
3287 case VPRecipeBase::VPWidenPHISC:
3288 case VPRecipeBase::VPWidenIntOrFpInductionSC:
3289 case VPRecipeBase::VPWidenPointerInductionSC:
3290 case VPRecipeBase::VPReductionPHISC:
3291 case VPRecipeBase::VPInterleaveEVLSC:
3292 case VPRecipeBase::VPInterleaveSC:
3293 case VPRecipeBase::VPWidenLoadEVLSC:
3294 case VPRecipeBase::VPWidenLoadSC:
3295 case VPRecipeBase::VPWidenStoreEVLSC:
3296 case VPRecipeBase::VPWidenStoreSC:
3302 auto WillGenerateTargetVectors = [&
TTI, VF](
Type *VectorTy) {
3303 unsigned NumLegalParts =
TTI.getNumberOfParts(VectorTy);
3319 if (R.getNumDefinedValues() == 0 &&
3328 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
3330 if (!Visited.
insert({ScalarTy}).second)
3344 [](
auto *VPRB) { return VPRB->isReplicator(); });
3352 auto *RedPhi = dyn_cast<VPReductionPHIRecipe>(&R);
3354 RecurrenceDescriptor::isFindLastRecurrenceKind(
3355 RedPhi->getRecurrenceKind());
3366 if (!TTI.preferEpilogueVectorization(VF * IC))
3371 : TTI.getEpilogueVectorizationMinVF();
3377 bool ScalarEpilogueAllowed) {
3379 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is disabled.\n");
3383 if (!ScalarEpilogueAllowed) {
3384 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because no "
3385 "epilogue is allowed.\n");
3392 <<
"LEV: Epilogue vectorization not supported with alias masking.\n");
3398 if (!isCandidateForEpilogueVectorization(MainPlan)) {
3399 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because the loop "
3400 "is not a supported candidate.\n");
3406 Config.getVScaleForTuning()) >=
3411 LLVM_DEBUG(
dbgs() <<
"LEV: Forced epilogue VF results in dead epilogue "
3412 "vector loop, skipping vectorizing epilogue.\n");
3416 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization factor is forced.\n");
3418 std::unique_ptr<VPlan> Clone(
3424 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization forced factor is not "
3429 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
3431 dbgs() <<
"LEV: Epilogue vectorization skipped due to opt for size.\n");
3435 if (!Config.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
3436 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is not profitable for "
3447 if (
match(&Exiting->back(),
3457 MainLoopVF = GetEffectiveVF(MainPlan, MainLoopVF);
3465 Type *TCType = Legal->getWidestInductionType();
3466 const SCEV *RemainingIterations =
nullptr;
3467 unsigned MaxTripCount = 0;
3470 const SCEV *KnownMinTC;
3472 bool ScalableRemIter =
false;
3476 ScalableRemIter = ScalableTC;
3477 RemainingIterations =
3479 }
else if (ScalableTC) {
3482 SE.
getConstant(TCType, Config.getVScaleForTuning().value_or(1)));
3486 RemainingIterations =
3490 if (RemainingIterations->
isZero())
3500 << MaxTripCount <<
"\n");
3503 auto SkipVF = [&](
const SCEV *VF,
const SCEV *RemIter) ->
bool {
3507 VPlan *BestPlan =
nullptr;
3508 for (
auto &NextVF : ProfitableVFs) {
3514 ElementCount EffectiveVF = GetEffectiveVF(CurrentPlan, NextVF.Width);
3529 if (!ScalableRemIter) {
3535 if (SkipVF(SE.
getElementCount(TCType, EffectiveVF), RemainingIterations))
3539 if (Result.Width.isScalar() ||
3540 isMoreProfitable(NextVF, Result, MaxTripCount,
3544 BestPlan = &CurrentPlan;
3552 << Result.Width <<
"\n");
3553 std::unique_ptr<VPlan> Clone(BestPlan->
duplicate());
3554 Clone->setVF(Result.Width);
3578 if (!CM->isEpilogueAllowed())
3584 "Unroll factor forced to be 1.\n");
3589 if (!Legal->isSafeForAnyVectorWidth())
3598 const bool HasReductions =
3610 if (LoopCost == 0) {
3612 LoopCost = CM->expectedCost(VF);
3614 LoopCost = cost(Plan, VF, &R);
3615 assert(LoopCost.
isValid() &&
"Expected to have chosen a VF with valid cost");
3624 for (
auto &Pair : R.MaxLocalUsers) {
3625 Pair.second = std::max(Pair.second, 1U);
3639 unsigned IC = UINT_MAX;
3641 for (
const auto &Pair : R.MaxLocalUsers) {
3642 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
3645 << TTI.getRegisterClassName(Pair.first)
3646 <<
" register class\n");
3654 unsigned MaxLocalUsers = Pair.second;
3655 unsigned LoopInvariantRegs = 0;
3656 if (R.LoopInvariantRegs.contains(Pair.first))
3657 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
3659 unsigned TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
3663 TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
3664 std::max(1U, (MaxLocalUsers - 1)));
3667 IC = std::min(IC, TmpIC);
3671 bool HasUnorderedReductions =
3675 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3676 return RedR && RedR->isOrdered();
3678 unsigned MaxInterleaveCount =
3679 TTI.getMaxInterleaveFactor(VF, HasUnorderedReductions);
3680 LLVM_DEBUG(
dbgs() <<
"LV: MaxInterleaveFactor for the target is "
3681 << MaxInterleaveCount <<
"\n");
3697 CM->isEpilogueAllowed());
3700 if (BestKnownTC && (BestKnownTC->isFixed() || VF.
isScalable())) {
3702 unsigned AvailableTC =
3704 unsigned EstimatedVF =
3712 unsigned InterleaveCountLB =
bit_floor(std::max(
3713 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
3727 unsigned InterleaveCountUB =
bit_floor(std::max(
3728 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
3729 MaxInterleaveCount = InterleaveCountLB;
3731 if (InterleaveCountUB != InterleaveCountLB) {
3732 unsigned TailTripCountUB =
3733 (AvailableTC % (EstimatedVF * InterleaveCountUB));
3734 unsigned TailTripCountLB =
3735 (AvailableTC % (EstimatedVF * InterleaveCountLB));
3738 if (TailTripCountUB == TailTripCountLB)
3739 MaxInterleaveCount = InterleaveCountUB;
3747 MaxInterleaveCount = InterleaveCountLB;
3751 assert(MaxInterleaveCount > 0 &&
3752 "Maximum interleave count must be greater than 0");
3756 if (IC > MaxInterleaveCount)
3757 IC = MaxInterleaveCount;
3760 IC = std::max(1u, IC);
3762 assert(IC > 0 &&
"Interleave count must be greater than 0.");
3766 if (VF.
isVector() && HasReductions) {
3767 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
3775 bool ScalarInterleavingRequiresPredication =
3777 return Legal->blockNeedsPredication(BB);
3779 bool ScalarInterleavingRequiresRuntimePointerCheck =
3780 (VF.
isScalar() && Legal->getRuntimePointerChecking()->Need);
3785 <<
"LV: IC is " << IC <<
'\n'
3786 <<
"LV: VF is " << VF <<
'\n');
3787 const bool AggressivelyInterleave =
3788 TTI.enableAggressiveInterleaving(HasReductions);
3789 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
3790 !ScalarInterleavingRequiresPredication && LoopCost <
SmallLoopCost) {
3799 unsigned NumStores = 0;
3800 unsigned NumLoads = 0;
3814 if (
unsigned StoreOps = InterleaveR->getNumStoreOperands())
3815 NumStores += StoreOps;
3817 NumLoads += InterleaveR->getNumDefinedValues();
3832 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
3833 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
3839 bool HasSelectCmpReductions =
3843 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3844 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
3845 RedR->getRecurrenceKind()) ||
3846 RecurrenceDescriptor::isFindIVRecurrenceKind(
3847 RedR->getRecurrenceKind()));
3849 if (HasSelectCmpReductions) {
3850 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving select-cmp reductions.\n");
3859 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
3860 bool HasOrderedReductions =
3863 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
3865 return RedR && RedR->isOrdered();
3867 if (HasOrderedReductions) {
3869 dbgs() <<
"LV: Not interleaving scalar ordered reductions.\n");
3874 SmallIC = std::min(SmallIC,
F);
3875 StoresIC = std::min(StoresIC,
F);
3876 LoadsIC = std::min(LoadsIC,
F);
3880 std::max(StoresIC, LoadsIC) > SmallIC) {
3882 dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
3883 return std::max(StoresIC, LoadsIC);
3888 if (VF.
isScalar() && AggressivelyInterleave) {
3892 return std::max(IC / 2, SmallIC);
3895 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
3901 if (AggressivelyInterleave) {
3921 "Expecting a scalar emulated instruction");
3934 if (InstsToScalarize.contains(VF) ||
3935 PredicatedBBsAfterVectorization.contains(VF))
3941 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
3951 ScalarCostsTy ScalarCosts;
3959 computePredInstDiscount(&
I, ScalarCosts, VF) >= 0) {
3960 for (
const auto &[
I, IC] : ScalarCosts)
3961 ScalarCostsVF.
insert({
I, IC});
3964 PredicatedBBsAfterVectorization[VF].insert(BB);
3966 if (Pred->getSingleSuccessor() == BB)
3967 PredicatedBBsAfterVectorization[VF].insert(Pred);
3975 assert(!isUniformAfterVectorization(PredInst, VF) &&
3976 "Instruction marked uniform-after-vectorization will be predicated");
3994 if (!
I->hasOneUse() || PredInst->
getParent() !=
I->getParent() ||
3995 isScalarAfterVectorization(
I, VF))
4000 if (isScalarWithPredication(
I, VF))
4013 for (
Use &U :
I->operands())
4015 if (isUniformAfterVectorization(J, VF))
4026 while (!Worklist.
empty()) {
4030 if (ScalarCosts.contains(
I))
4050 if (isScalarWithPredication(
I, VF) && !
I->getType()->isVoidTy()) {
4053 ScalarCost +=
TTI.getScalarizationOverhead(
4066 for (Use &U :
I->operands())
4069 "Instruction has non-scalar type");
4070 if (CanBeScalarized(J))
4072 else if (needsExtract(J, VF)) {
4084 ScalarCost /= getPredBlockCostDivisor(Config.
CostKind,
I->getParent());
4088 Discount += VectorCost - ScalarCost;
4089 ScalarCosts[
I] = ScalarCost;
4117 LLVM_DEBUG(
dbgs() <<
"LV: Found an estimated cost of " <<
C <<
" for VF "
4118 << VF <<
" For instruction: " <<
I <<
'\n');
4139 const Loop *TheLoop) {
4146LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *
I,
4149 "Scalarization cost of instruction implies vectorization.");
4151 return InstructionCost::getInvalid();
4154 auto *SE = PSE.
getSE();
4186 if (isPredicatedInst(
I)) {
4187 Cost /= getPredBlockCostDivisor(Config.
CostKind,
I->getParent());
4191 VectorType::get(IntegerType::getInt1Ty(ValTy->
getContext()), VF);
4197 if (useEmulatedMaskMemRefHack(
I, VF))
4207 Instruction *
I, ElementCount VF, InstWidening Kind) {
4208 assert((Kind == CM_Widen || Kind == CM_Widen_Reverse) &&
4209 "Expected a consecutive widening decision");
4216 if (isMaskRequired(
I)) {
4217 unsigned IID =
I->getOpcode() == Instruction::Load
4218 ? Intrinsic::masked_load
4219 : Intrinsic::masked_store;
4221 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS),
4229 if (Kind == CM_Widen_Reverse)
4236LoopVectorizationCostModel::getUniformMemOpCost(Instruction *
I,
4237 ElementCount VF)
const {
4238 assert(isUniformMemOp(*
I, VF));
4255 bool IsLoopInvariantStoreValue =
Legal->isInvariant(
SI->getValueOperand());
4264 if (!IsLoopInvariantStoreValue)
4271LoopVectorizationCostModel::getGatherScatterCost(Instruction *
I,
4272 ElementCount VF)
const {
4279 if (!isUniform(Ptr, VF))
4282 unsigned IID =
I->getOpcode() == Instruction::Load
4283 ? Intrinsic::masked_gather
4284 : Intrinsic::masked_scatter;
4288 MemIntrinsicCostAttributes(IID, VectorTy, Ptr, isMaskRequired(
I),
4294LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *
I,
4295 ElementCount VF)
const {
4296 const auto *Group = getInterleavedAccessGroup(
I);
4297 assert(Group &&
"Fail to get an interleaved access group.");
4304 unsigned InterleaveFactor = Group->getFactor();
4305 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4308 SmallVector<unsigned, 4> Indices;
4309 for (
unsigned IF = 0; IF < InterleaveFactor; IF++)
4310 if (Group->getMember(IF))
4314 bool UseMaskForGaps =
4315 (Group->requiresScalarEpilogue() && !isEpilogueAllowed()) ||
4318 InsertPos->
getOpcode(), WideVecTy, Group->getFactor(), Indices,
4319 Group->getAlign(), AS, Config.
CostKind, isMaskRequired(
I),
4322 if (Group->isReverse()) {
4325 "Reverse masked interleaved access not supported.");
4326 Cost += Group->getNumMembers() *
4333std::optional<InstructionCost>
4339 if (Config.getInLoopReductions().empty() || VF.
isScalar() ||
4341 return std::nullopt;
4359 return std::nullopt;
4370 Instruction *LastChain = Config.getInLoopReductionImmediateChain(RetI);
4372 return std::nullopt;
4378 ReductionPhi = Config.getInLoopReductionImmediateChain(ReductionPhi);
4387 BaseCost =
TTI.getMinMaxReductionCost(
4390 BaseCost =
TTI.getArithmeticReductionCost(RdxDesc.
getOpcode(), VectorTy,
4398 BaseCost +=
TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy,
4404 if (Config.useOrderedReductions(RdxDesc))
4416 if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
4422 !
TheLoop->isLoopInvariant(Op0) && !
TheLoop->isLoopInvariant(Op1) &&
4434 TTI.getCastInstrCost(Op0->
getOpcode(), MulType, ExtType,
4437 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, Config.CostKind);
4440 Config.CostKind, RedOp);
4447 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
4448 return I == RetI ? RedCost : 0;
4450 !
TheLoop->isLoopInvariant(RedOp)) {
4460 Config.CostKind, RedOp);
4461 if (RedCost.
isValid() && RedCost < BaseCost + ExtCost)
4462 return I == RetI ? RedCost : 0;
4463 }
else if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
4467 !
TheLoop->isLoopInvariant(Op0) && !
TheLoop->isLoopInvariant(Op1)) {
4486 Instruction::Mul, VectorTy, Config.CostKind);
4492 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
4493 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
4494 ExtraExtCost =
TTI.getCastInstrCost(
4501 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
4502 return I == RetI ? RedCost : 0;
4506 Instruction::Mul, VectorTy, Config.CostKind);
4512 if (RedCost.
isValid() && RedCost < MulCost + BaseCost)
4513 return I == RetI ? RedCost : 0;
4517 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
4521LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *
I,
4532 return TTI.getAddressComputationCost(PtrTy,
nullptr,
nullptr,
4534 TTI.getMemoryOpCost(
I->getOpcode(), ValTy, Alignment, AS,
4537 return getWideningCost(
I, VF);
4541LoopVectorizationCostModel::getScalarizationOverhead(Instruction *
I,
4542 ElementCount VF)
const {
4547 return InstructionCost::getInvalid();
4559 VIC = TTI::VectorInstrContext::Load;
4561 VIC = TTI::VectorInstrContext::Store;
4581 Instruction::op_range
Ops = CI ? CI->
args() :
I->operands();
4586 for (
auto *V : filterExtractingOperands(
Ops, VF))
4590 ? TTI::VectorInstrContext::Store
4617 if (isUniformMemOp(
I, VF)) {
4618 auto IsLegalToScalarize = [&]() {
4638 return TheLoop->isLoopInvariant(
SI.getValueOperand());
4642 Config.isLegalGatherOrScatter(&
I, VF)
4643 ? getGatherScatterCost(&
I, VF)
4651 IsLegalToScalarize() ? getUniformMemOpCost(&
I, VF)
4657 if (GatherScatterCost < ScalarizationCost)
4665 if (std::optional<InstWidening> Decision =
4668 getConsecutiveMemOpCost(&
I, VF, *Decision));
4674 unsigned NumAccesses = 1;
4677 assert(Group &&
"Fail to get an interleaved access group.");
4683 NumAccesses = Group->getNumMembers();
4685 InterleaveCost = getInterleaveGroupCost(&
I, VF);
4689 Config.isLegalGatherOrScatter(&
I, VF)
4690 ? getGatherScatterCost(&
I, VF) * NumAccesses
4694 getMemInstScalarizationCost(&
I, VF) * NumAccesses;
4700 if (InterleaveCost <= GatherScatterCost &&
4701 InterleaveCost < ScalarizationCost) {
4703 Cost = InterleaveCost;
4704 }
else if (GatherScatterCost < ScalarizationCost) {
4706 Cost = GatherScatterCost;
4709 Cost = ScalarizationCost;
4718 getMemInstScalarizationCost(
I, VF));
4732 if (
TTI.prefersVectorizedAddressing())
4741 if (PtrDef &&
TheLoop->contains(PtrDef) &&
4749 while (!Worklist.
empty()) {
4751 for (
auto &
Op :
I->operands())
4758 auto UpdateMemOpUserCost = [
this, VF](
LoadInst *
LI) {
4762 for (
User *U :
LI->users()) {
4772 for (
auto *
I : AddrDefs) {
4796 getMemoryInstructionCost(
4798 : getMemInstScalarizationCost(Member, VF);
4810 ForcedScalars[VF].insert(
I);
4821 return !OpI || !
TheLoop->contains(OpI) ||
4825 [
this](
Value *
Op) { return shouldConsiderInvariant(Op); }));
4837 return InstsToScalarize[VF][
I];
4840 auto ForcedScalar = ForcedScalars.find(VF);
4841 if (VF.
isVector() && ForcedScalar != ForcedScalars.end()) {
4842 auto InstSet = ForcedScalar->second;
4843 if (InstSet.count(
I))
4848 const auto &MinBWs = Config.getMinimalBitwidths();
4849 uint64_t InstrMinBWs = MinBWs.lookup(
I);
4850 Type *RetTy =
I->getType();
4853 auto *SE =
PSE.getSE();
4857 [[maybe_unused]]
auto HasSingleCopyAfterVectorization =
4862 auto Scalarized = InstsToScalarize.find(VF);
4863 assert(Scalarized != InstsToScalarize.end() &&
4864 "VF not yet analyzed for scalarization profitability");
4865 return !Scalarized->second.count(
I) &&
4867 auto *UI = cast<Instruction>(U);
4868 return !Scalarized->second.count(UI);
4877 assert(
I->getOpcode() == Instruction::GetElementPtr ||
4878 I->getOpcode() == Instruction::PHI ||
4879 (
I->getOpcode() == Instruction::BitCast &&
4880 I->getType()->isPointerTy()) ||
4881 HasSingleCopyAfterVectorization(
I, VF));
4887 !
TTI.getNumberOfParts(VectorTy))
4891 switch (
I->getOpcode()) {
4892 case Instruction::GetElementPtr:
4898 case Instruction::UncondBr:
4899 case Instruction::CondBr: {
4906 bool ScalarPredicatedBB =
false;
4909 (PredicatedBBsAfterVectorization[VF].count(BI->
getSuccessor(0)) ||
4910 PredicatedBBsAfterVectorization[VF].count(BI->
getSuccessor(1))) &&
4912 ScalarPredicatedBB =
true;
4914 if (ScalarPredicatedBB) {
4921 return (
TTI.getScalarizationOverhead(
4923 false,
true, Config.CostKind) +
4924 (
TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind) *
4930 return TTI.getCFInstrCost(Instruction::UncondBr, Config.CostKind);
4938 case Instruction::Switch: {
4940 return TTI.getCFInstrCost(Instruction::Switch, Config.CostKind);
4942 return Switch->getNumCases() *
4943 TTI.getCmpSelInstrCost(
4945 toVectorTy(Switch->getCondition()->getType(), VF),
4949 case Instruction::PHI: {
4954 return TTI.getShuffleCost(
4963 Type *ResultTy = Phi->getType();
4969 auto *Phi = dyn_cast<PHINode>(U);
4970 if (Phi && Phi->getParent() == TheLoop->getHeader())
4975 auto &ReductionVars =
Legal->getReductionVars();
4976 auto Iter = ReductionVars.find(HeaderUser);
4977 if (Iter != ReductionVars.end() &&
4979 Iter->second.getRecurrenceKind()))
4982 return (Phi->getNumIncomingValues() - 1) *
4983 TTI.getCmpSelInstrCost(
4984 Instruction::Select,
toVectorTy(ResultTy, VF),
4992 Legal->getReductionVars().contains(Phi) &&
4993 !Config.isInLoopReduction(Phi)) {
4995 Intrinsic::vp_merge,
toVectorTy(Phi->getType(), VF),
4996 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
4997 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
5000 return TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
5002 case Instruction::UDiv:
5003 case Instruction::SDiv:
5004 case Instruction::URem:
5005 case Instruction::SRem:
5013 case Instruction::Add:
5014 case Instruction::Sub: {
5015 auto Info =
Legal->getHistogramInfo(
I);
5022 if (!RHS || RHS->getZExtValue() != 1)
5023 MulCost =
TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
5028 Type *ScalarTy =
I->getType();
5032 {PtrTy, ScalarTy, MaskTy});
5035 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind) + MulCost +
5036 TTI.getArithmeticInstrCost(
I->getOpcode(), VectorTy,
5041 case Instruction::FAdd:
5042 case Instruction::FSub:
5043 case Instruction::Mul:
5044 case Instruction::FMul:
5045 case Instruction::FDiv:
5046 case Instruction::FRem:
5047 case Instruction::Shl:
5048 case Instruction::LShr:
5049 case Instruction::AShr:
5050 case Instruction::And:
5051 case Instruction::Or:
5052 case Instruction::Xor: {
5056 if (
I->getOpcode() == Instruction::Mul &&
5057 ((
TheLoop->isLoopInvariant(
I->getOperand(0)) &&
5058 PSE.getSCEV(
I->getOperand(0))->isOne()) ||
5059 (
TheLoop->isLoopInvariant(
I->getOperand(1)) &&
5060 PSE.getSCEV(
I->getOperand(1))->isOne())))
5069 Value *Op2 =
I->getOperand(1);
5075 auto Op2Info =
TTI.getOperandInfo(Op2);
5081 return TTI.getArithmeticInstrCost(
5082 I->getOpcode(), VectorTy, Config.CostKind,
5083 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5086 case Instruction::FNeg: {
5087 return TTI.getArithmeticInstrCost(
5088 I->getOpcode(), VectorTy, Config.CostKind,
5089 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5090 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5091 I->getOperand(0),
I);
5093 case Instruction::Select: {
5098 const Value *Op0, *Op1;
5109 return TTI.getArithmeticInstrCost(
5111 VectorTy, Config.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1},
5115 Type *CondTy =
SI->getCondition()->getType();
5121 Pred = Cmp->getPredicate();
5122 return TTI.getCmpSelInstrCost(
5123 I->getOpcode(), VectorTy, CondTy, Pred, Config.CostKind,
5124 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None},
I);
5126 case Instruction::ICmp:
5127 case Instruction::FCmp: {
5128 Type *ValTy =
I->getOperand(0)->getType();
5134 InstrMinBWs == MinBWs.lookup(Op0AsInstruction)) &&
5135 "if both the operand and the compare are marked for "
5136 "truncation, they must have the same bitwidth");
5141 return TTI.getCmpSelInstrCost(
5144 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None},
I);
5146 case Instruction::Store:
5147 case Instruction::Load: {
5152 "CM decision should be taken at this point");
5159 return getMemoryInstructionCost(
I, VF);
5161 case Instruction::BitCast:
5162 if (
I->getType()->isPointerTy())
5165 case Instruction::ZExt:
5166 case Instruction::SExt:
5167 case Instruction::FPToUI:
5168 case Instruction::FPToSI:
5169 case Instruction::FPExt:
5170 case Instruction::PtrToInt:
5171 case Instruction::IntToPtr:
5172 case Instruction::SIToFP:
5173 case Instruction::UIToFP:
5174 case Instruction::Trunc:
5175 case Instruction::FPTrunc: {
5179 "Expected a load or a store!");
5204 unsigned Opcode =
I->getOpcode();
5207 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
5210 CCH = ComputeCCH(
Store);
5213 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
5214 Opcode == Instruction::FPExt) {
5216 CCH = ComputeCCH(
Load);
5224 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
5225 Trunc->getSrcTy(), CCH, Config.CostKind,
5233 Type *SrcScalarTy =
I->getOperand(0)->getType();
5237 MinBWs.lookup(Op0AsInstruction));
5245 (
I->getOpcode() == Instruction::ZExt ||
5246 I->getOpcode() == Instruction::SExt))
5250 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH,
5251 Config.CostKind,
I);
5253 case Instruction::Call:
5255 case Instruction::ExtractValue:
5256 return TTI.getInstructionCost(
I, Config.CostKind);
5257 case Instruction::Alloca:
5262 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, Config.CostKind);
5263 case Instruction::Freeze:
5267 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
5283 auto IsLiveOutDead = [
this, RequiresScalarEpilogue](
User *U) {
5284 return RequiresScalarEpilogue &&
5298 all_of(
I.users(), [
this, IsLiveOutDead](
User *U) {
5299 return VecValuesToIgnore.contains(U) ||
5300 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
5309 if (Group->getInsertPos() == &
I)
5312 DeadInterleavePointerOps.
push_back(PointerOp);
5323 for (
unsigned I = 0;
I != DeadInterleavePointerOps.
size(); ++
I) {
5326 Instruction *UI = cast<Instruction>(U);
5327 return !VecValuesToIgnore.contains(U) &&
5328 (!isAccessInterleaved(UI) ||
5329 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
5349 for (
unsigned I = 0;
I != DeadOps.
size(); ++
I) {
5361 if ((ThenEmpty && ElseEmpty) ||
5363 ElseBB->
phis().empty()) ||
5365 ThenBB->
phis().empty())) {
5377 return !VecValuesToIgnore.contains(U) &&
5378 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
5386 [
this](
User *U) { return ValuesToIgnore.contains(U); }))
5395 for (
const auto &Reduction :
Legal->getReductionVars()) {
5402 for (
const auto &Induction :
Legal->getInductionVars()) {
5409 CM->collectValuesToIgnore();
5410 Config.collectElementTypesForWidening(&CM->ValuesToIgnore);
5416 Config.collectInLoopReductions();
5421 Legal->collectUnitStridePredicates();
5423 auto VPlan1 = tryToBuildVPlan1();
5427 if (!OrigLoop->isInnermost()) {
5432 buildVPlans(*VPlan1, VF, VF);
5439 Config.computeMinimalBitwidths();
5442 if (CM->blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
5446 <<
"LV: Invalidate all interleaved groups due to fold-tail by masking "
5447 "which requires masked-interleaved support.\n");
5448 if (CM->InterleaveInfo.invalidateGroups())
5452 CM->invalidateCostModelingDecisions();
5455 if (CM->foldTailByMasking())
5456 Legal->prepareToFoldTailByMasking();
5463 "UserVF ignored because it may be larger than the maximal safe VF",
5464 "InvalidUserVF", ORE, OrigLoop);
5467 "VF needs to be a power of two");
5470 CM->collectNonVectorizedAndSetWideningDecisions(UserVF);
5471 buildVPlans(*VPlan1, UserVF, UserVF);
5475 CM->collectNonVectorizedAndSetWideningDecisions(EpilogueUserVF);
5476 buildVPlans(*VPlan1, EpilogueUserVF, EpilogueUserVF);
5478 if (!VPlans.empty() && VPlans.front()->getSingleVF() == UserVF) {
5482 cost(*VPlans.front(), UserVF,
nullptr).isValid()) {
5490 "InvalidCost", ORE, OrigLoop);
5503 for (
const auto &VF : VFCandidates) {
5505 CM->collectNonVectorizedAndSetWideningDecisions(VF);
5517 bool ReusePrintingSlotTracker)
5521#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5522 if (ReusePrintingSlotTracker)
5523 PlanForSlotTracker = &Plan;
5536 return CM.ValuesToIgnore.contains(UI) ||
5537 (IsVector &&
CM.VecValuesToIgnore.contains(UI)) ||
5543 CM.setWideningDecision(
I, VF,
5548 return CM.getPredBlockCostDivisor(
CostKind, BB);
5552 return CM.isScalarWithPredication(
I, VF) ||
5553 CM.isUniformAfterVectorization(
I, VF) ||
CM.isForcedScalar(
I, VF) ||
5554 (VF.
isVector() &&
CM.isProfitableToScalarize(
I, VF));
5558 return CM.isMaskRequired(
I);
5598 if (
PHINode *IVPhi = WideIV->getPHINode())
5599 WidenedIVs.
insert(IVPhi);
5603 for (
const auto &[
IV, IndDesc] : Legal->getInductionVars()) {
5607 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
5608 SmallVector<Instruction *> IVInsts = {IVInc};
5609 for (
unsigned I = 0;
I != IVInsts.
size();
I++) {
5610 for (
Value *
Op : IVInsts[
I]->operands()) {
5612 if (
Op ==
IV || !OpI || !OrigLoop->contains(OpI) || !
Op->hasOneUse())
5618 for (User *U :
IV->users()) {
5625 for (Instruction *IVInst : IVInsts) {
5630 dbgs() <<
"Cost of " << InductionCost <<
" for VF " << VF
5631 <<
": induction instruction " << *IVInst <<
"\n";
5633 Cost += InductionCost;
5643 for (BasicBlock *BB : OrigLoop->blocks()) {
5647 if (BB == OrigLoop->getLoopLatch())
5649 auto BranchCost = CostCtx.
getLegacyCost(BB->getTerminator(), VF);
5663 for (Instruction *ForcedScalar : CostCtx.
CM.ForcedScalars[VF]) {
5669 dbgs() <<
"Cost of " << ForcedCost <<
" for VF " << VF
5670 <<
": forced scalar " << *ForcedScalar <<
"\n";
5681 switch (
I->getOpcode()) {
5682 case Instruction::SDiv:
5683 case Instruction::UDiv:
5684 case Instruction::SRem:
5685 case Instruction::URem:
5691 for (
const auto &[Scalarized, ScalarCost] : CostCtx.
CM.InstsToScalarize[VF]) {
5692 if (UseVPlanCostModel(Scalarized) ||
5697 dbgs() <<
"Cost of " << ScalarCost <<
" for VF " << VF
5698 <<
": profitable to scalarize " << *Scalarized <<
"\n";
5708 VPCostContext CostCtx(*TLI, Plan, *CM, Config,
5716 if (RU && Config.shouldConsiderRegPressureForVF(VF))
5720 unsigned EstimatedWidth =
5723 <<
" (Estimated cost per lane: ");
5729 (void)EstimatedWidthAsAPFloat.convertFromAPInt(
5733 SmallString<16> Str;
5734 CostPerLane.toString(Str, 3);
5743std::pair<VectorizationFactor, VPlan *>
5748 VPlan &FirstPlan = *VPlans[0];
5751 if (VPlans.size() == 1) {
5756 "must have a single scalar VF, UserVF or an outer loop");
5761 assert(VPlans[0]->getSingleVF() == UserVF &&
5762 "expected second plan to be for the forced UserVF");
5764 "expected first plan to be for the forced epilogue VF");
5770 ?
"Reciprocal Throughput\n"
5772 ?
"Instruction Latency\n"
5775 ?
"Code Size and Latency\n"
5780 "More than a single plan/VF w/o any plan having scalar VF");
5784 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << ScalarCost <<
".\n");
5788 bool ForceVectorization =
5790 if (ForceVectorization) {
5797 VPlan *PlanForBestVF = &FirstPlan;
5799 for (
auto &
P : VPlans) {
5801 P->vectorFactors().end());
5805 return Config.shouldConsiderRegPressureForVF(VF);
5810 for (
unsigned I = 0;
I < VFs.
size();
I++) {
5817 <<
"LV: Not considering vector loop of width " << VF
5818 <<
" because it will not generate any vector instructions.\n");
5824 <<
"LV: Not considering vector loop of width " << VF
5825 <<
" because it would cause replicated blocks to be generated,"
5826 <<
" which isn't allowed when optimizing for size.\n");
5834 if (isMoreProfitable(CurrentFactor, BestFactor,
P->hasScalarTail())) {
5835 BestFactor = CurrentFactor;
5836 PlanForBestVF =
P.get();
5840 if (isMoreProfitable(CurrentFactor, ScalarFactor,
P->hasScalarTail()))
5841 ProfitableVFs.push_back(CurrentFactor);
5845 VPlan &BestPlan = *PlanForBestVF;
5848 "when vectorizing, the scalar cost must be computed.");
5851 return {BestFactor, &BestPlan};
5860 : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal),
5861 CM(
std::
move(CM)), Config(Config), IAI(IAI), PSE(PSE), ORE(ORE) {}
5872 "Trying to execute plan with unsupported VF");
5874 "Trying to execute plan with unsupported UF");
5876 ++LoopsEarlyExitVectorized;
5879 *PSE.getSE(), TTI, Config.CostKind, BestVF, BestUF);
5886 bool HasBranchWeights =
5888 if (HasBranchWeights) {
5889 std::optional<unsigned> VScale = Config.getVScaleForTuning();
5891 BestVPlan, BestVF, VScale);
5897 *Legal->getRuntimePointerChecking()->getDiffChecks(),
5899 ++LoopsPartialAliasVectorized;
5906 BestVF, BestUF, PSE);
5920 OrigLoop->getStartLoc(),
5921 OrigLoop->getHeader())
5922 <<
"Created vector loop never executes due to insufficient trip "
5949 std::optional<uint64_t> MaxRuntimeStep;
5950 if (
auto MaxVScale =
getMaxVScale(*OrigLoop->getHeader()->getParent(), TTI))
5952 assert((LI->getUniqueLatchExitBlock(*OrigLoop) || RequiresScalarEpilogue) &&
5953 "loops not exiting via the latch without required epilogue?");
5955 VectorPH, HasTailFolded, RequiresScalarEpilogue,
5956 &BestVPlan.
getVFxUF(), MaxRuntimeStep);
5982 OrigLoop->getParentLoop());
5984#ifdef EXPENSIVE_CHECKS
5985 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
6003 if (!Exit->hasPredecessors())
6014 TTI.getUnrollingPreferences(OrigLoop, SE, UP, ORE);
6033 MDNode *LID = OrigLoop->getLoopID();
6034 unsigned OrigLoopInvocationWeight = 0;
6035 std::optional<unsigned> OrigAverageTripCount =
6047 bool DisableRuntimeUnroll = !ILV.
RTChecks.hasChecks() && !BestVF.
isScalar();
6049 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
6051 HeaderVPBB, BestVPlan,
6053 OrigAverageTripCount, OrigLoopInvocationWeight,
6055 DisableRuntimeUnroll, UnrollVectorizedLoop);
6063 return ExpandedSCEVs;
6072 dbgs() <<
"Create Skeleton for epilogue vectorized loop (first pass)\n"
6073 <<
"Main Loop VF:" <<
EPI.MainLoopVF
6074 <<
", Main Loop UF:" <<
EPI.MainLoopUF
6075 <<
", Epilogue Loop VF:" <<
EPI.EpilogueVF
6076 <<
", Epilogue Loop UF:" <<
EPI.EpilogueUF <<
"\n";
6082 dbgs() <<
"intermediate fn:\n"
6083 << *
OrigLoop->getHeader()->getParent() <<
"\n";
6097 OriginalScalarPH->
setName(
"vec.epilog.iter.check");
6105 R.moveBefore(*NewEntry, NewEntry->
end());
6109 Plan.setEntry(NewEntry);
6112 return OriginalScalarPH;
6117 dbgs() <<
"Create Skeleton for epilogue vectorized loop (second pass)\n"
6118 <<
"Epilogue Loop VF:" <<
EPI.EpilogueVF
6119 <<
", Epilogue Loop UF:" <<
EPI.EpilogueUF <<
"\n";
6125 dbgs() <<
"final fn:\n" << *
OrigLoop->getHeader()->getParent() <<
"\n";
6130 return CM.isPredicatedInst(
I);
6134 return CM.TTI.prefersVectorizedAddressing();
6140 VPI->
getOpcode() == Instruction::Store) &&
6141 "Must be called with either a load or store");
6146 CM.getWideningDecision(
I, VF);
6148 "CM decision should be taken at this point.");
6151 if (CM.isScalarAfterVectorization(
I, VF) ||
6152 CM.isProfitableToScalarize(
I, VF))
6167 CM.getWideningDecision(
I,
Range.Start);
6174 Builder.setInsertPoint(VPI);
6183 if (VPI->
getOpcode() == Instruction::Load) {
6185 auto *LoadR = Builder.createWidenLoad(*
Load, Ptr, Mask, Consecutive, *VPI,
6186 Load->getDebugLoc());
6189 LoadR->getDebugLoc());
6197 Store->getDebugLoc());
6198 return Builder.createWidenStore(*
Store, Ptr, StoredVal, Mask, Consecutive,
6199 *VPI,
Store->getDebugLoc());
6203VPRecipeBuilder::tryToOptimizeInductionTruncate(
VPInstruction *VPI,
6221 PHINode *Phi = WidenIV->getPHINode();
6222 VPIRValue *Start = WidenIV->getStartValue();
6236 "Instruction should have been handled earlier");
6253 case Instruction::SDiv:
6254 case Instruction::UDiv:
6255 case Instruction::SRem:
6256 case Instruction::URem:
6258 if (CM.isPredicatedInst(
I))
6259 return new VPWidenIntrinsicRecipe(
6263 case Instruction::Add:
6264 case Instruction::And:
6265 case Instruction::AShr:
6266 case Instruction::FAdd:
6267 case Instruction::FCmp:
6268 case Instruction::FDiv:
6269 case Instruction::FMul:
6270 case Instruction::FNeg:
6271 case Instruction::FRem:
6272 case Instruction::FSub:
6273 case Instruction::ICmp:
6274 case Instruction::LShr:
6275 case Instruction::Mul:
6276 case Instruction::Or:
6277 case Instruction::Select:
6278 case Instruction::Shl:
6279 case Instruction::Sub:
6280 case Instruction::Xor:
6281 case Instruction::Freeze:
6284 case Instruction::ExtractValue: {
6287 assert(EVI->getNumIndices() == 1 &&
"Expected one extractvalue index");
6288 unsigned Idx = EVI->getIndices()[0];
6289 NewOps.push_back(Plan.getConstantInt(32, Idx));
6290 return new VPWidenRecipe(*
I, NewOps, *VPI, *VPI, VPI->
getDebugLoc());
6296 if (VPI->
getOpcode() != Instruction::Store)
6306 unsigned Opcode = HI->Update->getOpcode();
6307 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
6308 "Histogram update operation must be an Add or Sub");
6314 HGramOps.
push_back(Plan.getOrAddLiveIn(HI->Update->getOperand(1)));
6318 if (CM.isMaskRequired(HI->Store))
6329 Legal->isInvariantAddressOfReduction(
SI->getPointerOperand())) {
6331 if (Legal->isInvariantStoreOfReduction(
SI)) {
6338 [[maybe_unused]]
auto *Rdx =
6341 "Store of reduction thats not the backedge value?");
6343 SI, {Val, Addr},
true ,
nullptr , *VPI, *VPI,
6345 FinalRedStoresBuilder.
insert(Recipe);
6358 [&](
ElementCount VF) {
return CM.isUniformAfterVectorization(
I, VF); },
6361 bool IsPredicated = CM.isPredicatedInst(
I);
6369 case Intrinsic::assume:
6370 case Intrinsic::lifetime_start:
6371 case Intrinsic::lifetime_end:
6393 VPValue *BlockInMask =
nullptr;
6394 if (!IsPredicated) {
6398 LLVM_DEBUG(
dbgs() <<
"LV: Scalarizing and predicating:" << *
I <<
"\n");
6409 assert((
Range.Start.isScalar() || !IsUniform || !IsPredicated ||
6411 "Should not predicate a uniform recipe");
6426 assert(!R->isPhi() &&
"phis must be handled earlier");
6431 "Call should have been handled by makeCallWideningDecisions");
6434 if (VPI->
getOpcode() == Instruction::Trunc &&
6435 (Recipe = tryToOptimizeInductionTruncate(VPI,
Range)))
6446 "Should have been handled prior to this!");
6448 if (!shouldWiden(Instr,
Range))
6451 if (VPI->
getOpcode() == Instruction::GetElementPtr) {
6462 CastR->getResultType(), CI, *VPI, *VPI,
6466 return tryToWiden(VPI);
6473VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan1() {
6474 bool IsInnerLoop = OrigLoop->isInnermost();
6479 std::optional<LoopVersioning> LVer;
6481 const LoopAccessInfo *LAI = Legal->getLAI();
6483 LI, DT, PSE.getSE());
6488 LVer->prepareNoAliasMetadata();
6495 Legal->getWidestInductionType(),
6496 PSE, LVer ? &*LVer :
nullptr);
6498 VPDominatorTree VPDT(*VPlan0);
6499 if (
const LoopAccessInfo *LAI = Legal->getLAI())
6509 VPDT, Legal->getInductionVars(), Legal->getReductionVars(),
6510 Legal->getFixedOrderRecurrences(), Config.getInLoopReductions(),
6511 Config.getHints().allowReordering())) {
6515 if (
const LoopAccessInfo *LAI = Legal->getLAI())
6520 bool ForceVectorization =
6523 !ForceVectorization &&
6526 unsigned SCEVCheckThreshold = ForceVectorization
6530 OptForSize, SCEVCheckThreshold, ORE, OrigLoop))
6540 if (Legal->hasUncountableEarlyExit()) {
6543 Legal->hasUncountableExitWithSideEffects()
6547 OrigLoop, PSE, *DT, Legal->getAssumptionCache(),
6556 if (CM->foldTailByMasking())
6568 auto MaxVFTimes2 = MaxVF * 2;
6570 VFRange SubRange = {VF, MaxVFTimes2};
6572 tryToBuildVPlan(std::unique_ptr<VPlan>(VPlan1.
duplicate()), SubRange);
6582 Config.getMinimalBitwidths());
6585 if (CM->foldTailWithEVL()) {
6587 Config.getMaxSafeElements());
6593 VPlans.push_back(std::move(
P));
6602 VPlans.push_back(std::move(Plan));
6612 if (Plan->isOuterLoop()) {
6613 for (ElementCount VF :
Range)
6616 *Plan, *TLI, PSE, OrigLoop))
6623 using namespace llvm::VPlanPatternMatch;
6624 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
6631 bool RequiresScalarEpilogueCheck =
6633 [
this](ElementCount VF) {
6634 return !CM->requiresScalarEpilogue(VF.
isVector());
6638 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6639 if (!RequiresScalarEpilogueCheck && MiddleVPBB->getNumSuccessors() == 2) {
6641 assert(MiddleVPBB->getSuccessors()[1] == Plan->getScalarPreheader() &&
6642 "second successor must be scalar preheader");
6643 BranchOnCond->setOperand(0, Plan->getFalse());
6650 bool IVUpdateMayOverflow =
false;
6651 for (ElementCount VF :
Range)
6659 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
6665 m_VPInstruction<Instruction::Add>(
6667 "Did not find the canonical IV increment");
6680 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
6681 auto ApplyIG = [IG,
this](ElementCount VF) ->
bool {
6683 CM->getWideningDecision(IG->getInsertPos(), VF) ==
6688 "Unsupported interleave factor for scalable vectors");
6693 InterleaveGroups.
insert(IG);
6700 VPRecipeBuilder RecipeBuilder(*Plan, Legal, *CM, Builder);
6705 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> RPOT(
6711 VPCostContext CostCtx(*TLI, *Plan, *CM, Config);
6714 RecipeBuilder, CostCtx);
6719 RecipeBuilder, CostCtx);
6725 make_range(VPBB->getFirstNonPhi(), VPBB->end()))) {
6728 if (
isa<VPWidenCanonicalIVRecipe, VPBlendRecipe, VPReductionRecipe,
6729 VPReplicateRecipe, VPWidenLoadRecipe, VPWidenStoreRecipe,
6730 VPWidenCallRecipe, VPWidenIntrinsicRecipe, VPVectorPointerRecipe,
6731 VPVectorEndPointerRecipe, VPHistogramRecipe>(&R) ||
6744 Builder.setInsertPoint(VPI);
6746 VPRecipeBase *Recipe =
6747 RecipeBuilder.tryToCreateWidenNonPhiRecipe(VPI,
Range);
6757 Builder.insert(Recipe);
6763 "Unexpected multidef recipe");
6765 R.eraseFromParent();
6771 "entry block must be set to a VPRegionBlock having a non-empty entry "
6782 addReductionResultComputation(Plan, RecipeBuilder,
Range.Start);
6818 InterleaveGroups, CM->isEpilogueAllowed());
6823 *OrigLoop, CostCtx,
Range);
6826 if (
Range.Start.isScalar())
6829 for (ElementCount VF :
Range)
6831 Plan->setName(
"Initial VPlan");
6835 if (CM->maskPartialAliasing())
6842void LoopVectorizationPlanner::addReductionResultComputation(
6844 using namespace VPlanPatternMatch;
6845 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
6846 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6848 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->
end())));
6850 VPValue *HeaderMask = Plan->getVectorLoopRegion()->getHeaderMask();
6851 for (VPRecipeBase &R :
6852 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
6858 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
6864 if (Blend->getNumIncomingValues() == 2 &&
6865 Blend->getMask(0) == HeaderMask) {
6866 auto *Sel = VPBuilder(Blend).createSelect(
6867 Blend->getMask(0), Blend->getIncomingValue(0),
6868 Blend->getIncomingValue(1), {},
"", *Blend);
6869 Blend->replaceAllUsesWith(Sel);
6870 Blend->eraseFromParent();
6875 auto *NewExitingVPV = OrigExitingVPV;
6879 if (!CM->usePredicatedReductionSelect(RecurrenceKind) &&
6891 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
6897 VPInstruction *FinalReductionResult;
6898 VPBuilder::InsertPointGuard Guard(Builder);
6899 Builder.setInsertPoint(MiddleVPBB, IP);
6907 bool TrueValIsPhi = AnyOfSelect->getOperand(1) == PhiR;
6909 VPValue *NewVal = TrueValIsPhi ? AnyOfSelect->getOperand(2)
6910 : AnyOfSelect->getOperand(1);
6916 VPValue *
Cmp = AnyOfSelect->getOperand(0);
6919 if (VPRecipeBase *CmpR =
Cmp->getDefiningRecipe())
6921 Builder.setInsertPoint(AnyOfSelect);
6926 Cmp = Builder.createNot(Cmp);
6933 VPValue *NewExiting = Builder.createOr(NewPhiR, Cmp);
6940 DenseMap<VPValue *, VPValue *> Substitutions = {{AnyOfSelect, NewExiting},
6942 std::function<void(VPSingleDefRecipe *)> CloneChain =
6943 [&](VPSingleDefRecipe *Old) {
6947 for (VPValue *
Op : Old->operands()) {
6953 VPSingleDefRecipe *
New;
6955 New =
B->cloneWithOperands(NewOps);
6957 New =
W->cloneWithOperands(NewOps);
6959 New = Rep->cloneWithOperands(NewOps);
6962 New->insertBefore(Old);
6963 Substitutions[Old] =
New;
6966 if (OrigExitingVPV != AnyOfSelect) {
6968 NewExiting = Substitutions.
lookup(OrigExitingVPV);
6970 NewPhiR->setOperand(1, NewExiting);
6973 Builder.setInsertPoint(MiddleVPBB, IP);
6974 FinalReductionResult =
6975 Builder.createAnyOfReduction(NewExiting, NewVal, Start, ExitDL);
6980 VPValue *ReductionOp = NewExitingVPV;
6983 assert(!PhiR->
isInLoop() &&
"Unexpected truncated inloop reduction!");
6985 "Unexpected truncated min-max recurrence!");
6987 ExtendOpc = RdxDesc.
isSigned() ? Instruction::SExt : Instruction::ZExt;
6989 VPBuilder::InsertPointGuard Guard(Builder);
6990 Builder.setInsertPoint(
6991 NewExitingVPV->getDefiningRecipe()->getParent(),
6992 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
6994 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
6995 VPWidenCastRecipe *Extnd =
6996 Builder.createWidenCast(ExtendOpc, ReductionOp, PhiTy);
7004 FinalReductionResult = Builder.createNaryOp(
7006 if (ExtendOpc != Instruction::CastOpsEnd)
7007 FinalReductionResult = Builder.createScalarCast(
7008 ExtendOpc, FinalReductionResult, PhiTy, {});
7013 for (
auto *U :
to_vector(OrigExitingVPV->users())) {
7015 if (FinalReductionResult == U || Parent->getParent())
7019 if (
match(U, m_VPInstruction<VPInstruction::ComputeReductionResult>()) ||
7021 match(U, m_VPInstruction<Instruction::ICmp>())))
7023 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
7039 VPBuilder PHBuilder(Plan->getVectorPreheader());
7040 VPValue *Iden = Plan->getOrAddLiveIn(
7042 auto *ScaleFactorVPV = Plan->getConstantInt(32, 1);
7043 VPValue *StartV = PHBuilder.createNaryOp(
7054 VPlan &Plan, GeneratedRTChecks &RTChecks,
bool HasBranchWeights)
const {
7055 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
7056 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
7057 assert((!Config.OptForSize ||
7059 "Cannot SCEV check stride or overflow when optimizing for size");
7061 SCEVCheckBlock, HasBranchWeights);
7063 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
7064 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
7068 "Runtime checks are not supported for outer loops yet");
7070 if (Config.OptForSize) {
7073 "Cannot emit memory checks when optimizing for size, unless forced "
7077 OrigLoop->getStartLoc(),
7078 OrigLoop->getHeader())
7079 <<
"Code-size may be reduced by not forcing "
7080 "vectorization, or by source-code modifications "
7081 "eliminating the need for runtime checks "
7082 "(e.g., adding 'restrict').";
7086 MemCheckBlock, HasBranchWeights);
7100 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(),
7118 if (
F->hasOptSize() ||
7144 if (
TTI->preferTailFoldingOverEpilogue(&TFI))
7166 "Options conflict, epilogue vectorization is disallowed while "
7167 "epilogue tail-folding allowed!",
7168 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7174 "applied without forced main/epilogue loop VF",
7175 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7181 "when VF of the main loop <= VF of the epilogue",
7182 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7186 if (!L->isInnermost()) {
7188 "Epilogue tail-folding is not supported for outer loop",
7189 "InvalidTailFoldedEpilogue", ORE, L);
7196 "Epilogue tail-folding can't be applied because scalar epilogue is "
7197 "required. Fall back to a normal epilogue",
7198 "InvalidTailFoldedEpilogue", ORE, L);
7205 "no epilogue is allowed.",
7206 "InvalidTailFoldedEpilogue", ORE, L);
7210 if (L->getExitingBlock() != L->getLoopLatch() ||
7213 "Epilogue tail-folding is not supported yet for early-exit loops",
7214 "InvalidTailFoldedEpilogue", ORE, L);
7231 if (S->getValueOperand()->getType()->isFloatTy())
7241 while (!Worklist.
empty()) {
7243 if (!L->contains(
I))
7245 if (!Visited.
insert(
I).second)
7255 I->getDebugLoc(), L->getHeader())
7256 <<
"floating point conversion changes vector width. "
7257 <<
"Mixed floating point precision requires an up/down "
7258 <<
"cast that will negatively impact performance.";
7261 for (
Use &
Op :
I->operands())
7277 for (
auto *PredVPBB : ExitVPBB->getPredecessors()) {
7283 << PredVPBB->getName() <<
":\n");
7284 Cost += PredVPBB->cost(VF, CostCtx);
7304 std::optional<unsigned> VScale) {
7316 <<
"LV: Interleaving only is not profitable due to runtime checks\n");
7383 uint64_t MinTC = std::max(MinTC1, MinTC2);
7385 MinTC =
alignTo(MinTC, IntVF);
7389 dbgs() <<
"LV: Minimum required TC for runtime checks to be profitable:"
7396 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is not beneficial: expected "
7397 "trip count < minimum profitable VF ("
7408 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
7410 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
7424 auto AddFreezeForFindLastIVReductions = [](
VPlan &Plan,
7425 bool UpdateResumePhis) {
7437 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {},
"fr");
7439 if (UpdateResumePhis)
7445 AddFreezeForFindLastIVReductions(MainPlan,
true);
7446 AddFreezeForFindLastIVReductions(EpiPlan,
false);
7451 [[maybe_unused]]
bool MatchedTC =
7453 assert(MatchedTC &&
"must match vector trip count");
7459 auto ResumePhiIter =
7461 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
7464 VPPhi *ResumePhi =
nullptr;
7465 if (ResumePhiIter == MainScalarPH->
phis().
end()) {
7467 "canonical IV must exist");
7471 {VectorTC, MainPlan.
getZero(Ty)}, {},
"vec.epilog.resume.val");
7474 ResumePhi->
setName(
"vec.epilog.resume.val");
7475 if (&MainScalarPH->
front() != ResumePhi)
7491 assert(isa<VPIRPhi>(R) &&
7492 "only VPIRPhis expected in the scalar header");
7493 VPValue *MainResumePhi = R.getOperand(0);
7494 VPValue *Bypass = MainResumePhi->getDefiningRecipe()->getOperand(1);
7495 return ResumeBuilder.createNaryOp(VPInstruction::ResumeForEpilogue,
7496 {MainResumePhi, Bypass});
7507 VPlan &MainPlan,
VPlan &Plan,
Loop *L,
const SCEV2ValueTy &ExpandedSCEVs,
7515 for (
auto [HeaderPhi, ResumeForEpi] :
7517 IRPhiToResumeForEpi[&
cast<VPIRPhi>(HeaderPhi).getIRPhi()] = ResumeForEpi;
7520 Header->
setName(
"vec.epilog.vector.body");
7532 for (
Value *Inc : ResumePhi->incoming_values()) {
7536 "Must only have a single non-zero incoming value");
7542 assert(ResumePhi->getNumIncomingValues() > 0 &&
7544 "all incoming values must be 0");
7553 if (isa<VPScalarIVStepsRecipe, VPDerivedIVRecipe>(U))
7555 unsigned Opc = cast<VPInstruction>(U)->getOpcode();
7556 return Instruction::isCast(Opc) || Opc == Instruction::Add;
7558 "the canonical IV should only be used by its increment or "
7559 "ScalarIVSteps when resetting the start value");
7560 VPBuilder Builder(Header, Header->getFirstNonPhi());
7565 assert(
Increment &&
"Must have a canonical IV increment at this point");
7571 Increment->replaceAllUsesWith(OffsetIVInc);
7579 Value *ResumeV =
nullptr;
7590 assert(RdxResult &&
"expected to find reduction result");
7599 VPValue *SentinelVPV =
nullptr;
7600 bool IsFindIV =
any_of(RdxResult->users(), [&](
VPUser *U) {
7601 return match(U, VPlanPatternMatch::m_SpecificICmp(
7602 ICmpInst::ICMP_NE, m_Specific(RdxResult),
7603 m_VPValue(SentinelVPV)));
7606 RecurKind RK = ReductionPhi->getRecurrenceKind();
7614 "expected live-in or Freeze");
7617 ResumePhi->getParent()->getFirstNonPHIIt());
7623 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
7627 assert(SentinelVPV &&
"expected to find icmp using RdxResult");
7629 ToFrozen[FreezeI->getOperand(0)] = StartV;
7632 Value *Cmp = Builder.CreateICmpEQ(ResumeV, StartV);
7645 "unexpected start value");
7653 assert((
Sub->getOpcode() == Instruction::Sub ||
7654 Sub->getOpcode() == Instruction::FSub) &&
7655 "Unexpected opcode");
7657 "Expected operand to match the original start value of the "
7661 [[maybe_unused]]
auto StartValueIsIdentity = [&] {
7666 return StartValue && StartValue->getValue() == IdentityValue;
7668 assert(StartValueIsIdentity() &&
7669 "Expected start value for partial sub-reduction to be zero "
7670 "(or negative zero)");
7672 Sub->setOperand(0, StartVal);
7681 ResumeV = IRPhiToResumeForEpi.
at(IndPhi)->getUnderlyingValue();
7683 assert(ResumeV &&
"Must have a resume value");
7697 if (VPI && VPI->
getOpcode() == Instruction::Freeze) {
7709 assert(ExpandedSCEVs.contains(ExpandR->getSCEV()) &&
7710 "Epilogue plan needs a SCEV not expanded for the main loop");
7716 ExpandR->eraseFromParent();
7720 unsigned MainLoopStep =
7722 unsigned EpilogueLoopStep =
7740 if (Phi.getBasicBlockIndex(Pred) != -1)
7742 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
7746 if (ScalarPH->hasPredecessors()) {
7750 for (
auto [ResumeV, HeaderPhi] :
7753 auto *EpiResumePhi =
7754 cast<PHINode>(HeaderPhiR->getIRPhi().getIncomingValueForBlock(PH));
7755 if (EpiResumePhi->getBasicBlockIndex(BypassBlock) == -1)
7757 auto *MainResumePhi =
cast<PHINode>(ResumeV->getUnderlyingValue());
7758 EpiResumePhi->setIncomingValueForBlock(
7759 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7772 GeneratedRTChecks &Checks,
7784 "expected this to be saved from the previous pass.");
7804 BasicBlock *SCEVCheckBlock = Checks.getSCEVChecks().second;
7805 BasicBlock *MemCheckBlock = Checks.getMemRuntimeChecks().second;
7807 RedirectEdge(SCEVCheckBlock, ScalarPH);
7809 RedirectEdge(MemCheckBlock, ScalarPH);
7818 for (
PHINode *Phi : PhisInBlock) {
7820 Phi->replaceIncomingBlockWith(
7822 VecEpilogueIterationCountCheck);
7829 return EPI.EpilogueIterationCountCheck == IncB;
7835 Phi->removeIncomingValue(BB);
7840 for (
auto *
I : InstsToMove)
7852 if (Phi.use_empty())
7853 Phi.eraseFromParent();
7858 "VPlan-native path is not enabled. Only process inner loops.");
7861 << L->getHeader()->getParent()->getName() <<
"' from "
7862 << L->getLocStr() <<
"\n");
7867 dbgs() <<
"LV: Loop hints:"
7878 Function *
F = L->getHeader()->getParent();
7898 L->getHeader(),
PSI,
7905 &Requirements, &Hints,
DB,
AC,
7908 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
7913 bool IsInnerLoop = L->isInnermost();
7917 LLVM_DEBUG(
dbgs() <<
"LV: cannot compute the outer-loop trip count\n");
7924 "early exit is not enabled",
7925 "UncountableEarlyExitLoopsDisabled",
ORE, L);
7931 "early exit and side effects is not enabled",
7932 "UncountableEarlyExitSideEffectLoopsDisabled",
7939 bool UseInterleaved =
7940 IsInnerLoop &&
TTI->enableInterleavedAccessVectorization();
7955 "requiring a scalar epilogue is unsupported",
7956 "UncountableEarlyExitUnsupported",
ORE, L);
7969 if (ExpectedTC && ExpectedTC->isFixed() &&
7971 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. "
7972 <<
"This loop is worth vectorizing only if no scalar "
7973 <<
"iteration overheads are incurred.");
7975 LLVM_DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
7991 if (
F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7993 "Can't vectorize when the NoImplicitFloat attribute is used",
7994 "loop not vectorized due to NoImplicitFloat attribute",
7995 "NoImplicitFloat",
ORE, L);
8005 TTI->isFPVectorizationPotentiallyUnsafe()) {
8007 "Potentially unsafe FP op prevents vectorization",
8008 "loop not vectorized due to unsafe FP support.",
"UnsafeFP",
ORE, L);
8013 bool AllowOrderedReductions;
8018 AllowOrderedReductions =
TTI->enableOrderedReductions();
8023 ExactFPMathInst->getDebugLoc(),
8024 ExactFPMathInst->getParent())
8025 <<
"loop not vectorized: cannot prove it is safe to reorder "
8026 "floating-point operations";
8028 LLVM_DEBUG(
dbgs() <<
"LV: loop not vectorized: cannot prove it is safe to "
8029 "reorder floating-point operations\n");
8040 std::make_unique<LoopVectorizationCostModel>(
8041 SEL, L, PSE,
LI, &LVL, *
TTI,
TLI,
AC,
ORE,
GetBFI,
F, IAI, Config),
8042 Config, IAI, PSE,
ORE);
8046 if (EpilogueTailLoweringStatus ==
8049 LLVM_DEBUG(
dbgs() <<
"LV: epilogue tail-folding is not supported yet\n");
8051 "The epilogue-tail-folding policy prefer-fold-tail is not supported "
8052 "yet, fall back to a normal epilogue",
8053 "UnsupportedEpilogueTailFoldingPolicy",
ORE, L);
8067 LVP.
plan(UserVF, UserIC);
8076 if (IsInnerLoop &&
ORE->allowExtraAnalysis(
LV_NAME))
8080 "Did not expect to alias-mask outer loop");
8088 unsigned SelectedIC = std::max(IC, UserIC);
8091 if (VF.Width.
isVector() || SelectedIC > 1) {
8098 if (Checks.getSCEVChecks().first &&
8099 match(Checks.getSCEVChecks().first,
m_One()))
8101 if (Checks.getMemRuntimeChecks().first &&
8102 match(Checks.getMemRuntimeChecks().first,
m_One()))
8107 bool ForceVectorization =
8111 if (!ForceVectorization &&
8116 DEBUG_TYPE,
"CantReorderMemOps", L->getStartLoc(),
8118 <<
"loop not vectorized: cannot prove it is safe to reorder "
8119 "memory operations";
8128 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
8129 bool VectorizeLoop =
true, InterleaveLoop =
true;
8131 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
8133 "VectorizationNotBeneficial",
8134 "the cost-model indicates that vectorization is not beneficial"};
8135 VectorizeLoop =
false;
8140 "UserIC should only be ignored due to unsafe dependencies");
8141 LLVM_DEBUG(
dbgs() <<
"LV: Ignoring user-specified interleave count.\n");
8142 IntDiagMsg = {
"InterleavingUnsafe",
8143 "Ignoring user-specified interleave count due to possibly "
8144 "unsafe dependencies in the loop."};
8145 InterleaveLoop =
false;
8149 LLVM_DEBUG(
dbgs() <<
"LV: Ignoring UserIC, because vectorization and "
8150 "interleaving should be avoided up front\n");
8151 IntDiagMsg = {
"InterleavingAvoided",
8152 "Ignoring UserIC, because interleaving was avoided up front"};
8153 InterleaveLoop =
false;
8154 }
else if (IC == 1 && UserIC <= 1) {
8158 "InterleavingNotBeneficial",
8159 "the cost-model indicates that interleaving is not beneficial"};
8160 InterleaveLoop =
false;
8162 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
8163 IntDiagMsg.second +=
8164 " and is explicitly disabled or interleave count is set to 1";
8166 }
else if (IC > 1 && UserIC == 1) {
8168 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving is beneficial but is explicitly "
8170 IntDiagMsg = {
"InterleavingBeneficialButDisabled",
8171 "the cost-model indicates that interleaving is beneficial "
8172 "but is explicitly disabled or interleave count is set to 1"};
8173 InterleaveLoop =
false;
8179 if (!VectorizeLoop && InterleaveLoop && LVL.
hasHistograms()) {
8180 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving without vectorization due "
8181 <<
"to histogram operations.\n");
8183 "HistogramPreventsScalarInterleaving",
8184 "Unable to interleave without vectorization due to constraints on "
8185 "the order of histogram operations"};
8186 InterleaveLoop =
false;
8190 IC = UserIC > 0 ? UserIC : IC;
8195 <<
"LV: Not interleaving due to partial aliasing vectorization.\n");
8197 "PartialAliasingVectorization",
8198 "Unable to interleave due to partial aliasing vectorization."};
8199 InterleaveLoop =
false;
8205 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving due to EE with side effects.\n");
8206 IntDiagMsg = {
"EEWithSideEffectsPreventsInterleaving",
8207 "Unable to interleave due to early exit with side effects."};
8208 InterleaveLoop =
false;
8213 if (!VectorizeLoop && !InterleaveLoop) {
8217 L->getStartLoc(), L->getHeader())
8218 << VecDiagMsg.second;
8222 L->getStartLoc(), L->getHeader())
8223 << IntDiagMsg.second;
8228 if (!VectorizeLoop && InterleaveLoop) {
8232 L->getStartLoc(), L->getHeader())
8233 << VecDiagMsg.second;
8235 }
else if (VectorizeLoop && !InterleaveLoop) {
8236 LLVM_DEBUG(
dbgs() <<
"LV: Found a vectorizable loop (" << VF.Width
8237 <<
") in " << L->getLocStr() <<
'\n');
8240 L->getStartLoc(), L->getHeader())
8241 << IntDiagMsg.second;
8243 }
else if (VectorizeLoop && InterleaveLoop) {
8244 LLVM_DEBUG(
dbgs() <<
"LV: Found a vectorizable loop (" << VF.Width
8245 <<
") in " << L->getLocStr() <<
'\n');
8251 using namespace ore;
8256 <<
"interleaved loop (interleaved count: "
8257 << NV(
"InterleaveCount", IC) <<
")";
8278 VPlan &BestPlan = *BestPlanPtr;
8280 std::unique_ptr<VPlan> EpiPlan =
8282 bool HasBranchWeights =
8285 VPlan &BestEpiPlan = *EpiPlan;
8286 VPlan &BestMainPlan = BestPlan;
8307 L->getLoopPredecessor()->getTerminator()->getDebugLoc(), PSE);
8319 EntryBB->
setName(
"iter.check");
8325 if (
BasicBlock *MemBB = Checks.getMemRuntimeChecks().second)
8327 else if (
BasicBlock *SCEVBB = Checks.getSCEVChecks().second)
8329 BasicBlock *ScalarPH = L->getLoopPreheader();
8332 BI->getSuccessor(BI->getSuccessor(0) == ScalarPH);
8337 Checks, BestEpiPlan);
8339 BestMainPlan, BestEpiPlan, L, ExpandedSCEVs, EPI, LVP, Config,
8340 *PSE.
getSE(), ResumeValues);
8347 ++LoopsEpilogueVectorized;
8352 VF.MinProfitableTripCount);
8362 assert(
DT->verify(DominatorTree::VerificationLevel::Fast) &&
8363 "DT not preserved correctly");
8377 if (!
TTI->getNumberOfRegisters(
TTI->getRegisterClassForType(
true)) &&
8382 bool Changed =
false, CFGChanged =
false;
8389 for (
const auto &L : *
LI)
8401 LoopsAnalyzed += Worklist.
size();
8404 while (!Worklist.
empty()) {
8433 "Invalid IR produced by LoopVectorize");
8463 if (!Result.MadeAnyChange)
8477 if (Result.MadeCFGChange) {
8492 static_cast<PassInfoMixin<LoopVectorizePass> *
>(
this)->
printPipeline(
8493 OS, MapClassName2PassName);
8496 OS << (InterleaveOnlyWhenForced ?
"" :
"no-") <<
"interleave-forced-only;";
8497 OS << (VectorizeOnlyWhenForced ?
"" :
"no-") <<
"vectorize-forced-only;";
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Lower Kernel Arguments
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
This file defines the DenseMap class.
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< ElementCount, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
This header provides classes for managing per-loop analyses.
static const char * VerboseDebug
This file defines the LoopVectorizationLegality class.
cl::opt< bool > VPlanBuildOuterloopStressTest
static cl::opt< bool > ConsiderRegPressure("vectorizer-consider-reg-pressure", cl::init(false), cl::Hidden, cl::desc("Discard VFs if their register pressure is too high."))
This file provides a LoopVectorizationPlanner class.
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop * > &V)
static cl::opt< unsigned > EpilogueVectorizationMinVF("epilogue-vectorization-minimum-VF", cl::Hidden, cl::desc("Only loops with vectorization factor equal to or larger than " "the specified value are considered for epilogue vectorization."))
static unsigned getMaxTCFromNonZeroRange(PredicatedScalarEvolution &PSE, Loop *L)
Get the maximum trip count for L from the SCEV unsigned range, excluding zero from the range.
static SmallVector< Instruction * > preparePlanForEpilogueVectorLoop(VPlan &MainPlan, VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationPlanner &LVP, VFSelectionContext &Config, ScalarEvolution &SE, ArrayRef< VPInstruction * > ResumeValues)
Prepare Plan for vectorizing the epilogue loop.
static Type * maybeVectorizeType(Type *Ty, ElementCount VF)
static ElementCount getSmallConstantTripCount(ScalarEvolution *SE, const Loop *L)
A version of ScalarEvolution::getSmallConstantTripCount that returns an ElementCount to include loops...
static cl::opt< unsigned > VectorizeMemoryCheckThreshold("vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks"))
static void connectEpilogueVectorLoop(VPlan &EpiPlan, Loop *L, EpilogueLoopVectorizationInfo &EPI, DominatorTree *DT, GeneratedRTChecks &Checks, ArrayRef< Instruction * > InstsToMove, ArrayRef< VPInstruction * > ResumeValues)
Connect the epilogue vector loop generated for EpiPlan to the main vector loop, after both plans have...
static cl::opt< unsigned > TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden, cl::desc("Loops with a constant trip count that is smaller than this " "value are vectorized only if no scalar iteration overheads " "are incurred."))
Loops with a known constant trip count below this number are vectorized only if no scalar iteration o...
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
static cl::opt< cl::boolOrDefault > ForceMaskedDivRem("force-widen-divrem-via-masked-intrinsic", cl::Hidden, cl::desc("Override cost based masked intrinsic widening " "for div/rem instructions"))
static void legacyCSE(BasicBlock *BB)
FIXME: This legacy common-subexpression-elimination routine is scheduled for removal,...
static VPIRBasicBlock * replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB, VPlan *Plan=nullptr)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
static Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
TailFoldingPolicyTy
Option tail-folding-policy controls the tail-folding strategy and lists all available options.
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static cl::opt< TailFoldingPolicyTy > EpilogueTailFoldingPolicy("epilogue-tail-folding-policy", cl::Hidden, cl::desc("Epilogue-tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate.")))
static cl::opt< bool > EnableEarlyExitVectorization("enable-early-exit-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits."))
static unsigned estimateElementCount(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the ElementCount at runtime.
static bool hasVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns true iff CI has a library vector variant usable at VF.
static constexpr uint32_t MinItersBypassWeights[]
static cl::opt< unsigned > ForceTargetNumScalarRegs("force-target-num-scalar-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of scalar registers."))
static SmallVector< VPInstruction * > preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
static cl::opt< unsigned > SmallLoopCost("small-loop-cost", cl::init(20), cl::Hidden, cl::desc("The cost of a loop that is considered 'small' by the interleaver."))
static cl::opt< bool > ForcePartialAliasingVectorization("force-partial-aliasing-vectorization", cl::init(false), cl::Hidden, cl::desc("Replace pointer diff checks with alias masks."))
static Function * getVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns the vector library variant function of CI usable at VF, respecting MaskRequired,...
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static bool hasForcedEpilogueVF()
static EpilogueLowering getEpilogueTailLowering(const LoopVectorizationCostModel &MainCM, const Loop *L, OptimizationRemarkEmitter *ORE, LoopVectorizationLegality &LVL, LoopVectorizeHints &Hints)
Determine how to lower the epilogue for the vector epilogue loop.
static cl::opt< TailFoldingStyle > ForceTailFoldingStyle("force-tail-folding-style", cl::desc("Force the tail folding style"), cl::init(TailFoldingStyle::None), cl::values(clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"), clEnumValN(TailFoldingStyle::Data, "data", "Create lane mask for data only, using active.lane.mask intrinsic"), clEnumValN(TailFoldingStyle::DataWithoutLaneMask, "data-without-lane-mask", "Create lane mask with compare/stepvector"), clEnumValN(TailFoldingStyle::DataAndControlFlow, "data-and-control", "Create lane mask using active.lane.mask intrinsic, and use " "it for both data and control flow"), clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl", "Use predicated EVL instructions for tail folding. If EVL " "is unsupported, fallback to data-without-lane-mask.")))
static void printOptimizedVPlan(VPlan &)
static cl::opt< bool > EnableEpilogueVectorization("enable-epilogue-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of epilogue loops."))
static cl::opt< bool > PreferPredicatedReductionSelect("prefer-predicated-reduction-select", cl::init(false), cl::Hidden, cl::desc("Prefer predicating a reduction operation over an after loop select."))
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to access PGO " "heuristics minimizing code growth in cold regions and being more " "aggressive in hot regions."))
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
static std::optional< ElementCount > getSmallBestKnownTC(PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true, bool CanExcludeZeroTrips=false, bool ComputeUpperBoundOnly=false)
Returns "best known" trip count, which is either a valid positive trip count or std::nullopt when an ...
static bool isIndvarOverflowCheckKnownFalse(const LoopVectorizationCostModel *Cost, ElementCount VF, std::optional< unsigned > UF=std::nullopt)
For the given VF and UF and maximum trip count computed for the loop, return whether the induction va...
static void addFullyUnrolledInstructionsToIgnore(Loop *L, const LoopVectorizationLegality::InductionList &IL, SmallPtrSetImpl< Instruction * > &InstsToIgnore)
Knowing that loop L executes a single vector iteration, add instructions that will get simplified and...
static bool hasFindLastReductionPhi(VPlan &Plan)
Returns true if the VPlan contains a VPReductionPHIRecipe with FindLast recurrence kind.
static cl::opt< bool > EnableInterleavedMemAccesses("enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on interleaved memory accesses in a loop"))
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
static cl::opt< bool > EnableMaskedInterleavedMemAccesses("enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"))
An interleave-group may need masking if it resides in a block that needs predication,...
static cl::opt< bool > ForceOrderedReductions("force-ordered-reductions", cl::init(false), cl::Hidden, cl::desc("Enable the vectorisation of loops with in-order (strict) " "FP reductions"))
static cl::opt< bool > EnableEarlyExitVectorizationWithSideEffects("enable-early-exit-vectorization-with-side-effects", cl::init(false), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits " "and side effects"))
static cl::opt< TailFoldingPolicyTy > TailFoldingPolicy("tail-folding-policy", cl::init(TailFoldingPolicyTy::None), cl::Hidden, cl::desc("Tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate."), clEnumValN(TailFoldingPolicyTy::MustFoldTail, "must-fold-tail", "always tail-fold, don't attempt vectorization if " "tail-folding fails.")))
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, EpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static InstructionCost calculateEarlyExitCost(VPCostContext &CostCtx, VPlan &Plan, ElementCount VF)
For loops with uncountable early exits, find the cost of doing work when exiting the loop early,...
cl::opt< bool > VPlanBuildOuterloopStressTest("vplan-build-outerloop-stress-test", cl::init(false), cl::Hidden, cl::desc("Build VPlan for every supported loop nest in the function and bail " "out right after the build (stress test the VPlan H-CFG construction " "in the VPlan-native vectorization path)."))
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
cl::opt< unsigned > NumberOfStoresToPredicate("vectorize-num-stores-pred", cl::init(1), cl::Hidden, cl::desc("Max number of stores to be predicated behind an if."))
The number of stores in a loop that are allowed to need predication.
static EpilogueLowering getEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
static void fixScalarResumeValuesFromBypass(BasicBlock *BypassBlock, Loop *L, VPlan &BestEpiPlan, ArrayRef< VPInstruction * > ResumeValues)
static cl::opt< unsigned > MaxNestedScalarReductionIC("max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, cl::desc("The maximum interleave count to use when interleaving a scalar " "reduction in a nested loop."))
static cl::opt< unsigned > ForceTargetMaxScalarInterleaveFactor("force-target-max-scalar-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "scalar loops."))
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
static cl::opt< ElementCount > EpilogueVectorizationForceVF("epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)), cl::Hidden, cl::desc("When epilogue vectorization is enabled, and a value greater than " "1 is specified, forces the given VF for all applicable epilogue " "loops. Note: This allows all scalable VFs >= vscale x 1."))
static bool willGenerateVectors(VPlan &Plan, ElementCount VF, const TargetTransformInfo &TTI)
Check if any recipe of Plan will generate a vector value, which will be assigned a vector register.
This file implements a map that provides insertion order iteration.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static InstructionCost getScalarizationOverhead(const TargetTransformInfo &TTI, Type *ScalarTy, VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, const TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None)
This is similar to TargetTransformInfo::getScalarizationOverhead, but if ScalarTy is a FixedVectorTyp...
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
A manager for alias analyses.
static constexpr roundingMode rmTowardZero
static const fltSemantics & IEEEdouble()
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getActiveBits() const
Compute the number of active bits in the value.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Represents analyses that only rely on functions' control flow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_UGT
unsigned greater than
@ ICMP_ULT
unsigned less than
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
Analysis pass which computes a CycleInfo.
static DebugLoc getTemporary()
static DebugLoc getUnknown()
An analysis that produces DemandedBits for a function.
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
constexpr bool isVector() const
One or more elements.
static constexpr ElementCount getScalable(ScalarTy MinVal)
static constexpr ElementCount getFixed(ScalarTy MinVal)
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
constexpr bool isScalar() const
Exactly one element.
void printDebugTracesAtEnd() override
EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Checks, VPlan &Plan)
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the epilogue loop strategy (i....
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
A specialized derived class of inner loop vectorizer that performs vectorization of main loops in the...
EpilogueVectorizerMainLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Check, VPlan &Plan)
void printDebugTracesAtEnd() override
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
Convenience struct for specifying and reasoning about fast-math flags.
Class to represent function types.
param_iterator param_begin() const
param_iterator param_end() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Common base class shared among various IRBuilders.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
A struct for saving information about induction variables.
const SCEV * getStep() const
ArrayRef< Instruction * > getCastInsts() const
Returns an ArrayRef to the type cast instructions in the induction update chain, that are redundant w...
@ IK_PtrInduction
Pointer induction var. Step = C.
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, GeneratedRTChecks &Checks, VPlan &Plan, ElementCount VecWidth, unsigned UnrollFactor)
EpilogueLoopVectorizationInfo & EPI
Holds and updates state information required to vectorize the main loop and its epilogue in two separ...
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
virtual void printDebugTracesAtStart()
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
const TargetTransformInfo * TTI
Target Transform Info.
friend class LoopVectorizationPlanner
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
DominatorTree * DT
Dominator Tree.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, ElementCount VecWidth, unsigned UnrollFactor, GeneratedRTChecks &RTChecks, VPlan &Plan)
void fixVectorizedLoop(VPTransformState &State)
Fix the vectorized code, taking care of header phi's, and more.
virtual BasicBlock * createVectorizedLoopSkeleton()
Creates a basic block for the scalar preheader.
virtual void printDebugTracesAtEnd()
AssumptionCache * AC
Assumption Cache.
IRBuilder Builder
The builder that we use.
VPBasicBlock * VectorPHVPBB
The vector preheader block of Plan, used as target for check blocks introduced during skeleton creati...
unsigned UF
The vectorization unroll factor to use.
GeneratedRTChecks & RTChecks
Structure to hold information about generated runtime checks, responsible for cleaning the checks,...
virtual ~InnerLoopVectorizer()=default
ElementCount VF
The vectorization SIMD factor to use.
Loop * OrigLoop
The original loop.
BasicBlock * createScalarPreheader(StringRef Prefix)
Create and return a new IR basic block for the scalar preheader whose name is prefixed with Prefix.
static InstructionCost getInvalid(CostType Val=0)
static InstructionCost getMax()
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
The group of interleaved loads/stores sharing the same stride and close to each other.
auto members() const
Return an iterator range over the non-null members of this group, in index order.
InstTy * getInsertPos() const
uint32_t getNumMembers() const
Drive the analysis of interleaved memory accesses in the loop.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
An instruction for reading from memory.
Type * getPointerOperandType() const
This analysis provides dependence information for the memory accesses of a loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const SymbolicStrideMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
Analysis pass that exposes the LoopInfo for a function.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
bool isPredicatedInst(Instruction *I) const
Returns true if I is an instruction that needs to be predicated at runtime.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
BlockFrequencyInfo * BFI
The BlockFrequencyInfo returned from GetBFI.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
bool isForcedScalar(Instruction *I, ElementCount VF) const
Returns true if I has been forced to be scalarized at VF.
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
bool preferTailFoldedLoop() const
Returns true if tail-folding is preferred over an epilogue.
void collectNonVectorizedAndSetWideningDecisions(ElementCount VF)
Collect values that will not be widened, including Uniforms, Scalars, and Instructions to Scalarize f...
bool isMaskRequired(Instruction *I) const
Wrapper function for LoopVectorizationLegality::isMaskRequired, that passes the Instruction I and if ...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const TargetTransformInfo & TTI
Vector target information.
friend class LoopVectorizationPlanner
const Function * TheFunction
LoopVectorizationLegality * Legal
Vectorization legality.
uint64_t getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind, const BasicBlock *BB)
A helper function that returns how much we should divide the cost of a predicated block by.
std::optional< InstWidening > memoryInstructionCanBeWidened(Instruction *I, ElementCount VF)
If I is a memory instruction with a consecutive pointer that can be widened, returns the widening kin...
std::optional< InstructionCost > getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy) const
Return the cost of instructions in an inloop reduction pattern, if I is part of that pattern.
InstructionCost getInstructionCost(Instruction *I, ElementCount VF)
Returns the execution time cost of an instruction for a given vector width.
bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
const TargetLibraryInfo * TLI
Target Library Info.
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr) const
Get the interleaved access group that Instr belongs to.
InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF.
bool maskPartialAliasing() const
Returns true if all loop blocks should have partial aliases masked.
bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalar after vectorization.
bool isOptimizableIVTruncate(Instruction *I, ElementCount VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable.
FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC)
Loop * TheLoop
The loop that we evaluate.
void tryToEnablePartialAliasMasking()
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
LoopVectorizationCostModel(EpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, InterleavedAccessInfo &IAI, VFSelectionContext &Config)
void invalidateCostModelingDecisions()
Invalidates decisions already taken by the cost model.
bool isAccessInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleaved access group.
void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
LoopInfo * LI
Loop Info analysis.
bool requiresScalarEpilogue(bool IsVectorizing) const
Returns true if we're required to use a scalar epilogue for at least the final iteration of the origi...
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const
Returns true if an artificially high cost for emulated masked memrefs should be used.
bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const
Returns true if the target machine supports masked loads or stores for I's data type and alignment.
bool isProfitableToScalarize(Instruction *I, ElementCount VF) const
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
bool isEpilogueAllowed() const
Returns true if an epilogue is allowed (e.g., not prevented by optsize or a loop hint annotation).
bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const
bool shouldConsiderInvariant(Value *Op)
Returns true if Op should be considered invariant and if it is trivially hoistable.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
bool foldTailWithEVL() const
Returns true if VP intrinsics with explicit vector length support should be generated in the tail fol...
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
AssumptionCache * AC
Assumption cache.
void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF.
InstWidening
Decision that was taken during cost calculation for memory instruction.
@ CM_InvalidatedDecision
A widening decision that has been invalidated after replacing the corresponding recipe during VPlan t...
bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF)
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool isScalarWithPredication(Instruction *I, ElementCount VF)
Returns true if I is an instruction which requires predication and for which our chosen predication s...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost MaskedCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
TailFoldingStyle getTailFoldingStyle() const
Returns the TailFoldingStyle that is best for the current loop.
void collectInstsToScalarize(ElementCount VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
bool isSafeForAnyVectorWidth() const
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
Planner drives the vectorization process after having passed Legality checks.
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, EpilogueVectorizationKind EpilogueVecKind=EpilogueVectorizationKind::None)
EpilogueVectorizationKind
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
@ None
Not part of epilogue vectorization.
@ Epilogue
Vectorizing the epilogue loop.
@ MainLoop
Vectorizing the main loop of epilogue vectorization.
void clearCostModel()
Destroy the cost model.
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
void updateLoopMetadataAndProfileInfo(Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan, bool VectorizingEpilogue, MDNode *OrigLoopID, std::optional< unsigned > OrigAverageTripCount, unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF, bool DisableRuntimeUnroll, bool UnrollVectorizedLoop)
Update loop metadata and profile info for both the scalar remainder loop and VectorLoop,...
LoopVectorizationCostModel & getCostModel()
Return the cost model. Must not be called after clearCostModel().
void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const
Attach the runtime checks of RTChecks to Plan.
unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF, InstructionCost LoopCost)
void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE)
Emit remarks for recipes with invalid costs in the available VPlans.
~LoopVectorizationPlanner()
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, std::unique_ptr< LoopVectorizationCostModel > CM, VFSelectionContext &Config, InterleavedAccessInfo &IAI, PredicatedScalarEvolution &PSE, OptimizationRemarkEmitter *ORE)
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
void printPlans(raw_ostream &O)
std::unique_ptr< VPlan > selectBestEpiloguePlan(VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC, bool ScalarEpilogueAllowed)
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount) const
Create a check to Plan to see if the vector loop should be executed based on its trip count.
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
std::pair< VectorizationFactor, VPlan * > computeBestVF()
Compute and return the most profitable vectorization factor and the corresponding best VPlan.
This holds vectorization requirements that must be verified late in the process.
Instruction * getExactFPInst()
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
enum ForceKind getForce() const
LLVM_ABI bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
bool isPotentiallyUnsafe() const
ElementCount getWidth() const
@ FK_Enabled
Forcing enabled.
@ FK_Undefined
Not selected.
@ FK_Disabled
Forcing disabled.
unsigned getPredicate() const
unsigned getInterleave() const
Represents a single loop in the control flow graph.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.