diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index fde6fb873..af0d9f01f 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -1833,7 +1833,13 @@ while the driver's exit handler waited on a lock, with every runtime thread alre region and up to 28 buffer addresses, each kernel pushing only the bytes it reads. Fields past it go to a 16-byte aligned block in the parameter ring, whose address is a field in the window: a kernel with more than 28 buffers. `Counters::metrics`' `ring_writes` counts each block and each - `set_bytes` copy. + `set_bytes` copy. A bind marks its own slot: the next dispatch checks that slot alone (its + buffer's alignment, its texture's storage) and fills its fields alone, with the dispatch + region, which each launch carries; a change of pipeline state, or of the module a dispatch + runs, checks and fills every slot. The block goes into the ring again only where one of its + fields changed, and a dispatch pushes only the words of the window its command buffer does not + hold, as a draw does (see Render encoders): a kernel of 30 buffers dispatched three times with + the same bindings writes one block and pushes once. `set_bytes` copies its bytes into the ring at the call, as Metal copies them. The ring is 2 MiB blocks of the floor's ring memory type (device-local, host-visible, coherent), split into 64 KiB chunks that a command buffer takes as it records and gives back when it retires; a block diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 1dde273cd..0078284e1 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -251,6 +251,16 @@ impl Pushed { } } +/// The bytes from the first of `a` and `b` to the end of the last: either where the other is +/// empty. +pub(crate) fn cover(a: Range, b: Range) -> Range { + match (a.is_empty(), b.is_empty()) { + (true, _) => b, + (_, true) => a, + _ => a.start.min(b.start)..a.end.max(b.end), + } +} + /// What the GPU uses: the recorder, the segments, and the blocks kept until retirement. pub(crate) struct Gpu { pub(crate) recorder: Option, diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 1cf9851d9..5e1198ad2 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -1,7 +1,7 @@ //! Compute command encoders: their binding state, their dispatches, and where barriers go. use crate::buffer::{Buffer, BufferInner, BufferObject}; -use crate::command::{Building, CommandBuffer}; +use crate::command::{cover, Building, CommandBuffer}; use crate::counters::Metric; use crate::device::Core; use crate::error::{Error, Gap, Limit, Refusal}; @@ -25,7 +25,7 @@ use metal2vulkan::metal::PixelFormat; use metal2vulkan::pipeline::{ grid_tile, nonuniform_region_bytes, region_bytes, DEEP_THREADGROUP, GRID_TILE_THREADS, }; -use std::ops::BitOr; +use std::ops::{BitOr, Range}; use std::sync::Arc; /// Metal's count of buffer argument table entries per stage. @@ -199,47 +199,257 @@ pub struct ComputeCommandEncoder { /// The module, workgroup size and `VkPipeline` of the last dispatch, while the state and the /// threadgroup memory lengths are unchanged. last: Option, - /// The parameters being filled, kept to reuse their bytes. + /// The parameters the dispatches filled, kept: a dispatch fills again only the fields of what + /// changed since ([`Rebound`]). parameters: Parameters, /// Whether a dispatch of the encoder wrote anything. wrote: bool, /// What a dispatch of the pipeline state reaches of the bound resources. facts: DispatchFacts, + /// What changed since the last dispatch filled its parameters, which the next dispatch finds + /// and fills again. + rebound: Rebound, /// The stage-in region set ([`ComputeCommandEncoder::set_stage_in_region`]), as the bytes of /// its push field: the origin and the size, each a `uvec4` with a zero `w`. stage_in_region: Option<[u8; 32]>, } /// What a dispatch of the encoder's pipeline state reaches of its bound resources and -/// declarations, worked out at the first dispatch after either changes and kept until the next -/// change: whether its buffers are aligned as its kernel takes them, whether it reaches a Managed -/// buffer's device copy or writes a texture over one, and whether it writes memory the host may -/// read. A dispatch after no change runs none of the scans. +/// declarations, found slot by slot and kept: whether its buffers are aligned as its kernel takes +/// them and its textures have the storage it uses, which of its slots reach a Managed buffer's +/// device copy or write a texture over one, and which write memory the host may read. The first +/// dispatch after a change of the pipeline state, or of the module a dispatch runs, finds every +/// slot's; the first after a binding or a declaration finds only what that call changed +/// ([`Rebound`]); a dispatch after no change finds nothing. /// /// A change is the encoder's own call: a pipeline state set, or a buffer, an offset, bytes or a -/// texture bound, or a resource declared. Nothing outside the encoder changes what a fact holds: -/// each is of the objects bound (a buffer's device copy and storage, a texture's storage) and of -/// the kernel, which do not change. What can change outside it between two dispatches, a Managed -/// buffer's textures over its device copy and the textures over a buffer in images of their own -/// that live, each dispatch looks at again where a fact says it may matter. +/// texture bound, or a resource declared. Nothing outside the encoder changes what a slot's fact +/// holds: each is of the object bound (a buffer's device copy and storage, a texture's storage) +/// and of the kernel, which do not change. What can change outside it between two dispatches, a +/// Managed buffer's textures over its device copy and the textures over a buffer in images of +/// their own that live, each dispatch looks at again where a fact says it may matter. #[derive(Default)] struct DispatchFacts { - /// The bound buffers are aligned as the state's kernels take them. - aligned: bool, - /// The module whose kernel the facts below are of, while they hold. + /// The checks hold: every slot met them but those the encoder's [`Rebound`] names. + held: bool, + /// The module whose kernel the slots below are of, while they hold. module: Option, - /// A buffer the kernel reaches has a device copy, or a texture it writes is over one. - managed: bool, - /// A write the host may read once the command buffer completes: to a Shared buffer or a - /// texture over one, bound or declared, or through an address outside the dispatch's - /// resources. - host: bool, - /// The nil buffer's address where a buffer argument the kernels reach is bound to nothing - /// (`Ring::nil`), else 0, and the zero range's where the kernels check a load (`Ring::zero`), - /// else 0, found with the alignments. + /// The bound buffers the kernel reaches that have a device copy, and the textures it writes + /// over one. + managed: Slots, + /// The bound Shared buffers the kernel writes, and the textures over one it writes: writes + /// the host may read once the command buffer completes. + host: Slots, + /// The nil buffer's address where a buffer argument the kernels reach was found bound to + /// nothing (`Ring::nil`), else 0, and the zero range's where the kernels check a load + /// (`Ring::zero`), else 0, found with the alignments. nil: (u64, u64), } +/// Buffer and texture slots, a bit each. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Slots { + buffers: u32, + textures: u128, +} + +impl Slots { + fn any(&self) -> bool { + self.buffers != 0 || self.textures != 0 + } + + /// Clears the slots `rebound` names. + fn forget(&mut self, rebound: &Rebound) { + self.buffers &= !rebound.buffers; + self.textures &= !rebound.textures; + } +} + +/// What changed since a dispatch last found its facts and filled its parameters: everything after +/// a change of the pipeline state; else a bit for each buffer, texture and sampler slot bound +/// since, the stage-in region set, and resources declared. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +struct Rebound { + all: bool, + buffers: u32, + textures: u128, + samplers: u16, + stage_in: bool, + declared: bool, +} + +impl Rebound { + /// Every slot, field and declaration. + const ALL: Rebound = Rebound { + all: true, + buffers: 0, + textures: 0, + samplers: 0, + stage_in: false, + declared: false, + }; + + fn buffer(&self, slot: u32) -> bool { + self.all || (self.buffers.checked_shr(slot)).is_some_and(|bits| bits & 1 == 1) + } + + fn texture(&self, slot: u32) -> bool { + self.all || (self.textures.checked_shr(slot)).is_some_and(|bits| bits & 1 == 1) + } + + fn sampler(&self, slot: u32) -> bool { + self.all || (self.samplers.checked_shr(slot)).is_some_and(|bits| bits & 1 == 1) + } + + /// Whether a field of `value` is filled again: a slot's where the slot changed, the stage-in + /// region's where it was set, the dispatch region's at every dispatch (each launch carries + /// its own), and every field after a change of the state. + fn field(&self, value: FieldValue) -> bool { + match value { + FieldValue::BufferAddress { slot, .. } | FieldValue::BufferBounds(slot) => { + self.buffer(slot) + } + FieldValue::TextureId(slot) | FieldValue::IntegerChannels(slot) => self.texture(slot), + FieldValue::SamplerId(slot) => self.sampler(slot), + FieldValue::StageInRegion => self.all || self.stage_in, + FieldValue::DispatchRegion => true, + FieldValue::ZeroAddress + | FieldValue::ConstexprSampler(_) + | FieldValue::Word(_) + | FieldValue::TessellationFactors + | FieldValue::AlphaTestReference + | FieldValue::FetchedColor(_) => self.all, + } + } +} + +impl DispatchFacts { + /// Checks, of the slots `rebound` names, what a dispatch of a kernel of `interface` reaches of + /// `slots` and `textures`: each buffer bound at an address of the alignment it takes + /// ([`check_alignment`]), with the nil buffer's address where one is bound to nothing + /// (`Ring::nil`) and the zero range's where the kernel checks a load (`Ring::zero`); no + /// swizzled texture it reads as storage; a storage element for each texture it stores to or + /// reads as storage; and, where `rebound` names the declarations, none of + /// `declared_unstored_write` where it may reach a texture beyond its slots. Every other slot + /// met them when it was found, so the first a dispatch fails is the one a check of every slot + /// meets first. + /// + /// Err: [`Refusal::BufferOffsetAlignment`]; [`Gap::SwizzledReadWrite`]; + /// [`Gap::StorageElement`]; [`Error::Vulkan`] where the nil buffer or the zero range cannot be + /// made. + fn find( + &mut self, + core: &Core, + (slots, textures): (&[Slot], &[Option>]), + declared_unstored_write: Option, + interface: &Interface, + rebound: &Rebound, + ) -> Result<(), Error> { + if rebound.all { + self.nil = (0, 0); + } + // A `set_bytes` copy is at a multiple of 16 in the ring, which every mask divides, and so + // is the nil buffer. + for field in &interface.fields { + match field.value { + FieldValue::BufferAddress { slot, mask } if rebound.buffer(slot) => { + match slots.get(slot as usize) { + Some(Slot::Buffer { buffer, offset }) => { + check_alignment(slot, mask, buffer, *offset)? + } + Some(Slot::Bytes(..)) => {} + Some(Slot::Empty) | None => self.nil.0 = core.ring.nil(core)?, + } + } + FieldValue::ZeroAddress if rebound.all => self.nil.1 = core.ring.zero(core)?, + _ => {} + } + } + for &slot in &interface.storage_reads { + if rebound.texture(slot) + && matches!(textures.get(slot as usize), Some(Some(t)) if t.swizzled()) + { + return Err(Error::Unsupported(Gap::SwizzledReadWrite { slot })); + } + } + for &(slot, access) in &interface.textures { + if !rebound.texture(slot) { + continue; + } + let read = interface.storage_reads.contains(&slot); + let stored = access != Access::Read || read; + let unstored = match textures.get(slot as usize) { + Some(Some(texture)) if stored => texture + .unstored() + .or_else(|| texture.unread().filter(|_| read)), + _ => None, + }; + if let Some(pixel_format) = unstored { + return Err(Error::Unsupported(Gap::StorageElement { + slot: Some(slot), + pixel_format, + })); + } + } + // A texture declared written with no storage element, which the kernel may reach through + // its storage image beyond its slots. + if let (true, true, Some(pixel_format)) = ( + rebound.all || rebound.declared, + interface.unbound_storage, + declared_unstored_write, + ) { + return Err(Error::Unsupported(Gap::StorageElement { + slot: None, + pixel_format, + })); + } + Ok(()) + } + + /// Finds again, of the slots `rebound` names, which of `slots` and `textures` a dispatch of a + /// kernel of `interface` reaches with a device copy (a buffer it reaches that has one, a + /// texture it writes over one: the only dispatches that may owe a Managed buffer's textures + /// over its device copy their copies), and which it writes that the host may read once the + /// command buffer completes (a Shared buffer, a texture over one). + fn reach( + &mut self, + (slots, textures): (&[Slot], &[Option>]), + interface: &Interface, + rebound: &Rebound, + ) { + if rebound.all { + (self.managed, self.host) = (Slots::default(), Slots::default()); + } + self.managed.forget(rebound); + self.host.forget(rebound); + for &(slot, access) in &interface.buffers { + if let (true, Some(Slot::Buffer { buffer, .. })) = + (rebound.buffer(slot), slots.get(slot as usize)) + { + if buffer.held().1.is_some() { + self.managed.buffers |= 1 << slot; + } + if access.writes() && buffer.is_shared() { + self.host.buffers |= 1 << slot; + } + } + } + for &(slot, access) in &interface.textures { + if let (true, Some(Some(texture))) = ( + access.writes() && rebound.texture(slot), + textures.get(slot as usize), + ) { + if texture.managed_over().is_some() { + self.managed.textures |= 1 << slot; + } + if texture.host_reads() { + self.host.textures |= 1 << slot; + } + } + } + } +} + /// Which of its state's modules a dispatch runs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Module { @@ -420,9 +630,13 @@ impl CommandBuffer { declared_shared_write: false, declared_unstored_write: None, last: None, - parameters: Parameters::default(), + parameters: Parameters { + mark: u64::MAX, + ..Parameters::default() + }, wrote: false, facts: DispatchFacts::default(), + rebound: Rebound::ALL, stage_in_region: None, }) } @@ -433,10 +647,10 @@ impl ComputeCommandEncoder { recording(&mut self.building) } - /// The pipeline state, a binding or a declaration changed: the next dispatch finds its facts - /// again. - fn changed(&mut self) { - self.facts = DispatchFacts::default(); + /// Buffer slot `slot` changed: the next dispatch finds its facts and fills its fields again. + fn rebound_buffer(&mut self, slot: usize) { + self.rebound.buffers |= 1 << slot; + self.facts.held = false; } /// `setComputePipelineState:`. The command buffer keeps the state until it retires. @@ -455,7 +669,8 @@ impl ComputeCommandEncoder { // SAFETY: the encoder holds the borrow, and it ends before its command buffer commits. self.pipeline = Some(unsafe { self.building().lend_pipeline(state) }); self.last = None; - self.changed(); + self.facts = DispatchFacts::default(); + self.rebound = Rebound::ALL; Ok(()) } @@ -496,7 +711,7 @@ impl ComputeCommandEncoder { None => Slot::Empty, }; self.slots[slot] = bound; - self.changed(); + self.rebound_buffer(slot); Ok(()) } @@ -528,7 +743,8 @@ impl ComputeCommandEncoder { None => None, }; self.textures[index as usize] = lent; - self.changed(); + self.rebound.textures |= 1 << index; + self.facts.held = false; Ok(()) } @@ -563,6 +779,7 @@ impl ComputeCommandEncoder { None => None, }; self.samplers[index as usize] = lent; + self.rebound.samplers |= 1 << index; Ok(()) } @@ -599,6 +816,7 @@ impl ComputeCommandEncoder { *at = word.to_le_bytes(); } self.stage_in_region = Some(bytes); + self.rebound.stage_in = true; } /// `setBufferOffset:atIndex:`. @@ -610,7 +828,7 @@ impl ComputeCommandEncoder { match &mut self.slots[slot] { Slot::Buffer { offset: bound, .. } => { *bound = offset; - self.changed(); + self.rebound_buffer(slot); Ok(()) } _ => Err(Error::Refused(Refusal::NoBufferAtIndex { index })), @@ -633,13 +851,9 @@ impl ComputeCommandEncoder { })); } let address = self.building().write_ring(bytes)?; - // Bytes are aligned, of no Managed or Shared buffer: a dispatch's facts change only where - // the slot held a buffer. - if !matches!(self.slots[slot], Slot::Bytes(..)) { - self.changed(); - } // At most one chunk, 64 KiB. self.slots[slot] = Slot::Bytes(address, bytes.len() as u32); + self.rebound_buffer(slot); Ok(()) } @@ -707,7 +921,8 @@ impl ComputeCommandEncoder { if access.writes() && self.declared_unstored_write.is_none() { self.declared_unstored_write = unstored; } - self.changed(); + self.rebound.declared = true; + self.facts.held = false; match self .declared .iter_mut() @@ -914,42 +1129,13 @@ impl ComputeCommandEncoder { return Err(Error::Limit(Limit::ThreadgroupThreads { size, max })); } // Every module of a state is the same function, with the same arguments and alignments, - // so the whole module answers this check and the next, once after each change. - if !self.facts.aligned { - self.facts.nil = check_alignments(&self.core, &self.slots, &inner.whole.interface)?; - for &slot in &inner.whole.interface.storage_reads { - if matches!(self.textures.get(slot as usize), Some(Some(t)) if t.swizzled()) { - return Err(Error::Unsupported(Gap::SwizzledReadWrite { slot })); - } - } + // so the whole module answers these checks, of what changed since they last held. + if !self.facts.held { + let bound = (&self.slots[..], &self.textures[..]); let interface = &inner.whole.interface; - for &(slot, access) in &interface.textures { - let read = interface.storage_reads.contains(&slot); - let stored = access != Access::Read || read; - let unstored = match self.textures.get(slot as usize) { - Some(Some(texture)) if stored => texture - .unstored() - .or_else(|| texture.unread().filter(|_| read)), - _ => None, - }; - if let Some(pixel_format) = unstored { - return Err(Error::Unsupported(Gap::StorageElement { - slot: Some(slot), - pixel_format, - })); - } - } - // A texture declared written with no storage element, which the kernel may reach - // through its storage image beyond its slots. - if let (true, Some(pixel_format)) = - (interface.unbound_storage, self.declared_unstored_write) - { - return Err(Error::Unsupported(Gap::StorageElement { - slot: None, - pixel_format, - })); - } - self.facts.aligned = true; + let unstored = self.declared_unstored_write; + (self.facts).find(&self.core, bound, unstored, interface, &self.rebound)?; + self.facts.held = true; } let core = &*self.core; let limits = &core.limits; @@ -1055,11 +1241,21 @@ impl ComputeCommandEncoder { pipeline: vk_pipeline, }); let interface = &kernel.interface; - if self.facts.module != Some(module) { - self.facts.managed = self.reaches_managed(interface); - self.facts.host = self.writes_host(interface); + // Every slot's where the module changed, whose interface may reach others, else those of + // what changed. + let rebound = match self.facts.module == Some(module) { + true => self.rebound, + false => Rebound::ALL, + }; + if rebound != Rebound::default() { + let bound = (&self.slots[..], &self.textures[..]); + self.facts.reach(bound, interface, &rebound); self.facts.module = Some(module); } + // A write the host may read once the command buffer completes: to a Shared buffer or a + // texture over one, bound or declared, or through an address outside the dispatch's + // resources. + let host = interface.writes_unbound || self.declared_shared_write || self.facts.host.any(); let wrote = { let accesses = Accesses { slots: &self.slots, @@ -1079,7 +1275,7 @@ impl ComputeCommandEncoder { let unbound = interface.reads_unbound || interface.writes_unbound; building.overs_before(overs, unbound)?; } - if self.facts.managed { + if self.facts.managed.any() { // A binding of a Managed buffer with textures over its device copy takes their // copies back first, and one whose compiled interface writes it owes them their // copies in; a texture slot written owes its copy back @@ -1111,7 +1307,7 @@ impl ComputeCommandEncoder { } // Marked after the hazards' barrier, which may have split the recording at a signal: // the mark is the dispatch's own segment's. - if self.facts.host { + if host { building.wrote_host(); } wrote @@ -1124,7 +1320,7 @@ impl ComputeCommandEncoder { } .ok_or(Error::Refused(Refusal::ThreadgroupSize { size, max })) }; - let ids = &state.numbered.ids; + let ids = &state.numbered.ids[..]; match (direct, grid) { (Some((threads, groups, ragged)), _) => { // A count past the device's limit on an axis is split: each piece starts at its @@ -1140,8 +1336,13 @@ impl ComputeCommandEncoder { let region = region(base, threads, ragged)?; let bound = (&self.slots[..], &self.textures[..], &self.samplers[..]); let regions = (®ion, self.stage_in_region.as_ref()); - self.parameters - .fill(kernel, (bound, self.facts.nil), ids, regions); + let fields = (&self.rebound, ids, regions); + (self.parameters).fill( + (kernel, module), + (bound, self.facts.nil), + fields, + ); + self.rebound = Rebound::default(); recording(&mut self.building).record_dispatch( core, vk_pipeline, @@ -1157,8 +1358,9 @@ impl ComputeCommandEncoder { let region = region([0; 3], [0; 3], false)?; let bound = (&self.slots[..], &self.textures[..], &self.samplers[..]); let regions = (®ion, self.stage_in_region.as_ref()); - self.parameters - .fill(kernel, (bound, self.facts.nil), ids, regions); + let fields = (&self.rebound, ids, regions); + (self.parameters).fill((kernel, module), (bound, self.facts.nil), fields); + self.rebound = Rebound::default(); recording(&mut self.building).record_dispatch( core, vk_pipeline, @@ -1169,46 +1371,6 @@ impl ComputeCommandEncoder { (None, Grid::Direct { .. }) => Ok(()), } } - - /// Whether a dispatch of a kernel of `interface` reaches a bound buffer that has a device - /// copy, or writes a bound texture over one: the only dispatches that may owe a Managed - /// buffer's textures over its device copy their copies. - fn reaches_managed(&self, interface: &Interface) -> bool { - (interface.buffers.iter()).any(|&(slot, _)| { - matches!( - self.slots.get(slot as usize), - Some(Slot::Buffer { buffer, .. }) if buffer.held().1.is_some() - ) - }) || (interface.textures.iter()).any(|&(slot, access)| { - access.writes() - && matches!( - self.textures.get(slot as usize), - Some(Some(texture)) if texture.managed_over().is_some() - ) - }) - } - - /// Whether a dispatch of a kernel of `interface` writes what the host may read once the - /// command buffer completes: a Shared buffer or a texture over one, bound or declared, or - /// memory through an address outside the dispatch's resources. - fn writes_host(&self, interface: &Interface) -> bool { - interface.writes_unbound - || self.declared_shared_write - || (interface.buffers.iter()).any(|&(slot, access)| { - access.writes() - && matches!( - self.slots.get(slot as usize), - Some(Slot::Buffer { buffer, .. }) if buffer.is_shared() - ) - }) - || (interface.textures.iter()).any(|&(slot, access)| { - access.writes() - && matches!( - self.textures.get(slot as usize), - Some(Some(texture)) if texture.host_reads() - ) - }) - } } /// The length `set` gives threadgroup memory index `index`, 0 where it gives none. @@ -1225,34 +1387,6 @@ fn recording(building: &mut Option) -> &mut Building { .expect("an encoder holds its command buffer's recording until it ends") } -/// [`check_alignment`] of each buffer bound in `slots` that `interface` reaches, the nil buffer's -/// address where one it reaches is bound to nothing (`Ring::nil`), else 0, and the zero range's -/// where it checks a load (`Ring::zero`), else 0. A `set_bytes` copy is at a multiple of 16 in the -/// ring, which every mask divides, and so is the nil buffer. -fn check_alignments( - core: &Core, - slots: &[Slot], - interface: &Interface, -) -> Result<(u64, u64), Error> { - let (mut nil, mut zero) = (0, 0); - for field in &interface.fields { - let (slot, mask) = match field.value { - FieldValue::BufferAddress { slot, mask } => (slot, mask), - FieldValue::ZeroAddress => { - zero = core.ring.zero(core)?; - continue; - } - _ => continue, - }; - match slots.get(slot as usize) { - Some(Slot::Buffer { buffer, offset }) => check_alignment(slot, mask, buffer, *offset)?, - Some(Slot::Bytes(..)) => {} - Some(Slot::Empty) | None => nil = core.ring.nil(core)?, - } - } - Ok((nil, zero)) -} - /// A slot's [`FieldValue::BufferBounds`] for a buffer of `length` bytes bound at `offset`: the /// bytes before the bind offset, then the length, each a `u32`. No buffer is longer than /// `MAX_BUFFER_LENGTH`, 2 GiB, so both fit. @@ -1272,37 +1406,51 @@ type Bound<'a> = ( ); impl Parameters { - /// Fills the push window and the ring block of one launch of `kernel` with `bound`, the - /// encoder's argument tables, whose regions are `region`, the `DispatchRegion` push field's - /// bytes, and `stage_in`, the `StageInRegion` field's where the encoder set a region (a - /// kernel that reads it has one: the dispatch checked first), and whose state gave its - /// numbered samplers `sampler_ids`. Only a kernel that reads the stage-in region copies it. - /// The block's address is written by [`Building::record_dispatch`] once the block is in the - /// ring. A buffer argument bound to nothing takes `nil`, the nil buffer's address, and bounds - /// of 0 and 0; the zero range's address is `zero`. + /// Fills, of the push window and the ring block of one launch of `kernel`, module `module`'s, + /// the fields `rebound` names, every field into bytes sized afresh where the bytes were of + /// another module or `rebound` names everything; each from `bound`, the encoder's argument + /// tables, whose regions are `region`, the `DispatchRegion` field's bytes, and `stage_in`, + /// the `StageInRegion` field's where the encoder set a region (a kernel that reads it has + /// one: the dispatch checked first), and whose state gave its numbered samplers + /// `sampler_ids`. Only a kernel that reads the stage-in region copies it. The block's address + /// is written by [`Building::record_dispatch`] once the block is in the ring, where a field + /// of it was filled. A buffer argument bound to nothing takes `nil`, the nil buffer's + /// address, and bounds of 0 and 0; the zero range's address is `zero`. /// /// Every buffer address is a multiple of the alignment the module takes it to have, which the - /// dispatch checked first ([`check_alignments`], which gave `nil`). + /// dispatch checked first ([`DispatchFacts::find`], which gave `nil`). fn fill( &mut self, - kernel: &Kernel, + (kernel, module): (&Kernel, Module), (bound, (nil, zero)): (Bound<'_>, (u64, u64)), - sampler_ids: &[u32], - (region, stage_in): (&[u8; 32], Option<&[u8; 32]>), + (rebound, sampler_ids, (region, stage_in)): Fields<'_>, ) { let (slots, textures, samplers) = bound; let interface: &Interface = &kernel.interface; - self.push.clear(); - self.push - .resize(interface.push_len.next_multiple_of(4) as usize, 0); - self.block.clear(); - self.block.resize(interface.block_len as usize, 0); + let all = rebound.all || self.module != Some(module); + if all { + self.push.clear(); + self.push + .resize(interface.push_len.next_multiple_of(4) as usize, 0); + self.block.clear(); + self.block.resize(interface.block_len as usize, 0); + self.unpushed = 0..self.push.len(); + self.block_owed = true; + self.module = Some(module); + } for field in &interface.fields { + if !all && !rebound.field(field.value) { + continue; + } let (bytes, at) = match field.place { Place::Push(offset) => (&mut self.push, offset as usize), - Place::Block(offset) => (&mut self.block, offset as usize), + Place::Block(offset) => { + self.block_owed = true; + (&mut self.block, offset as usize) + } }; - match field.value { + // Each field's bytes, and how many. + let len = match field.value { FieldValue::BufferAddress { slot, .. } => { let address = match slots.get(slot as usize) { Some(Slot::Buffer { buffer, offset }) => { @@ -1313,6 +1461,7 @@ impl Parameters { }; let word = address_word(address); bytes[at..at + 8].copy_from_slice(&word.to_le_bytes()); + 8 } FieldValue::BufferBounds(slot) => { let bounds = match slots.get(slot as usize) { @@ -1321,14 +1470,19 @@ impl Parameters { Some(Slot::Empty) | None => [0; 8], }; bytes[at..at + 8].copy_from_slice(&bounds); + 8 + } + FieldValue::ZeroAddress => { + bytes[at..at + 8].copy_from_slice(&zero.to_le_bytes()); + 8 } - FieldValue::ZeroAddress => bytes[at..at + 8].copy_from_slice(&zero.to_le_bytes()), FieldValue::TextureId(slot) => { let id = match textures.get(slot as usize) { Some(Some(texture)) => texture.gpu_resource_id().to_bits(), _ => 0, }; bytes[at..at + 8].copy_from_slice(&id.to_le_bytes()); + 8 } FieldValue::SamplerId(slot) => { let id = match samplers.get(slot as usize) { @@ -1336,6 +1490,7 @@ impl Parameters { _ => 0, }; bytes[at..at + 8].copy_from_slice(&id.to_le_bytes()); + 8 } FieldValue::IntegerChannels(slot) => { let word = match textures.get(slot as usize) { @@ -1345,35 +1500,162 @@ impl Parameters { _ => 0, }; bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + 4 } FieldValue::ConstexprSampler(place) => { let index = sampler_ids.get(place).copied().unwrap_or(0); bytes[at..at + 4].copy_from_slice(&index.to_le_bytes()); + 4 } - FieldValue::DispatchRegion => bytes[at..at + 32].copy_from_slice(region), - FieldValue::StageInRegion => { - if let Some(stage_in) = stage_in { + FieldValue::DispatchRegion => { + bytes[at..at + 32].copy_from_slice(region); + 32 + } + FieldValue::StageInRegion => match stage_in { + Some(stage_in) => { bytes[at..at + 32].copy_from_slice(stage_in); + 32 } - } + None => 0, + }, // A compute content has none of these (`pipeline::interface`). FieldValue::Word(_) | FieldValue::TessellationFactors | FieldValue::AlphaTestReference - | FieldValue::FetchedColor(_) => {} + | FieldValue::FetchedColor(_) => 0, + }; + if let Place::Push(_) = field.place { + self.unpushed = cover(self.unpushed.clone(), at..at + len); } } self.block_address = (interface.block_len > 0).then_some(interface.block_address); } } +/// What [`Parameters::fill`] fills: the fields of what changed, the state's numbered samplers, +/// and the launch's dispatch region and the encoder's stage-in region. +type Fields<'a> = (&'a Rebound, &'a [u32], (&'a [u8; 32], Option<&'a [u8; 32]>)); + /// A dispatch's parameters: the push window's bytes, and the ring block's with where its address -/// goes in the window. +/// goes in the window; kept by the encoder, whose dispatches fill only the fields of what changed +/// since the last ([`Parameters::fill`]), write the block into the ring only where a field of it +/// changed, and push only the words their command buffer does not hold. #[derive(Default)] struct Parameters { push: Vec, block: Vec, block_address: Option, + /// The module whose kernel's fields the bytes are, while they are. + module: Option, + /// The push bytes filled since the encoder's last push. + unpushed: Range, + /// A field of the block was filled since it was last written into the ring. + block_owed: bool, + /// The mark the encoder's last push left in its command buffer's push bytes (`Pushed`): + /// while they hold it, no other push came between, and they hold `push` but `unpushed`. + /// `u64::MAX`, which no push leaves, before its first. + mark: u64, +} + +/// A dispatch's facts and fields: the slots that reach a device copy and that write what the host +/// reads, the push bytes with the block's address zeroed (each fill writes its own block), and +/// the block's bytes. +#[cfg(test)] +#[derive(Debug, PartialEq)] +pub(crate) struct DispatchFilled { + facts: [Slots; 2], + push: Vec, + block: Vec, +} + +/// An encoder's facts and fields beside a find and fill of every slot +/// ([`ComputeCommandEncoder::refilled`]). +#[cfg(test)] +pub(crate) struct DispatchRefilled { + /// The facts and fields the encoder's dispatches left, found and filled slot by slot since + /// the pipeline state was set. + pub(crate) slot_by_slot: DispatchFilled, + /// A find and fill of every slot of what is bound now ([`Rebound::ALL`]) for the last + /// dispatch's module and region, or its refusal's text. + pub(crate) whole: Result, + /// The push bytes as the encoder holds them. + pub(crate) push: Vec, + /// The push bytes its command buffer holds. + pub(crate) held: Vec, +} + +#[cfg(test)] +impl ComputeCommandEncoder { + /// Its facts and fields beside a find and fill of every slot of what is bound now, after a + /// dispatch filled its parameters. + pub(crate) fn refilled(&self) -> DispatchRefilled { + let state = &self.pipeline.as_ref().expect("a pipeline state set").inner; + let inner = &state.compiled; + let filled = |facts: &DispatchFacts, parameters: &Parameters| { + let mut push = parameters.push.clone(); + if let Some(at) = parameters.block_address { + let at = at as usize; + push[at..at + 8].fill(0); + } + DispatchFilled { + facts: [facts.managed, facts.host], + push, + block: parameters.block.clone(), + } + }; + let bound = (&self.slots[..], &self.textures[..]); + let mut facts = DispatchFacts::default(); + let unstored = self.declared_unstored_write; + let whole = (facts.find( + &self.core, + bound, + unstored, + &inner.whole.interface, + &Rebound::ALL, + )) + .map(|()| { + let module = (self.parameters.module).expect("a dispatch filled its parameters"); + let kernel = match module { + Module::Partial => { + inner.later_kernel(Which::Partial, || Error::Refused(Refusal::NoPipeline)) + } + Module::Emulated => { + inner.later_kernel(Which::Emulated, || Error::Refused(Refusal::NoPipeline)) + } + Module::Whole | Module::Tiles => Ok(&inner.whole), + } + .expect("the module's kernel"); + // The dispatch region is each launch's own: the last launch's. + let mut region = [0; 32]; + for field in &kernel.interface.fields { + if let FieldValue::DispatchRegion = field.value { + let (bytes, at) = match field.place { + Place::Push(offset) => (&self.parameters.push, offset as usize), + Place::Block(offset) => (&self.parameters.block, offset as usize), + }; + region.copy_from_slice(&bytes[at..at + 32]); + } + } + facts.reach(bound, &kernel.interface, &Rebound::ALL); + let mut parameters = Parameters::default(); + let tables = (&self.slots[..], &self.textures[..], &self.samplers[..]); + let regions = (®ion, self.stage_in_region.as_ref()); + let fields = (&Rebound::ALL, &state.numbered.ids[..], regions); + parameters.fill((kernel, module), (tables, facts.nil), fields); + filled(&facts, ¶meters) + }) + .map_err(|error| format!("{error:?}")); + let held = (self.building.as_ref()) + .expect("an encoder holds its command buffer's recording until it ends") + .pushed() + .to_vec(); + DispatchRefilled { + slot_by_slot: filled(&self.facts, &self.parameters), + whole, + push: self.parameters.push.clone(), + held, + } + } } impl Drop for ComputeCommandEncoder { @@ -1484,8 +1766,10 @@ impl Building { Ok(wrote) } - /// Binds `pipeline` where it is not bound, writes the parameters' ring block and its address, - /// pushes the window, and records the dispatch, on `core`, the recording's device. + /// Binds `pipeline` where it is not bound, writes the parameters' ring block and its address + /// where a field of the block was filled since it was last written, pushes the words of the + /// window the command buffer does not hold, and records the dispatch, on `core`, the + /// recording's device. fn record_dispatch( &mut self, core: &Core, @@ -1494,10 +1778,12 @@ impl Building { launch: &Launch<'_>, ) -> Result<(), Error> { let device = &core.device; - if let Some(at) = parameters.block_address { + if let (Some(at), true) = (parameters.block_address, parameters.block_owed) { let address = self.write_ring(¶meters.block)?; let at = at as usize; parameters.push[at..at + 8].copy_from_slice(&address.to_le_bytes()); + parameters.unpushed = cover(parameters.unpushed.clone(), at..at + 8); + parameters.block_owed = false; } let push = ¶meters.push[..]; debug_assert!(push.len() <= PUSH_BYTES as usize); @@ -1524,12 +1810,16 @@ impl Building { if self.bind(pipeline) { device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, pipeline); } - // Every word of the window compared with what the command buffer holds, whoever - // pushed it: the words that differ are pushed. + // The words the command buffer does not hold: every one at its first use, else those + // the fills changed (`Pushed`). let words = match push.is_empty() { true => None, - false => self.push_words(push, 0..push.len(), &mut u64::MAX), + false => { + let unpushed = parameters.unpushed.clone(); + self.push_words(push, unpushed, &mut parameters.mark) + } }; + parameters.unpushed = 0..0; if let Some(words) = words { // Word-aligned: each field is at a multiple of its size, 4 bytes or more, and the // window ends at a multiple of 4. diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index f1875b1c4..805bb2ce5 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -74,7 +74,7 @@ //! carries [`PrecisionNote::DepthDenormals`]. use crate::buffer::{Buffer, BufferInner, BufferObject}; -use crate::command::{Building, CommandBuffer}; +use crate::command::{cover, Building, CommandBuffer}; use crate::counters::Metric; use crate::depth_stencil::{DepthStencilState, Face, Tests}; use crate::device::Core; @@ -2868,16 +2868,6 @@ fn fill_push( (written, filled) } -/// The bytes from the first of `a` and `b` to the end of the last: either where the other is -/// empty. -fn cover(a: Range, b: Range) -> Range { - match (a.is_empty(), b.is_empty()) { - (true, _) => b, - (_, true) => a, - _ => a.start.min(b.start)..a.end.max(b.end), - } -} - /// The copy of `area` from an image into its shadow, of `aspects`, at the same place in both. fn region(area: &Area, aspects: vk::ImageAspectFlags) -> vk::ImageCopy { let layers = vk::ImageSubresourceLayers { diff --git a/crates/metal2vulkan-rt/src/tests/push_window.rs b/crates/metal2vulkan-rt/src/tests/push_window.rs index 0eab0136f..da2955189 100644 --- a/crates/metal2vulkan-rt/src/tests/push_window.rs +++ b/crates/metal2vulkan-rt/src/tests/push_window.rs @@ -3,17 +3,17 @@ //! buffer's address, and the containment check's fields: the zero range's address and each //! buffer's bounds (its bytes before the bind offset and its length, 8 bytes), which come last in //! the order, so they are the first to go to a parameter block. A kernel of 12 buffers (232 -//! bytes) pushes them all and writes nothing into the parameter ring, and its dispatches after -//! the first push nothing, their bytes held. One of 24 buffers pushes its block's address, every -//! buffer's address, the zero range's and one buffer's bounds, and the other 23 bounds go to a -//! block; one of 30 pushes 26 addresses, and the other 4, the zero range's and the 30 bounds go -//! to a block. Each of those two writes one block a dispatch, whose -//! new address each dispatch pushes. All answer the fold of their inputs. +//! bytes) pushes them all and writes nothing into the parameter ring. One of 24 buffers pushes +//! its block's address, every buffer's address, the zero range's and one buffer's bounds, and the +//! other 23 bounds go to a block; one of 30 pushes 26 addresses, and the other 4, the zero +//! range's and the 30 bounds go to a block. Each of those two writes its block at its first +//! dispatch alone. Each kernel's dispatches after its first, of the same bindings and grid, push +//! nothing, their bytes held. All answer the fold of their inputs. //! //! `llvm-as` assembles the kernels; without it the test skips visibly. #[cfg(any(m2v_gpu, m2v_cpu_icd))] -mod on_device { +pub(crate) mod on_device { use crate::pipeline::{FieldValue, Place}; use crate::tests::command::on_device::{each_device, finished}; use crate::{ @@ -30,7 +30,7 @@ mod on_device { /// A kernel of `buffers` buffers: thread `gid` folds word `gid` of the first `buffers - 1` /// (`s ยท 3 + v`) into word `gid` of the last. - fn kernel(buffers: u32) -> String { + pub(crate) fn kernel(buffers: u32) -> String { let inputs = buffers - 1; let mut params = Vec::new(); let mut meta = Vec::new(); @@ -77,23 +77,22 @@ define void @wide({}) {{\nentry:\n{body} %out = getelementptr inbounds i32, ptr } /// Word `gid` of input `k`. - fn word(k: u32, gid: u32) -> u32 { + pub(crate) fn word(k: u32, gid: u32) -> u32 { (k + 1).wrapping_mul(0x9e37_79b9) ^ gid.wrapping_mul(0x85eb_ca6b) } - /// The kernel of 12 buffers writes nothing into the ring, and pushes once for its three - /// dispatches of the same bindings; the kernel of 24 pushes every address and has only check - /// fields in its block, and the kernel of 30 has 4 addresses there too; each of those writes - /// one block a dispatch, whose new address each dispatch pushes. Each answers the fold of its - /// inputs. + /// The kernel of 12 buffers writes nothing into the ring; the kernel of 24 pushes every + /// address and has only check fields in its block, and the kernel of 30 has 4 addresses there + /// too; each of those writes its block at its first dispatch alone. Each pushes once for its + /// three dispatches of the same bindings, and answers the fold of its inputs. #[test] fn every_device_pushes_24_buffer_addresses_and_rings_30() { - // Each kernel's buffers, its addresses and check fields in the block, its blocks a - // dispatch, and its pushes over the dispatches. - for (buffers, (addresses, checks), blocks, pushes) in [ - (12u32, (0usize, 0usize), 0u64, 1u64), - (24, (0, 23), 1, DISPATCHES), - (30, (4, 31), 1, DISPATCHES), + // Each kernel's buffers, its addresses and check fields in the block, and its blocks + // over the dispatches; each pushes once. + for (buffers, (addresses, checks), blocks) in [ + (12u32, (0usize, 0usize), 0u64), + (24, (0, 23), 1), + (30, (4, 31), 1), ] { let bitcode = match llvm_assemble_text(&kernel(buffers)) { Ok(bitcode) => bitcode, @@ -180,14 +179,10 @@ define void @wide({}) {{\nentry:\n{body} %out = getelementptr inbounds i32, ptr let after = device.counters().metrics(); let writes = after.ring_writes - before.ring_writes; assert_eq!(command_buffer.error(), None, "{what}"); - assert_eq!(writes, blocks * DISPATCHES, "{what}: ring writes"); + assert_eq!(writes, blocks, "{what}: ring writes"); let pushed = after.pushes - before.pushes; let held = after.pushes_held - before.pushes_held; - assert_eq!( - (pushed, held), - (pushes, DISPATCHES - pushes), - "{what}: pushes, held" - ); + assert_eq!((pushed, held), (1, DISPATCHES - 1), "{what}: pushes, held"); let inputs = buffers - 1; let contents = bound[inputs as usize].contents().expect("a Shared buffer"); for gid in 0..THREADS { diff --git a/crates/metal2vulkan-rt/src/tests/refill.rs b/crates/metal2vulkan-rt/src/tests/refill.rs index 9e22de058..3d3b39215 100644 --- a/crates/metal2vulkan-rt/src/tests/refill.rs +++ b/crates/metal2vulkan-rt/src/tests/refill.rs @@ -1,6 +1,6 @@ -//! A draw finds and fills again only what changed: under a device cfg, on every device of the -//! cfg's kind, with the owned fixtures `examples/runtime_examples.ll` and -//! `engine/fca_vertex_unread_attribute.ll` and fragment functions this test writes: +//! A draw or a dispatch finds and fills again only what changed: under a device cfg, on every +//! device of the cfg's kind, with the owned fixtures `examples/runtime_examples.ll` and +//! `engine/fca_vertex_unread_attribute.ll` and fragment functions and kernels this test writes: //! - over 1,200 random calls of one encoder (pipeline states of 30 spilled buffers with two //! textures and a sampler, of 12 buffers, and of a fixed-function vertex binding; buffers, //! offsets, bytes and nothing bound at the vertex and fragment functions' slots; textures, @@ -13,6 +13,15 @@ //! the pipeline state that changes no word (every pipeline has the device's one layout), and, //! in a pass after a dispatch in the same command buffer, only the words of the window the //! dispatch's push changed; every pixel reads the values its draw was bound. +//! - over 1,200 random calls of one compute encoder (pipeline states of 30 buffers, whose fields +//! spill into a parameter block, of 12, and of two textures and two buffers; buffers, offsets, +//! bytes and nothing bound; textures; declarations; dispatches of 16 to 64 threads), each +//! dispatch's facts, push bytes and parameter block, found and filled slot by slot, equal a find +//! and fill of every slot, and its command buffer holds those push bytes; a dispatch refused is +//! refused alike. Never committed. +//! - a dispatch pushes only the words its command buffer does not hold: the whole window at the +//! first, the words a buffer bound or an offset changed, none for the same bindings and grid; +//! each output holds the fold of the inputs it was bound. //! //! `llvm-as` assembles the fixtures; without it a device test skips visibly. @@ -23,11 +32,12 @@ mod on_device { use crate::tests::draw::on_device::{ examples, floats, library, pass, read, run, state, target, vertices, Buffers, SIDE, }; + use crate::tests::push_window::on_device::{kernel, word}; use crate::{ Buffer, ColorAttachmentDescriptor, ComputePipelineDescriptor, Device, DispatchType, Error, FunctionDescriptor, IndexClass, Library, LoadAction, Metrics, PixelFormat, PrimitiveType, - RenderPipelineDescriptor, RenderPipelineState, SamplerDescriptor, ScissorRect, StageSource, - Texture, TextureDescriptor, TextureType, TextureUsage, + RenderPipelineDescriptor, RenderPipelineState, Resource, ResourceUsage, SamplerDescriptor, + ScissorRect, StageSource, Texture, TextureDescriptor, TextureType, TextureUsage, }; use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; use metal2vulkan::metal::{DataType, VertexFormat}; @@ -152,13 +162,18 @@ mod on_device { /// The library of [`fragments`] of `functions`, or None where `llvm-as` is missing. fn fragment_library(functions: &[(&str, u32, u32, bool, bool)]) -> Option { - match llvm_assemble_text(&fragments(functions)) { + text_library(&fragments(functions)) + } + + /// The library of LLVM text `text`, or None where `llvm-as` is missing. + fn text_library(text: &str) -> Option { + match llvm_assemble_text(text) { Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")), Err(AssembleError::Missing(why)) => { eprintln!("SKIPPED: {why}"); None } - Err(error) => panic!("the fragment functions: {error:?}"), + Err(error) => panic!("the functions: {error:?}"), } } @@ -576,4 +591,285 @@ mod on_device { ); }); } + + /// A kernel that reads texel (0, 0) of textures 0 and 1 and stores their sum into buffer 0 at + /// the element buffer 1's first word names, a store the containment check takes. + const TWO_READS: &str = r#"; Owned synthetic kernel. +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +define void @two_reads(ptr addrspace(1) %t0, ptr addrspace(1) %t1, ptr addrspace(1) %out, ptr addrspace(1) %in) { +entry: + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %r0 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t0, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v0 = extractvalue { <4 x float>, i8 } %r0, 0 + %r1 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t1, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v1 = extractvalue { <4 x float>, i8 } %r1, 0 + %sum = fadd <4 x float> %v0, %v1 + %i = load i32, ptr addrspace(1) %in, align 4 + %w = zext i32 %i to i64 + %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %w + store <4 x float> %sum, ptr addrspace(1) %p, align 16 + ret void +} + +declare ptr addrspace(2) @air.get_read_sampler() +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) + +!air.kernel = !{!0} +!air.version = !{!7} +!air.language_version = !{!8} +!0 = !{ptr @two_reads, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5, !6} +!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t0"} +!4 = !{i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t1"} +!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!6 = !{i32 3, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"in"} +!7 = !{i32 2, i32 8, i32 0} +!8 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// A compute pipeline descriptor of the kernel `name` of LLVM text `text`, or None where + /// `llvm-as` is missing. + fn compute_descriptor(text: &str, name: &str) -> Option { + let library = text_library(text)?; + let function = library.function(name).expect("the kernel"); + Some(ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + ))) + } + + /// Over 1,200 random calls of one compute encoder, every dispatch's facts and fields equal a + /// find and fill of every slot, and its command buffer holds its push bytes; a refused + /// dispatch is refused alike. + #[test] + fn every_device_refills_only_what_a_dispatchs_binds_change() { + let mut descriptors = Vec::new(); + for (text, name) in [ + (kernel(30), "wide"), + (kernel(12), "wide"), + (TWO_READS.to_owned(), "two_reads"), + ] { + let Some(descriptor) = compute_descriptor(&text, name) else { + return; + }; + descriptors.push(descriptor); + } + each_device("refill_dispatch", |name, _, device| { + let states: Vec<_> = (descriptors.iter()) + .map(|d| { + (device.new_compute_pipeline_state(d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }) + .collect(); + assert!( + states[0].inner.compiled.whole.interface.block_len > 0, + "{name}: the 30 buffers' fields spill into a parameter block" + ); + let _textures = (device.grant_indices(IndexClass::Texture, 1, 3)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + // Two textures a kernel may read as storage, and one it may not. + let textures: Vec = (1..=3) + .map(|index| { + let format = PixelFormat::RGBA32Float; + let mut d = TextureDescriptor::new(TextureType::Type2D, format, 4, 4); + d.usage = match index { + 3 => TextureUsage::SHADER_READ, + _ => TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, + }; + (device.new_texture(&d, Some(index))) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }) + .collect(); + let mut buffers = Buffers::new(&device); + let bound: Vec = (0..4u8).map(|k| buffers.of(&device, &[k; 256])).collect(); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + // Offsets inside the buffers, one off every argument's alignment, one past their end. + const OFFSETS: [u64; 5] = [0, 16, 48, 2, 4096]; + let mut sequence = Sequence(0x2545_f491_4f6c_dd1d); + let (mut dispatched, mut refused) = (0, 0); + let call = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + call(encoder.set_compute_pipeline_state(&states[0])); + for step in 0..1_200 { + match sequence.below(12) { + 0 => call(encoder.set_compute_pipeline_state(&states[sequence.below(3)])), + 1..=3 => { + let slot = sequence.below(31) as u32; + let buffer = (sequence.below(8) != 0).then(|| &bound[sequence.below(4)]); + let offset = OFFSETS[sequence.below(5)]; + call(encoder.set_buffer(buffer, offset, slot)); + } + 4 => { + // Refused where the slot holds no buffer, as Metal's. + let (slot, offset) = + (sequence.below(31) as u32, OFFSETS[sequence.below(5)]); + let _ = encoder.set_buffer_offset(offset, slot); + } + 5 => { + let slot = sequence.below(31) as u32; + call(encoder.set_bytes(&[step as u8; 96], slot)); + } + 6 => { + let texture = + (sequence.below(6) != 0).then(|| &textures[sequence.below(3)]); + call(encoder.set_texture(texture, sequence.below(2) as u32)); + } + 7 => { + let buffer = Resource::Buffer(&bound[sequence.below(4)]); + call(encoder.use_resource(buffer, ResourceUsage::READ)); + } + _ => { + let groups = 1 + sequence.below(4) as u32; + let result = match sequence.below(2) { + 0 => encoder.dispatch_threadgroups([groups, 1, 1], [16, 1, 1]), + _ => encoder.dispatch_threads([16 * groups, 1, 1], [16, 1, 1]), + }; + let refilled = encoder.refilled(); + match result { + Ok(()) => { + assert_eq!( + Ok(&refilled.slot_by_slot), + refilled.whole.as_ref(), + "{name}: step {step}: slot by slot and whole" + ); + assert_eq!( + refilled.held.get(..refilled.push.len()), + Some(&refilled.push[..]), + "{name}: step {step}: the command buffer's push bytes" + ); + dispatched += 1; + } + Err(error) => { + assert_eq!( + refilled.whole.err(), + Some(format!("{error:?}")), + "{name}: step {step}: the refusal" + ); + refused += 1; + } + } + } + } + } + assert!( + dispatched > 100 && refused > 10, + "{name}: {dispatched} dispatched, {refused} refused" + ); + encoder.end_encoding(); + println!( + "{name}: {dispatched} dispatches equal a whole find and fill, {refused} refused alike" + ); + }); + } + + /// One compute encoder of the kernel of 12 buffers: its first dispatch pushes the whole + /// window; another output bound pushes the changed words alone; an offset and another output + /// push the changed words alone; the same bindings and grid push none. Each output holds the + /// fold of the inputs it was bound. + #[test] + fn every_device_dispatches_push_only_the_words_they_change() { + let Some(twelve) = compute_descriptor(&kernel(12), "wide") else { + return; + }; + each_device("refill_dispatch_push", |name, _, device| { + const THREADS: u32 = 64; + const SKEW: u32 = 16; + let state = (device + .new_compute_pipeline_state(&twelve, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let window = u64::from( + state + .inner + .compiled + .whole + .interface + .push_len + .next_multiple_of(4), + ); + let mut buffers = Buffers::new(&device); + // Eleven inputs, each word `i` of input `k` `word(k, i)`, `SKEW` words past the + // threads; three outputs. + let inputs: Vec = (0..11) + .map(|k| { + let bytes: Vec = (0..THREADS + SKEW) + .flat_map(|i| word(k, i).to_le_bytes()) + .collect(); + buffers.of(&device, &bytes) + }) + .collect(); + let outputs: Vec = (0..3) + .map(|_| buffers.of(&device, &[0; THREADS as usize * 4])) + .collect(); + let queue = device.new_command_queue(4).expect("a queue"); + let call = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + settled(&device); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let before = device.counters().metrics(); + let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + call(encoder.set_compute_pipeline_state(&state)); + for (k, input) in inputs.iter().enumerate() { + call(encoder.set_buffer(Some(input), 0, k as u32)); + } + call(encoder.set_buffer(Some(&outputs[0]), 0, 11)); + let mut want = Vec::new(); + let mut held = Vec::new(); + for step in 0..4 { + match step { + 1 => call(encoder.set_buffer(Some(&outputs[1]), 0, 11)), + 2 => { + call(encoder.set_buffer_offset(u64::from(SKEW) * 4, 3)); + call(encoder.set_buffer(Some(&outputs[2]), 0, 11)); + } + _ => {} + } + call(encoder.dispatch_threads([THREADS, 1, 1], [THREADS, 1, 1])); + let refilled = encoder.refilled(); + let bytes = changed(&held, &refilled.push); + want.push(bytes); + held = refilled.held; + } + encoder.end_encoding(); + assert_eq!( + pushes(&device, &before), + (3, 1, want.iter().sum()), + "{name}: pushes, pushes held and bytes ({want:?})" + ); + assert_eq!(want[0], window, "{name}: the first dispatch's whole window"); + assert!( + (1..window).contains(&want[1]) && (1..window).contains(&want[2]), + "{name}: the changed words at a bind: {want:?} of {window}" + ); + assert_eq!(want[3], 0, "{name}: the same bindings and grid: {want:?}"); + run(name, &command_buffer); + for (output, skewed) in outputs.iter().zip([false, false, true]) { + let contents = output.contents().expect("a Shared buffer"); + for gid in 0..THREADS { + let input = |k: u32| match (skewed, k) { + (true, 3) => word(k, gid + SKEW), + _ => word(k, gid), + }; + let want = + (1..11).fold(input(0), |s, k| s.wrapping_mul(3).wrapping_add(input(k))); + // SAFETY: the word lies in the buffer, which is alive, and its work completed. + let got = unsafe { + contents + .as_ptr() + .cast::() + .add(gid as usize) + .read_unaligned() + }; + assert_eq!( + got, want, + "{name}: thread {gid}, offset at input 3: {skewed}" + ); + } + } + println!("{name}: dispatches pushed {want:?} bytes of a window of {window}"); + }); + } }