[llvm] [SLP][X86] Forward gather VL to getShuffleCost for broadcast-of-load (PR #195859)
Alexey Bataev via llvm-commits
llvm-commits at lists.llvm.org
Tue May 5 06:59:13 PDT 2026
https://github.com/alexey-bataev created https://github.com/llvm/llvm-project/pull/195859
ShuffleCostEstimator::finalize() emits the user-visible final shuffle on
top of the gather node, but it called the local createShuffle helper
without forwarding the gathered scalars. Consequently
X86TTIImpl::getShuffleCost(), which folds vbroadcast{ss,sd} of a
load into TCC_Free under AVX/AVX2, could not see the underlying load
and overestimated the cost of the splat permutation by one unit,
occasionally dropping a profitable vectorization.
Also, modified the TTI cost estimation to handle correctly the cost for
the scalar code before actual admission of the vector broadcast.
>From 435db271b75f91c1c14f20bf754c1ebe95f2a555 Mon Sep 17 00:00:00 2001
From: Alexey Bataev <a.bataev at outlook.com>
Date: Tue, 5 May 2026 06:58:54 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
=?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Created using spr 1.3.7
---
.../lib/Target/X86/X86TargetTransformInfo.cpp | 35 +++++++++++++-
.../Transforms/Vectorize/SLPVectorizer.cpp | 47 +++++++++++++++----
.../SLPVectorizer/X86/broadcast-load-cost.ll | 2 +-
.../X86/revec-scalar-insertelement.ll | 8 ++--
4 files changed, 77 insertions(+), 15 deletions(-)
diff --git a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
index 1bc0ff397e476..b2b77265b06a5 100644
--- a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
+++ b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
@@ -1576,8 +1576,41 @@ InstructionCost X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
LT.first = 1;
// If we're broadcasting a load then AVX/AVX2 can do this for free.
+ // If many-used-load whose every use is one of a small set of operations
+ // that SLP can rewrite into a single vector lane, codegen can fold it into
+ // the free broadcast.
using namespace PatternMatch;
- if (!Args.empty() && match(Args[0], m_OneUse(m_Load(m_Value()))) &&
+ auto IsBroadcastLoadFoldUser = [&](const User *U) {
+ if (isa<InsertElementInst>(U) && U->getOperand(1) == Args[0])
+ return true;
+ if (U->getType()->isVectorTy())
+ return false;
+ // Terminators (return/branch/switch/indirectbr/resume/invoke EH)
+ // and phis carry the value across control flow.
+ if (const auto *I = dyn_cast<Instruction>(U))
+ if (I->isTerminator() ||
+ isa<PHINode, AtomicRMWInst, AtomicCmpXchgInst>(I))
+ return false;
+ // Only pure calls can be folded.
+ if (const auto *CB = dyn_cast<CallBase>(U))
+ return CB->doesNotAccessMemory() && !CB->mayHaveSideEffects();
+ return true;
+ };
+ auto IsFoldableSLPBroadcastLoad = [&]() {
+ if (!match(Args[0], m_Load(m_Value())))
+ return false;
+ auto *FVT = dyn_cast<FixedVectorType>(DstTy);
+ if (!FVT)
+ return false;
+ // getNumUses() counts each Use, matching the per-lane broadcast
+ // accounting (a use like `op %x, %x` consumes two broadcast lanes).
+ if (Args[0]->getNumUses() != FVT->getNumElements())
+ return false;
+ return all_of(Args[0]->users(), IsBroadcastLoadFoldUser);
+ };
+ if (!Args.empty() &&
+ (match(Args[0], m_OneUse(m_Load(m_Value()))) ||
+ IsFoldableSLPBroadcastLoad()) &&
(ST->hasAVX2() ||
(ST->hasAVX() && LT.second.getScalarSizeInBits() >= 32)))
return TTI::TCC_Free;
diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 43faf44564c9d..a1cc43f353a6a 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -13823,9 +13823,10 @@ class BaseShuffleAnalysis {
/// Smart shuffle instruction emission, walks through shuffles trees and
/// tries to find the best matching vector for the actual shuffle
/// instruction.
- template <typename T, typename ShuffleBuilderTy>
+ template <typename T, typename ShuffleBuilderTy, typename... Args>
static T createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask,
- ShuffleBuilderTy &Builder, Type *ScalarTy) {
+ ShuffleBuilderTy &Builder, Type *ScalarTy,
+ Args... Arguments) {
assert(V1 && "Expected at least one vector value.");
unsigned ScalarTyNumElements = getNumElements(ScalarTy);
SmallVector<int> NewMask(Mask);
@@ -13940,7 +13941,7 @@ class BaseShuffleAnalysis {
assert(V1 && "Expected non-null value after looking through shuffles.");
if (!IsIdentity)
- return Builder.createShuffleVector(V1, NewMask);
+ return Builder.createShuffleVector(V1, NewMask, Arguments...);
return Builder.createIdentity(V1);
}
@@ -15204,6 +15205,19 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
bool IsFinalized = false;
SmallVector<int> CommonMask;
SmallVector<PointerUnion<Value *, const TreeEntry *>, 2> InVectors;
+ /// Captures the original scalar VL of a single, "clean" gather() call so
+ /// the values can be forwarded as the Args operand to getShuffleCost() for
+ /// the final permutation in finalize(). This lets the target cost model
+ /// recognize patterns such as broadcast-of-load (e.g. on X86,
+ /// vbroadcast{ss,sd} folds the broadcast and the load into one instruction
+ /// under AVX/AVX2 and is reported as TCC_Free by getShuffleCost). The
+ /// state machine is:
+ /// * engaged + empty: tracking active, no qualifying gather seen yet.
+ /// * engaged + non-empty: exactly one qualifying gather observed and its
+ /// VL still corresponds to InVectors.front().
+ /// * disengaged: the cached VL is no longer trustworthy (multiple
+ /// gather() calls, or a state-mutating add() happened).
+ std::optional<SmallVector<Value *>> BVValues = SmallVector<Value *>();
const TargetTransformInfo &TTI;
InstructionCost Cost = 0;
SmallDenseSet<Value *> VectorizedVals;
@@ -15496,14 +15510,16 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
return ::getShuffleCost(TTI, TTI::SK_PermuteTwoSrc,
cast<VectorType>(V1->getType()), Mask);
}
- InstructionCost createShuffleVector(Value *V1, ArrayRef<int> Mask) const {
+ InstructionCost createShuffleVector(Value *V1, ArrayRef<int> Mask,
+ ArrayRef<Value *> VL) const {
// Empty mask or identity mask are free.
unsigned VF =
cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
if (isEmptyOrIdentity(Mask, VF))
return TTI::TCC_Free;
- return ::getShuffleCost(TTI, TTI::SK_PermuteSingleSrc,
- cast<VectorType>(V1->getType()), Mask);
+ return ::getShuffleCost(
+ TTI, TTI::SK_PermuteSingleSrc, cast<VectorType>(V1->getType()), Mask,
+ TTI::TCK_RecipThroughput, /*Index=*/0, /*SubTp=*/nullptr, VL);
}
InstructionCost createIdentity(Value *) const { return TTI::TCC_Free; }
InstructionCost createPoison(Type *Ty, unsigned VF) const {
@@ -15518,7 +15534,7 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
InstructionCost
createShuffle(const PointerUnion<Value *, const TreeEntry *> &P1,
const PointerUnion<Value *, const TreeEntry *> &P2,
- ArrayRef<int> Mask) {
+ ArrayRef<int> Mask, ArrayRef<Value *> VL = {}) {
ShuffleCostBuilder Builder(TTI);
SmallVector<int> CommonMask(Mask);
Value *V1 = P1.dyn_cast<Value *>(), *V2 = P2.dyn_cast<Value *>();
@@ -15726,7 +15742,7 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
if (InVectors.size() == 2)
InVectors.pop_back();
return ExtraCost + BaseShuffleAnalysis::createShuffle<InstructionCost>(
- V1, V2, CommonMask, Builder, ScalarTy);
+ V1, V2, CommonMask, Builder, ScalarTy, VL);
}
public:
@@ -15876,6 +15892,7 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
SameNodesEstimated = true;
}
void add(const TreeEntry &E1, const TreeEntry &E2, ArrayRef<int> Mask) {
+ BVValues.reset();
if (&E1 == &E2) {
assert(all_of(Mask,
[&](int Idx) {
@@ -15900,6 +15917,7 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
estimateNodesPermuteCost(E1, &E2, Mask, Part, SliceSize);
}
void add(const TreeEntry &E1, ArrayRef<int> Mask) {
+ BVValues.reset();
if (InVectors.empty()) {
CommonMask.assign(Mask.begin(), Mask.end());
InVectors.assign(1, &E1);
@@ -15935,6 +15953,8 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
}
/// Adds another one input vector and the mask for the shuffling.
void add(Value *V1, ArrayRef<int> Mask, bool ForExtracts = false) {
+ if (BVValues && !isa<Constant>(V1))
+ BVValues.reset();
if (InVectors.empty()) {
assert(CommonMask.empty() && !ForExtracts &&
"Expected empty input mask/vectors.");
@@ -15984,6 +16004,12 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
Value *gather(ArrayRef<Value *> VL, unsigned MaskVF = 0,
Value *Root = nullptr) {
Cost += getBuildVectorCost(VL, Root);
+ if (BVValues) {
+ if (BVValues->empty() && InVectors.empty())
+ BVValues->assign(VL.begin(), VL.end());
+ else
+ BVValues.reset();
+ }
if (!Root) {
// FIXME: Need to find a way to avoid use of getNullValue here.
SmallVector<Constant *> Vals;
@@ -16113,10 +16139,13 @@ class BoUpSLP::ShuffleCostEstimator : public BaseShuffleAnalysis {
assert(InVectors.size() == 1 && "Expected only one vector with no mask");
return Cost;
}
+ ArrayRef<Value *> VL;
+ if (BVValues)
+ VL = *BVValues;
return Cost +
createShuffle(InVectors.front(),
InVectors.size() == 2 ? InVectors.back() : nullptr,
- CommonMask);
+ CommonMask, VL);
}
~ShuffleCostEstimator() {
diff --git a/llvm/test/Transforms/SLPVectorizer/X86/broadcast-load-cost.ll b/llvm/test/Transforms/SLPVectorizer/X86/broadcast-load-cost.ll
index a0e6ffc4a250c..6ee5fc8adef27 100644
--- a/llvm/test/Transforms/SLPVectorizer/X86/broadcast-load-cost.ll
+++ b/llvm/test/Transforms/SLPVectorizer/X86/broadcast-load-cost.ll
@@ -17,7 +17,7 @@
; YAML-NEXT: Function: bcast_v2f64_load
; YAML-NEXT: Args:
; YAML-NEXT: - String: 'Stores SLP vectorized with cost '
-; YAML-NEXT: - Cost: '-1'
+; YAML-NEXT: - Cost: '-2'
define void @bcast_v2f64_load(ptr %A, double %y, double %z, ptr %S) {
; CHECK-LABEL: define void @bcast_v2f64_load(
diff --git a/llvm/test/Transforms/SLPVectorizer/X86/revec-scalar-insertelement.ll b/llvm/test/Transforms/SLPVectorizer/X86/revec-scalar-insertelement.ll
index c714b24c3d85e..6a53cfa5ec1c8 100644
--- a/llvm/test/Transforms/SLPVectorizer/X86/revec-scalar-insertelement.ll
+++ b/llvm/test/Transforms/SLPVectorizer/X86/revec-scalar-insertelement.ll
@@ -6,10 +6,10 @@ define <8 x i16> @test(ptr %0) {
; CHECK-SAME: ptr [[TMP0:%.*]]) #[[ATTR0:[0-9]+]] {
; CHECK-NEXT: [[VECTOR_PH:.*:]]
; CHECK-NEXT: [[TMP1:%.*]] = load i16, ptr [[TMP0]], align 2
-; CHECK-NEXT: [[TMP2:%.*]] = insertelement <8 x i16> zeroinitializer, i16 [[TMP1]], i64 0
-; CHECK-NEXT: [[TMP3:%.*]] = insertelement <8 x i16> [[TMP2]], i16 [[TMP1]], i64 1
-; CHECK-NEXT: [[TMP4:%.*]] = insertelement <8 x i16> [[TMP3]], i16 [[TMP1]], i64 3
-; CHECK-NEXT: [[TMP5:%.*]] = insertelement <8 x i16> [[TMP4]], i16 [[TMP1]], i64 5
+; CHECK-NEXT: [[TMP2:%.*]] = insertelement <4 x i16> poison, i16 [[TMP1]], i32 0
+; CHECK-NEXT: [[TMP3:%.*]] = shufflevector <4 x i16> [[TMP2]], <4 x i16> poison, <4 x i32> zeroinitializer
+; CHECK-NEXT: [[TMP4:%.*]] = shufflevector <4 x i16> [[TMP3]], <4 x i16> poison, <8 x i32> <i32 0, i32 1, i32 poison, i32 2, i32 poison, i32 3, i32 poison, i32 poison>
+; CHECK-NEXT: [[TMP5:%.*]] = shufflevector <8 x i16> zeroinitializer, <8 x i16> [[TMP4]], <8 x i32> <i32 8, i32 9, i32 2, i32 11, i32 4, i32 13, i32 6, i32 7>
; CHECK-NEXT: ret <8 x i16> [[TMP5]]
;
vector.ph:
More information about the llvm-commits
mailing list