Translator: a fragment's quad reduction reads its quad through quad instructions, helpers included

What: in a fragment function, a quad reduction (sum, product, min, max,
and, or, xor) now asks OpGroupNonUniformQuadAnyKHR whether each of the
four quad lanes takes part ("the quad lane is j"), and reads each lane's
value with OpGroupNonUniformQuadBroadcast from constant lane j. The four
lanes then fold in Metal's order, (x0 op x1) op (x2 op x3), with a lane
that takes no part counted as the identity, as before. Every lane folds
the same four values in the same order, so each gets the same bits.
Kernels and vertex functions have no helpers and keep the ballot form
(the ballot of the active lanes, then a shuffle per lane). The IR gains
GroupInst::QuadAny: QuadControlKHR, SPV_KHR_quad_control and
shaderQuadControl, with no scope operand. The interpreter, the
serializer, the requirement deriver and the builder follow.

Why: Metal's helpers take part in a quad reduction. Vulkan section 9.31
runs quad group operations over the quad's helpers in every entry, and
its other group operations (a ballot, a shuffle) over them only where
the entry declares MaximallyReconvergesKHR. AMD's open Vulkan driver
leaves a helper out of the ballot even though the entry declares
MaximallyReconvergesKHR beside RequireFullQuadsKHR. The device test
quad_control's pixel [0,0] read [322,95,67] against [320,95,30]: quad
lane 1, the helper, was missing from AND and XOR. A form with only quad
instructions is right by the spec on every device, whatever the entry's
reconvergence (rung 1).

