diff --git a/crates/metal2vulkan/src/lower/simd/group.rs b/crates/metal2vulkan/src/lower/simd/group.rs index c7fc32e34..7cfa8682d 100644 --- a/crates/metal2vulkan/src/lower/simd/group.rs +++ b/crates/metal2vulkan/src/lower/simd/group.rs @@ -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 { 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) diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index 258bf764c..9d9531e2a 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -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!( diff --git a/crates/metal2vulkan/src/lower/simd/tests.rs b/crates/metal2vulkan/src/lower/simd/tests.rs index 2cf9fac73..8f4aacce4 100644 --- a/crates/metal2vulkan/src/lower/simd/tests.rs +++ b/crates/metal2vulkan/src/lower/simd/tests.rs @@ -39,6 +39,7 @@ fn plan(scope: GroupScope, op: GroupOp, form: Form, konst: Option) -> 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:?}"); diff --git a/crates/metal2vulkan/src/lower/simd/workgroup.rs b/crates/metal2vulkan/src/lower/simd/workgroup.rs index 672946bdc..ca8eb7a9c 100644 --- a/crates/metal2vulkan/src/lower/simd/workgroup.rs +++ b/crates/metal2vulkan/src/lower/simd/workgroup.rs @@ -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 { diff --git a/crates/metal2vulkan/src/spirv/builder/ops/group.rs b/crates/metal2vulkan/src/spirv/builder/ops/group.rs index 6bbd07f31..e5b45a262 100644 --- a/crates/metal2vulkan/src/spirv/builder/ops/group.rs +++ b/crates/metal2vulkan/src/spirv/builder/ops/group.rs @@ -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 { + 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) + } } diff --git a/crates/metal2vulkan/src/spirv/interp/group.rs b/crates/metal2vulkan/src/spirv/interp/group.rs index b6b61fce3..70a9616f9 100644 --- a/crates/metal2vulkan/src/spirv/interp/group.rs +++ b/crates/metal2vulkan/src/spirv/interp/group.rs @@ -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))) + }) + } } } diff --git a/crates/metal2vulkan/src/spirv/ir/inst.rs b/crates/metal2vulkan/src/spirv/ir/inst.rs index 06e5c8be9..04353ebd6 100644 --- a/crates/metal2vulkan/src/spirv/ir/inst.rs +++ b/crates/metal2vulkan/src/spirv/ir/inst.rs @@ -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, } } } diff --git a/crates/metal2vulkan/src/spirv/requirements/mod.rs b/crates/metal2vulkan/src/spirv/requirements/mod.rs index d527fa417..f8d2d6fc2 100644 --- a/crates/metal2vulkan/src/spirv/requirements/mod.rs +++ b/crates/metal2vulkan/src/spirv/requirements/mod.rs @@ -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); diff --git a/crates/metal2vulkan/src/spirv/serialize/mod.rs b/crates/metal2vulkan/src/spirv/serialize/mod.rs index 2b5b0a729..e081af4e4 100644 --- a/crates/metal2vulkan/src/spirv/serialize/mod.rs +++ b/crates/metal2vulkan/src/spirv/serialize/mod.rs @@ -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)?); diff --git a/crates/metal2vulkan/src/tests/engine_simd.rs b/crates/metal2vulkan/src/tests/engine_simd.rs index 91389dc80..48c403c5c 100644 --- a/crates/metal2vulkan/src/tests/engine_simd.rs +++ b/crates/metal2vulkan/src/tests/engine_simd.rs @@ -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,