diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index b05e46d1a..0536a666d 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -4203ea5bcb2efa022b91460bcaf5ece7e6894a4670dcbd306f8dfc73685b11d7 +f985a4212b9578205d4191b074ab95041db5e2b72b9afbec2fa17e03449bdde2 diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index e357d682b..cebd2e0cb 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -890,6 +890,7 @@ codec_enum! { PatchIndexAddress, ControlPointIndexAddress, DepthRangeFold, + GroupCountsAddress, } Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 35e89b831..9a8b70854 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2380; +pub const SEMANTICS_VERSION: u32 = 2381; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 72a0b807e..1f3bbdb7c 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -1373,8 +1373,10 @@ fn unwritten_slots( /// record a preprocess writes for its dispatch beside the group counts; and it runs no emulated /// simdgroups: its threads return early past the grid, which no workgroup barrier may follow. A /// folded variant reads its group counts and every grid builtin's region from the record a -/// preprocess writes for its dispatch, whatever builtins it reads; its workgroups past Metal's last -/// threadgroup return early as wholes, so it runs emulated simdgroups too. +/// preprocess writes for its dispatch, whatever builtins it reads, and a folded object function +/// its draw's counts at `GroupCountsAddress` and the rest of its region from its own +/// `DispatchRegion` ([`object_region`]); its workgroups past Metal's last threadgroup return early +/// as wholes, so it runs emulated simdgroups too. fn plan_replay(cx: &mut SelectCx<'_>, sources: &[SlotRef]) -> Result<(), Error> { // A replayed command is a compute dispatch with no stage-in region and no tile pass, or a // draw whose vertex function fetches no attribute in fixed function: its buffers are the @@ -1409,8 +1411,15 @@ fn plan_replay(cx: &mut SelectCx<'_>, sources: &[SlotRef]) -> Result<(), Error> if cx.inputs.flat_grid && cx.inputs.emulated_simdgroups { return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); } - // A folded variant reads its group counts from the record whatever builtins it reads. - if cx.push.remove(&PushField::DispatchRegion) || cx.inputs.flat_grid || cx.inputs.folded_groups + // A folded object function reads its draw's group counts at their address and the rest of + // its region from its own field, whatever builtins it reads ([`object_region`]); a folded + // kernel, a flat variant and a replay variant read their region from a record. + if pieces { + cx.push.insert(PushField::DispatchRegion); + cx.push.insert(PushField::GroupCountsAddress); + } else if cx.push.remove(&PushField::DispatchRegion) + || cx.inputs.flat_grid + || cx.inputs.folded_groups { cx.push.insert(PushField::ReplayRegionAddress); } @@ -1467,6 +1476,52 @@ pub fn replay_region(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResu ) } +/// The `DispatchRegion` value (`array`) of a folded object function's draw: its own +/// field, as the draw pushed it (its threadgroup size `L`, and its threads per grid and partial +/// flag where the draw states them), whose first `xyz`, a region base no folded function reads, +/// holds the draw's three group counts, read at `GroupCountsAddress` (Metal's +/// `MTLDispatchThreadgroupsIndirectArguments`, three `u32`s at a multiple of 4). Routed here by +/// `EmitCx::push_field` for a folded object function's `DispatchRegion`. +pub fn object_region(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { + let pushed = cx.held_push_field(fb, PushField::DispatchRegion)?; + let address = cx.push_field(fb, PushField::GroupCountsAddress)?; + let u32_ = fb.module().ty(SType::Int { + width: 32, + signed: false, + })?; + let mut words = Vec::with_capacity(4); + for at in 0..3u64 { + let at = match at { + 0 => address, + at => { + let offset = crate::memory::roots::k64(fb, 4 * at)?; + fb.binary(crate::spirv::ir::BinOp::IAdd, address, offset)? + } + }; + let place = fb.device_place(at, u32_)?; + let access = crate::spirv::ir::MemAccess { + aligned: Some(4), + ..crate::spirv::ir::MemAccess::default() + }; + words.push(fb.load(place, access)?); + } + let first = fb.composite_extract(pushed, &[0])?; + words.push(fb.composite_extract(first, &[3])?); + let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; + let first = fb.composite_construct(uvec4, &words)?; + let second = fb.composite_extract(pushed, &[1])?; + let two = fb.module().constant(Constant::Scalar { + ty: u32_, + bits: ConstBits(2), + })?; + let region = fb.module().ty(SType::Array { + elem: uvec4, + len: two, + stride: Some(16), + })?; + fb.composite_construct(region, &[first, second]) +} + /// The Metal address of `slot` in a device-replay variant, in `SlotGuestBase`'s shape (a `uvec2`, /// low word first): its root entry's `guest + bind_offset`, which is the bound buffer's /// `gpu_address + offset` the field would hold, 0 for an unbound slot (a zero entry), as the field diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index 80c93bff4..28d98061e 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -182,7 +182,12 @@ //! / (sx, sy, sz)` `x` fastest, in 64 bits ([`KernelDecl::folded`]); a workgroup past the last //! returns before the body as a whole ([`emit_entry`]). Its threadgroup and thread positions in the //! grid come from that count; its other grid builtins read the region record at -//! `ReplayRegionAddress` (base 0, `MultiRegion` 1). +//! `ReplayRegionAddress` (base 0, `MultiRegion` 1). An object function, always folded +//! ([`DispatchPlan::draw_pieces`]), reads its draw's group counts at `GroupCountsAddress` (Metal's +//! `MTLDispatchThreadgroupsIndirectArguments`) and the rest of its region from its own +//! `DispatchRegion` (`access::object_region`): its threadgroups per grid are the counts, and its +//! threads per grid the counts times `L`, wrapping as Metal's do, or the region's grid where its +//! draw states one (a draw of threads). So the counts need nothing beside them. //! //! **Facts.** Every kernel depends on `ThreadsPerThreadgroup` and `LocalSizeLimits`, and on //! `IndirectGroupCount` (any kernel may be dispatched indirectly, and the planner clamps @@ -2137,9 +2142,9 @@ impl KernelDecl { /// over the dispatch (plus `DrawIndex · nx · ny · nz` for a folded object function, whose /// draw's pieces each run that many), counted over Metal's group counts `x` fastest, all in 64 /// bits. A kernel's counts are `threads_per_grid / (sx, sy, sz)` (`region[1].xyz`); a folded - /// object function's are the record's base words (`region[0].xyz`, which no folded variant - /// reads as a base), since its threads per grid are Metal's, wrapped to 32 bits - /// (`bind::mesh_arguments`). Every value it reads is the workgroup's, so the whole workgroup + /// object function's are its draw's counts, read at `GroupCountsAddress` into `region[0].xyz`, + /// which no folded variant reads as a base (`access::object_region`), since its threads per + /// grid are Metal's, wrapped to 32 bits. Every value it reads is the workgroup's, so the whole workgroup /// is inside or past. Inside the grid each axis's position is below its /// count, so it fits its `u32`; past it the position is unused. A count of zero runs no /// workgroup (the preprocess writes a zero dispatch), so no running invocation divides by it. @@ -2209,6 +2214,18 @@ impl KernelDecl { Ok((pos, inside)) } + /// A folded object function's group counts: its region's first `xyz` + /// (`access::object_region`, which reads them at the draw's `GroupCountsAddress`). + fn object_counts( + &self, + fb: &mut FunctionBuilder<'_>, + region: &mut RegionFn<'_>, + ) -> BResult { + let r = region(fb)?; + let first = fb.composite_extract(r, &[0])?; + fb.vector_shuffle(first, first, &[0, 1, 2]) + } + /// The threadgroup position in the Metal grid: `base + WorkgroupId`. fn group_pos(&self, fb: &mut FunctionBuilder<'_>, base: Option) -> BResult { let wg = self.load(fb, self.workgroup_id)?; @@ -2268,6 +2285,22 @@ impl KernelDecl { let pos = self.local_pos(fb, region)?; return fb.binary(BinOp::IAdd, first, pos); } + // A folded object function's grid is its draw's group counts (`region[0].xyz`, + // read at their address), and its threads per grid the counts times `L`, wrapping + // as Metal's do, or the region's grid where its draw states one (a draw of + // threads). + K::ThreadgroupsPerGrid if self.draw_index.is_some() => { + return self.object_counts(fb, region); + } + K::ThreadsPerGrid if self.draw_index.is_some() => { + let counts = self.object_counts(fb, region)?; + let l = self.nominal(fb, region)?; + let whole = fb.binary(BinOp::IMul, counts, l)?; + return match self.region_threads(fb, region)? { + Some((mr, t)) => fb.select(mr, t, whole), + None => Ok(whole), + }; + } _ => {} } } diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index ba30dfd0f..8bd8c4d3b 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -723,10 +723,26 @@ impl<'a> EmitCx<'a> { self.fail("a merged draw's fragment slot table read before its entry") }), PushField::SlotGuestBase(slot) => access::replay_guest_base(self, fb, slot), + // A folded object function's counts are at their address, its region its own. + PushField::DispatchRegion + if self.plan.dispatch.as_ref().is_some_and(|d| d.draw_pieces) => + { + access::object_region(self, fb) + } PushField::DispatchRegion => access::replay_region(self, fb), _ => Err(self.fail("a derived push field without its source")), }; } + self.held_push_field(fb, field) + } + + /// Push field `field` as the push block or the stage's `ArgumentTable` holds it, whatever the + /// function derives it from ([`EmitCx::derives`]). + pub(crate) fn held_push_field( + &mut self, + fb: &mut FunctionBuilder<'_>, + field: PushField, + ) -> BResult { let member = self.decl.push.iter().find(|m| m.field == field).copied(); let (Some(member), Some(g)) = (member, self.decl.push_global) else { // A field the push block does not hold is in the stage's `ArgumentTable`, which the diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index 8f498f288..c1a081202 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -173,6 +173,7 @@ pub const fn shape(f: PushField) -> FieldShape { | PushField::CaptureIndexAddress | PushField::MergedDrawAddress | PushField::ReplayRegionAddress + | PushField::GroupCountsAddress | PushField::TessellationFactorAddress | PushField::PatchIndexAddress | PushField::ControlPointIndexAddress diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index bd9e7e207..40bdb7e21 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1764,6 +1764,7 @@ fn identity_pushes(field: PushField, loc: PushLoc, views: bool) -> bool { | PushField::SlotBounds(_) | PushField::ZeroAddress | PushField::DispatchRegion + | PushField::GroupCountsAddress | PushField::TextureIntegerChannels(_) | PushField::TextureLevels(_) | PushField::TextureLevelBase(_) @@ -1814,13 +1815,7 @@ fn identity_refusal(plan: &Plan) -> Option<(IdentityCause, String)> { // A kernel on a device that binds its buffer arguments reaches each storage view at its // pushed bind offset (`AccessPlan::robust_views`). let views = plan.families.access.robust_views; - let field = (plan.push.fields.iter()).find(|f| { - // An object function's grid is folded: its region is the record its draw's pieces read - // (`lower::mesh`'s object grid, `bind::mesh_arguments`). - let object_region = - matches!(f.field, PushField::ReplayRegionAddress) && plan.stage == Stage::Object; - !object_region && !identity_pushes(f.field, f.loc, views) - }); + let field = (plan.push.fields.iter()).find(|f| !identity_pushes(f.field, f.loc, views)); if let Some(f) = field { return Some(( IdentityCause::EncoderValue, diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index ef2c3e517..53ad49100 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -199,7 +199,9 @@ pub enum RuntimeFact { /// (`LoweringInputs::folded_groups`): it runs a threadgroup dispatch of its own threadgroup /// size whose group counts it reads from the 32-byte region record at its /// `PushField::ReplayRegionAddress`, which a preprocess writes beside the dispatch's group - /// counts, folded within the device's limits. Its plans state the variant. + /// counts, folded within the device's limits. Its plans state the variant. An object function, + /// always folded, reads its draw's group counts at its `PushField::GroupCountsAddress` instead, + /// and the rest of its region from its own `PushField::DispatchRegion`. FoldedGroups, /// The vertex or fragment function was compiled under `VariantKey::replay_bindings` /// (`LoweringInputs::replay_bindings`): every buffer it reads is in the slot table at its diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 508500938..798e4b9f3 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -364,8 +364,10 @@ pub struct LoweringInputs { /// threadgroup partition runs any group counts on one variant of the call's threadgroup size. /// It needs device addresses, and refuses a stage-input region, a tile function, `flat_grid` /// and `replay_bindings` (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`). An object - /// function is folded whatever this says: its draws run its grid in pieces - /// (`bind::mesh_arguments`), its one grid form. Any other function compiles as without it. + /// function is folded whatever this says, its one grid form: it reads its draw's group counts + /// at its `PushField::GroupCountsAddress` and the rest of its region from its own + /// `PushField::DispatchRegion`, and its draws run its grid in pieces within the task stage's + /// limits. Any other function compiles as without it. #[cfg_attr(feature = "serde", serde(default))] pub folded_groups: bool, /// The kernel runs a `dispatchThreads` grid that is not a whole number of threadgroups in the diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index eac2e846d..28e48a58c 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -501,6 +501,13 @@ pub enum PushField { /// Metal's `threads_per_grid`; an indirect dispatch states a zero grid, and its kernel takes /// `NumWorkgroups` times its workgroup size. DispatchRegion, + /// Device address (`u64`) of a draw's three threadgroup counts, Metal's + /// `MTLDispatchThreadgroupsIndirectArguments` (three `u32`s at a multiple of 4): a folded + /// object function's grid in threadgroups (`lower::dispatch`'s folded groups), which it reads + /// there, its threadgroup size, its threads per grid where the draw states them, and its + /// partial flag in its [`PushField::DispatchRegion`]. An indirect buffer holds counts in this + /// layout. Placed after the region, so the push window always holds it. + GroupCountsAddress, /// Device address (`u64`) of the region record a device-replay variant's dispatch reads its /// `DispatchRegion` value from: the replay's preprocess writes one record per replayed command /// and region, so a ragged or split command's regions take the base, nominal size, and grid of @@ -742,6 +749,7 @@ mod tests { PushField::RootTableAddress, PushField::CaptureIndexAddress, PushField::DispatchRegion, + PushField::GroupCountsAddress, PushField::ReplayRegionAddress, PushField::BaseVertexInstance, PushField::VerticesPerPrimitive, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8d9f3efd9..a58ee9bcc 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -10115,6 +10115,7 @@ variant metal2vulkan::pipeline::PushField::DepthClampRange DepthClampRange variant metal2vulkan::pipeline::PushField::DepthRangeFold DepthRangeFold variant metal2vulkan::pipeline::PushField::DispatchRegion DispatchRegion variant metal2vulkan::pipeline::PushField::FetchedColor FetchedColor { color: u32, texels: SampledType } +variant metal2vulkan::pipeline::PushField::GroupCountsAddress GroupCountsAddress variant metal2vulkan::pipeline::PushField::IndirectBase IndirectBase variant metal2vulkan::pipeline::PushField::IndirectRange IndirectRange variant metal2vulkan::pipeline::PushField::IndirectSequence IndirectSequence diff --git a/docs/API.md b/docs/API.md index fe768b224..2e207204e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1204,10 +1204,13 @@ measured on the M3 Max) draws nothing: an object function's wrapper launches not grid. An object grid runs at any count Metal runs, past the task stage's limits too: an object function -is always compiled folded, its one grid form, its object stage reading the -threadgroups Metal runs and its grid from a 32-byte region record at its -`PushField::ReplayRegionAddress`, so a draw runs its grid in pieces within the task limits. Metal's -threads per grid wrap to 32 bits along each axis, as its builtins report them. The lowering takes +is always compiled folded, its one grid form, so a draw runs its grid in pieces within the task +limits. Its object stage reads the draw's three group counts at its `PushField::GroupCountsAddress` +(Metal's `MTLDispatchThreadgroupsIndirectArguments` layout, three `u32`s at a multiple of 4) and +its threadgroup size, and its threads per grid and partial flag where the draw states them, from +its own `PushField::DispatchRegion`: its threadgroups per grid are the counts, and its threads per +grid the counts times its threadgroup size, wrapping to 32 bits along each axis as Metal's +builtins report them, or the region's grid for a draw of threads. The lowering takes a grid of up to 2^29 threadgroups on every device, the most Metal's GPU ran within its watchdog's 5 seconds; Metal's GPU discards a larger one and fails its command buffer with Metal's error.