What full_quads asks: unchanged, shaderQuadControl. A fragment
reduction's operation class moves from Ballot and Shuffle to Quad.
Vulkan requires the Quad class wherever shaderQuadControl is supported
(vkspec: "If the shaderQuadControl feature is supported,
supportedOperations must include VK_SUBGROUP_FEATURE_QUAD_BIT"). No new
query.

Votes: a fragment's quad votes, quad_ballot, prefix sums, shuffles and
broadcasts keep the ballot form in this commit, as does every fragment
simdgroup operation. The planner ruled this item to reductions alone:
no stream's fragment calls a quad or simdgroup function, and 43 corpus
fragment rows need full quads. Under that driver a vote read through
the ballot is expected to carry the same defect (unverified).

Also: the simd module doc no longer says ClusteredReduce(4) for quad
reductions and votes. The Helpers paragraph and full_quads state what
9.31 gives under RequireFullQuadsKHR.
This commit is contained in:
Anees Iqbal committed 2026-11-23 04:05:51 -08:00
1 parent 35f0c2d89a
commit 54517169dd
10 files changed
+193 -34

No files matched your search

+41 -16
View File
@@ -114,14 +114,16 @@ pub fn cluster_ops(g: &GroupPlan) -> OpBits {
/// Quads are the same in every tier: aligned groups of four subgroup lanes. A reduction, a
/// prefix sum or product and the first active lane's broadcast read the quad's lanes by shuffles
/// under the ballot of its active lanes, in Metal's order; a vote is the quad's bits of the ballot.
/// A broadcast or shuffle-xor by a constant lane or mask is Vulkan's quad class where the stage
/// under the ballot of its active lanes, in Metal's order, except a fragment's reduction, which
/// reads them by quad instructions ([`quad_reduce`]); a vote is the quad's bits of the ballot. A
/// broadcast or shuffle-xor by a constant lane or mask is Vulkan's quad class where the stage
/// takes it, and a shuffle elsewhere.
fn quad_ops(g: &GroupPlan) -> OpBits {
use GroupOp as G;
match (g.op, g.konst) {
(G::ShuffleXor, Some(0)) => OpBits::NONE,
(G::Broadcast | G::ShuffleXor, Some(_)) if g.quad_instructions => OpBits::QUAD,
(op, _) if g.helpers && combines(op) && !scan(op) => OpBits::QUAD,
(G::BroadcastFirst, _) => OpBits::BALLOT.union(OpBits::SHUFFLE),
(op, _) if combines(op) => OpBits::BALLOT.union(OpBits::SHUFFLE),
(G::All | G::Any | G::Ballot | G::IsFirst | G::ActiveThreadsMask, _) => OpBits::BALLOT,
@@ -235,8 +237,9 @@ pub(super) fn words(g: &GroupPlan) -> u32 {
+ match g.op {
op if scan(op) => 2048 + 32 * round,
G::ShuffleAndFillUp | G::ShuffleAndFillDown => 160,
// A quad's four reads under its ballot bits, three combinations and the result's
// rounding ([`quad_tree`]).
// A quad's four reads with whether each lane takes part (by its ballot bits, or a
// fragment's quad votes), three combinations and the result's rounding
// ([`quad_tree`]).
op if combines(op) && g.scope == GroupScope::Quad => 512 + 4 * round,
op if combines(op) => 64 + round,
_ => 128,
@@ -833,8 +836,20 @@ pub(super) fn fill_source(
Ok((src, inside))
}
/// A quad reduction in every subgroup tier: the quad's four lanes read under the ballot of its
/// active lanes ([`quad_tree`]).
/// A quad reduction in every subgroup tier: the quad's four lanes, each with whether it takes
/// part, combined in Metal's order ([`quad_tree`]).
///
/// A fragment's quad holds helpers, which take part in Metal's reductions (`full_quads`). Vulkan
/// runs its quad instructions over a quad's helpers, and its other group operations, a ballot and
/// a shuffle among them, over them only where the entry maximally reconverges (section 9.31,
/// "Helper Invocations"). So there lane `j` takes part when `OpGroupNonUniformQuadAnyKHR` of
/// "the quad lane is `j`" holds, and its value is `OpGroupNonUniformQuadBroadcast` from quad lane
/// `j`: every lane folds the same four values in the same order, bit for bit. A lane that takes
/// no part is read as poison, which [`quad_tree`]'s selects never take (SPIR-V's `OpSelect` keeps
/// an operand it does not select from its result).
///
/// Elsewhere lane `j` takes part when its bit of the ballot of the active lanes is set, and its
/// value is the shuffle from it, or from the calling lane when it takes no part.
fn quad_reduce(
fb: &mut FunctionBuilder<'_>,
ln: &Lane,
@@ -842,17 +857,27 @@ fn quad_reduce(
v: SValue,
) -> BResult<SValue> {
let x = pre(fb, g, v)?;
let word = ln.active(fb)?;
let act = ln.quad_bits(fb, word)?;
let base = bin_k(fb, BinOp::BitwiseAnd, ln.l, !3)?;
let zero = k(fb, 0)?;
let mut lanes = Vec::with_capacity(4);
for j in 0..4 {
let bit = bin_k(fb, BinOp::ShiftRightLogical, act, j)?;
let bit = bin_k(fb, BinOp::BitwiseAnd, bit, 1)?;
let on = fb.binary(BinOp::INotEqual, bit, zero)?;
let from = bin_k(fb, BinOp::BitwiseOr, base, j)?;
lanes.push((ln.read_or_own(fb, None, x, on, from)?, on));
if g.helpers {
let q = bin_k(fb, BinOp::BitwiseAnd, ln.l, 3)?;
for j in 0..4 {
let me = bin_k(fb, BinOp::IEqual, q, j)?;
let on = fb.group_quad_any(me)?;
let i = k(fb, j)?;
lanes.push((fb.group_quad_broadcast(x, i)?, on));
}
} else {
let word = ln.active(fb)?;
let act = ln.quad_bits(fb, word)?;
let base = bin_k(fb, BinOp::BitwiseAnd, ln.l, !3)?;
let zero = k(fb, 0)?;
for j in 0..4 {
let bit = bin_k(fb, BinOp::ShiftRightLogical, act, j)?;
let bit = bin_k(fb, BinOp::BitwiseAnd, bit, 1)?;
let on = fb.binary(BinOp::INotEqual, bit, zero)?;
let from = bin_k(fb, BinOp::BitwiseOr, base, j)?;
lanes.push((ln.read_or_own(fb, None, x, on, from)?, on));
}
}
let r = quad_tree(fb, g, &lanes)?;
post(fb, g, r)
+23 -10
View File
@@ -95,10 +95,14 @@
//! is read through the calling lane without the ballot's bit extract or a shuffle naming it.
//!
//! **Helpers**. A fragment function whose group operations read, combine, or count other lanes
//! declares `RequireFullQuadsKHR`, so each quad starts with its four invocations and its helpers
//! take part in every group operation, as Metal's helpers do in a quad the primitive or the target
//! cuts (a fill reads a helper's value, a quad sum folds it in). A profile without
//! `shaderQuadControl` refuses such a function.
//! declares `RequireFullQuadsKHR`, so each quad starts with its four invocations, as Metal runs the
//! helpers of a quad the primitive or the target cuts, and they take part in its group operations
//! (a fill reads a helper's value, a quad sum folds it in). Vulkan runs its quad instructions over
//! a quad's helpers in every entry, and its other group operations over them only where the entry
//! declares `MaximallyReconvergesKHR` (section 9.31, "Helper Invocations"), as every such entry
//! does where the profile has maximal reconvergence (**Reconvergence**, below). A quad reduction
//! there reads its quad through quad instructions alone. A profile without `shaderQuadControl`
//! refuses such a function.
//!
//! In compute the flattened tiers derive every Metal thread builtin from the subgroup partition
//! (`lower::dispatch`), so simdgroup `k` is exactly the linear threads `[32k, 32k + 32)` and a
@@ -111,9 +115,12 @@
//! are Metal's 2×2 pixel quads in fragment and four consecutive linear threads in the flattened
//! compute tiers): shuffles with `(L & ~3) | (idx & 3)`, `OpGroupNonUniformQuadSwap` and
//! `OpGroupNonUniformQuadBroadcast` for constant masks and lanes where the stage takes Vulkan's
//! quad instructions (else the shuffles from the same lanes), `ClusteredReduce` with cluster size 4
//! for reductions and votes, and the ballot word for `is_first`, the active mask, and `quad_ballot`
//! (the quad's four bits, quad lane `j` at bit `j`). A simdgroup's `simd_active_threads_mask` is
//! quad instructions (else the shuffles from the same lanes), reductions, prefix sums and products
//! over the quad's four lanes in Metal's order, each lane read by a shuffle under its bit of the
//! ballot of the active lanes (a fragment's reduction by `OpGroupNonUniformQuadBroadcast` under
//! `OpGroupNonUniformQuadAnyKHR` of its quad lane, **Helpers** above), and the ballot word for
//! votes, `is_first`, the active mask, and `quad_ballot` (the quad's four bits, quad lane `j` at
//! bit `j`). A simdgroup's `simd_active_threads_mask` is
//! the ballot of `true`, held as the 64-bit ballot is. A fragment's `[[thread_index_in_quadgroup]]`
//! is the subgroup lane's low two bits ([`select_param`]), or, on a profile without the fragment
//! quad tier, the pixel's place in its aligned 2x2 block, read from `FragCoord`.
@@ -204,6 +211,10 @@ pub struct GroupPlan {
/// partly live blocks; elsewhere it is a shuffle from the lane it reads, through the live lanes
/// outside kernels, where a quad may lack a lane.
pub quad_instructions: bool,
/// The function is a fragment function, whose quads hold helpers ([`full_quads`]): a quad
/// reduction reads its quad through quad instructions, which Vulkan runs over the quad's
/// helpers whatever the entry's reconvergence (section 9.31, "Helper Invocations").
pub helpers: bool,
}
/// The simd strategies.
@@ -482,9 +493,10 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
/// ([`SimdPlan::full_quads`]), and a profile without `shaderQuadControl` refuses it. Metal runs the
/// helpers of a quad the primitive or the target cuts, and they take part: a fill or shuffle reads
/// a helper's value, a reduction folds it in (measured on the M3 Max and the M4). Vulkan launches
/// and activates them for every group operation only under `RequireFullQuadsKHR`; without it a
/// helper may be absent or inactive, and no other form gives its value. After the tier, so a stage
/// without the classes is refused as before.
/// them only under `RequireFullQuadsKHR`; without it a helper may be absent, and no other form
/// gives its value. Its quad instructions run over the helpers it launches, and its other group
/// operations where the entry maximally reconverges (the module's **Helpers**). After the tier,
/// so a stage without the classes is refused as before.
pub fn full_quads(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.stage != Stage::Fragment || !cx.families.simd.observes_lanes {
return Ok(());
@@ -1019,6 +1031,7 @@ fn select_group(
konst,
quad_instructions: cx.stage == Stage::Kernel
&& cx.profile.fields().subgroup.quad_instructions(cx.stage),
helpers: cx.stage == Stage::Fragment,
};
group::check(&plan).map_err(|()| not_lowered())?;
if matches!(
+28 -2
View File
@@ -39,6 +39,7 @@ fn plan(scope: GroupScope, op: GroupOp, form: Form, konst: Option<u32>) -> Group
arith: combine(op, form, Some(Sign::Signed)).expect("combine"),
konst,
quad_instructions: true,
helpers: false,
}
}
@@ -50,14 +51,24 @@ fn without_quads(g: GroupPlan) -> GroupPlan {
}
}
/// `plan` in a fragment function, whose quads hold helpers.
fn in_fragment(g: GroupPlan) -> GroupPlan {
GroupPlan {
quad_instructions: false,
helpers: true,
..g
}
}
/// The classes each operation needs follow the SPIR-V the tier emits: a `Direct` vote is
/// `OpGroupNonUniformAll` (vote), a `Cluster32` one a ballot word; a `Direct` reduction or product
/// is arithmetic, a `Cluster32` one clustered; a `Cluster32` prefix sum or product is ballot and
/// shuffles; a rotate up is a shuffle; a quad broadcast or shuffle-xor by a constant is the quad
/// class where the stage takes quad instructions and a shuffle elsewhere.
/// class where the stage takes quad instructions and a shuffle elsewhere; a fragment's quad
/// reduction is the quad class, its prefix sum ballot and shuffles.
#[test]
fn operation_classes_follow_the_tier() {
let cases: [(GroupPlan, OpBits, OpBits); 21] = [
let cases: [(GroupPlan, OpBits, OpBits); 24] = [
(
plan(S::Simdgroup, G::Shuffle, F32, None),
OpBits::SHUFFLE,
@@ -163,6 +174,21 @@ fn operation_classes_follow_the_tier() {
OpBits::BALLOT,
OpBits::BALLOT,
),
(
in_fragment(plan(S::Quad, G::Sum, F32, None)),
OpBits::QUAD,
OpBits::QUAD,
),
(
in_fragment(plan(S::Quad, G::Xor, LANE_FORM, None)),
OpBits::QUAD,
OpBits::QUAD,
),
(
in_fragment(plan(S::Quad, G::PrefixInclusiveSum, F32, None)),
OpBits::BALLOT.union(OpBits::SHUFFLE),
OpBits::BALLOT.union(OpBits::SHUFFLE),
),
];
for (g, d, c) in cases {
assert_eq!(direct_ops(&g), d, "{g:?}");
@@ -1582,6 +1582,7 @@ mod tests {
arith: None,
konst: None,
quad_instructions: true,
helpers: false,
};
let half4 = Held::Float(FloatFmt::Half);
let u32_ = Held::Int {
@@ -1,6 +1,7 @@
//! Subgroup (`GroupNonUniform*`) constructors.
//!
//! The execution scope is always `Subgroup`; cluster sizes are constant powers of two. Which ops a
//! The execution scope is always `Subgroup` (the quad vote, `OpGroupNonUniformQuadAnyKHR`, has no
//! scope operand); cluster sizes are constant powers of two. Which ops a
//! device supports (and in which stages) is the profile's concern, checked by requirement
//! derivation; every subgroup operation is tangled.
@@ -160,4 +161,13 @@ impl FunctionBuilder<'_> {
let dir_id = self.u32_const(dir.bits())?;
self.group(GroupInst::QuadSwap { value, dir, dir_id }, v.ty)
}
/// `OpGroupNonUniformQuadAnyKHR` of a `bool` scalar. Result: `bool`.
pub fn group_quad_any(&mut self, pred: Value) -> BResult<Value> {
self.want(crate::spv::Op::GroupNonUniformQuadAnyKHR, 0, pred, |n| {
n.is_bool() && n.is_scalar()
})?;
let ty = self.bool_ty(1)?;
self.group(GroupInst::QuadAny(pred), ty)
}
}
@@ -164,6 +164,16 @@ pub(super) fn exec(p: &Prog<'_>, op: &GroupInst, size: u32, lanes: &[&Lane]) ->
};
per_lane(&|id| from(&vals, i64::from(id ^ x)))
}
GroupInst::QuadAny(v) => {
let vals = operand(*v)?;
per_lane(&|id| {
let mut any = false;
for (k, b) in &vals {
any |= (*k & !3) == (id & !3) && b.s()? != 0;
}
Ok(Val::S(u64::from(any)))
})
}
}
}
+12 -3
View File
@@ -718,6 +718,11 @@ pub enum GroupInst {
dir: QuadDirection,
dir_id: ConstId,
},
/// `OpGroupNonUniformQuadAnyKHR` (`SPV_KHR_quad_control`): whether a `bool` predicate holds
/// for any active invocation of the calling invocation's quad, helpers included. The
/// instruction has no execution scope operand: its scope is the quad, and the serializer
/// writes no scope for it.
QuadAny(Value),
}
impl GroupInst {
@@ -731,7 +736,8 @@ impl GroupInst {
| GroupInst::BroadcastFirst(v)
| GroupInst::Ballot(v)
| GroupInst::Arith { value: v, .. }
| GroupInst::QuadSwap { value: v, .. } => f(*v),
| GroupInst::QuadSwap { value: v, .. }
| GroupInst::QuadAny(v) => f(*v),
GroupInst::BallotBitExtract {
ballot: a,
index: b,
@@ -753,7 +759,8 @@ impl GroupInst {
| GroupInst::BroadcastFirst(v)
| GroupInst::Ballot(v)
| GroupInst::Arith { value: v, .. }
| GroupInst::QuadSwap { value: v, .. } => f(v),
| GroupInst::QuadSwap { value: v, .. }
| GroupInst::QuadAny(v) => f(v),
GroupInst::BallotBitExtract {
ballot: a,
index: b,
@@ -783,7 +790,8 @@ impl GroupInst {
| GroupInst::Ballot(_)
| GroupInst::BallotBitExtract { .. }
| GroupInst::Shuffle { .. }
| GroupInst::QuadBroadcast { .. } => {}
| GroupInst::QuadBroadcast { .. }
| GroupInst::QuadAny(_) => {}
}
}
@@ -804,6 +812,7 @@ impl GroupInst {
GroupInst::Arith { op, .. } => op.to_spirv(),
GroupInst::QuadBroadcast { .. } => Op::GroupNonUniformQuadBroadcast,
GroupInst::QuadSwap { .. } => Op::GroupNonUniformQuadSwap,
GroupInst::QuadAny(_) => Op::GroupNonUniformQuadAnyKHR,
}
}
}
@@ -1342,6 +1342,12 @@ impl Deriver<'_> {
}
(Cap::GroupNonUniformQuad, SubgroupOp::Quad)
}
// `SPV_KHR_quad_control`'s quad vote, a fragment's (`lower::simd`).
GroupInst::QuadAny(_) => {
self.ext(SpirvExtension::KhrQuadControl);
self.feat(VkFeature::ShaderQuadControl);
(Cap::QuadControlKHR, SubgroupOp::Quad)
}
};
self.cap(Cap::GroupNonUniform);
self.cap(c);
@@ -2057,7 +2057,11 @@ impl Ser<'_> {
),
Inst::Derivative { op, a } => w.inst(op.to_spirv(), &with(head()?, &[v(*a)?])),
Inst::Group { scope, op } => {
let mut o = with(head()?, &[self.cid(scope.id)?]);
// `OpGroupNonUniformQuadAnyKHR` has no execution scope operand.
let mut o = match op {
GroupInst::QuadAny(_) => head()?,
_ => with(head()?, &[self.cid(scope.id)?]),
};
self.group_operands(&mut o, op)?;
w.inst(op.to_spirv(), &o)
}
@@ -2101,7 +2105,8 @@ impl Ser<'_> {
GroupInst::All(a)
| GroupInst::Any(a)
| GroupInst::BroadcastFirst(a)
| GroupInst::Ballot(a) => o.push(v(*a)?),
| GroupInst::Ballot(a)
| GroupInst::QuadAny(a) => o.push(v(*a)?),
GroupInst::BallotBitExtract { ballot, index } => {
o.push(v(*ballot)?);
o.push(v(*index)?);
@@ -1614,6 +1614,60 @@ fn fragment_group_operations_run_full_quads() {
);
}
/// A fragment's quad reduction reads its quad through quad instructions alone, which Vulkan runs
/// over the quad's helpers in every entry (section 9.31): on every committed profile with
/// `shaderQuadControl`, `fragment_quad_bitwise`'s AND, OR and XOR each ask
/// `OpGroupNonUniformQuadAnyKHR` whether each of the four quad lanes takes part and read each by
/// `OpGroupNonUniformQuadBroadcast` (4 of each per reduction, 12 in all), and its quad prefix sum
/// alone reads by a ballot and shuffles. A kernel's quad reductions (`quad_bitwise`), whose quads
/// hold no helpers, keep the ballot of the active lanes and take no quad vote.
#[test]
fn fragment_quad_reductions_read_their_quads_by_quad_instructions() {
let Some(quads) = assemble("gsm2_quad_ops") else {
return;
};
let count = |text: &str, op: &str| text.lines().filter(|l| l.contains(op)).count();
let mut fragments = 0;
for (name, p) in committed_profiles().expect("profiles") {
if !p.fields().subgroup.quad_control {
continue;
}
let a = compile(&quads, "fragment_quad_bitwise", &p).expect("compile");
let (_, words) = link_and_validate(&a, &p).expect("valid");
let text = spirv_dis(&words);
assert_eq!(
count(&text, "OpGroupNonUniformQuadAnyKHR"),
12,
"fragment_quad_bitwise on {name}"
);
assert_eq!(
count(&text, "OpGroupNonUniformQuadBroadcast"),
12,
"fragment_quad_bitwise on {name}"
);
assert_eq!(
count(&text, "OpGroupNonUniformBallot "),
1,
"fragment_quad_bitwise on {name}: the prefix sum's ballot alone"
);
fragments += 1;
if let Ok(a) = compile(&quads, "quad_bitwise", &p) {
let (_, words) = link_and_validate(&a, &p).expect("valid");
let text = spirv_dis(&words);
assert_eq!(
count(&text, "OpGroupNonUniformQuadAnyKHR"),
0,
"quad_bitwise on {name}"
);
assert!(
count(&text, "OpGroupNonUniformBallot ") > 0,
"quad_bitwise on {name}"
);
}
}
assert!(fragments > 0, "no committed profile has quad control");
}
/// MoltenVK 1.4.2 drops `VK_KHR_shader_quad_control` (`shaderQuadControl`) on Apple's GPUs. The
/// committed `moltenvk-m3` description, a capture of 1.4.2 that states neither the feature nor
/// its extension, refuses each fragment function whose group operations observe other lanes,