[llvm-branch-commits] [llvm] [LV] Only create partial reductions when profitable. (PR #181706)
Sander de Smalen via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Thu Mar 12 08:58:00 PDT 2026
https://github.com/sdesmalen-arm updated https://github.com/llvm/llvm-project/pull/181706
>From 3a12a31edd65c0b7633f5c0b624d1442188da113 Mon Sep 17 00:00:00 2001
From: Sander de Smalen <sander.desmalen at arm.com>
Date: Tue, 10 Feb 2026 09:33:11 +0000
Subject: [PATCH 1/4] [LV] Only create partial reductions when profitable.
We want the LV cost-model to make the best possible decision of
VF and whether or not to use partial reductions. At the moment,
when the LV can use partial reductions for a given VF range, it
assumes those are always preferred. After transforming the plan to
use partial reductions, it then chooses the most profitable VF. It
is possible for a different VF to have been more profitable, if it
wouldn't have chosen to use partial reductions.
This PR changes that, to first decide whether partial reductions
are more profitable for a given chain. If not, then it won't do
the transform.
---
.../Transforms/Vectorize/VPlanTransforms.cpp | 166 ++++++++++--------
.../AArch64/partial-reduce-chained.ll | 14 +-
.../LoopVectorize/AArch64/vector-reverse.ll | 8 +-
3 files changed, 101 insertions(+), 87 deletions(-)
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index dc8631404e8aa..e918cebf19258 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -4339,23 +4339,19 @@ tryToMatchAndCreateExtendedReduction(VPReductionRecipe *Red, VPCostContext &Ctx,
cast<VPWidenCastRecipe>(VecOp)->computeCost(VF, Ctx);
InstructionCost RedCost = Red->computeCost(VF, Ctx);
- if (Red->isPartialReduction()) {
- TargetTransformInfo::PartialReductionExtendKind ExtKind =
- TargetTransformInfo::getPartialReductionExtendKind(ExtOpc);
- // FIXME: Move partial reduction creation, costing and clamping
- // here from LoopVectorize.cpp.
- ExtRedCost = Ctx.TTI.getPartialReductionCost(
- Opcode, SrcTy, nullptr, RedTy, VF, ExtKind,
- llvm::TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
- RedTy->isFloatingPointTy()
- ? std::optional{Red->getFastMathFlags()}
- : std::nullopt);
- } else if (!RedTy->isFloatingPointTy()) {
- // TTI::getExtendedReductionCost only supports integer types.
- ExtRedCost = Ctx.TTI.getExtendedReductionCost(
- Opcode, ExtOpc == Instruction::CastOps::ZExt, RedTy, SrcVecTy,
- Red->getFastMathFlags(), CostKind);
- }
+ // For partial reductions, the decision has already been
+ // made at the point of transforming reductions -> partial
+ // reductions for a given plan, based on the cost-model.
+ if (Red->isPartialReduction())
+ return true;
+
+ // TTI::getExtendedReductionCost for in-loop reductions
+ // only supports integer types.
+ if (RedTy->isFloatingPointTy())
+ return false;
+ ExtRedCost = Ctx.TTI.getExtendedReductionCost(
+ Opcode, ExtOpc == Instruction::CastOps::ZExt, RedTy, SrcVecTy,
+ Red->getFastMathFlags(), CostKind);
return ExtRedCost.isValid() && ExtRedCost < ExtCost + RedCost;
},
Range);
@@ -4405,37 +4401,24 @@ tryToMatchAndCreateMulAccumulateReduction(VPReductionRecipe *Red,
Ext0 ? Ctx.Types.inferScalarType(Ext0->getOperand(0)) : RedTy;
InstructionCost MulAccCost;
- if (Red->isPartialReduction()) {
- Type *SrcTy2 =
- Ext1 ? Ctx.Types.inferScalarType(Ext1->getOperand(0)) : nullptr;
- // FIXME: Move partial reduction creation, costing and clamping
- // here from LoopVectorize.cpp.
- MulAccCost = Ctx.TTI.getPartialReductionCost(
- Opcode, SrcTy, SrcTy2, RedTy, VF,
- Ext0 ? TargetTransformInfo::getPartialReductionExtendKind(
- Ext0->getOpcode())
- : TargetTransformInfo::PR_None,
- Ext1 ? TargetTransformInfo::getPartialReductionExtendKind(
- Ext1->getOpcode())
- : TargetTransformInfo::PR_None,
- Mul->getOpcode(), CostKind,
- RedTy->isFloatingPointTy()
- ? std::optional{Red->getFastMathFlags()}
- : std::nullopt);
- } else {
- // Only partial reductions support mixed or floating-point extends
- // at the moment.
- if (Ext0 && Ext1 &&
- (Ext0->getOpcode() != Ext1->getOpcode() ||
- Ext0->getOpcode() == Instruction::CastOps::FPExt))
- return false;
+ // For partial reductions, the decision has already been
+ // made at the point of transforming reductions -> partial
+ // reductions for a given plan, based on the cost-model.
+ if (Red->isPartialReduction())
+ return true;
+
+ // Only partial reductions support mixed or floating-point extends
+ // at the moment.
+ if (Ext0 && Ext1 &&
+ (Ext0->getOpcode() != Ext1->getOpcode() ||
+ Ext0->getOpcode() == Instruction::CastOps::FPExt))
+ return false;
- bool IsZExt =
- !Ext0 || Ext0->getOpcode() == Instruction::CastOps::ZExt;
- auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
- MulAccCost = Ctx.TTI.getMulAccReductionCost(IsZExt, Opcode, RedTy,
- SrcVecTy, CostKind);
- }
+ bool IsZExt =
+ !Ext0 || Ext0->getOpcode() == Instruction::CastOps::ZExt;
+ auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
+ MulAccCost = Ctx.TTI.getMulAccReductionCost(IsZExt, Opcode, RedTy,
+ SrcVecTy, CostKind);
InstructionCost MulCost = Mul->computeCost(VF, Ctx);
InstructionCost RedCost = Red->computeCost(VF, Ctx);
@@ -6010,12 +5993,11 @@ static void transformToPartialReduction(const VPPartialReductionChain &Chain,
[&NewResult](VPUser &U, unsigned Idx) { return &U != NewResult; });
}
-/// Check if a partial reduction chain is is supported by the target (i.e. does
-/// not have an invalid cost) for the given VF range. Clamps the range and
-/// returns true if profitable for any VF.
-static bool isValidPartialReduction(const VPPartialReductionChain &Chain,
- Type *PhiType, VPCostContext &CostCtx,
- VFRange &Range) {
+/// Returns the cost of a link in a partial-reduction chain for a given VF.
+static InstructionCost
+getPartialReductionLinkCost(VPCostContext &CostCtx,
+ const VPPartialReductionChain &Chain,
+ ElementCount VF) {
auto GetExtInfo = [&CostCtx](VPWidenCastRecipe *Ext)
-> std::pair<Type *, TargetTransformInfo::PartialReductionExtendKind> {
if (!Ext)
@@ -6025,6 +6007,7 @@ static bool isValidPartialReduction(const VPPartialReductionChain &Chain,
static_cast<Instruction::CastOps>(Ext->getOpcode()));
return {ExtOpType, ExtKind};
};
+
ExtendedReductionOperand ExtendedOp = Chain.ExtendedOp;
VPWidenCastRecipe *ExtendA = ExtendedOp.CastRecipes[0];
VPWidenCastRecipe *ExtendB = ExtendedOp.CastRecipes[1];
@@ -6034,38 +6017,35 @@ static bool isValidPartialReduction(const VPPartialReductionChain &Chain,
std::tie(ExtOpTypeA, ExtKindA) = GetExtInfo(ExtendA);
std::tie(ExtOpTypeB, ExtKindB) = GetExtInfo(ExtendB);
+ std::optional<unsigned> BinOpc;
+ if (ExtendedOp.BinOp && ExtendedOp.BinOp != Chain.ReductionBinOp)
+ BinOpc = ExtendedOp.BinOp->getOpcode();
+
// If ExtendB is nullptr but there's a separate BinOp, the second operand
// was a constant that can use the same extend kind as the first.
- if (!ExtendB && ExtendedOp.BinOp &&
- ExtendedOp.BinOp != Chain.ReductionBinOp) {
+ if (!ExtendB && BinOpc) {
const APInt *Const = nullptr;
for (VPValue *Op : ExtendedOp.BinOp->operands()) {
if (match(Op, m_APInt(Const)))
break;
}
if (!Const || !canConstantBeExtended(Const, ExtOpTypeA, ExtKindA))
- return false;
+ return InstructionCost::getInvalid();
ExtOpTypeB = ExtOpTypeA;
ExtKindB = ExtKindA;
}
- std::optional<unsigned> BinOpc;
- if (ExtendedOp.BinOp && ExtendedOp.BinOp != Chain.ReductionBinOp)
- BinOpc = ExtendedOp.BinOp->getOpcode();
+ Type *RdxType = CostCtx.Types.inferScalarType(Chain.ReductionBinOp);
+ std::optional<llvm::FastMathFlags> Flags;
+ if (RdxType->isFloatingPointTy())
+ Flags = Chain.ReductionBinOp->getFastMathFlags();
- VPWidenRecipe *WidenRecipe = Chain.ReductionBinOp;
- return LoopVectorizationPlanner::getDecisionAndClampRange(
- [&](ElementCount VF) {
- return CostCtx.TTI
- .getPartialReductionCost(
- WidenRecipe->getOpcode(), ExtOpTypeA, ExtOpTypeB, PhiType, VF,
- ExtKindA, ExtKindB, BinOpc, CostCtx.CostKind,
- PhiType->isFloatingPointTy()
- ? std::optional{WidenRecipe->getFastMathFlags()}
- : std::nullopt)
- .isValid();
- },
- Range);
+ unsigned Opcode = Chain.RK == RecurKind::Sub
+ ? (unsigned)Instruction::Add
+ : Chain.ReductionBinOp->getOpcode();
+ return CostCtx.TTI.getPartialReductionCost(Opcode, ExtOpTypeA, ExtOpTypeB,
+ RdxType, VF, ExtKindA, ExtKindB,
+ BinOpc, CostCtx.CostKind, Flags);
}
/// Checks if \p Op (which is an operand of \p UpdateR) is an extended reduction
@@ -6114,8 +6094,7 @@ matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
assert(Operands.size() <= 2 && "expected at most 2 operands");
for (const auto &[I, OpVal] : enumerate(Operands)) {
- // Allow constant as second operand - validation happens in
- // isValidPartialReduction.
+ // Allow constant as second operand - validation happens later.
const APInt *Unused;
if (I > 0 && CastRecipes[0] && match(OpVal, m_APInt(Unused)))
continue;
@@ -6216,10 +6195,17 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
if (!PHISize.hasKnownScalarFactor(ExtSrcSize))
return std::nullopt;
+ /// Check if a partial reduction chain is supported by the target (i.e.
+ /// does not have an invalid cost) for the given VF range. Clamps the range
+ /// and returns true if feasible for any VF.
VPPartialReductionChain Chain(
{UpdateR, *ExtendedOp,
static_cast<unsigned>(PHISize.getKnownScalarFactor(ExtSrcSize)), RK});
- if (!isValidPartialReduction(Chain, PhiType, CostCtx, Range))
+ if (!LoopVectorizationPlanner::getDecisionAndClampRange(
+ [&](ElementCount VF) {
+ return getPartialReductionLinkCost(CostCtx, Chain, VF).isValid();
+ },
+ Range))
return std::nullopt;
Chains.push_back(Chain);
@@ -6273,6 +6259,28 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
});
};
+ auto IsProfitablePartialReductionChainForVF =
+ [&](ArrayRef<VPPartialReductionChain> Chain, ElementCount VF) -> bool {
+ InstructionCost PartialCost = 0, RegularCost = 0;
+
+ // The chain is a profitable partial reduction chain if
+ // the cost of handling the entire chain is cheaper when
+ // using partial reductions than when handling the entire
+ // chain using regular reductions.
+ for (const VPPartialReductionChain &Link : Chain) {
+ ExtendedReductionOperand ExtendedOp = Link.ExtendedOp;
+ PartialCost += getPartialReductionLinkCost(CostCtx, Link, VF);
+ RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
+ if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
+ RegularCost += ExtendedOp.BinOp->computeCost(VF, CostCtx);
+ if (ExtendedOp.CastRecipes[0])
+ RegularCost += ExtendedOp.CastRecipes[0]->computeCost(VF, CostCtx);
+ if (ExtendedOp.CastRecipes[1])
+ RegularCost += ExtendedOp.CastRecipes[1]->computeCost(VF, CostCtx);
+ }
+ return PartialCost.isValid() && PartialCost <= RegularCost;
+ };
+
// Validate chains: check that extends are only used by partial reductions,
// and that reduction bin ops are only used by other partial reductions with
// matching scale factors, are outside the loop region or the select
@@ -6311,6 +6319,14 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
}
}
}
+
+ // Clear the chain if it is not profitable.
+ if (!LoopVectorizationPlanner::getDecisionAndClampRange(
+ [&](ElementCount VF) {
+ return IsProfitablePartialReductionChainForVF(Chains, VF);
+ },
+ Range))
+ Chains.clear();
}
for (auto &[Phi, Chains] : ChainsByPhi)
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/partial-reduce-chained.ll b/llvm/test/Transforms/LoopVectorize/AArch64/partial-reduce-chained.ll
index 15e0220b71d61..98d3ee86cf276 100644
--- a/llvm/test/Transforms/LoopVectorize/AArch64/partial-reduce-chained.ll
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/partial-reduce-chained.ll
@@ -893,7 +893,7 @@ define i32 @chained_partial_reduce_sub_add_sub(ptr %a, ptr %b, ptr %c, i32 %N) #
; CHECK-SVE-MAXBW-NEXT: br label [[VECTOR_BODY:%.*]]
; CHECK-SVE-MAXBW: vector.body:
; CHECK-SVE-MAXBW-NEXT: [[INDEX:%.*]] = phi i64 [ 0, [[VECTOR_PH]] ], [ [[INDEX_NEXT:%.*]], [[VECTOR_BODY]] ]
-; CHECK-SVE-MAXBW-NEXT: [[VEC_PHI:%.*]] = phi <vscale x 2 x i32> [ zeroinitializer, [[VECTOR_PH]] ], [ [[PARTIAL_REDUCE4:%.*]], [[VECTOR_BODY]] ]
+; CHECK-SVE-MAXBW-NEXT: [[VEC_PHI:%.*]] = phi <vscale x 8 x i32> [ zeroinitializer, [[VECTOR_PH]] ], [ [[TMP15:%.*]], [[VECTOR_BODY]] ]
; CHECK-SVE-MAXBW-NEXT: [[TMP7:%.*]] = getelementptr inbounds nuw i8, ptr [[A]], i64 [[INDEX]]
; CHECK-SVE-MAXBW-NEXT: [[TMP8:%.*]] = getelementptr inbounds nuw i8, ptr [[B]], i64 [[INDEX]]
; CHECK-SVE-MAXBW-NEXT: [[TMP9:%.*]] = getelementptr inbounds nuw i8, ptr [[C]], i64 [[INDEX]]
@@ -902,20 +902,18 @@ define i32 @chained_partial_reduce_sub_add_sub(ptr %a, ptr %b, ptr %c, i32 %N) #
; CHECK-SVE-MAXBW-NEXT: [[WIDE_LOAD2:%.*]] = load <vscale x 8 x i8>, ptr [[TMP9]], align 1
; CHECK-SVE-MAXBW-NEXT: [[TMP13:%.*]] = sext <vscale x 8 x i8> [[WIDE_LOAD]] to <vscale x 8 x i32>
; CHECK-SVE-MAXBW-NEXT: [[TMP14:%.*]] = sext <vscale x 8 x i8> [[WIDE_LOAD1]] to <vscale x 8 x i32>
-; CHECK-SVE-MAXBW-NEXT: [[TMP16:%.*]] = mul nsw <vscale x 8 x i32> [[TMP13]], [[TMP14]]
-; CHECK-SVE-MAXBW-NEXT: [[TMP17:%.*]] = sub nsw <vscale x 8 x i32> zeroinitializer, [[TMP16]]
-; CHECK-SVE-MAXBW-NEXT: [[PARTIAL_REDUCE:%.*]] = call <vscale x 2 x i32> @llvm.vector.partial.reduce.add.nxv2i32.nxv8i32(<vscale x 2 x i32> [[VEC_PHI]], <vscale x 8 x i32> [[TMP17]])
; CHECK-SVE-MAXBW-NEXT: [[TMP12:%.*]] = sext <vscale x 8 x i8> [[WIDE_LOAD2]] to <vscale x 8 x i32>
+; CHECK-SVE-MAXBW-NEXT: [[TMP10:%.*]] = mul nsw <vscale x 8 x i32> [[TMP13]], [[TMP14]]
+; CHECK-SVE-MAXBW-NEXT: [[TMP11:%.*]] = sub <vscale x 8 x i32> [[VEC_PHI]], [[TMP10]]
; CHECK-SVE-MAXBW-NEXT: [[TMP18:%.*]] = mul nsw <vscale x 8 x i32> [[TMP13]], [[TMP12]]
-; CHECK-SVE-MAXBW-NEXT: [[PARTIAL_REDUCE3:%.*]] = call <vscale x 2 x i32> @llvm.vector.partial.reduce.add.nxv2i32.nxv8i32(<vscale x 2 x i32> [[PARTIAL_REDUCE]], <vscale x 8 x i32> [[TMP18]])
+; CHECK-SVE-MAXBW-NEXT: [[TMP16:%.*]] = add <vscale x 8 x i32> [[TMP11]], [[TMP18]]
; CHECK-SVE-MAXBW-NEXT: [[TMP19:%.*]] = mul nsw <vscale x 8 x i32> [[TMP14]], [[TMP12]]
-; CHECK-SVE-MAXBW-NEXT: [[TMP20:%.*]] = sub <vscale x 8 x i32> zeroinitializer, [[TMP19]]
-; CHECK-SVE-MAXBW-NEXT: [[PARTIAL_REDUCE4]] = call <vscale x 2 x i32> @llvm.vector.partial.reduce.add.nxv2i32.nxv8i32(<vscale x 2 x i32> [[PARTIAL_REDUCE3]], <vscale x 8 x i32> [[TMP20]])
+; CHECK-SVE-MAXBW-NEXT: [[TMP15]] = sub <vscale x 8 x i32> [[TMP16]], [[TMP19]]
; CHECK-SVE-MAXBW-NEXT: [[INDEX_NEXT]] = add nuw i64 [[INDEX]], [[TMP3]]
; CHECK-SVE-MAXBW-NEXT: [[TMP22:%.*]] = icmp eq i64 [[INDEX_NEXT]], [[N_VEC]]
; CHECK-SVE-MAXBW-NEXT: br i1 [[TMP22]], label [[MIDDLE_BLOCK:%.*]], label [[VECTOR_BODY]], !llvm.loop [[LOOP12:![0-9]+]]
; CHECK-SVE-MAXBW: middle.block:
-; CHECK-SVE-MAXBW-NEXT: [[TMP23:%.*]] = call i32 @llvm.vector.reduce.add.nxv2i32(<vscale x 2 x i32> [[PARTIAL_REDUCE4]])
+; CHECK-SVE-MAXBW-NEXT: [[TMP17:%.*]] = call i32 @llvm.vector.reduce.add.nxv8i32(<vscale x 8 x i32> [[TMP15]])
; CHECK-SVE-MAXBW-NEXT: [[CMP_N:%.*]] = icmp eq i64 [[WIDE_TRIP_COUNT]], [[N_VEC]]
; CHECK-SVE-MAXBW-NEXT: br i1 [[CMP_N]], label [[FOR_COND_CLEANUP:%.*]], label [[SCALAR_PH]]
; CHECK-SVE-MAXBW: scalar.ph:
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/vector-reverse.ll b/llvm/test/Transforms/LoopVectorize/AArch64/vector-reverse.ll
index 114ed5b0a4e5e..ede64f09a2aec 100644
--- a/llvm/test/Transforms/LoopVectorize/AArch64/vector-reverse.ll
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/vector-reverse.ll
@@ -203,17 +203,17 @@ define i32 @reverse_store_with_partial_reduction(ptr noalias %dst, ptr noalias %
; CHECK-NEXT: [[N_MOD_VF10:%.*]] = urem i64 [[TMP0]], 4
; CHECK-NEXT: [[N_VEC11:%.*]] = sub i64 [[TMP0]], [[N_MOD_VF10]]
; CHECK-NEXT: [[TMP32:%.*]] = sub i64 [[N]], [[N_VEC11]]
-; CHECK-NEXT: [[TMP33:%.*]] = insertelement <2 x i32> zeroinitializer, i32 [[BC_MERGE_RDX]], i32 0
+; CHECK-NEXT: [[TMP26:%.*]] = insertelement <4 x i32> zeroinitializer, i32 [[BC_MERGE_RDX]], i32 0
; CHECK-NEXT: br label %[[VEC_EPILOG_VECTOR_BODY:.*]]
; CHECK: [[VEC_EPILOG_VECTOR_BODY]]:
; CHECK-NEXT: [[INDEX12:%.*]] = phi i64 [ [[VEC_EPILOG_RESUME_VAL]], %[[VEC_EPILOG_PH]] ], [ [[INDEX_NEXT18:%.*]], %[[VEC_EPILOG_VECTOR_BODY]] ]
-; CHECK-NEXT: [[VEC_PHI13:%.*]] = phi <2 x i32> [ [[TMP33]], %[[VEC_EPILOG_PH]] ], [ [[PARTIAL_REDUCE16:%.*]], %[[VEC_EPILOG_VECTOR_BODY]] ]
+; CHECK-NEXT: [[VEC_PHI13:%.*]] = phi <4 x i32> [ [[TMP26]], %[[VEC_EPILOG_PH]] ], [ [[TMP33:%.*]], %[[VEC_EPILOG_VECTOR_BODY]] ]
; CHECK-NEXT: [[OFFSET_IDX:%.*]] = sub i64 [[N]], [[INDEX12]]
; CHECK-NEXT: [[TMP34:%.*]] = load i16, ptr [[SRC]], align 2
; CHECK-NEXT: [[BROADCAST_SPLATINSERT14:%.*]] = insertelement <4 x i16> poison, i16 [[TMP34]], i64 0
; CHECK-NEXT: [[BROADCAST_SPLAT15:%.*]] = shufflevector <4 x i16> [[BROADCAST_SPLATINSERT14]], <4 x i16> poison, <4 x i32> zeroinitializer
; CHECK-NEXT: [[TMP35:%.*]] = sext <4 x i16> [[BROADCAST_SPLAT15]] to <4 x i32>
-; CHECK-NEXT: [[PARTIAL_REDUCE16]] = call <2 x i32> @llvm.vector.partial.reduce.add.v2i32.v4i32(<2 x i32> [[VEC_PHI13]], <4 x i32> [[TMP35]])
+; CHECK-NEXT: [[TMP33]] = add <4 x i32> [[VEC_PHI13]], [[TMP35]]
; CHECK-NEXT: [[TMP36:%.*]] = getelementptr i16, ptr [[DST]], i64 [[OFFSET_IDX]]
; CHECK-NEXT: [[TMP38:%.*]] = getelementptr i16, ptr [[TMP36]], i64 -3
; CHECK-NEXT: [[REVERSE17:%.*]] = shufflevector <4 x i16> [[BROADCAST_SPLAT15]], <4 x i16> poison, <4 x i32> <i32 3, i32 2, i32 1, i32 0>
@@ -222,7 +222,7 @@ define i32 @reverse_store_with_partial_reduction(ptr noalias %dst, ptr noalias %
; CHECK-NEXT: [[TMP39:%.*]] = icmp eq i64 [[INDEX_NEXT18]], [[N_VEC11]]
; CHECK-NEXT: br i1 [[TMP39]], label %[[VEC_EPILOG_MIDDLE_BLOCK:.*]], label %[[VEC_EPILOG_VECTOR_BODY]], !llvm.loop [[LOOP9:![0-9]+]]
; CHECK: [[VEC_EPILOG_MIDDLE_BLOCK]]:
-; CHECK-NEXT: [[TMP40:%.*]] = call i32 @llvm.vector.reduce.add.v2i32(<2 x i32> [[PARTIAL_REDUCE16]])
+; CHECK-NEXT: [[TMP37:%.*]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[TMP33]])
; CHECK-NEXT: [[CMP_N19:%.*]] = icmp eq i64 [[TMP0]], [[N_VEC11]]
; CHECK-NEXT: br i1 [[CMP_N19]], [[EXIT]], label %[[VEC_EPILOG_SCALAR_PH]]
; CHECK: [[VEC_EPILOG_SCALAR_PH]]:
>From ad51459fcb791e1b707bc2571a7169426d80893f Mon Sep 17 00:00:00 2001
From: Sander de Smalen <sander.desmalen at arm.com>
Date: Thu, 12 Mar 2026 13:41:14 +0000
Subject: [PATCH 2/4] Address suggestions
---
.../Transforms/Vectorize/VPlanTransforms.cpp | 59 +++++++++++--------
1 file changed, 33 insertions(+), 26 deletions(-)
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index e918cebf19258..226354c2bf486 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -4326,6 +4326,12 @@ tryToMatchAndCreateExtendedReduction(VPReductionRecipe *Red, VPCostContext &Ctx,
Type *RedTy = Ctx.Types.inferScalarType(Red);
VPValue *VecOp = Red->getVecOp();
+ // For partial reductions, the decision has already been
+ // made at the point of transforming reductions -> partial
+ // reductions for a given plan, based on the cost-model.
+ if (Red->isPartialReduction())
+ return new VPExpressionRecipe(cast<VPWidenCastRecipe>(VecOp), Red);
+
// Clamp the range if using extended-reduction is profitable.
auto IsExtendedRedValidAndClampRange =
[&](unsigned Opcode, Instruction::CastOps ExtOpc, Type *SrcTy) -> bool {
@@ -4339,12 +4345,6 @@ tryToMatchAndCreateExtendedReduction(VPReductionRecipe *Red, VPCostContext &Ctx,
cast<VPWidenCastRecipe>(VecOp)->computeCost(VF, Ctx);
InstructionCost RedCost = Red->computeCost(VF, Ctx);
- // For partial reductions, the decision has already been
- // made at the point of transforming reductions -> partial
- // reductions for a given plan, based on the cost-model.
- if (Red->isPartialReduction())
- return true;
-
// TTI::getExtendedReductionCost for in-loop reductions
// only supports integer types.
if (RedTy->isFloatingPointTy())
@@ -4396,17 +4396,17 @@ tryToMatchAndCreateMulAccumulateReduction(VPReductionRecipe *Red,
VPWidenCastRecipe *OuterExt) -> bool {
return LoopVectorizationPlanner::getDecisionAndClampRange(
[&](ElementCount VF) {
- TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
- Type *SrcTy =
- Ext0 ? Ctx.Types.inferScalarType(Ext0->getOperand(0)) : RedTy;
- InstructionCost MulAccCost;
-
// For partial reductions, the decision has already been
// made at the point of transforming reductions -> partial
// reductions for a given plan, based on the cost-model.
if (Red->isPartialReduction())
return true;
+ TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
+ Type *SrcTy =
+ Ext0 ? Ctx.Types.inferScalarType(Ext0->getOperand(0)) : RedTy;
+ InstructionCost MulAccCost;
+
// Only partial reductions support mixed or floating-point extends
// at the moment.
if (Ext0 && Ext1 &&
@@ -5830,6 +5830,8 @@ struct VPPartialReductionChain {
/// This allows distinguishing between Sub and AddWithSub recurrences,
/// when the ReductionBinOp is a Instruction::Sub.
RecurKind RK;
+ /// The cost of the link in the reduction chain.
+ DenseMap<ElementCount, InstructionCost> PartialReductionCost;
};
static VPSingleDefRecipe *
@@ -5996,7 +5998,7 @@ static void transformToPartialReduction(const VPPartialReductionChain &Chain,
/// Returns the cost of a link in a partial-reduction chain for a given VF.
static InstructionCost
getPartialReductionLinkCost(VPCostContext &CostCtx,
- const VPPartialReductionChain &Chain,
+ const VPPartialReductionChain &Link,
ElementCount VF) {
auto GetExtInfo = [&CostCtx](VPWidenCastRecipe *Ext)
-> std::pair<Type *, TargetTransformInfo::PartialReductionExtendKind> {
@@ -6008,7 +6010,7 @@ getPartialReductionLinkCost(VPCostContext &CostCtx,
return {ExtOpType, ExtKind};
};
- ExtendedReductionOperand ExtendedOp = Chain.ExtendedOp;
+ ExtendedReductionOperand ExtendedOp = Link.ExtendedOp;
VPWidenCastRecipe *ExtendA = ExtendedOp.CastRecipes[0];
VPWidenCastRecipe *ExtendB = ExtendedOp.CastRecipes[1];
@@ -6018,7 +6020,7 @@ getPartialReductionLinkCost(VPCostContext &CostCtx,
std::tie(ExtOpTypeB, ExtKindB) = GetExtInfo(ExtendB);
std::optional<unsigned> BinOpc;
- if (ExtendedOp.BinOp && ExtendedOp.BinOp != Chain.ReductionBinOp)
+ if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
BinOpc = ExtendedOp.BinOp->getOpcode();
// If ExtendB is nullptr but there's a separate BinOp, the second operand
@@ -6035,14 +6037,14 @@ getPartialReductionLinkCost(VPCostContext &CostCtx,
ExtKindB = ExtKindA;
}
- Type *RdxType = CostCtx.Types.inferScalarType(Chain.ReductionBinOp);
+ Type *RdxType = CostCtx.Types.inferScalarType(Link.ReductionBinOp);
std::optional<llvm::FastMathFlags> Flags;
if (RdxType->isFloatingPointTy())
- Flags = Chain.ReductionBinOp->getFastMathFlags();
+ Flags = Link.ReductionBinOp->getFastMathFlags();
- unsigned Opcode = Chain.RK == RecurKind::Sub
+ unsigned Opcode = Link.RK == RecurKind::Sub
? (unsigned)Instruction::Add
- : Chain.ReductionBinOp->getOpcode();
+ : Link.ReductionBinOp->getOpcode();
return CostCtx.TTI.getPartialReductionCost(Opcode, ExtOpTypeA, ExtOpTypeB,
RdxType, VF, ExtKindA, ExtKindB,
BinOpc, CostCtx.CostKind, Flags);
@@ -6163,7 +6165,7 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
VPValue *ExitValue = RdxResult->getOperand(0);
match(ExitValue, m_Select(m_VPValue(), m_VPValue(ExitValue), m_VPValue()));
- SmallVector<VPPartialReductionChain> Chains;
+ SmallVector<VPPartialReductionChain> Chain;
RecurKind RK = RedPhiR->getRecurrenceKind();
Type *PhiType = CostCtx.Types.inferScalarType(RedPhiR);
TypeSize PHISize = PhiType->getPrimitiveSizeInBits();
@@ -6198,24 +6200,27 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
/// Check if a partial reduction chain is supported by the target (i.e.
/// does not have an invalid cost) for the given VF range. Clamps the range
/// and returns true if feasible for any VF.
- VPPartialReductionChain Chain(
+ VPPartialReductionChain Link(
{UpdateR, *ExtendedOp,
static_cast<unsigned>(PHISize.getKnownScalarFactor(ExtSrcSize)), RK});
if (!LoopVectorizationPlanner::getDecisionAndClampRange(
[&](ElementCount VF) {
- return getPartialReductionLinkCost(CostCtx, Chain, VF).isValid();
+ InstructionCost Cost =
+ getPartialReductionLinkCost(CostCtx, Link, VF);
+ Link.PartialReductionCost[VF] = Cost;
+ return Cost.isValid();
},
Range))
return std::nullopt;
- Chains.push_back(Chain);
+ Chain.push_back(Link);
CurrentValue = PrevValue;
}
// The chains were collected by traversing backwards from the exit value.
// Reverse the chains so they are in program order.
- std::reverse(Chains.begin(), Chains.end());
- return Chains;
+ std::reverse(Chain.begin(), Chain.end());
+ return Chain;
}
} // namespace
@@ -6269,7 +6274,9 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
// chain using regular reductions.
for (const VPPartialReductionChain &Link : Chain) {
ExtendedReductionOperand ExtendedOp = Link.ExtendedOp;
- PartialCost += getPartialReductionLinkCost(CostCtx, Link, VF);
+ assert(Link.PartialReductionCost.contains(VF) &&
+ "Expected cost to have been calculated for VF");
+ PartialCost += Link.PartialReductionCost.lookup(VF);
RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
RegularCost += ExtendedOp.BinOp->computeCost(VF, CostCtx);
@@ -6322,7 +6329,7 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
// Clear the chain if it is not profitable.
if (!LoopVectorizationPlanner::getDecisionAndClampRange(
- [&](ElementCount VF) {
+ [&, &Chains = Chains](ElementCount VF) {
return IsProfitablePartialReductionChainForVF(Chains, VF);
},
Range))
>From 48260624239e394d25a53d57fbd42dc125fa311a Mon Sep 17 00:00:00 2001
From: Sander de Smalen <sander.desmalen at arm.com>
Date: Thu, 12 Mar 2026 15:33:35 +0000
Subject: [PATCH 3/4] Address suggestion
---
.../Transforms/Vectorize/VPlanTransforms.cpp | 20 +++++--------------
1 file changed, 5 insertions(+), 15 deletions(-)
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index 226354c2bf486..25733e994531b 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -5830,8 +5830,6 @@ struct VPPartialReductionChain {
/// This allows distinguishing between Sub and AddWithSub recurrences,
/// when the ReductionBinOp is a Instruction::Sub.
RecurKind RK;
- /// The cost of the link in the reduction chain.
- DenseMap<ElementCount, InstructionCost> PartialReductionCost;
};
static VPSingleDefRecipe *
@@ -6203,16 +6201,6 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
VPPartialReductionChain Link(
{UpdateR, *ExtendedOp,
static_cast<unsigned>(PHISize.getKnownScalarFactor(ExtSrcSize)), RK});
- if (!LoopVectorizationPlanner::getDecisionAndClampRange(
- [&](ElementCount VF) {
- InstructionCost Cost =
- getPartialReductionLinkCost(CostCtx, Link, VF);
- Link.PartialReductionCost[VF] = Cost;
- return Cost.isValid();
- },
- Range))
- return std::nullopt;
-
Chain.push_back(Link);
CurrentValue = PrevValue;
}
@@ -6274,9 +6262,11 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
// chain using regular reductions.
for (const VPPartialReductionChain &Link : Chain) {
ExtendedReductionOperand ExtendedOp = Link.ExtendedOp;
- assert(Link.PartialReductionCost.contains(VF) &&
- "Expected cost to have been calculated for VF");
- PartialCost += Link.PartialReductionCost.lookup(VF);
+ InstructionCost LinkCost = getPartialReductionLinkCost(CostCtx, Link, VF);
+ if (!LinkCost.isValid())
+ return false;
+
+ PartialCost += LinkCost;
RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
RegularCost += ExtendedOp.BinOp->computeCost(VF, CostCtx);
>From fd9f09df4f99a0b11086c7ca23f2654722e520ca Mon Sep 17 00:00:00 2001
From: Sander de Smalen <sander.desmalen at arm.com>
Date: Thu, 12 Mar 2026 15:53:21 +0000
Subject: [PATCH 4/4] Address nit
---
llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index 25733e994531b..c2f0d9d3ef16e 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -6270,10 +6270,9 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
RegularCost += ExtendedOp.BinOp->computeCost(VF, CostCtx);
- if (ExtendedOp.CastRecipes[0])
- RegularCost += ExtendedOp.CastRecipes[0]->computeCost(VF, CostCtx);
- if (ExtendedOp.CastRecipes[1])
- RegularCost += ExtendedOp.CastRecipes[1]->computeCost(VF, CostCtx);
+ for (VPWidenCastRecipe *Extend : ExtendedOp.CastRecipes)
+ if (Extend)
+ RegularCost += Extend->computeCost(VF, CostCtx);
}
return PartialCost.isValid() && PartialCost <= RegularCost;
};
More information about the llvm-branch-commits
mailing list