[llvm] [VPlan] Untie tail folding from optimizeInductionLiveOutUsers. NFC (PR #207984)
Luke Lau via llvm-commits
llvm-commits at lists.llvm.org
Tue Jul 7 05:14:34 PDT 2026
https://github.com/lukel97 created https://github.com/llvm/llvm-project/pull/207984
Long term it would be good to have the VPlan as the single source of truth as to whether or not the plan is tail folded, since this would allow us to e.g. bail during `VPlanTransforms::foldTailByMasking` or do the legality checks inside it, instead of in the cost model.
To that effect, this PR removes the use of `LoopVectorizationCostModel::foldTailByMasking` from `optimizeInductionLiveOutUsers`. We don't actually really care if the plan is tail folded, we're just intermingling the value of the induction variable at the scalar preheader with the value at the latch exit.
We really want to compute the value of IVs at two places, when entering the scalar loop when we've completed __vector trip-count iterations__, and at the latch exit when we've completed __original trip-count iterations__.
Currently for a non-tail folded plan, we just use the vector trip-count in both places. It just so happens that the only user in the latch exit will be an incoming value of a phi, coming from the branch in the middleVPBB when `original trip-count == vector trip-count`, so using the vector trip-count in this case is correct.
For tail folded loops, the vector trip-count will be greater than the original trip-count so we have to use the actual trip-count value for it to be correct. This makes the resume value for the scalar preheader wrong, but because it's tail folded the value is never actually used.
This PR untangles this by computing the values at the latch exit + scalar preheader separately. If we branch to the latch exit when `original trip-count == vector trip-count` then this reuses the vector trip-count in the latch exit to prevent regressions.
>From 2334c2a0b5720d7b0a4990b71174999aea7b1a3c Mon Sep 17 00:00:00 2001
From: Luke Lau <luke at igalia.com>
Date: Tue, 30 Jun 2026 23:53:55 +0800
Subject: [PATCH] [VPlan] Untie tail folding from
optimizeInductionLiveOutUsers. NFC
---
.../Transforms/Vectorize/LoopVectorize.cpp | 6 +--
.../Transforms/Vectorize/VPlanTransforms.cpp | 48 ++++++++++++++-----
.../Transforms/Vectorize/VPlanTransforms.h | 3 +-
...fmax-without-fast-math-flags-interleave.ll | 2 +-
4 files changed, 40 insertions(+), 19 deletions(-)
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 6bb68d1f7bb19..4e7fb170526be 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -6626,8 +6626,7 @@ VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VPlanPtr Plan,
if (!RUN_VPLAN_PASS(VPlanTransforms::tryToConvertVPInstructionsToVPRecipes,
*Plan, *TLI))
return nullptr;
- RUN_VPLAN_PASS(VPlanTransforms::optimizeInductionLiveOutUsers, *Plan, PSE,
- /*FoldTail=*/false);
+ RUN_VPLAN_PASS(VPlanTransforms::optimizeInductionLiveOutUsers, *Plan, PSE);
return Plan;
}
@@ -6796,8 +6795,7 @@ VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VPlanPtr Plan,
// Optimize FindIV reductions to use sentinel-based approach when possible.
RUN_VPLAN_PASS(VPlanTransforms::optimizeFindIVReductions, *Plan, PSE,
*OrigLoop);
- RUN_VPLAN_PASS(VPlanTransforms::optimizeInductionLiveOutUsers, *Plan, PSE,
- CM.foldTailByMasking());
+ RUN_VPLAN_PASS(VPlanTransforms::optimizeInductionLiveOutUsers, *Plan, PSE);
// Apply mandatory transformation to handle reductions with multiple in-loop
// uses if possible, bail out otherwise.
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index 39e8ae5dd3b8c..574f2a345b14a 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -1153,32 +1153,56 @@ optimizeLatchExitInductionUser(VPlan &Plan, VPValue *Op,
}
void VPlanTransforms::optimizeInductionLiveOutUsers(
- VPlan &Plan, PredicatedScalarEvolution &PSE, bool FoldTail) {
- // Compute end values for all inductions.
+ VPlan &Plan, PredicatedScalarEvolution &PSE) {
+ // Compute the value inductions at two points:
+ // - when exiting the loop from the latch, at trip-count iterations.
+ // - when resuming at the scalar preheader, at vector trip-count iterations.
VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
auto *VectorPH = cast<VPBasicBlock>(VectorRegion->getSinglePredecessor());
VPBuilder VectorPHBuilder(VectorPH, VectorPH->begin());
- DenseMap<VPValue *, VPValue *> EndValues;
- VPValue *ResumeTC =
- FoldTail ? Plan.getTripCount() : &Plan.getVectorTripCount();
+ DenseMap<VPValue *, VPValue *> LatchExitValues, ResumeValues;
for (auto &Phi : VectorRegion->getEntryBasicBlock()->phis()) {
auto *WideIV = dyn_cast<VPWidenInductionRecipe>(&Phi);
if (!WideIV)
continue;
- if (VPValue *EndValue =
- tryToComputeEndValueForInduction(WideIV, VectorPHBuilder, ResumeTC))
- EndValues[WideIV] = EndValue;
+ if (VPValue *EndValue = tryToComputeEndValueForInduction(
+ WideIV, VectorPHBuilder, Plan.getTripCount()))
+ LatchExitValues[WideIV] = EndValue;
+ if (VPValue *EndValue = tryToComputeEndValueForInduction(
+ WideIV, VectorPHBuilder, &Plan.getVectorTripCount()))
+ ResumeValues[WideIV] = EndValue;
}
VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
+ VPBasicBlock *LatchExitVPBB = nullptr;
+ // Try and find the latch exit from MiddleVPBB.
+ if (Plan.isExitBlock(MiddleVPBB->getSuccessors()[0])) {
+ LatchExitVPBB = cast<VPBasicBlock>(MiddleVPBB->getSuccessors()[0]);
+ // If we branch to the latch exit on TC == VTC, then the IVs at the latch
+ // exit are equal to the IVs at the scalar preheader. Reuse ResumeValues
+ // to avoid computing the same value in two different ways.
+ if (match(MiddleVPBB->getTerminator(),
+ m_BranchOnCond(m_SpecificICmp(
+ CmpInst::ICMP_EQ, m_Specific(Plan.getTripCount()),
+ m_Specific(&Plan.getVectorTripCount())))))
+ LatchExitValues = ResumeValues;
+ }
+
+ // Optimize users in the latch exit and in the scalar preheader.
for (VPRecipeBase &R : make_early_inc_range(*MiddleVPBB)) {
VPValue *Op;
if (!match(&R, m_ExitingIVValue(m_VPValue(Op))))
continue;
auto *WideIV = cast<VPWidenInductionRecipe>(Op);
- if (VPValue *EndValue = EndValues.lookup(WideIV)) {
- R.getVPSingleValue()->replaceAllUsesWith(EndValue);
- R.eraseFromParent();
+ for (VPUser *U : to_vector(R.getVPSingleValue()->users())) {
+ auto *UR = cast<VPRecipeBase>(U);
+ if (UR->getParent() == LatchExitVPBB) {
+ if (VPValue *EndValue = LatchExitValues.lookup(WideIV))
+ UR->replaceUsesOfWith(R.getVPSingleValue(), EndValue);
+ } else if (UR->getParent() == Plan.getScalarPreheader()) {
+ if (VPValue *EndValue = ResumeValues.lookup(WideIV))
+ UR->replaceUsesOfWith(R.getVPSingleValue(), EndValue);
+ }
}
}
@@ -1191,7 +1215,7 @@ void VPlanTransforms::optimizeInductionLiveOutUsers(
VPValue *Escape = nullptr;
if (PredVPBB == MiddleVPBB)
Escape = optimizeLatchExitInductionUser(
- Plan, ExitIRI->getOperand(Idx), EndValues, PSE);
+ Plan, ExitIRI->getOperand(Idx), LatchExitValues, PSE);
else
Escape = optimizeEarlyExitInductionUser(
Plan, ExitIRI->getOperand(Idx), PSE);
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.h b/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
index 3260526552281..05fe7591a6fe1 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.h
@@ -417,8 +417,7 @@ struct VPlanTransforms {
/// IV values by feeding them precomputed end values instead, possibly taken
/// one step backwards.
static void optimizeInductionLiveOutUsers(VPlan &Plan,
- PredicatedScalarEvolution &PSE,
- bool FoldTail);
+ PredicatedScalarEvolution &PSE);
/// Add explicit broadcasts for live-ins and VPValues defined in \p Plan's entry block if they are used as vectors.
static void materializeBroadcasts(VPlan &Plan);
diff --git a/llvm/test/Transforms/LoopVectorize/fmax-without-fast-math-flags-interleave.ll b/llvm/test/Transforms/LoopVectorize/fmax-without-fast-math-flags-interleave.ll
index b8a15df2886e5..8206afea5b0d8 100644
--- a/llvm/test/Transforms/LoopVectorize/fmax-without-fast-math-flags-interleave.ll
+++ b/llvm/test/Transforms/LoopVectorize/fmax-without-fast-math-flags-interleave.ll
@@ -324,7 +324,7 @@ define float @fmaxnum_tailfold(ptr %src, i64 %n) #0 {
; CHECK-NEXT: [[TMP54:%.*]] = select <4 x i1> [[TMP2]], <4 x float> [[TMP52]], <4 x float> [[VEC_PHI1]]
; CHECK-NEXT: [[TMP60:%.*]] = select i1 [[TMP57]], <4 x float> [[VEC_PHI]], <4 x float> [[TMP53]]
; CHECK-NEXT: [[TMP61:%.*]] = select i1 [[TMP57]], <4 x float> [[VEC_PHI1]], <4 x float> [[TMP54]]
-; CHECK-NEXT: [[TMP62:%.*]] = select i1 [[TMP57]], i64 [[INDEX]], i64 [[TMP0]]
+; CHECK-NEXT: [[TMP62:%.*]] = select i1 [[TMP57]], i64 [[INDEX]], i64 [[N_VEC]]
; CHECK-NEXT: [[RDX_MINMAX:%.*]] = call <4 x float> @llvm.maxnum.v4f32(<4 x float> [[TMP60]], <4 x float> [[TMP61]])
; CHECK-NEXT: [[TMP63:%.*]] = call float @llvm.vector.reduce.fmax.v4f32(<4 x float> [[RDX_MINMAX]])
; CHECK-NEXT: [[TMP64:%.*]] = xor i1 [[TMP57]], true
More information about the llvm-commits
mailing list