[llvm] 18d5b9e - [LV] Simplify costing partial reduction chain links (NFCI) (#190980)

via llvm-commits llvm-commits at lists.llvm.org
Thu Apr 9 04:03:56 PDT 2026


Author: Benjamin Maxwell
Date: 2026-04-09T12:03:50+01:00
New Revision: 18d5b9ec0cfd09b374636daea047ab5e7dc9bc3e

URL: https://github.com/llvm/llvm-project/commit/18d5b9ec0cfd09b374636daea047ab5e7dc9bc3e
DIFF: https://github.com/llvm/llvm-project/commit/18d5b9ec0cfd09b374636daea047ab5e7dc9bc3e.diff

LOG: [LV] Simplify costing partial reduction chain links (NFCI) (#190980)

Previously, `getPartialReductionLinkCost()` needed to figure out what
case `matchExtendedReductionOperand()` matched to compute a cost. This
made adding new cases to `matchExtendedReductionOperand()` more complex
and added some redundancy.

This patch updates `ExtendedReductionOperand` so that it contains all
the information needed to compute the cost ready to pass to
`getPartialReductionCost()`. This means matching new operand forms only
needs to be done in `matchExtendedReductionOperand()`.

This is split off from #188043 (this change simplifies matching absolute
difference operands).

Added: 
    

Modified: 
    llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
index ef8c88ad81785..83ab470e1516f 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp
@@ -5975,12 +5975,20 @@ void VPlanTransforms::optimizeFindIVReductions(VPlan &Plan,
 
 namespace {
 
-/// Holds the binary operation used to compute the extended operand and the
-/// casts that feed into it.
+using ExtendKind = TTI::PartialReductionExtendKind;
+struct ReductionExtend {
+  Type *SrcType = nullptr;
+  ExtendKind Kind = ExtendKind::PR_None;
+};
+
+/// Describes the extends used to compute the extended reduction operand.
+/// ExtendB is optional. If ExtendB is present, ExtendsUser is a binary
+/// operation.
 struct ExtendedReductionOperand {
-  VPWidenRecipe *BinOp = nullptr;
-  // Note: The second cast recipe may be null.
-  std::array<VPWidenCastRecipe *, 2> CastRecipes = {};
+  /// The recipe that consumes the extends.
+  VPWidenRecipe *ExtendsUser = nullptr;
+  /// Extend descriptions (inputs to getPartialReductionCost).
+  ReductionExtend ExtendA, ExtendB;
 };
 
 /// A chain of recipes that form a partial reduction. Matches either
@@ -5989,7 +5997,7 @@ struct ExtendedReductionOperand {
 struct VPPartialReductionChain {
   /// The top-level binary operation that forms the reduction to a scalar
   /// after the loop body.
-  VPWidenRecipe *ReductionBinOp;
+  VPWidenRecipe *ReductionBinOp = nullptr;
   /// The user of the extends that is then reduced.
   ExtendedReductionOperand ExtendedOp;
   unsigned ScaleFactor;
@@ -6164,44 +6172,13 @@ static InstructionCost
 getPartialReductionLinkCost(VPCostContext &CostCtx,
                             const VPPartialReductionChain &Link,
                             ElementCount VF) {
-  auto GetExtInfo = [&CostCtx](VPWidenCastRecipe *Ext)
-      -> std::pair<Type *, TargetTransformInfo::PartialReductionExtendKind> {
-    if (!Ext)
-      return {nullptr, TargetTransformInfo::PR_None};
-    Type *ExtOpType = CostCtx.Types.inferScalarType(Ext->getOperand(0));
-    auto ExtKind = TargetTransformInfo::getPartialReductionExtendKind(
-        static_cast<Instruction::CastOps>(Ext->getOpcode()));
-    return {ExtOpType, ExtKind};
-  };
-
+  Type *RdxType = CostCtx.Types.inferScalarType(Link.ReductionBinOp);
   const ExtendedReductionOperand &ExtendedOp = Link.ExtendedOp;
-  VPWidenCastRecipe *ExtendA = ExtendedOp.CastRecipes[0];
-  VPWidenCastRecipe *ExtendB = ExtendedOp.CastRecipes[1];
-
-  Type *ExtOpTypeA, *ExtOpTypeB;
-  TargetTransformInfo::PartialReductionExtendKind ExtKindA, ExtKindB;
-  std::tie(ExtOpTypeA, ExtKindA) = GetExtInfo(ExtendA);
-  std::tie(ExtOpTypeB, ExtKindB) = GetExtInfo(ExtendB);
-
-  std::optional<unsigned> BinOpc;
-  if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.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 && 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 InstructionCost::getInvalid();
-    ExtOpTypeB = ExtOpTypeA;
-    ExtKindB = ExtKindA;
-  }
+  std::optional<unsigned> BinOpc = std::nullopt;
+  // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
+  if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
+    BinOpc = ExtendedOp.ExtendsUser->getOpcode();
 
-  Type *RdxType = CostCtx.Types.inferScalarType(Link.ReductionBinOp);
   std::optional<llvm::FastMathFlags> Flags;
   if (RdxType->isFloatingPointTy())
     Flags = Link.ReductionBinOp->getFastMathFlags();
@@ -6209,13 +6186,13 @@ getPartialReductionLinkCost(VPCostContext &CostCtx,
   unsigned Opcode = Link.RK == RecurKind::Sub
                         ? (unsigned)Instruction::Add
                         : Link.ReductionBinOp->getOpcode();
-  return CostCtx.TTI.getPartialReductionCost(Opcode, ExtOpTypeA, ExtOpTypeB,
-                                             RdxType, VF, ExtKindA, ExtKindB,
-                                             BinOpc, CostCtx.CostKind, Flags);
+  return CostCtx.TTI.getPartialReductionCost(
+      Opcode, ExtendedOp.ExtendA.SrcType, ExtendedOp.ExtendB.SrcType, RdxType,
+      VF, ExtendedOp.ExtendA.Kind, ExtendedOp.ExtendB.Kind, BinOpc,
+      CostCtx.CostKind, Flags);
 }
 
-static TTI::PartialReductionExtendKind
-getPartialReductionExtendKind(VPWidenCastRecipe *Cast) {
+static ExtendKind getPartialReductionExtendKind(VPWidenCastRecipe *Cast) {
   return TTI::getPartialReductionExtendKind(Cast->getOpcode());
 }
 
@@ -6234,7 +6211,8 @@ getPartialReductionExtendKind(VPWidenCastRecipe *Cast) {
 ///
 /// Note: The second operand of UpdateR corresponds to \p Op in the examples.
 static std::optional<ExtendedReductionOperand>
-matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
+matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op,
+                              VPTypeAnalysis &TypeInfo) {
   assert(is_contained(UpdateR->operands(), Op) &&
          "Op should be operand of UpdateR");
 
@@ -6242,6 +6220,7 @@ matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
   if (match(Op, m_WidenAnyExtend(m_VPValue()))) {
     auto *CastRecipe = cast<VPWidenCastRecipe>(Op);
     VPValue *CastSource = CastRecipe->getOperand(0);
+    OuterExtKind = getPartialReductionExtendKind(CastRecipe);
     if (match(CastSource, m_Mul(m_VPValue(), m_VPValue())) ||
         match(CastSource, m_FMul(m_VPValue(), m_VPValue()))) {
       // Match: ext(mul(...))
@@ -6250,13 +6229,15 @@ matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
       // by widening the inner extends to match it. See
       // optimizeExtendsForPartialReduction.
       Op = CastSource;
-      OuterExtKind = getPartialReductionExtendKind(CastRecipe);
     } else if (UpdateR->getOpcode() == Instruction::Add ||
                UpdateR->getOpcode() == Instruction::FAdd) {
       // Match: UpdateR(PrevValue, ext(...))
       // TODO: Remove the add/fadd restriction (we should be able to handle this
       // case for sub reductions too).
-      return ExtendedReductionOperand{UpdateR, {CastRecipe, nullptr}};
+      return ExtendedReductionOperand{
+          UpdateR,
+          /*ExtendA=*/{TypeInfo.inferScalarType(CastSource), *OuterExtKind},
+          /*ExtendB=*/{}};
     }
   }
 
@@ -6283,13 +6264,16 @@ matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
     return std::nullopt;
 
   auto *LHSCast = cast<VPWidenCastRecipe>(LHS);
+  Type *LHSInputType = TypeInfo.inferScalarType(LHSCast->getOperand(0));
+  ExtendKind LHSExtendKind = getPartialReductionExtendKind(LHSCast);
 
   // The RHS of the operation can be an extend or a constant integer.
-  // The constant will be validated in isValidPartialReduction.
+  const APInt *RHSConst = nullptr;
   VPWidenCastRecipe *RHSCast = nullptr;
   if (match(RHS, m_WidenAnyExtend(m_VPValue())))
     RHSCast = cast<VPWidenCastRecipe>(RHS);
-  else if (!isa<VPConstantInt>(RHS))
+  else if (!match(RHS, m_APInt(RHSConst)) ||
+           !canConstantBeExtended(RHSConst, LHSInputType, LHSExtendKind))
     return std::nullopt;
 
   // The outer extend kind must match the inner extends for folding.
@@ -6298,7 +6282,15 @@ matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
         getPartialReductionExtendKind(Cast) != OuterExtKind)
       return std::nullopt;
 
-  return ExtendedReductionOperand{BinOp, {LHSCast, RHSCast}};
+  Type *RHSInputType = LHSInputType;
+  ExtendKind RHSExtendKind = LHSExtendKind;
+  if (RHSCast) {
+    RHSInputType = TypeInfo.inferScalarType(RHSCast->getOperand(0));
+    RHSExtendKind = getPartialReductionExtendKind(RHSCast);
+  }
+
+  return ExtendedReductionOperand{
+      BinOp, {LHSInputType, LHSExtendKind}, {RHSInputType, RHSExtendKind}};
 }
 
 /// Examines each operation in the reduction chain corresponding to \p RedPhiR,
@@ -6317,9 +6309,10 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
   VPValue *ExitValue = RdxResult->getOperand(0);
   match(ExitValue, m_Select(m_VPValue(), m_VPValue(ExitValue), m_VPValue()));
 
+  VPTypeAnalysis &TypeInfo = CostCtx.Types;
   SmallVector<VPPartialReductionChain> Chain;
   RecurKind RK = RedPhiR->getRecurrenceKind();
-  Type *PhiType = CostCtx.Types.inferScalarType(RedPhiR);
+  Type *PhiType = TypeInfo.inferScalarType(RedPhiR);
   TypeSize PHISize = PhiType->getPrimitiveSizeInBits();
 
   // Work backwards from the ExitValue examining each reduction operation.
@@ -6335,16 +6328,15 @@ getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
     // Find the extended operand. The other operand (PrevValue) is the next link
     // in the reduction chain.
     std::optional<ExtendedReductionOperand> ExtendedOp =
-        matchExtendedReductionOperand(UpdateR, Op);
+        matchExtendedReductionOperand(UpdateR, Op, TypeInfo);
     if (!ExtendedOp) {
-      ExtendedOp = matchExtendedReductionOperand(UpdateR, PrevValue);
+      ExtendedOp = matchExtendedReductionOperand(UpdateR, PrevValue, TypeInfo);
       if (!ExtendedOp)
         return std::nullopt;
       std::swap(Op, PrevValue);
     }
 
-    Type *ExtSrcType = CostCtx.Types.inferScalarType(
-        ExtendedOp->CastRecipes[0]->getOperand(0));
+    Type *ExtSrcType = ExtendedOp->ExtendA.SrcType;
     TypeSize ExtSrcSize = ExtSrcType->getPrimitiveSizeInBits();
     if (!PHISize.hasKnownScalarFactor(ExtSrcSize))
       return std::nullopt;
@@ -6393,15 +6385,15 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
   DenseMap<VPSingleDefRecipe *, unsigned> ScaledReductionMap;
   for (const auto &[_, Chains] : ChainsByPhi)
     for (const VPPartialReductionChain &Chain : Chains) {
-      PartialReductionOps.insert(Chain.ExtendedOp.BinOp);
+      PartialReductionOps.insert(Chain.ExtendedOp.ExtendsUser);
       ScaledReductionMap[Chain.ReductionBinOp] = Chain.ScaleFactor;
     }
 
   // A partial reduction is invalid if any of its extends are used by
   // something that isn't another partial reduction. This is because the
   // extends are intended to be lowered along with the reduction itself.
-  auto ExtendUsersValid = [&](VPWidenCastRecipe *Ext) {
-    return !Ext || all_of(Ext->users(), [&](VPUser *U) {
+  auto ExtendUsersValid = [&](VPValue *Ext) {
+    return !isa<VPWidenCastRecipe>(Ext) || all_of(Ext->users(), [&](VPUser *U) {
       return PartialReductionOps.contains(cast<VPRecipeBase>(U));
     });
   };
@@ -6421,10 +6413,11 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
 
       PartialCost += LinkCost;
       RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
-      if (ExtendedOp.BinOp && ExtendedOp.BinOp != Link.ReductionBinOp)
-        RegularCost += ExtendedOp.BinOp->computeCost(VF, CostCtx);
-      for (VPWidenCastRecipe *Extend : ExtendedOp.CastRecipes)
-        if (Extend)
+      // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
+      if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
+        RegularCost += ExtendedOp.ExtendsUser->computeCost(VF, CostCtx);
+      for (VPValue *Op : ExtendedOp.ExtendsUser->operands())
+        if (auto *Extend = dyn_cast<VPWidenCastRecipe>(Op))
           RegularCost += Extend->computeCost(VF, CostCtx);
     }
     return PartialCost.isValid() && PartialCost <= RegularCost;
@@ -6437,7 +6430,7 @@ void VPlanTransforms::createPartialReductions(VPlan &Plan,
   // reductions where the types of the other operands don't match.
   for (auto &[RedPhiR, Chains] : ChainsByPhi) {
     for (const VPPartialReductionChain &Chain : Chains) {
-      if (!all_of(Chain.ExtendedOp.CastRecipes, ExtendUsersValid)) {
+      if (!all_of(Chain.ExtendedOp.ExtendsUser->operands(), ExtendUsersValid)) {
         Chains.clear();
         break;
       }


        


More information about the llvm-commits mailing list