From 7055ff84c528aa03e950d3590923db9b56d1b696 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 12:24:12 -0800 Subject: [PATCH] RUNTIME 2472: Compute encoders move as one pointer, and a core ends in its box ComputeCommandEncoder held its whole state (888 bytes) by value, so its open's return, each move by a caller (a consumer that boxes it copies it into the box), and end_encoding's self each copied it whole. Its state now lies in a box of its own (Body), and the encoder is that one pointer, as the render encoder already boxes its lowering. A core's end read the whole core out of its box onto the stack (EncoderCore::unboxed_apart in end_encoding) and passed it by value to end_with_replay, which took it apart again. end_with_replay now takes the boxed core, takes it apart where it ends, and hands its emptied box on: with a compute encoder's bind state to the command buffer's park (compute::Parking, then Parked), else back to the device's spares. The same Vulkan commands; no API change. Verified: tests::encoder_moves asserts the encoder is one pointer (it was 888 bytes against the old bound of 1 KiB). With: Compute encoders: fields through the body box everywhere; end_with_replay over a boxed or held core; end_with_replay: take the held core through one plain reference until it is taken apart. Why: a compute encoder was 888 bytes moved by value through open, the caller's Box::new and end, and its core was read out of its box whole at its end (reims decodecost: large-value memcpy 4.0% of the decoder thread). Now a move copies 8 bytes and the core is taken apart inside its box. Measured (lane encbox, msi lavapipe, dispatch_chain --dispatches 5 --groups 64 --only encoders, release, base/tip alternated twice, m3-max-37522): encode per encoder 4613 -> 4465 ns (-0.15 us), end 1102 -> 1013 ns; thread CPU 6645 -> 6488 ns. Below the 0.3 us bar for a perf claim; kept as a built, structural, measured-positive change. Checks: clippy plain, m2v_cpu_icd, m2v_gpu (-p metal2vulkan-runtime, all targets, all features) 0 in m3-max-37545; tests::encoder_moves asserts the encoder is one pointer; the lavapipe compute/encoder/render/blit suites (m3-max-37547) and rustdoc follow on development. --- crates/metal2vulkan-runtime/src/blit.rs | 10 +- crates/metal2vulkan-runtime/src/compute.rs | 399 ++++++++++-------- .../metal2vulkan-runtime/src/compute/live.rs | 23 +- crates/metal2vulkan-runtime/src/encoder.rs | 113 +++-- crates/metal2vulkan-runtime/src/render.rs | 3 +- .../src/tests/encoder_moves.rs | 12 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- 7 files changed, 344 insertions(+), 218 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 15411a4ab..ae2638c46 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -28,7 +28,7 @@ use super::buffer::Buffer; use super::command_buffer::CommandBuffer; use super::copy_run::CopyRun; use super::degradation::Degradation; -use super::encoder::{EncoderCore, Replayed}; +use super::encoder::{EncoderCore, HeldCore, Replayed}; use super::encoder_fold::Joining; use super::error::{invalid, CopyQueueProblem, Error, Problem}; use super::fresh_unwritten::FreshRead; @@ -818,6 +818,12 @@ impl BlitCommandEncoder { if let Some(pattern) = pattern { core.retain(pattern); } - core.end_with_replay(EncoderKind::Blit, (None, None), log.map(Replay::Blit), None) + EncoderCore::end_with_replay( + HeldCore(core), + EncoderKind::Blit, + (None, None), + log.map(Replay::Blit), + None, + ) } } diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index ddace12eb..44c344140 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -121,7 +121,7 @@ mod live; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) use live::SET_ASIDE_BYTES; use live::{Across, LiveDispatch}; -pub(crate) use live::{Parked, SpareLiveDispatches}; +pub(crate) use live::{Parked, Parking, SpareLiveDispatches}; /// Entries of a compute encoder's threadgroup memory table. pub(super) const THREADGROUP_SLOTS: u32 = 31; @@ -178,9 +178,16 @@ pub(super) fn imageblock_size(width: u64, height: u64) -> Result, +} + +/// A compute encoder's state, which the encoder holds in a box ([`ComputeCommandEncoder`]). +struct Body { /// In a box of its own (`EncoderCore::boxed`), which its end empties and gives the device back - /// for the next encoder (`encoder::SpareCores`): the encoder moves, from its open to its end, - /// with a pointer to its core rather than the core. + /// for the next encoder (`encoder::SpareCores`): the core goes from its open to its end as a + /// pointer to it. core: Box, dispatch_type: DispatchType, pipeline: Option, @@ -227,7 +234,7 @@ pub(super) struct EncoderState { impl std::fmt::Debug for ComputeCommandEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ComputeCommandEncoder") - .field("dispatch_type", &self.dispatch_type) + .field("dispatch_type", &self.body.dispatch_type) .finish() } } @@ -323,7 +330,7 @@ impl CommandBuffer { let raw = core.cut_reusable()?; self.state().predication.laid_into(raw); } - Ok(ComputeCommandEncoder { + let body = Box::new(Body { core, dispatch_type, pipeline: None, @@ -338,7 +345,8 @@ impl CommandBuffer { dispatches: 0, live, heaps_noted: None, - }) + }); + Ok(ComputeCommandEncoder { body }) } } @@ -352,9 +360,8 @@ impl ComputeCommandEncoder { ) -> Result { let replaying = EncoderCore::replaying(command_buffer, dispatch_type == DispatchType::Serial)?; - let core = replaying.boxed(); - Ok(ComputeCommandEncoder { - core, + let body = Box::new(Body { + core: replaying.boxed(), dispatch_type, pipeline: None, table: ArgumentTable::compute(), @@ -368,7 +375,8 @@ impl ComputeCommandEncoder { dispatches: 0, live: command_buffer.device().shared().live_dispatches.take(), heaps_noted: None, - }) + }); + Ok(ComputeCommandEncoder { body }) } /// End an encoder made by [`replaying`](Self::replaying): what it recorded, and what it made @@ -377,11 +385,17 @@ impl ComputeCommandEncoder { // Its unit of command predication takes what it encoded again, as at its end // (`predication.rs`). self.end_predication()?; - self.table.let_go_all(&mut self.core); + self.body.table.let_go_all(&mut self.body.core); + let Body { + core, + residency, + live, + .. + } = *self.body; // Its bind state goes on to the device's next compute encoder (`compute/live.rs`). - self.core.device().shared().live_dispatches.give(self.live); - let replayed = EncoderCore::unboxed(self.core).finish_replay()?; - Ok((replayed, Some(self.residency))) + core.device().shared().live_dispatches.give(live); + let replayed = EncoderCore::unboxed(core).finish_replay()?; + Ok((replayed, Some(residency))) } /// Log the call `call` makes of the log, before it runs, where the encoder logs @@ -390,7 +404,7 @@ impl ComputeCommandEncoder { &mut self, call: impl FnOnce(&mut CallLog) -> ComputeCall, ) -> Option { - let log = self.log.as_mut()?; + let log = self.body.log.as_mut()?; let call = call(log); let extra = call.extra(); Some(log.push(call, extra)) @@ -404,11 +418,11 @@ impl ComputeCommandEncoder { call: impl FnOnce(&mut CallLog) -> ComputeCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { - let _call = self.core.begin_call(); - let _for = self.core.notices_for(); + let _call = self.body.core.begin_call(); + let _for = self.body.core.notices_for(); let at = self.log(call); let ran = run(self); - if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.log) { + if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.body.log) { log.refuse(at); } ran @@ -422,7 +436,7 @@ impl ComputeCommandEncoder { result: &Result, call: fn(bool) -> ComputeCall, ) { - let (Some(at), Some(log)) = (at, &mut self.log) else { + let (Some(at), Some(log)) = (at, &mut self.body.log) else { return; }; match result { @@ -435,7 +449,7 @@ impl ComputeCommandEncoder { /// command predication (`predication.rs`), whose laying its check submits again and whose /// copies encode its own calls again. pub(super) fn stop_logging(&mut self) { - self.log = None; + self.body.log = None; } } @@ -486,7 +500,7 @@ fn degrade_dispatch( impl ComputeCommandEncoder { /// `dispatchType`. pub fn dispatch_type(&self) -> DispatchType { - self.dispatch_type + self.body.dispatch_type } /// `setComputePipelineState:`. A state of another device is refused. @@ -497,16 +511,17 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::PipelineState(state.clone()), |this| { - this.core + this.body + .core .check_device("set_compute_pipeline_state", state.bound_device()?)?; - this.pipeline = Some(state.clone()); - if let Some(trail) = this.core.trail() { + this.body.pipeline = Some(state.clone()); + if let Some(trail) = this.body.core.trail() { trail.compute(state); } - if let Some(times) = this.core.times() { + if let Some(times) = this.body.core.times() { times.compute(state); } - (this.core.routes).state_set(state.indirect_command_writes(), || { + (this.body.core.routes).state_set(state.indirect_command_writes(), || { vec![state.function_name().to_owned()] }); Ok(()) @@ -528,8 +543,9 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::Buffer(buffer.cloned(), offset, index), |this| { - this.table - .set_buffer(&mut this.core, "set_buffer", buffer, offset, index) + this.body + .table + .set_buffer(&mut this.body.core, "set_buffer", buffer, offset, index) }, ) } @@ -546,8 +562,13 @@ impl ComputeCommandEncoder { self.logged( |log| ComputeCall::Buffers(log.buffer_span(buffers), log.word_span(offsets), first), |this| { - this.table - .set_buffers(&mut this.core, "set_buffers", buffers, offsets, first) + this.body.table.set_buffers( + &mut this.body.core, + "set_buffers", + buffers, + offsets, + first, + ) }, ) } @@ -565,8 +586,12 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::BufferOffset(offset, index), |this| { - this.table - .set_buffer_offset(&mut this.core, "set_buffer_offset", offset, index) + this.body.table.set_buffer_offset( + &mut this.body.core, + "set_buffer_offset", + offset, + index, + ) }, ) } @@ -590,8 +615,8 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::BufferWithStride(buffer.cloned(), offset, stride, index), |this| { - this.table.set_buffer_with_stride( - &mut this.core, + this.body.table.set_buffer_with_stride( + &mut this.body.core, "set_buffer_with_stride", buffer, offset, @@ -619,8 +644,8 @@ impl ComputeCommandEncoder { ComputeCall::BuffersWithStrides(buffers, offsets, log.word_span(strides), first) }, |this| { - this.table.set_buffers_with_strides( - &mut this.core, + this.body.table.set_buffers_with_strides( + &mut this.body.core, "set_buffers_with_strides", buffers, offsets, @@ -644,8 +669,8 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::BufferOffsetWithStride(offset, stride, index), |this| { - this.table.set_buffer_offset_with_stride( - &mut this.core, + this.body.table.set_buffer_offset_with_stride( + &mut this.body.core, "set_buffer_offset_with_stride", offset, stride, @@ -667,8 +692,9 @@ impl ComputeCommandEncoder { self.logged( |log| ComputeCall::Bytes(log.byte_span(bytes), index), |this| { - this.table - .set_bytes(&mut this.core, "set_bytes", bytes, None, index) + this.body + .table + .set_bytes(&mut this.body.core, "set_bytes", bytes, None, index) }, ) } @@ -687,8 +713,8 @@ impl ComputeCommandEncoder { self.logged( |log| ComputeCall::BytesWithStride(log.byte_span(bytes), stride, index), |this| { - this.table.set_bytes( - &mut this.core, + this.body.table.set_bytes( + &mut this.body.core, "set_bytes_with_stride", bytes, Some(stride), @@ -711,8 +737,8 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::FunctionTable(table.cloned(), index), |this| { - this.table.set_function_tables( - &mut this.core, + this.body.table.set_function_tables( + &mut this.body.core, "set_visible_function_table", &[table], index, @@ -737,8 +763,8 @@ impl ComputeCommandEncoder { ) }, |this| { - this.table.set_function_tables( - &mut this.core, + this.body.table.set_function_tables( + &mut this.body.core, "set_visible_function_tables", tables, first, @@ -754,8 +780,9 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::Texture(texture.cloned(), index), |this| { - this.table - .set_textures(&mut this.core, "set_texture", &[texture], index) + this.body + .table + .set_textures(&mut this.body.core, "set_texture", &[texture], index) }, ) } @@ -766,8 +793,9 @@ impl ComputeCommandEncoder { self.logged( |log| ComputeCall::Textures(log.texture_span(textures), first), |this| { - this.table - .set_textures(&mut this.core, "set_textures", textures, first) + this.body + .table + .set_textures(&mut this.body.core, "set_textures", textures, first) }, ) } @@ -782,8 +810,8 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::Sampler(sampler.cloned(), index), |this| { - this.table.set_samplers( - &mut this.core, + this.body.table.set_samplers( + &mut this.body.core, "set_sampler_state", &[sampler], None, @@ -808,8 +836,13 @@ impl ComputeCommandEncoder { ) }, |this| { - this.table - .set_samplers(&mut this.core, "set_sampler_states", samplers, None, first) + this.body.table.set_samplers( + &mut this.body.core, + "set_sampler_states", + samplers, + None, + first, + ) }, ) } @@ -836,8 +869,8 @@ impl ComputeCommandEncoder { ) }, |this| { - this.table.set_samplers( - &mut this.core, + this.body.table.set_samplers( + &mut this.body.core, "set_sampler_state_with_lod_clamps", &[sampler], Some((&[lod_min_clamp], &[lod_max_clamp])), @@ -868,8 +901,8 @@ impl ComputeCommandEncoder { })) }, |this| { - this.table.set_samplers( - &mut this.core, + this.body.table.set_samplers( + &mut this.body.core, "set_sampler_states_with_lod_clamps", samplers, Some((lod_min_clamps, lod_max_clamps)), @@ -889,7 +922,7 @@ impl ComputeCommandEncoder { |this| { const CALL: &str = "set_threadgroup_memory_length"; check_index(CALL, index, THREADGROUP_SLOTS)?; - this.threadgroup_lengths.insert(index, length); + this.body.threadgroup_lengths.insert(index, length); Ok(()) }, ) @@ -909,7 +942,7 @@ impl ComputeCommandEncoder { self.logged( |_| ComputeCall::ImageblockSize(width, height), |this| { - this.imageblock = imageblock_size(width, height) + this.body.imageblock = imageblock_size(width, height) .map_err(|p| invalid("set_imageblock_size", p))?; Ok(()) }, @@ -928,8 +961,8 @@ impl ComputeCommandEncoder { |this| { let Region { origin, size } = region; let origin = Size::new(origin.x, origin.y, origin.z).truncated(); - this.stage_in_region = Some(StageInRegion::new(origin, size.truncated())); - this.indirect_stage_in = None; + this.body.stage_in_region = Some(StageInRegion::new(origin, size.truncated())); + this.body.indirect_stage_in = None; Ok(()) }, ) @@ -960,15 +993,17 @@ impl ComputeCommandEncoder { |_| ComputeCall::StageInRegionIndirect(indirect_buffer.clone(), indirect_buffer_offset), |this| { const CALL: &str = "set_stage_in_region_indirect"; - this.core.check_device(CALL, indirect_buffer.generation())?; + this.body + .core + .check_device(CALL, indirect_buffer.generation())?; let offset = indirect_dispatch::arguments_offset( CALL, (indirect_buffer.length(), indirect_buffer.copy_reach()), indirect_buffer_offset, STAGE_IN_REGION_BYTES, )?; - this.indirect_stage_in = Some((indirect_buffer.clone(), offset)); - this.stage_in_region = None; + this.body.indirect_stage_in = Some((indirect_buffer.clone(), offset)); + this.body.stage_in_region = None; Ok(()) }, ) @@ -1130,13 +1165,14 @@ impl ComputeCommandEncoder { ) -> Result<(), Error> { self.sync_heaps(); let reads = self + .body .pipeline .as_ref() .is_some_and(ComputePipelineState::reads_texture_handles); self.dispatch_indirect_resident(call, buffer, offset, arguments)?; self.command_encoded(reads); - self.dispatches += 1; - if let Some(times) = self.core.times() { + self.body.dispatches += 1; + if let Some(times) = self.body.core.times() { times.worked(); } Ok(()) @@ -1150,10 +1186,10 @@ impl ComputeCommandEncoder { offset: u64, arguments: Arguments, ) -> Result<(), Error> { - let Some(pipeline) = self.pipeline.clone() else { + let Some(pipeline) = self.body.pipeline.clone() else { return Err(invalid(call, Problem::NoPipelineState)); }; - self.core.check_device(call, buffer.generation())?; + self.body.core.check_device(call, buffer.generation())?; let offset = indirect_dispatch::arguments_offset( call, (buffer.length(), buffer.copy_reach()), @@ -1165,11 +1201,11 @@ impl ComputeCommandEncoder { } let tables = DispatchTables { pipeline: &pipeline, - table: &self.table, - threadgroup_lengths: &self.threadgroup_lengths, - imageblock: self.imageblock, - stage_in_region: self.stage_in_region, - residency: &self.residency, + table: &self.body.table, + threadgroup_lengths: &self.body.threadgroup_lengths, + imageblock: self.body.imageblock, + stage_in_region: self.body.stage_in_region, + residency: &self.body.residency, forms: BufferForms::Bound, }; let flat = FlatCall { @@ -1177,19 +1213,23 @@ impl ComputeCommandEncoder { offset, arguments, }; - if self.indirect_stage_in.is_none() + if self.body.indirect_stage_in.is_none() && record( - &mut self.core, + &mut self.body.core, &tables, call, Counts::Flat(flat), - Some((self.dispatches, &mut *self.live)), + Some((self.body.dispatches, &mut *self.body.live)), )? { return Ok(()); } - let copy = - indirect_dispatch::copy_arguments(&mut self.core, buffer, offset, arguments.bytes())?; + let copy = indirect_dispatch::copy_arguments( + &mut self.body.core, + buffer, + offset, + arguments.bytes(), + )?; self.defer_dispatch(call, pipeline, HostDispatch::Indirect { arguments, copy }) } @@ -1201,9 +1241,9 @@ impl ComputeCommandEncoder { pipeline: ComputePipelineState, dispatch: HostDispatch, ) -> Result<(), Error> { - let stage_in_copy = match &self.indirect_stage_in { + let stage_in_copy = match &self.body.indirect_stage_in { Some((buffer, offset)) => Some(indirect_dispatch::copy_arguments( - &mut self.core, + &mut self.body.core, buffer, *offset, STAGE_IN_REGION_BYTES, @@ -1211,22 +1251,24 @@ impl ComputeCommandEncoder { None => None, }; let gate = self + .body .core .command_buffer() .state() .predication_mut() .host_gate(); - self.core + self.body + .core .defer(Deferred::Dispatch(Arc::new(ArgumentDispatch { call, dispatch, stage_in_copy, pipeline, - table: self.table.clone(), - threadgroup_lengths: self.threadgroup_lengths.clone(), - imageblock: self.imageblock, - stage_in_region: self.stage_in_region, - ordered: self.dispatch_type == DispatchType::Serial, + table: self.body.table.clone(), + threadgroup_lengths: self.body.threadgroup_lengths.clone(), + imageblock: self.body.imageblock, + stage_in_region: self.body.stage_in_region, + ordered: self.body.dispatch_type == DispatchType::Serial, gate, }))) } @@ -1240,12 +1282,12 @@ impl ComputeCommandEncoder { /// are not a compute encoder's, so a scope of only `RENDER_TARGETS` records nothing. On a /// serial encoder, which orders its dispatches anyway, it adds nothing Metal would not do. pub fn memory_barrier_with_scope(&mut self, scope: BarrierScope) { - let _for = self.core.notices_for(); + let _for = self.body.core.notices_for(); self.log(|_| ComputeCall::BarrierWithScope(scope)); if !scope.intersects(BarrierScope::BUFFERS.union(BarrierScope::TEXTURES)) { return; } - self.core.memory_barrier(); + self.body.core.memory_barrier(); self.capture(|| Event::Barrier); } @@ -1287,10 +1329,10 @@ impl ComputeCommandEncoder { usage: ResourceUsage, ) -> Result<(), Error> { for resource in resources { - self.core.check_device(call, resource.device())?; + self.body.core.check_device(call, resource.device())?; } if resources.iter().any(ResourceRef::is_memoryless) { - self.core.fail_memoryless_use(); + self.body.core.fail_memoryless_use(); return Ok(()); } // A texture's shadow left unmade is made as the encoder makes it resident: its resource @@ -1304,18 +1346,19 @@ impl ComputeCommandEncoder { // Its records held where they lie in device-local memory, before any listing of // them reads where they lie (`indirect_command_buffer/home.rs`). if let ResourceRef::IndirectCommandBuffer(icb) = resource { - icb.hold_records(&mut self.core, usage.contains(ResourceUsage::WRITE)); + icb.hold_records(&mut self.body.core, usage.contains(ResourceUsage::WRITE)); } let used = self + .body .residency .use_resource(resource, usage, RenderStages::empty()); if let Some(used) = used { - self.core.made_resident(used); + self.body.core.made_resident(used); } if let ResourceRef::IndirectCommandBuffer(icb) = resource { if usage.contains(ResourceUsage::WRITE) { - self.core.routes.writable(icb); - self.core.retain(icb.gpu_write()); + self.body.core.routes.writable(icb); + self.body.core.retain(icb.gpu_write()); } } } @@ -1353,11 +1396,11 @@ impl ComputeCommandEncoder { fn use_heaps_of(&mut self, call: &'static str, heaps: &[&Heap]) -> Result<(), Error> { for heap in heaps { - self.core.check_device(call, heap.generation())?; + self.body.core.check_device(call, heap.generation())?; } for heap in heaps { - for used in self.residency.use_heap(heap, RenderStages::empty()) { - self.core.made_resident(used); + for used in self.body.residency.use_heap(heap, RenderStages::empty()) { + self.body.core.made_resident(used); } } Ok(()) @@ -1426,7 +1469,7 @@ impl ComputeCommandEncoder { |_| ComputeCall::Execute(icb.clone(), range.clone()), |this| { const CALL: &str = indirect_execute::CALL; - this.core.check_device(CALL, icb.generation())?; + this.body.core.check_device(CALL, icb.generation())?; if icb.is_render() { return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands( IndirectRule::OtherEncoderKind, @@ -1518,8 +1561,10 @@ impl ComputeCommandEncoder { |_| ComputeCall::ExecuteIndirect(icb.clone(), range_buffer.clone(), offset), |this| { const CALL: &str = indirect_execute::CALL_INDIRECT; - this.core.check_device(CALL, icb.generation())?; - this.core.check_device(CALL, range_buffer.generation())?; + this.body.core.check_device(CALL, icb.generation())?; + this.body + .core + .check_device(CALL, range_buffer.generation())?; if icb.is_render() { return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands( IndirectRule::OtherEncoderKind, @@ -1532,7 +1577,8 @@ impl ComputeCommandEncoder { if icb.has_no_command_types() { return Ok(()); } - let range = indirect_execute::range_from(&mut this.core, range_buffer, offset)?; + let range = + indirect_execute::range_from(&mut this.body.core, range_buffer, offset)?; this.defer_execution(icb, range, pipeline, check)?; this.worked(); this.capture(|| Event::ExecuteIndirect(icb.clone(), range_buffer.clone(), offset)); @@ -1548,7 +1594,7 @@ impl ComputeCommandEncoder { call: &'static str, icb: &IndirectCommandBuffer, ) -> Result, Error> { - match (&self.pipeline, icb.descriptor().inherit_pipeline_state) { + match (&self.body.pipeline, icb.descriptor().inherit_pipeline_state) { (_, false) => Ok(None), (Some(pipeline), true) => Ok(Some(pipeline.clone())), (None, true) => Err(invalid(call, Problem::NoPipelineState)), @@ -1565,19 +1611,24 @@ impl ComputeCommandEncoder { pipeline: Option, check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, ) -> Result<(), Error> { - if let Some(trail) = self.core.trail() { + if let Some(trail) = self.body.core.trail() { trail.execution(range.given()); } - icb.hold_records(&mut self.core, false); + icb.hold_records(&mut self.body.core, false); self.sync_heaps(); // Its commands bind the heap sets as they record, later. - self.core.command_buffer().state().heaps.executes_later(); + self.body + .core + .command_buffer() + .state() + .heaps + .executes_later(); // Its commands run the states their records name, where it inherits none. if !icb.descriptor().inherit_pipeline_state { - self.core.routes.executed(icb); + self.body.core.routes.executed(icb); } let table = if icb.descriptor().inherit_buffers { - self.table.clone() + self.body.table.clone() } else { ArgumentTable::default() }; @@ -1585,8 +1636,8 @@ impl ComputeCommandEncoder { // gate the GPU-alone path's preprocess of a fixed range runs from (`gpu_execute.rs`), one // invocation per command where the counter is 0. let (gate, further, preprocess_gate) = { - let device = self.core.device().clone(); - let mut state = self.core.command_buffer().state(); + let device = self.body.core.device().clone(); + let mut state = self.body.core.command_buffer().state(); let (predication, uploads) = state.predication_and_uploads(); let gate = predication.host_gate(); let (further, preprocess_gate) = match (&gate, &range) { @@ -1600,9 +1651,9 @@ impl ComputeCommandEncoder { (gate, further, preprocess_gate) }; if let Some(step) = further { - predication::record_further(&mut self.core, &step)?; + predication::record_further(&mut self.body.core, &step)?; } - self.core.defer(Deferred::Execute(Arc::new(Execute { + self.body.core.defer(Deferred::Execute(Arc::new(Execute { icb: icb.clone(), range, pipeline, @@ -1622,7 +1673,7 @@ impl ComputeCommandEncoder { /// (`Residency::sync_heaps`), held until the command buffer completes: a command reaches /// every texture its heaps hold as it is encoded. fn sync_heaps(&mut self) { - self.residency.sync_heaps(); + self.body.residency.sync_heaps(); } /// Once a command was encoded, note the heaps the encoder used; and where it reads texture @@ -1630,20 +1681,21 @@ impl ComputeCommandEncoder { fn command_encoded(&mut self, reads: bool) { // The command, encoded, used the heaps of what the encoder made resident: noted once a // change of it, as an earlier command noted those it held then. - let generation = self.residency.generation(); - if self.heaps_noted != Some(generation) { - self.core.touch_heaps(self.residency.heaps()); - self.heaps_noted = Some(generation); + let generation = self.body.residency.generation(); + if self.body.heaps_noted != Some(generation) { + self.body.core.touch_heaps(self.body.residency.heaps()); + self.body.heaps_noted = Some(generation); } if !reads { return; } // A texture the kernel's handles reach whose blocks a carrier holds reads as the neutral: // among those made resident, as the encoder keeps the first (`compute/live.rs`). - let bound = self.table.textures.values(); - let resident = (self.live.unreadable).of(self.core.device(), &self.residency); + let bound = self.body.table.textures.values(); + let resident = + (self.body.live.unreadable).of(self.body.core.device(), &self.body.residency); degrade_unreadable( - self.core.device(), + self.body.core.device(), resident.into_iter().chain(bound), "a dispatch", ); @@ -1651,89 +1703,92 @@ impl ComputeCommandEncoder { /// The encoder's core. pub(super) fn core(&mut self) -> &mut EncoderCore { - &mut self.core + &mut self.body.core } /// The encoder's state now, which a predicated loop's copies replay a command with. pub(super) fn encoder_state(&self) -> EncoderState { EncoderState { - pipeline: self.pipeline.clone(), - table: self.table.clone(), - threadgroup_lengths: self.threadgroup_lengths.clone(), - imageblock: self.imageblock, - stage_in_region: self.stage_in_region, - indirect_stage_in: self.indirect_stage_in.clone(), + pipeline: self.body.pipeline.clone(), + table: self.body.table.clone(), + threadgroup_lengths: self.body.threadgroup_lengths.clone(), + imageblock: self.body.imageblock, + stage_in_region: self.body.stage_in_region, + indirect_stage_in: self.body.indirect_stage_in.clone(), } } /// Set the encoder's state back to `state`: what the table it replaces binds is held until /// the command buffer completes (`ArgumentTable::let_go_all`). pub(super) fn restore_state(&mut self, state: EncoderState) { - self.table.let_go_all(&mut self.core); - self.pipeline = state.pipeline; - self.table = state.table; - self.threadgroup_lengths = state.threadgroup_lengths; - self.imageblock = state.imageblock; - self.stage_in_region = state.stage_in_region; - self.indirect_stage_in = state.indirect_stage_in; + self.body.table.let_go_all(&mut self.body.core); + self.body.pipeline = state.pipeline; + self.body.table = state.table; + self.body.threadgroup_lengths = state.threadgroup_lengths; + self.body.imageblock = state.imageblock; + self.body.stage_in_region = state.stage_in_region; + self.body.indirect_stage_in = state.indirect_stage_in; } /// The bodies of the predicated loops the encoder has open. pub(super) fn captures(&mut self) -> &mut Captures { - &mut self.captures + &mut self.body.captures } /// What the encoder made resident so far, which a predicated loop carried to its unit's next /// encoder replays its commands with (`predication.rs`). pub(super) fn residency_now(&self) -> Residency { - self.residency.clone() + self.body.residency.clone() } /// Make resident here what `residency`, an earlier encoder's of the unit, made resident: a /// predicated loop's copy replays that encoder's commands here (`predication.rs`). pub(super) fn carry_residency(&mut self, residency: &Residency) { - self.residency.carry(residency); + self.body.residency.carry(residency); } /// `label`: the label [`set_label`](Self::set_label) gave it, or `None`, as Metal's is `nil` /// until set. pub fn label(&self) -> Option { - self.core.command_buffer().open_encoder_label() + self.body.core.command_buffer().open_encoder_label() } /// `setLabel:`: label it `label`, which its command buffer's ended encoders keep /// ([`CommandBuffer::ended_encoders`](crate::CommandBuffer::ended_encoders)) and the /// runtime's notices naming the command buffer state, as [`CommandBuffer::set_label`](crate::CommandBuffer::set_label)'s. pub fn set_label(&mut self, label: &str) { - self.core.command_buffer().label_open_encoder(label); + self.body.core.command_buffer().label_open_encoder(label); } /// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds /// what an encoder was handed. pub fn end_encoding(mut self) -> Result<(), Error> { - let _call = self.core.begin_call(); - let _for = self.core.notices_for(); + let _call = self.body.core.begin_call(); + let _for = self.body.core.notices_for(); // Its unit of command predication takes what it encoded (`predication.rs`): as its core // ends, under the one lock that takes, where its command buffer has no record. - let unit_work = self.captures.unpredicated_work(); + let unit_work = self.body.captures.unpredicated_work(); if unit_work.is_none() { self.end_predication()?; } - self.table.let_go_all(&mut self.core); - // Its log, which its command buffer keeps where a rebind may need it (`replay.rs`). - let replay = self.log.map(|log| Replay::Compute { - dispatch_type: self.dispatch_type, + self.body.table.let_go_all(&mut self.body.core); + let Body { + core, + dispatch_type, + residency, log, - }); - // Its core's box and its bind state go on to its command buffer's next compute encoder - // (`compute/live.rs`). - let (core, room) = EncoderCore::unboxed_apart(self.core); - let parked = Parked::new(room, self.live); - // What it made resident joins its command buffer's (`residency.rs`), and is its own - // (`CommandBuffer::ended_encoders`). - core.end_with_replay( + live, + .. + } = *self.body; + // Its log, which its command buffer keeps where a rebind may need it (`replay.rs`). + let replay = log.map(|log| Replay::Compute { dispatch_type, log }); + // Its core's box, emptied as the core ends, and its bind state go on to its command + // buffer's next compute encoder (`compute/live.rs`). What it made resident joins its + // command buffer's (`residency.rs`), and is its own (`CommandBuffer::ended_encoders`). + EncoderCore::end_with_replay( + core, EncoderKind::Compute, - (Some(self.residency), Some(parked)), + (Some(residency), Some(Parking::new(live))), replay, unit_work, ) @@ -1754,7 +1809,7 @@ impl ComputeCommandEncoder { /// /// Refused: no pipeline state set (plain Metal faults). fn threadgroup(&self, call: &'static str, threads: Size) -> Result, Error> { - let Some(pipeline) = &self.pipeline else { + let Some(pipeline) = &self.body.pipeline else { return Err(invalid(call, Problem::NoPipelineState)); }; let total = threads.wrapping_volume(); @@ -1777,10 +1832,13 @@ impl ComputeCommandEncoder { /// nothing (`CommandBufferError::InvalidResource`, an M3 Max under macOS 27.0.1), so the /// encoder fails it and the dispatch records nothing (`EncoderCore::fail_memoryless_use`). fn fails_on_memoryless(&mut self) -> bool { - let uses = (self.pipeline.as_ref()) - .is_some_and(|state| self.table.uses_memoryless(state.interface(), Stage::Kernel)); + let uses = (self.body.pipeline.as_ref()).is_some_and(|state| { + self.body + .table + .uses_memoryless(state.interface(), Stage::Kernel) + }); if uses { - self.core.fail_memoryless_use(); + self.body.core.fail_memoryless_use(); } uses } @@ -1790,13 +1848,14 @@ impl ComputeCommandEncoder { fn dispatch(&mut self, call: &'static str, dispatch: Dispatch) -> Result<(), Error> { self.sync_heaps(); let reads = self + .body .pipeline .as_ref() .is_some_and(ComputePipelineState::reads_texture_handles); self.dispatch_resident(call, dispatch)?; self.command_encoded(reads); - self.dispatches += 1; - if let Some(times) = self.core.times() { + self.body.dispatches += 1; + if let Some(times) = self.body.core.times() { times.worked(); } Ok(()) @@ -1804,28 +1863,28 @@ impl ComputeCommandEncoder { /// [`dispatch`](Self::dispatch) with the heaps' textures resident. fn dispatch_resident(&mut self, call: &'static str, dispatch: Dispatch) -> Result<(), Error> { - let Some(pipeline) = &self.pipeline else { + let Some(pipeline) = &self.body.pipeline else { return Err(invalid(call, Problem::NoPipelineState)); }; - if self.indirect_stage_in.is_some() { + if self.body.indirect_stage_in.is_some() { let pipeline = pipeline.clone(); return self.defer_dispatch(call, pipeline, HostDispatch::Direct(dispatch)); } let tables = DispatchTables { pipeline, - table: &self.table, - threadgroup_lengths: &self.threadgroup_lengths, - imageblock: self.imageblock, - stage_in_region: self.stage_in_region, - residency: &self.residency, + table: &self.body.table, + threadgroup_lengths: &self.body.threadgroup_lengths, + imageblock: self.body.imageblock, + stage_in_region: self.body.stage_in_region, + residency: &self.body.residency, forms: BufferForms::Bound, }; record( - &mut self.core, + &mut self.body.core, &tables, call, Counts::Direct(dispatch), - Some((self.dispatches, &mut *self.live)), + Some((self.body.dispatches, &mut *self.body.live)), ) .map(drop) } diff --git a/crates/metal2vulkan-runtime/src/compute/live.rs b/crates/metal2vulkan-runtime/src/compute/live.rs index c3d8d0936..247e2f4c5 100644 --- a/crates/metal2vulkan-runtime/src/compute/live.rs +++ b/crates/metal2vulkan-runtime/src/compute/live.rs @@ -597,18 +597,29 @@ pub(crate) struct Parked { live: Box, } -impl Parked { - /// `room` and `live`, an ended compute encoder's: the lists of its resident textures' shadows - /// and carriers emptied, as the device's spares empty them, and the sampler states its memo's - /// entry and those of the states it set aside listed let go (the device's live ones, which its +/// An ending compute encoder's bind state on its way to its command buffer's park, which the box +/// of its core joins, emptied, as the core ends (`EncoderCore::end_with_replay`): [`Parked`]. +pub(crate) struct Parking(Box); + +impl Parking { + /// `live`, an ending compute encoder's: the lists of its resident textures' shadows and + /// carriers emptied, as the device's spares empty them, and the sampler states its memo's entry + /// and those of the states it set aside listed let go (the device's live ones, which its /// command buffer holds none of: `DispatchMemo::unlist_samplers`). - pub(in crate::compute) fn new(room: CoreBox, mut live: Box) -> Parked { + pub(in crate::compute) fn new(mut live: Box) -> Parking { live.shadows.let_go(); live.unreadable.let_go(); live.unlist_samplers(); - Parked { room, live } + Parking(live) } + /// Parked with `room`, the box of the encoder's core, emptied. + pub(crate) fn with_room(self, room: CoreBox) -> Parked { + Parked { room, live: self.0 } + } +} + +impl Parked { /// The core's box and the bind state, for the compute encoder that opens on them. pub(in crate::compute) fn into_parts(self) -> (CoreBox, Box) { (self.room, self.live) diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 0c46e3d7c..838113568 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -51,7 +51,7 @@ use super::buffer::Buffer; use super::churn_counts::KeepBy; use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer, State}; -use super::compute::Parked; +use super::compute::Parking; use super::copy_run::CopyRun; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; @@ -704,6 +704,43 @@ pub(super) fn check_device( } } +/// A core as its encoder's end takes it ([`EncoderCore::end_with_replay`]): in its box, which the +/// end empties and hands on, or by value ([`HeldCore`]). +pub(super) trait EndCore: std::ops::DerefMut { + /// The core, and its box, emptied, where it lay in one. + fn apart(self) -> (EncoderCore, Option); +} + +impl EndCore for Box { + fn apart(self) -> (EncoderCore, Option) { + let (core, room) = EncoderCore::unboxed_apart(self); + (core, Some(room)) + } +} + +/// A core its encoder holds by value to its end (a blit encoder's). +pub(super) struct HeldCore(pub(super) EncoderCore); + +impl std::ops::Deref for HeldCore { + type Target = EncoderCore; + + fn deref(&self) -> &EncoderCore { + &self.0 + } +} + +impl std::ops::DerefMut for HeldCore { + fn deref_mut(&mut self) -> &mut EncoderCore { + &mut self.0 + } +} + +impl EndCore for HeldCore { + fn apart(self) -> (EncoderCore, Option) { + (self.0, None) + } +} + impl EncoderCore { /// The core in a box its device kept from an ended encoder's ([`SpareCores`]), else a new one. pub(super) fn boxed(self) -> Box { @@ -3829,45 +3866,48 @@ impl EncoderCore { /// `unit_work`: a compute encoder's dispatches since its last record, which its unit of /// command predication takes under this end's one lock of the command buffer's state where /// the command buffer has no record (`predication.rs`); `None` where the encoder's end gave - /// them to its unit already, and for other encoders. `parked`: a compute encoder's core box - /// and bind state, which the command buffer keeps for its next compute encoder under the same - /// lock (`compute/live.rs`). + /// them to its unit already, and for other encoders. `parking`: a compute encoder's bind + /// state, which the command buffer keeps for its next compute encoder under the same lock, with + /// the core's box, emptied (`compute/live.rs`); the box of any other goes back to the device's + /// spares ([`SpareCores`]). A boxed core is taken apart here, where it ends, rather than read + /// whole out of its box before. pub(super) fn end_with_replay( - mut self, + mut held: impl EndCore, kind: EncoderKind, - (residency, parked): (Option, Option), + (residency, parking): (Option, Option), replay: Option, unit_work: Option, ) -> Result<(), Error> { + let core: &mut EncoderCore = &mut held; // A pass ended holds no command buffer (`render.rs`); this one ends here if one did. - self.release_pass()?; + core.release_pass()?; // What Metal's identifier allocations follow as the command buffer is scheduled // (`unique_identifier.rs`): a compute or blit encoder that encoded a command, and any // render encoder. - let worked = self.recorded || !self.executions.is_empty() || !self.segments.is_empty(); + let worked = core.recorded || !core.executions.is_empty() || !core.segments.is_empty(); let work = ScheduledWork { dispatch: worked && matches!(kind, EncoderKind::Compute | EncoderKind::Blit), render: kind == EncoderKind::Render, }; - let sharing = self.shadows.sharing_truth(); + let sharing = core.shadows.sharing_truth(); if sharing > 0 { - self.device().shared().counts.shadows_sharing_truth(sharing); + core.device().shared().counts.shadows_sharing_truth(sharing); } - let copies = self.shadows.finish(); - let copies = self.sample_moves(copies); - self.count_shadow_copies(&copies); - self.shadow_copies(&copies); + let copies = core.shadows.finish(); + let copies = core.sample_moves(copies); + core.count_shadow_copies(&copies); + core.shadow_copies(&copies); // Its end, where the device times its encoders, after its last command // (`encoder_times.rs`); none inside a predicated loop's laying, which its check may submit // again. - if self.times.is_some() { - let laying = (self.open.command_buffer.state().predication_mut()).laying(); + if core.times.is_some() { + let laying = (core.open.command_buffer.state().predication_mut()).laying(); let raw = match laying { true => None, - false => self.raw_recording(), + false => core.raw_recording(), }; - if let (Some(times), Some(raw)) = (self.times.as_deref_mut(), raw) { - let device = self.open.command_buffer.device().shared().vk(); + if let (Some(times), Some(raw)) = (core.times.as_deref_mut(), raw) { + let device = core.open.command_buffer.device().shared().vk(); // SAFETY: `raw` is the encoder's, recording outside a render pass instance (its // pass ended above), after every command of the encoder, and only this encoder // records it; outside a laying, it is submitted once at most. @@ -3880,12 +3920,12 @@ impl EncoderCore { // Why it keeps none, where a command named a buffer over host pages: the rebound notice // says (`command_buffer/rebound_use.rs`). let unlogged = match &replay { - _ if !self.taken.encodes_again() => None, + _ if !core.taken.encodes_again() => None, None => Some(Unlogged::NoCalls), - Some(_) if !self.segments.iter().all(Segment::records_again) => { + Some(_) if !core.segments.iter().all(Segment::records_again) => { Some(Unlogged::Segments) } - Some(_) if self.fails_command_buffer.is_some() || self.faults.is_some() => { + Some(_) if core.fails_command_buffer.is_some() || core.faults.is_some() => { Some(Unlogged::Fails) } Some(_) => None, @@ -3895,14 +3935,14 @@ impl EncoderCore { // group of encoders that may be encoded again (`encoder_fold.rs`). let mut held_log = None; let replay = replay.and_then(|log| { - let keeps = self.segments.iter().all(Segment::records_again) - && self.fails_command_buffer.is_none() - && self.faults.is_none() - && self.taken.encodes_again(); + let keeps = core.segments.iter().all(Segment::records_again) + && core.fails_command_buffer.is_none() + && core.faults.is_none() + && core.taken.encodes_again(); if !keeps { - match self.joining.is_some() { + match core.joining.is_some() { true => held_log = Some(log), - false => self.device().shared().scheduler.spare_logs().give(log), + false => core.device().shared().scheduler.spare_logs().give(log), } return None; } @@ -3910,14 +3950,23 @@ impl EncoderCore { }); // Its commands were recorded for one layout of each image it holds // (`texture/held_depth.rs`). - if self.uses.broke_hold() { + if core.uses.broke_hold() { return Err(internal("a held depth used but as its attachment")); } // The commands its orders took in: none of a part of one command (`tracker::EncoderUses`). - let taken_in = self.uses.taken_in(); + let taken_in = core.uses.taken_in(); if taken_in > 0 { - self.counts().commands_ordered_inside(taken_in); + core.counts().commands_ordered_inside(taken_in); } + // Its box, emptied, goes on with a compute encoder's bind state, else back to the device. + let (core, room) = held.apart(); + let parked = room.and_then(|room| match parking { + Some(parking) => Some(parking.with_room(room)), + None => { + core.device().shared().cores.give(room); + None + } + }); // Its last `VkCommandBuffer` stays recording, the command buffer's tail: its batch's end // may go into it (`CommandBufferShared::close_tail`). let EncoderCore { @@ -3950,7 +3999,7 @@ impl EncoderCore { trail, times, .. - } = self; + } = core; ended.push(raw); // The tail of the group it joined, where its commands began, is its group's first part's // (`encoder_fold.rs`): its own `VkCommandBuffer`s are those after it, where it went on in diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 7f11f766b..cc13358f3 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -4605,7 +4605,8 @@ impl RenderLowering { core.fail_command_buffer(CommandBufferError::CallRefused(call)); (core.command_buffer().state()).refuse_call(Error::Degraded(Box::new(notice))); } - EncoderCore::unboxed(core).end_with_replay( + EncoderCore::end_with_replay( + core, EncoderKind::Render, (Some(residency), None), log.map(Replay::Render), diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_moves.rs b/crates/metal2vulkan-runtime/src/tests/encoder_moves.rs index 27859f3bc..c6a193f84 100644 --- a/crates/metal2vulkan-runtime/src/tests/encoder_moves.rs +++ b/crates/metal2vulkan-runtime/src/tests/encoder_moves.rs @@ -1,13 +1,13 @@ //! What a compute encoder moves by value: `compute_command_encoder` returns it, and //! `end_encoding` takes it, so each of those, and each move of it in between, copies the encoder -//! whole. Its core and its bind state lie in boxes the device recycles (`encoder::SpareCores`, -//! `compute::SpareLiveDispatches`), so a move copies pointers to them: under 1 KiB, where the two -//! held in place would make each move a copy of over 4 KiB. +//! whole. Its state lies in a box of its own, and its core and its bind state in boxes the device +//! recycles (`encoder::SpareCores`, `compute::SpareLiveDispatches`), so a move copies one pointer, +//! where its state held in place made each move a copy of 888 bytes. -/// A compute encoder is at most 1 KiB. +/// A compute encoder is one pointer. #[test] -fn a_compute_encoder_moves_at_most_1_kib() { +fn a_compute_encoder_moves_one_pointer() { let size = std::mem::size_of::(); println!("ENCODER-MOVES ComputeCommandEncoder {size} bytes"); - assert!(size <= 1024, "{size} bytes"); + assert_eq!(size, std::mem::size_of::(), "{size} bytes"); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index e3304d76c..8503dfcd6 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2471; +pub const RUNTIME_VERSION: u32 = 2472; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles