diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index a75cb651b..761bbe9ad 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -235,13 +235,15 @@ impl NarrowedSlots { .map(|&(slot, levels, ..)| (slot, levels)) } - /// Whether a write among `uses` meets the levels a narrowed slot reads. + /// Whether a write among `uses` meets the levels a narrowed slot reads: their memory + /// (`UseRange::shares_memory`, so a write of another texture placed in the same heap apart + /// from them meets none). pub(super) fn written_by(&self, uses: &[Use]) -> bool { (self.slots.iter()).any(|(.., narrowed, _)| { (uses.iter()).any(|used| { !used.write.is_empty() && used.key == narrowed.key - && used.range.overlaps(&narrowed.range) + && used.range.shares_memory(&narrowed.range) }) }) } diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index a306c730d..b0287546b 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -82,7 +82,7 @@ use super::texture_descriptor::{ Creator, Refused, TextureDescriptor, TextureLayout, TextureProblem, }; use super::texture_placement::TexturePlacement; -use super::tracker::{Access, Use, UseRange}; +use super::tracker::{Access, ImagePlace, Use, UseRange}; use super::two_planes; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::view_plan::ViewRecord; @@ -1963,6 +1963,7 @@ impl Texels { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: self.tracked(), drops_writes: false, @@ -2435,6 +2436,7 @@ impl Texels { aspects, levels: 0..1, layers: 0..slices, + place: ImagePlace::WHOLE, }, tracked: self.tracked(), drops_writes: false, diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 273148fff..e1c102cd9 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2058,8 +2058,8 @@ degradations! { /// A heap texture sized or made (`heap_texture_size_and_align`, `Heap::new_texture`) /// whose images on the device need more bytes or a coarser alignment than Metal's answer, /// which the runtime models (`texture/heap_tiled.rs`): under the default - /// `HeapAnswerPolicy::Device`, a single-sample texture whose image binds into the heap's - /// memory, which lies in that image (`texture/heap::device_heap_answer`); under + /// `HeapAnswerPolicy::Device`, a texture whose image binds into the heap's memory, which + /// lies in that image (`texture/heap::device_heap_answer`); under /// `HeapAnswerPolicy::Metal`, one that no shadow of its bytes holds to Metal's answer /// (`texture/heap::held_to_metal`): not a multisample texture, whose image lies in memory /// of its own, nor one whose planes or Metal's tiles fit its bytes. The answer is then the diff --git a/crates/metal2vulkan-runtime/src/fresh_unwritten.rs b/crates/metal2vulkan-runtime/src/fresh_unwritten.rs index d61d234ef..5800368af 100644 --- a/crates/metal2vulkan-runtime/src/fresh_unwritten.rs +++ b/crates/metal2vulkan-runtime/src/fresh_unwritten.rs @@ -656,6 +656,7 @@ impl FreshUnwritten { aspects, levels, layers, + .. } = &used.range else { continue; diff --git a/crates/metal2vulkan-runtime/src/render/color_groups.rs b/crates/metal2vulkan-runtime/src/render/color_groups.rs index 81d8f99e9..21336a5e6 100644 --- a/crates/metal2vulkan-runtime/src/render/color_groups.rs +++ b/crates/metal2vulkan-runtime/src/render/color_groups.rs @@ -673,7 +673,7 @@ impl RenderLowering { let reads_watched = uses.iter().any(|used| { watched .iter() - .any(|w| used.key == w.key && used.range.overlaps(&w.range)) + .any(|w| used.key == w.key && used.range.shares_memory(&w.range)) }); if reads_watched { return Err(gap()); diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index d7d36d99e..807c613f1 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -62,7 +62,7 @@ use crate::render_values::{LoadAction, StoreAction}; use crate::residency::Used; use crate::resource::ResourceKey; use crate::shadow::{self, ShadowCopies, ShadowCopy, ShadowUse, Within}; -use crate::tracker::{Access, Use, UseRange}; +use crate::tracker::{Access, ImagePlace, Use, UseRange}; use crate::work_counts::{ColorTaken, Counters}; use crate::Device; use ash::vk; @@ -138,16 +138,22 @@ fn span(a: &UseRange, b: &UseRange) -> UseRange { aspects, levels, layers, + place, }, UseRange::Image { aspects: b_aspects, levels: b_levels, layers: b_layers, + place: b_place, }, ) => UseRange::Image { aspects: *aspects | *b_aspects, levels: levels.start.min(b_levels.start)..levels.end.max(b_levels.end), layers: layers.start.min(b_layers.start)..layers.end.max(b_layers.end), + place: match place == b_place { + true => *place, + false => ImagePlace::WHOLE, + }, }, // An image's uses are all of one kind; another kind on one key takes the later. (_, b) => b.clone(), @@ -970,19 +976,29 @@ fn count_colors( } } -/// Whether `target` is the whole of its texture, a 2D texture of one level, and the pass's -/// render area covers it: a clear of it replaces every texel. +/// Whether `target` is the whole of its texture, a 2D texture of one level and one slice (a +/// multisample one too), and the pass's render area covers it: a clear of it replaces every texel, +/// every sample of each. fn whole(target: &Target, layout: &PassLayout) -> bool { - one_image(target) + let planar = matches!( + target.texture.texture_type(), + TextureType::Type2D | TextureType::Type2DMultisample + ); + planar + && one_slice(target) && [target.texture.width(), target.texture.height()] == layout.extent.map(u64::from) } /// Whether `target` is the whole of its texture, a 2D texture of one level and one slice, whose /// pixels are its texels. fn one_image(target: &Target) -> bool { + target.texture.texture_type() == TextureType::Type2D && one_slice(target) +} + +/// Whether `target` is its texture's one level and one slice. +fn one_slice(target: &Target) -> bool { let texture = &target.texture; - texture.texture_type() == TextureType::Type2D - && texture.mipmap_level_count() == 1 + texture.mipmap_level_count() == 1 && texture.array_length() == 1 && target.level == 0 && target.layer == 0 @@ -993,7 +1009,7 @@ fn one_image(target: &Target) -> bool { mod tests { use super::{InstanceShadows, RANGES_PER_BUFFER}; use crate::resource::ResourceKey; - use crate::tracker::{Access, Use, UseRange}; + use crate::tracker::{Access, ImagePlace, Use, UseRange}; use ash::vk; use std::ops::Range; @@ -1033,6 +1049,7 @@ mod tests { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, ..bytes(c, 0..0, true) }; @@ -1075,6 +1092,7 @@ mod tests { aspects: vk::ImageAspectFlags::COLOR, levels, layers: 0..1, + place: ImagePlace::WHOLE, }, ..bytes(key, 0..0, false) }; @@ -1122,6 +1140,7 @@ mod tests { aspects: vk::ImageAspectFlags::COLOR, levels, layers: 0..1, + place: ImagePlace::WHOLE, }, ..bytes(c, 0..0, false) }; diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index 50f4b9fe6..98c705f67 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -2422,11 +2422,13 @@ fn any_access(uses: &[Use]) -> bool { .any(|used| used.read != Access::NONE || used.write != Access::NONE) } -/// Whether one of `uses` that reads or writes meets `attached`'s memory. +/// Whether one of `uses` that reads or writes meets `attached`'s memory: of its key, over a range +/// that shares memory with it (`UseRange::shares_memory`: a texture placed in the attachment's +/// heap apart from it shares the heap's key but none of its bytes). fn meets(attached: &Use, uses: &[Use]) -> bool { uses.iter() .filter(|used| used.read != Access::NONE || used.write != Access::NONE) - .any(|used| attached.key == used.key && attached.range.overlaps(&used.range)) + .any(|used| attached.key == used.key && attached.range.shares_memory(&used.range)) } /// The targets of `layout`'s attachments, in the order [`shares_attachment`] takes them: its diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 1146f7816..9886481c9 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -846,12 +846,16 @@ impl ShadowCopies { pub(super) fn taken_at_use(self, levels: u32, later: LaterLevels) -> ShadowCopies { let (shadow_range, aspects) = match self.shadow_range { UseRange::Image { - aspects, layers, .. + aspects, + layers, + place, + .. } => ( UseRange::Image { aspects, levels: 0..levels, layers, + place, }, aspects, ), diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 0b39a3843..8b967f8e2 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -154,7 +154,7 @@ use super::shadow_copy_back::{self, CopyBack, WordView}; use super::shadow_copy_in::CopyIn; use super::texture::heap_tiled::SampleMoves; use super::texture::kept_image::{KeptImage, KeptImages, KeptLease, TakenImage}; -use super::tracker::{Access, Barrier, Use, UseRange}; +use super::tracker::{Access, Barrier, ImagePlace, Use, UseRange}; use super::values::{HazardTrackingMode, ResourceOptions}; use super::Device; use crate::device::functions::Vk; @@ -664,6 +664,7 @@ impl ShadowMerge { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }; (identity.key, identity.tracked, range) } diff --git a/crates/metal2vulkan-runtime/src/tests/attached_levels.rs b/crates/metal2vulkan-runtime/src/tests/attached_levels.rs index c766e0e16..ed3ce71b6 100644 --- a/crates/metal2vulkan-runtime/src/tests/attached_levels.rs +++ b/crates/metal2vulkan-runtime/src/tests/attached_levels.rs @@ -10,15 +10,21 @@ //! the owned fixture `validation/fixtures/public/engine/alv_levels.ll`, through a runtime sampler //! of nearest filters and mip filter. //! +//! The texture placed in a tracked `Private` placement heap reads its levels so too, where the +//! draw writes a heap buffer placed apart from it (`hpr_level1_write` of the owned fixture +//! `hpr_reads.ll`): that write meets none of its bytes (`UseRange::shares_memory`), though the +//! heap's resources share one key. A write of a heap buffer over its bytes takes the copy, as +//! before. +//! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. use super::blit_holds::{device, Scratch, WAIT}; use super::encoder_holds::library; use crate::{ - BlitOption, Buffer, CommandQueue, Device, LoadAction, Origin, PipelineOptions, - RenderPassDescriptor, RenderPipelineState, ResourceOptions, SamplerState, Size, StoreAction, - Texture, TextureDescriptor, WorkCounts, + BlitOption, Buffer, CommandQueue, Device, HazardTrackingMode, HeapDescriptor, HeapType, + LoadAction, Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, SamplerState, Size, StoreAction, Texture, TextureDescriptor, WorkCounts, }; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{PixelFormat, PrimitiveType, SamplerMipFilter, TextureUsage}; @@ -74,11 +80,17 @@ struct Tools { impl Tools { fn new(device: &Device) -> Tools { let levels = library(device, "engine/alv_levels.ll"); + let writes = library(device, "engine/hpr_reads.ll"); let vertex = levels.new_function_with_name("alv_rect").unwrap(); - let pipelines = ["alv_level1", "alv_level2", "alv_implicit"] - .into_iter() - .map(|name| { - let fragment = levels.new_function_with_name(name).unwrap(); + let pipelines = [ + (&levels, "alv_level1"), + (&levels, "alv_level2"), + (&levels, "alv_implicit"), + (&writes, "hpr_level1_write"), + ]; + let pipelines = (pipelines.into_iter()) + .map(|(library, name)| { + let fragment = library.new_function_with_name(name).unwrap(); let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function( vertex.function_descriptor(), )); @@ -102,11 +114,12 @@ impl Tools { /// The private texture, each level holding its color. fn texture(&self) -> Texture { let device = self.queue.device(); - let mut descriptor = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, true); - descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - descriptor.resource_options = ResourceOptions::private(); - let texture = device.new_texture(&descriptor).unwrap(); + self.filled(device.new_texture(&descriptor()).unwrap()) + } + + /// `texture`, of [`descriptor`], each level filled with its color. + fn filled(&self, texture: Texture) -> Texture { + let device = self.queue.device(); assert_eq!(texture.mipmap_level_count(), LEVELS as u64); let command_buffer = self.queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); @@ -147,6 +160,18 @@ impl Tools { (texture, level): (&Texture, u64), function: &str, sampler: &SamplerState, + ) -> (Moved, Vec) { + self.pass_writing((texture, level), function, sampler, None) + } + + /// [`pass`](Self::pass), `written` bound at fragment buffer slot 0, which `hpr_level1_write` + /// writes. + fn pass_writing( + &self, + (texture, level): (&Texture, u64), + function: &str, + sampler: &SamplerState, + written: Option<&Buffer>, ) -> (Moved, Vec) { let device = self.queue.device(); let before = device.work_counts(); @@ -158,6 +183,9 @@ impl Tools { color.store_action = StoreAction::Store; let command_buffer = self.queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + if let Some(written) = written { + encoder.set_fragment_buffer(Some(written), 0, 0).unwrap(); + } let state = (self.pipelines.iter()).find(|(name, _)| *name == function); encoder .set_render_pipeline_state(&state.unwrap().1) @@ -195,6 +223,14 @@ impl Tools { } } +/// The texture's descriptor: `RGBA8Unorm`, [`SIDE`] a side, every level, read and rendered. +fn descriptor() -> TextureDescriptor { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, true); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + descriptor +} + /// A sampler of nearest filters and mip filter, its levels of detail clamped into /// `[min_lod, max_lod]`. fn sampler(device: &Device, (min_lod, max_lod): (f32, f32)) -> SamplerState { @@ -329,3 +365,58 @@ fn reads_of_the_levels_apart_from_the_attached_one_read_them_in_place() { ); } } + +/// The texture placed in a tracked `Private` placement heap, level 2 attached and level 1 read by +/// `hpr_level1_write`: where the draw writes a heap buffer placed apart from the texture, the read +/// stays narrowed, in place; where it writes a heap buffer over the texture's first bytes, the +/// narrowed slot is withdrawn for its copy (`WorkCounts::attached_read_slots_written`). Either +/// way it writes level 1's color. +#[test] +fn a_write_of_a_heap_buffer_placed_apart_leaves_a_narrowed_read_in_place() { + let scratch = Scratch::new("attached-levels-heap"); + let device = device(&scratch.0); + let tools = Tools::new(&device); + let tracked = ResourceOptions::private().with_hazard_tracking_mode(HazardTrackingMode::Tracked); + let mut placed = descriptor(); + placed.resource_options = tracked; + let answer = device.heap_texture_size_and_align(&placed).unwrap(); + // A heap buffer's offset is a multiple of 256 bytes: the first past the texture's answer. + let apart = answer.size.next_multiple_of(256); + let heap = HeapDescriptor::new(HeapType::Placement, apart + 256, tracked); + let heap = device.new_heap(&heap).unwrap(); + let unclamped = sampler(&device, (0.0, f32::MAX)); + let narrowed = Moved { + narrowed: 1, + past: 0, + reaching: 0, + first_level: 0, + copied: false, + }; + // Withdrawn: no slot narrowed, one counted as written. + let withdrawn = Moved { + narrowed: 0, + ..narrowed + }; + for (case, at, moved, withdrawals) in [ + ("a heap buffer placed apart written", apart, &narrowed, 0), + ("a heap buffer over the texture written", 0, &withdrawn, 1), + ] { + let texture = tools.filled(heap.new_texture_at_offset(&placed, 0).unwrap()); + let written = heap.new_buffer_at_offset(16, tracked, at).unwrap(); + let function = "hpr_level1_write"; + let before = device.work_counts().attached_read_slots_written; + let pass = tools.pass_writing((&texture, 2), function, &unclamped, Some(&written)); + let (counted, bytes) = pass; + let withdrawn = device.work_counts().attached_read_slots_written - before; + assert_eq!( + (&counted, withdrawn), + (moved, withdrawals), + "{case}: the counts" + ); + let wrong = bytes.iter().position(|&byte| byte != COLORS[1]); + assert_eq!( + wrong, None, + "{case}: every byte of level 2 is level 1's color" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/heap.rs b/crates/metal2vulkan-runtime/src/tests/heap.rs index b88fe4c38..c54a0ffd0 100644 --- a/crates/metal2vulkan-runtime/src/tests/heap.rs +++ b/crates/metal2vulkan-runtime/src/tests/heap.rs @@ -683,19 +683,21 @@ fn a_heap_texture_is_held_to_metal_s_answer_by_its_image_or_by_a_shadow() { /// Under `HeapAnswerPolicy::Device` a heap texture whose images need more of the heap than /// Metal's answer answers the larger of the two in each field (`device_heap_answer`), the images' -/// alignment at most 64 KiB and no more than the larger of the answer's size and 4096; every -/// other texture keeps Metal's -/// answer (`None`): one whose images fit it, one whose image does not bind into the heap's memory, -/// a 4:2:2 or one-plane YCbCr texture, a multisample one, and one whose answer is a measured -/// route's. The numbers are the devices': an RTX 5080 Laptop's 64x64 render target (16384 at 1024 -/// where Metal answers 16512 at 128), the Iris Xe's compressed `RGBA16Float` 77x77 texture (98688 +/// alignment at most a heap's memory's own (`HEAP_BASE_ALIGNMENT`, 256 KiB) and no more than the +/// larger of the answer's size and 4096; every other texture keeps Metal's answer (`None`): one +/// whose images fit it, one whose image does not bind into the heap's memory, +/// a 4:2:2 or one-plane YCbCr texture, and one whose answer is a measured route's. A multisample +/// texture whose image binds there answers as a single-sample one, an RX 7900 XTX's 4-sample +/// render target's 256 KiB alignment included. The numbers are the devices': +/// an RTX 5080 Laptop's 64x64 render target (16384 at 1024 where Metal answers 16512 at 128), the +/// Iris Xe's compressed `RGBA16Float` 77x77 texture (98688 /// at 65536 where Metal answers 98816 at 128) and 1x1 array (16448 at 65536 where Metal answers 128 /// at 128), an RTX 3090's 1x1 array (512 at 1024), and a `Shared` texture's linear image over host /// pages that asks more than its optimal image. #[test] fn a_device_answer_takes_the_larger_of_metal_s_and_the_images_where_they_need_more() { use crate::texture::heap::{ - device_heap_answer, HeapTextureShape, DEVICE_ANSWER_FREE_ALIGN, DEVICE_ANSWER_MOST_ALIGN, + device_heap_answer, HeapTextureShape, DEVICE_ANSWER_FREE_ALIGN, HEAP_BASE_ALIGNMENT, }; use crate::SizeAndAlign; let answer = |size, align| SizeAndAlign { size, align }; @@ -716,7 +718,7 @@ fn a_device_answer_takes_the_larger_of_metal_s_and_the_images_where_they_need_mo let iris = device_heap_answer(answer(98816, 128), &[answer(98688, 65536)], plain, bound); assert_eq!(iris, Some(answer(98816, 65536))); // An alignment past both the answer's size and a page (the Iris Xe's 1x1 array), or past the - // largest a Mac answers: Metal's holds, its image put in place to fit it as before. Up to a + // heap's memory's own: Metal's holds, its image put in place to fit it as before. Up to a // page, the answer's whatever its size (the 3090's 1x1 array). let tiny = device_heap_answer(answer(128, 128), &[answer(16448, 65536)], plain, bound); assert_eq!(tiny, None); @@ -725,10 +727,10 @@ fn a_device_answer_takes_the_larger_of_metal_s_and_the_images_where_they_need_mo let page = DEVICE_ANSWER_FREE_ALIGN; let paged = device_heap_answer(answer(128, 128), &[answer(512, page * 2)], plain, bound); assert_eq!(paged, None); - let past = DEVICE_ANSWER_MOST_ALIGN * 2; + let past = HEAP_BASE_ALIGNMENT * 2; let coarse = device_heap_answer(answer(1 << 20, 128), &[answer(1 << 20, past)], plain, bound); assert_eq!(coarse, None); - let most = DEVICE_ANSWER_MOST_ALIGN; + let most = HEAP_BASE_ALIGNMENT; let at_most = device_heap_answer(answer(1 << 20, 128), &[answer(1 << 20, most)], plain, bound); assert_eq!(at_most, Some(answer(1 << 20, most))); // A `Shared` texture's routes: the larger of its optimal image and the linear one over host @@ -747,14 +749,19 @@ fn a_device_answer_takes_the_larger_of_metal_s_and_the_images_where_they_need_mo rows: true, ..plain }, - HeapTextureShape { - multisample: true, - ..plain - }, ]; for shape in shapes { assert_eq!(device_heap_answer(metal, &needs, shape, bound), None); } + let multisample = HeapTextureShape { + multisample: true, + ..plain + }; + let samples = device_heap_answer(metal, &needs, multisample, bound); + assert_eq!(samples, Some(answer(16384, 1024))); + let radv = [answer(1 << 21, 256 << 10)]; + let radv = device_heap_answer(answer(1 << 21, 128), &radv, multisample, bound); + assert_eq!(radv, Some(answer(1 << 21, 256 << 10))); assert_eq!( device_heap_answer(metal, &needs, plain, (true, false)), None diff --git a/crates/metal2vulkan-runtime/src/tests/heap_placed_reads.rs b/crates/metal2vulkan-runtime/src/tests/heap_placed_reads.rs new file mode 100644 index 000000000..e5413ae46 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/heap_placed_reads.rs @@ -0,0 +1,331 @@ +//! Textures placed apart in one tracked `Private` placement heap, each at an offset the device's +//! answers lay it out at (`Device::heap_texture_size_and_align`), share no bytes, as on Metal: a +//! draw that reads one while its pass renders another reads the texture itself, not a copy of it +//! (`texture/attached_reads.rs`, `WorkCounts::attached_read_slots`), and announces no use of its +//! attachment's memory (`Degradation::AttachmentReadInPlace`, `render_target::shares_attachment`). +//! Every image bound in the heap's memory is the heap buffer's resource to hazard tracking +//! (`texture/heap.rs`), one key for all of them, so the memory each presents is its range of the +//! heap's bytes. A texture placed over the attachment's own bytes shares its memory, and so does a +//! heap buffer over them: the draw that reads that texture reads its copy, and the draw that reads +//! either announces it; a heap buffer placed apart shares none. +//! +//! A pass of five colors on a device that draws four at once draws in groups +//! (`render/color_groups.rs`) and refuses a draw that reads what a later group renders +//! (`NotImplemented(ColorAttachmentGroups)`): of its attachments in one heap, the draw that reads +//! a heap buffer placed apart from them draws, and the draw that reads one over its fifth +//! attachment's bytes is refused. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_rect` and +//! `tob_read` of `tob_renders.ll`, `cg_cover` of `color_groups.ll`, and `hpr_one` and +//! `hpr_five` of `hpr_reads.ll`, owned fixtures of `validation/fixtures/public/engine/` +//! (`llvm-as`). + +use super::blit_holds::{options, Scratch, WAIT}; +use super::draw_again::{device, Heard}; +use super::encoder_holds::{bytes_of, library}; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBufferStatus, CommandQueue, Degradation, Device, Error, + HazardTrackingMode, HeapDescriptor, HeapType, LoadAction, Origin, PipelineOptions, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, RuntimeGap, Size, StoreAction, + Texture, TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; + +/// The side of each texture. +const SIDE: u64 = 64; + +/// The color the read texture is cleared to, and its texels' bytes. +const READ_COLOR: [f64; 4] = [0.25, 0.5, 0.75, 1.0]; +const READ_BYTES: [u8; 4] = [0x40, 0x80, 0xbf, 0xff]; + +/// A tracked `Private` heap's options. +fn tracked() -> ResourceOptions { + ResourceOptions::private().with_hazard_tracking_mode(HazardTrackingMode::Tracked) +} + +/// An `RGBA8Unorm` render target the shaders read, of the heap's options. +fn target() -> TextureDescriptor { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = tracked(); + descriptor +} + +/// The state that draws `vertex` with `fragment`, each a fixture's function by its path under the +/// fixtures and its name, into `colors`. +fn state( + device: &Device, + vertex: (&str, &str), + fragment: (&str, &str), + colors: &[PixelFormat], +) -> RenderPipelineState { + let function = |(path, name): (&str, &str)| { + let function = library(device, path).new_function_with_name(name).unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let mut descriptor = RenderPipelineDescriptor::new(function(vertex)); + descriptor.fragment = Some(function(fragment)); + for (color, &format) in descriptor.color_attachments.iter_mut().zip(colors) { + *color = Some(ColorAttachmentDescriptor::new(format)); + } + (device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())).unwrap() +} + +/// What a draw reads: a texture at fragment texture slot 0, or a buffer at fragment buffer slot 0. +#[derive(Clone, Copy)] +enum Bound<'a> { + Texture(&'a Texture), + Buffer(&'a Buffer), +} + +/// A pass of `texture` that loads it `load`, clearing to `clear`, and stores it. +fn pass_of(texture: &Texture, load: LoadAction, clear: [f64; 4]) -> RenderPassDescriptor { + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = load; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(clear[0], clear[1], clear[2], clear[3]); + pass +} + +/// What one reading pass counted and announced. +#[derive(Debug, PartialEq, Eq)] +struct Read { + /// `WorkCounts::attached_read_slots`: the draw's slots that read a copy. + copied_slots: u64, + /// `Degradation::AttachmentReadInPlace` notices. + announced: usize, +} + +/// The heap, its device's tools and the notices it heard. +struct Lane { + device: Device, + heard: Heard, + queue: CommandQueue, + /// `tob_rect` and `tob_read`: each pixel the texel under it of the texture at slot 0. + reads_texture: RenderPipelineState, + /// `cg_cover` and `hpr_one`: each pixel the buffer's first `float4` plus a tint. + reads_buffer: RenderPipelineState, +} + +impl Lane { + /// One pass that clears `target` and draws over all of it once, reading `bound`. + fn read(&self, target: &Texture, bound: Bound<'_>) -> Read { + let before = self.device.work_counts(); + let heard = self.heard.lock().unwrap().len(); + let command_buffer = self.queue.command_buffer().unwrap(); + let pass = pass_of(target, LoadAction::Clear, [0.0; 4]); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + let vertices = match bound { + Bound::Texture(texture) => { + encoder + .set_render_pipeline_state(&self.reads_texture) + .unwrap(); + let rect: [f32; 4] = [-1.0, -1.0, 1.0, 1.0]; + let rect = bytes_of(&rect, f32::to_le_bytes); + encoder.set_vertex_bytes(&rect, 0).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + 6 + } + Bound::Buffer(buffer) => { + encoder + .set_render_pipeline_state(&self.reads_buffer) + .unwrap(); + encoder.set_fragment_buffer(Some(buffer), 0, 0).unwrap(); + 3 + } + }; + (encoder.draw_primitives(PrimitiveType::Triangle, 0, vertices, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let after = self.device.work_counts(); + let announced = (self.heard.lock().unwrap()[heard..].iter()) + .filter(|notice| notice.degradation == Degradation::AttachmentReadInPlace) + .count(); + Read { + copied_slots: after.attached_read_slots - before.attached_read_slots, + announced, + } + } + + /// Clear `texture` to `color` in a pass of no draw. + fn clear(&self, texture: &Texture, color: [f64; 4]) { + let command_buffer = self.queue.command_buffer().unwrap(); + let pass = pass_of(texture, LoadAction::Clear, color); + let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + } + + /// The bytes of `texture`'s texels, blitted into a buffer. + fn texels(&self, texture: &Texture) -> Vec { + let row = SIDE * 4; + let back: Buffer = (self.device) + .new_buffer(row * SIDE, ResourceOptions::shared()) + .unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + let size = Size::new(SIDE, SIDE, 1); + (blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + size, + &back, + 0, + row, + row * SIDE, + BlitOption::None, + )) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let contents = back.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command buffer writes now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), (row * SIDE) as usize) }.to_vec() + } +} + +#[test] +fn a_draw_reads_a_texture_placed_apart_from_its_attachment_in_place() { + let scratch = Scratch::new("heap-placed-reads"); + let heard = Heard::default(); + let device = device(&scratch.0, &[Degradation::AttachmentReadInPlace], &heard); + let answer = device.heap_texture_size_and_align(&target()).unwrap(); + // The attachment at 0, the texture read at the next offset its answer takes, apart. + let apart = answer.size.next_multiple_of(answer.align); + let descriptor = HeapDescriptor::new(HeapType::Placement, apart + answer.size, tracked()); + let heap = device.new_heap(&descriptor).unwrap(); + let attachment = heap.new_texture_at_offset(&target(), 0).unwrap(); + let beside = heap.new_texture_at_offset(&target(), apart).unwrap(); + // Over the attachment's bytes: a texture, and a buffer of the heap. + let over = heap.new_texture_at_offset(&target(), 0).unwrap(); + let bytes = heap.new_buffer_at_offset(256, tracked(), 0).unwrap(); + // A heap buffer's offset is a multiple of 256 bytes: the first inside the texture's range. + let elsewhere = heap.new_buffer_at_offset(256, tracked(), apart.next_multiple_of(256)); + let elsewhere = elsewhere.unwrap(); + let lane = Lane { + queue: device.new_command_queue().unwrap(), + reads_texture: state( + &device, + ("engine/tob_renders.ll", "tob_rect"), + ("engine/tob_renders.ll", "tob_read"), + &[PixelFormat::RGBA8Unorm], + ), + reads_buffer: state( + &device, + ("engine/color_groups.ll", "cg_cover"), + ("engine/hpr_reads.ll", "hpr_one"), + &[PixelFormat::RGBA8Unorm], + ), + device, + heard, + }; + lane.clear(&beside, READ_COLOR); + let apart_read = Read { + copied_slots: 0, + announced: 0, + }; + let read = lane.read(&attachment, Bound::Texture(&beside)); + assert_eq!( + read, apart_read, + "a texture placed apart from the attachment" + ); + let texels = lane.texels(&attachment); + let wrong = texels.chunks(4).filter(|t| *t != READ_BYTES).count(); + assert_eq!(wrong, 0, "texels of the attachment not the texture's read"); + let read = lane.read(&attachment, Bound::Buffer(&elsewhere)); + let what = "a heap buffer placed apart from the attachment"; + assert_eq!(read, apart_read, "{what}"); + // Over the attachment's own bytes: the texture's slot reads its copy, and reading it or a + // heap buffer over those bytes announces the read. + let read = lane.read(&attachment, Bound::Texture(&over)); + let shared = Read { + copied_slots: 1, + announced: 1, + }; + assert_eq!(read, shared, "a texture placed over the attachment's bytes"); + let read = lane.read(&attachment, Bound::Buffer(&bytes)); + let bytes_read = Read { + copied_slots: 0, + announced: 1, + }; + assert_eq!( + read, bytes_read, + "a heap buffer over the attachment's bytes" + ); +} + +#[test] +fn a_pass_drawn_in_groups_draws_reading_a_heap_buffer_placed_apart_from_its_attachments() { + let scratch = Scratch::new("heap-placed-groups"); + let mut options = options(&scratch.0); + options.color_attachment_limit = Some(4); + let device = Device::system_default_with(&options).unwrap(); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA16Float, 16, 16, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = tracked(); + let answer = device.heap_texture_size_and_align(&descriptor).unwrap(); + let apart = answer.size.next_multiple_of(answer.align); + let heap = HeapDescriptor::new(HeapType::Placement, 6 * apart, tracked()); + let heap = device.new_heap(&heap).unwrap(); + // The five attachments, each at its own offset; a heap buffer past them, and one over the + // fifth's first bytes (a heap buffer's offset is a multiple of 256 bytes). + let attachments: Vec = (0..5) + .map(|at| heap.new_texture_at_offset(&descriptor, at * apart).unwrap()) + .collect(); + let buffer_at = |at: u64| { + let offset = (at * apart).next_multiple_of(256); + heap.new_buffer_at_offset(16, tracked(), offset).unwrap() + }; + let (past, over) = (buffer_at(5), buffer_at(4)); + let five = [PixelFormat::RGBA16Float; 5]; + let state = state( + &device, + ("engine/color_groups.ll", "cg_cover"), + ("engine/hpr_reads.ll", "hpr_five"), + &five, + ); + let queue = device.new_command_queue().unwrap(); + // One pass clearing the attachments and drawing over them, reading `read`. + let draw = |read: &Buffer| -> Result<(), Error> { + let mut pass = RenderPassDescriptor::new(); + for (color, texture) in pass.color_attachments.iter_mut().zip(&attachments) { + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + } + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + encoder.set_fragment_buffer(Some(read), 0, 0).unwrap(); + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drawn + }; + let before = device.work_counts().color_group_passes; + draw(&past).expect("a draw reading a heap buffer placed apart from the attachments"); + let grouped = device.work_counts().color_group_passes - before; + assert!(grouped > 0, "the pass of five colors drew in groups"); + let refused = draw(&over); + assert!( + matches!( + refused, + Err(Error::NotImplemented(RuntimeGap::ColorAttachmentGroups)) + ), + "a draw reading a heap buffer over the fifth attachment's bytes: {refused:?}" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/heap_placed_targets.rs b/crates/metal2vulkan-runtime/src/tests/heap_placed_targets.rs new file mode 100644 index 000000000..1601b34bb --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/heap_placed_targets.rs @@ -0,0 +1,559 @@ +//! A frame's render targets placed once in one tracked `Private` placement heap, each at the +//! offset the device's answers lay it out at (`Device::heap_texture_size_and_align`), as a port of +//! placed resources makes them, against the same textures made by the device. The frame: a +//! depth-only pass into a shadow map; a pass into a 4-sample color and depth, both cleared and +//! neither stored, that resolves the color and samples the shadow map; a kernel that reads the +//! resolve and one that writes a texture; a pass into a second-format view of another texture; +//! and a pass into an sRGB view of the final target, of no load, whose draws sample those two. +//! +//! Every texture of the frame lies in its own bytes of the heap, so the heap's frame reads and +//! writes what the device's does (the final target's texels and the kernel's reads of the +//! resolve alike) and needs no copy the device's frame does not make: no draw reads a copy of a +//! texture it does not render (`WorkCounts::attached_read_slots`), none announces a use of its +//! attachments' memory (`Degradation::AttachmentReadInPlace`), and a texture whose image lies in +//! the heap's memory is no shadow of it, so none of the shadows' copies, sample moves or image +//! copies run (`WorkCounts::shadow_copies`, `heap_sample_move_images_lent`, `vkCmdCopyImage`). A +//! texture held as a shadow (an image the heap's memory takes at no answer the device gives) is +//! printed; under the default `HeapAnswerPolicy::Device` neither multisample target is one, each +//! in its image at its device's answer (`texture/heap.rs`'s `device_heap_answer`; an RX 7900 XTX +//! aligns a 4-sample image past 128 texels a side to 256 KiB, past every Mac's answer), and under +//! `HeapAnswerPolicy::Metal` the frame clears them whole, so it moves none of their samples in +//! (`render/shadows.rs`). Each lane prints its counted frames' mean wall time, a figure of +//! release builds alone. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixtures' +//! `tob_rect`, `tob_solid` and `tob_sample` (`engine/tob_renders.ll`), `pdc_vertex` and +//! `pdc_constexpr` (`engine/pdc_compare_clamp.ll`), and `a8r_write` and `a8r_read` +//! (`engine/a8r_targets.ll`). + +use super::blit_holds::{Scratch, WAIT}; +use super::draw_again::Heard; +use super::encoder_holds::{bytes_of, library}; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBufferStatus, CommandQueue, ComputePipelineState, + Degradation, DepthStencilState, Device, DeviceKind, DeviceOptions, HazardTrackingMode, Heap, + HeapDescriptor, HeapType, Library, LoadAction, MessageSink, Origin, PipelineOptions, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, SamplerState, ShaderCacheOptions, + Size, StoreAction, Texture, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::device::HeapAnswerPolicy; +use metal2vulkan::metal::state::DepthStencilDescriptor; +use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, TextureType, TextureUsage}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// The frame's extent: past 128 texels a side, where an RX 7900 XTX aligns a multisample image to +/// 256 KiB. +const WIDTH: u64 = 320; +const HEIGHT: u64 = 192; + +/// The shadow map's side. +const SHADOW: u64 = 256; + +/// The frames each lane runs, and the first one counted and timed: the first makes the pipelines' +/// first uses and the shadows' first copies. +const FRAMES: u64 = 12; +const COUNTED_FROM: u64 = 2; + +/// The kernel `a8r_read` reads the resolve at 8 x 8 texels. +const READ_SIDE: u64 = 8; + +/// The textures of the frame, by name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Target { + MsaaColor, + MsaaDepth, + Hdr, + Final, + Ui, + Post, + Shadow, +} + +const TARGETS: [Target; 7] = [ + Target::MsaaColor, + Target::MsaaDepth, + Target::Hdr, + Target::Final, + Target::Ui, + Target::Post, + Target::Shadow, +]; + +/// A tracked `Private` heap's options, its textures' too. +fn tracked() -> ResourceOptions { + ResourceOptions::private().with_hazard_tracking_mode(HazardTrackingMode::Tracked) +} + +/// The descriptor of `target`. +fn descriptor(target: Target) -> TextureDescriptor { + let read_target = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let (pf, side, usage) = match target { + Target::MsaaColor => (PixelFormat::RGBA16Float, None, TextureUsage::RENDER_TARGET), + Target::MsaaDepth => (PixelFormat::Depth32Float, None, TextureUsage::RENDER_TARGET), + Target::Hdr => (PixelFormat::RGBA16Float, None, read_target), + Target::Final => (PixelFormat::RGBA8Unorm, None, read_target), + Target::Ui => ( + PixelFormat::RGBA8Unorm, + None, + read_target | TextureUsage::PIXEL_FORMAT_VIEW, + ), + Target::Post => ( + PixelFormat::RGBA8Unorm, + None, + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, + ), + Target::Shadow => (PixelFormat::Depth32Float, Some(SHADOW), read_target), + }; + let (width, height) = side.map_or((WIDTH, HEIGHT), |side| (side, side)); + let mut descriptor = TextureDescriptor::texture_2d(pf, width, height, false); + descriptor.usage = usage; + descriptor.resource_options = tracked(); + if matches!(target, Target::MsaaColor | Target::MsaaDepth) { + descriptor.texture_type = TextureType::Type2DMultisample; + descriptor.sample_count = 4; + } + descriptor +} + +/// A device of the kind the cfg selects, its heap textures answered under `answers`, that +/// announces `AttachmentReadInPlace` at every occurrence, its notices into `heard`. +fn device(cache: &Path, answers: HeapAnswerPolicy, heard: &Heard) -> Device { + let heard = Arc::clone(heard); + let mut options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + messages: Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + heard.lock().unwrap().push(notice.clone()); + } + })), + announce_each: [Degradation::AttachmentReadInPlace].into_iter().collect(), + ..DeviceOptions::default() + }; + options.policy.heap_answers = answers; + Device::system_default_with(&options).unwrap() +} + +/// The frame's textures, placed in one heap (`heap`) or made by the device. +struct Targets { + textures: Vec, + /// The heap's size, where they lie in one. + heap: Option<(Heap, u64)>, +} + +impl Targets { + /// Each of [`TARGETS`] placed one after another at its answered alignment in one heap, as a + /// program places them by the answers. + fn placed(device: &Device) -> Targets { + let mut offsets = Vec::new(); + let mut end: u64 = 0; + for target in TARGETS { + let answer = device.heap_texture_size_and_align(&descriptor(target)); + let answer = answer.unwrap(); + let offset = end.next_multiple_of(answer.align); + offsets.push(offset); + end = offset + answer.size; + } + let heap = HeapDescriptor::new(HeapType::Placement, end, tracked()); + let heap = device.new_heap(&heap).unwrap(); + let textures = (TARGETS.iter().zip(offsets)) + .map(|(target, offset)| heap.new_texture_at_offset(&descriptor(*target), offset)) + .collect::, _>>() + .unwrap(); + Targets { + textures, + heap: Some((heap, end)), + } + } + + /// Each of [`TARGETS`] made by the device. + fn made(device: &Device) -> Targets { + let textures = TARGETS + .iter() + .map(|target| device.new_texture(&descriptor(*target)).unwrap()) + .collect(); + Targets { + textures, + heap: None, + } + } + + fn get(&self, target: Target) -> &Texture { + &self.textures[target as usize] + } +} + +/// The device's pipelines and states. +struct Tools { + queue: CommandQueue, + depth_only: RenderPipelineState, + scene: RenderPipelineState, + ui: RenderPipelineState, + composite: RenderPipelineState, + write: ComputePipelineState, + read: ComputePipelineState, + depth_less: DepthStencilState, + sampler: SamplerState, +} + +impl Tools { + fn new(device: &Device) -> Tools { + let renders = library(device, "engine/tob_renders.ll"); + let compares = library(device, "engine/pdc_compare_clamp.ll"); + let targets = library(device, "engine/a8r_targets.ll"); + let function = |library: &Library, name: &str| { + let function = library.new_function_with_name(name).unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let render = |vertex, fragment: Option, colors: Option| { + let mut descriptor = RenderPipelineDescriptor::new(vertex); + descriptor.fragment = fragment; + descriptor.color_attachments[0] = colors.map(ColorAttachmentDescriptor::new); + descriptor + }; + let options = PipelineOptions::default(); + let made = |descriptor: &RenderPipelineDescriptor| { + (device.new_render_pipeline_state(descriptor, &options)).unwrap() + }; + let mut depth_only = render(function(&renders, "tob_rect"), None, None); + depth_only.depth_format = Some(PixelFormat::Depth32Float); + let mut scene = render( + function(&compares, "pdc_vertex"), + Some(function(&compares, "pdc_constexpr")), + Some(PixelFormat::RGBA16Float), + ); + scene.depth_format = Some(PixelFormat::Depth32Float); + scene.raster_sample_count = 4; + let ui = render( + function(&renders, "tob_rect"), + Some(function(&renders, "tob_solid")), + Some(PixelFormat::BGRA8Unorm), + ); + let composite = render( + function(&renders, "tob_rect"), + Some(function(&renders, "tob_sample")), + Some(PixelFormat::RGBA8UnormSRGB), + ); + let kernel = |name| { + let descriptor = ComputePipelineDescriptor::new(function(&targets, name)); + (device.new_compute_pipeline_state(&descriptor, &options)).unwrap() + }; + let mut less = DepthStencilDescriptor::default(); + less.depth_compare_function = CompareFunction::Less; + less.depth_write_enabled = true; + Tools { + queue: device.new_command_queue().unwrap(), + depth_only: made(&depth_only), + scene: made(&scene), + ui: made(&ui), + composite: made(&composite), + write: kernel("a8r_write"), + read: kernel("a8r_read"), + depth_less: device.new_depth_stencil_state(&less).unwrap(), + sampler: device.new_sampler_state(&SamplerDescriptor::new()).unwrap(), + } + } +} + +/// The bytes of a rectangle from corner `(x0, y0)` to `(x1, y1)` (`tob_rect`'s `r`). +fn rect(r: [f32; 4]) -> Vec { + bytes_of(&r, f32::to_le_bytes) +} + +/// One frame into `targets`, its final target's texels blitted into `back` and the kernel's +/// reads of the resolve into `read`. +fn frame(tools: &Tools, targets: &Targets, (back, read): (&Buffer, &Buffer)) { + let final_view = (targets.get(Target::Final)) + .new_texture_view(PixelFormat::RGBA8UnormSRGB) + .unwrap(); + let ui_view = (targets.get(Target::Ui)) + .new_texture_view(PixelFormat::BGRA8Unorm) + .unwrap(); + let command_buffer = tools.queue.command_buffer().unwrap(); + // The shadow pass: the left half of the map at depth 0. + let mut pass = RenderPassDescriptor::new(); + let depth = &mut pass.depth_attachment; + depth.texture = Some(targets.get(Target::Shadow).clone()); + depth.load_action = LoadAction::Clear; + depth.clear_depth = 1.0; + depth.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder + .set_render_pipeline_state(&tools.depth_only) + .unwrap(); + encoder.set_depth_stencil_state(&tools.depth_less).unwrap(); + encoder + .set_vertex_bytes(&rect([-1.0, -1.0, 0.0, 1.0]), 0) + .unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + // The scene: 4 samples cleared, the color resolved, neither stored; the draw compares the + // shadow map's centre. + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(targets.get(Target::MsaaColor).clone()); + color.resolve_texture = Some(targets.get(Target::Hdr).clone()); + color.load_action = LoadAction::Clear; + color.clear_color = ClearColor::new(0.05, 0.07, 0.1, 1.0); + color.store_action = StoreAction::MultisampleResolve; + let depth = &mut pass.depth_attachment; + depth.texture = Some(targets.get(Target::MsaaDepth).clone()); + depth.load_action = LoadAction::Clear; + depth.clear_depth = 1.0; + depth.store_action = StoreAction::DontCare; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&tools.scene).unwrap(); + encoder.set_depth_stencil_state(&tools.depth_less).unwrap(); + let refs: [f32; 4] = [0.5, 0.5, 0.0, 0.0]; + (encoder.set_fragment_bytes(&bytes_of(&refs, f32::to_le_bytes), 0)).unwrap(); + (encoder.set_fragment_texture(Some(targets.get(Target::Shadow)), 0)).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + // The kernels: one reads the resolve, one writes the post target. + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&tools.read).unwrap(); + encoder + .set_texture(Some(targets.get(Target::Hdr)), 0) + .unwrap(); + encoder.set_buffer(Some(read), 0, 1).unwrap(); + let grid = Size::new(READ_SIDE, READ_SIDE, 1); + encoder.dispatch_threads(grid, grid).unwrap(); + encoder.set_compute_pipeline_state(&tools.write).unwrap(); + encoder + .set_texture(Some(targets.get(Target::Post)), 0) + .unwrap(); + let post: [f32; 4] = [0.75, 0.25, 0.5, 1.0]; + (encoder.set_bytes(&bytes_of(&post, f32::to_le_bytes), 0)).unwrap(); + let all = Size::new(WIDTH, HEIGHT, 1); + encoder.dispatch_threads(all, Size::new(8, 8, 1)).unwrap(); + encoder.end_encoding().unwrap(); + // The UI: its second-format view cleared, a rectangle drawn. + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(ui_view); + color.load_action = LoadAction::Clear; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&tools.ui).unwrap(); + encoder + .set_vertex_bytes(&rect([-0.5, -0.5, 0.5, 0.5]), 0) + .unwrap(); + let solid: [f32; 4] = [0.2, 0.4, 0.6, 1.0]; + (encoder.set_fragment_bytes(&bytes_of(&solid, f32::to_le_bytes), 0)).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + // The composite into the final target's sRGB view: the post target sampled on the left, the + // UI on the right. + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(final_view); + color.load_action = LoadAction::DontCare; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&tools.composite).unwrap(); + (encoder.set_fragment_sampler_state(Some(&tools.sampler), 0)).unwrap(); + for (half, read) in [ + ([-1.0, -1.0, 0.0, 1.0], Target::Post), + ([0.0, -1.0, 1.0, 1.0], Target::Ui), + ] { + encoder.set_vertex_bytes(&rect(half), 0).unwrap(); + (encoder.set_fragment_texture(Some(targets.get(read)), 0)).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + } + encoder.end_encoding().unwrap(); + // The read-back. + let mut blit = command_buffer.blit_command_encoder().unwrap(); + let row = WIDTH * 4; + (blit.copy_from_texture_to_buffer( + targets.get(Target::Final), + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + back, + 0, + row, + row * HEIGHT, + BlitOption::None, + )) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// What the counted frames did, each a frame's mean: the counts that differ between a heap's +/// frame and the device's. +#[derive(Debug, Default, PartialEq, Eq)] +struct Done { + attached_read_slots: u64, + attachment_reads_through_copies: u64, + shadow_copies: u64, + shadow_attachment_textures: u64, + shadow_attachment_clears_in_part: u64, + heap_sample_move_images_lent: u64, + image_copies: u64, + buffer_image_copies: u64, +} + +impl Done { + fn of(before: &WorkCounts, after: &WorkCounts, frames: u64) -> Done { + let delta = |count: fn(&WorkCounts) -> u64| (count(after) - count(before)) / frames; + let calls = |counts: &WorkCounts, command: &str| -> u64 { + (counts.copy_sites.iter()) + .filter(|site| site.command == command) + .map(|site| site.calls) + .sum() + }; + let copies = |command: &str| (calls(after, command) - calls(before, command)) / frames; + Done { + attached_read_slots: delta(|c| c.attached_read_slots), + attachment_reads_through_copies: delta(|c| c.attachment_reads_through_copies), + shadow_copies: delta(|c| c.shadow_copies), + shadow_attachment_textures: delta(|c| c.shadow_attachment_textures), + shadow_attachment_clears_in_part: delta(|c| c.shadow_attachment_clears_in_part), + heap_sample_move_images_lent: delta(|c| c.heap_sample_move_images_lent), + image_copies: copies("vkCmdCopyImage"), + buffer_image_copies: copies("vkCmdCopyBufferToImage"), + } + } +} + +/// What a lane of [`FRAMES`] frames read and did. +struct Ran { + texels: Vec, + read: Vec, + done: Done, + announced: usize, + /// The textures held as shadows of the heap's bytes, by name. + shadows: Vec, + /// The counted frames' mean wall time, each committed and waited for: a figure of release + /// builds alone, printed, never checked. + frame: Duration, +} + +/// [`FRAMES`] frames into `targets`. +fn run(device: &Device, heard: &Heard, tools: &Tools, targets: &Targets) -> Ran { + let shared = ResourceOptions::shared(); + let back = device.new_buffer(WIDTH * 4 * HEIGHT, shared).unwrap(); + let read = (device.new_buffer(READ_SIDE * READ_SIDE * 16, shared)).unwrap(); + let mut before = None; + for at in 0..FRAMES { + if at == COUNTED_FROM { + before = Some((device.work_counts(), Instant::now())); + } + frame(tools, targets, (&back, &read)); + } + let (before, started) = before.unwrap(); + let frame = started.elapsed() / (FRAMES - COUNTED_FROM) as u32; + let done = Done::of(&before, &device.work_counts(), FRAMES - COUNTED_FROM); + let announced = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::AttachmentReadInPlace) + .count(); + let shadows = (TARGETS.iter().zip(&targets.textures)) + .filter(|(_, texture)| texture.shadow().is_some()) + .map(|(target, _)| *target) + .collect(); + let bytes = |buffer: &Buffer| { + let contents = buffer.contents().unwrap(); + let length = buffer.length() as usize; + // SAFETY: the buffer's bytes, which no command buffer writes now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), length) }.to_vec() + }; + Ran { + texels: bytes(&back), + read: bytes(&read), + done, + announced, + shadows, + frame, + } +} + +/// A heap's frames and the device's, under `answers`. +fn lanes(leg: &str, answers: HeapAnswerPolicy) -> (Ran, Ran) { + let scratch = Scratch::new(leg); + let heard = Heard::default(); + let device = device(&scratch.0, answers, &heard); + let tools = Tools::new(&device); + let made = run(&device, &heard, &tools, &Targets::made(&device)); + heard.lock().unwrap().clear(); + let targets = Targets::placed(&device); + let placed = run(&device, &heard, &tools, &targets); + let size = targets.heap.as_ref().map(|(_, size)| *size); + let answers = TARGETS.map(|target| device.heap_texture_size_and_align(&descriptor(target))); + eprintln!( + "{leg}: {:?} heap of {size:?} bytes, answers {answers:?}, shadows {:?}; a frame: placed \ + {:?} in {:.3} ms, made {:?} in {:.3} ms", + device.name(), + placed.shadows, + placed.done, + placed.frame.as_secs_f64() * 1e3, + made.done, + made.frame.as_secs_f64() * 1e3, + ); + assert_eq!( + placed.texels, made.texels, + "{leg}: the final target's texels" + ); + assert_eq!( + placed.read, made.read, + "{leg}: the kernel's reads of the resolve" + ); + (placed, made) +} + +#[test] +fn a_frame_of_targets_placed_apart_in_a_heap_copies_nothing_the_device_s_does_not() { + let (placed, made) = lanes("heap-placed-targets", HeapAnswerPolicy::Device); + assert_eq!( + placed.announced, 0, + "reads of an attachment's memory announced" + ); + assert_eq!(placed.done.attached_read_slots, 0, "{:?}", placed.done); + assert_eq!(made.done, Done::default(), "the device's frame"); + for target in [Target::MsaaColor, Target::MsaaDepth] { + assert!(!placed.shadows.contains(&target), "{target:?} a shadow"); + } + if placed.shadows.is_empty() { + assert_eq!(placed.done, made.done, "a frame of no shadow"); + } +} + +#[test] +fn a_frame_under_metal_s_answers_moves_no_cleared_multisample_target_s_samples_in() { + let (placed, _) = lanes("heap-placed-targets-metal", HeapAnswerPolicy::Metal); + assert_eq!( + placed.announced, 0, + "reads of an attachment's memory announced" + ); + assert_eq!( + placed.done.shadow_attachment_clears_in_part, 0, + "{:?}", + placed.done + ); + assert_eq!( + placed.done.heap_sample_move_images_lent, 0, + "{:?}", + placed.done + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/held_depth.rs b/crates/metal2vulkan-runtime/src/tests/held_depth.rs index d7e1c3501..3b287c1a5 100644 --- a/crates/metal2vulkan-runtime/src/tests/held_depth.rs +++ b/crates/metal2vulkan-runtime/src/tests/held_depth.rs @@ -4,7 +4,7 @@ use crate::resource::ResourceKey; use crate::texture::held_depth::{need, BatchMoves, HeldImage, HeldImages, HELD}; -use crate::tracker::{Access, Use, UseRange}; +use crate::tracker::{Access, ImagePlace, Use, UseRange}; use ash::vk::{self, Handle}; use metal2vulkan::vk::{ImageAspectFlags, ImageLayout}; use std::collections::BTreeSet; @@ -135,6 +135,7 @@ fn a_move_is_a_write_of_the_whole_image() { aspects: vk::ImageAspectFlags::DEPTH, levels: 0..1, layers: 0..4, + place: ImagePlace::WHOLE, }, Access::new( vk::PipelineStageFlags2::ALL_COMMANDS, diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 3dae2cf46..48f980f2f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -276,6 +276,10 @@ mod heap_footprint_formats; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_one_plane_rows; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod heap_placed_reads; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod heap_placed_targets; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_refused_notice; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_sampler_array; diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs index c584df1a0..059e8e279 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs @@ -10,7 +10,7 @@ use super::super::shadow::{ Within, }; use super::super::shadow_merge::ScratchSpares; -use super::super::tracker::{Access, Use, UseRange}; +use super::super::tracker::{Access, ImagePlace, Use, UseRange}; use ash::vk; use metal2vulkan::error::Feature; use std::ops::Range; @@ -92,6 +92,7 @@ fn shadow_in( aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: true, drops_writes: false, @@ -1454,6 +1455,7 @@ fn view_of(image: ResourceKey, levels: Range, layers: Range) -> Arc, layers: Range) aspects, levels, layers, + place: ImagePlace::WHOLE, } } @@ -2538,3 +2539,44 @@ fn writes_of_no_stage_widen_no_fence_and_name_their_batch_the_writer() { "the batch writes them" ); } + +/// An image placed in a heap at `bytes` of the heap's memory, at level 0 and layer 0. +fn placed(bytes: Range) -> UseRange { + UseRange::Image { + aspects: vk::ImageAspectFlags::COLOR, + levels: 0..1, + layers: 0..1, + place: ImagePlace::bytes(bytes), + } +} + +/// Images placed apart in one heap order as one resource (Metal tracks a tracked heap so), but +/// share no memory; images over the same bytes, a heap's bytes over an image's, and two uses of +/// one image at its subresources do. +#[test] +fn placed_images_share_memory_where_their_bytes_meet() { + let (a, b) = (placed(0..4096), placed(4096..8192)); + assert!(a.overlaps(&b), "a heap's images order as one"); + assert!(!a.shares_memory(&b) && !b.shares_memory(&a)); + let over = placed(2048..6144); + assert!(a.shares_memory(&over) && b.shares_memory(&over)); + assert!(a.shares_memory(&a.clone())); + let other_level = UseRange::Image { + aspects: vk::ImageAspectFlags::COLOR, + levels: 1..2, + layers: 0..1, + place: ImagePlace::bytes(0..4096), + }; + assert!( + !a.shares_memory(&other_level), + "another level of the same image" + ); + assert!(a.shares_memory(&UseRange::Bytes(4000..4100))); + assert!(!a.shares_memory(&UseRange::Bytes(4096..5000))); + assert!(UseRange::Bytes(4096..5000).shares_memory(&b)); + // An image of no known place meets every range of another kind, and others as before. + let whole = image(vk::ImageAspectFlags::COLOR, 0..1, 0..1); + assert!(whole.shares_memory(&UseRange::Bytes(1 << 40..(1 << 40) + 1))); + assert!(whole.shares_memory(&a) && a.shares_memory(&whole)); + assert_eq!(a.hull(&b).map(|h| h == placed(0..8192)), Some(false)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/wrapped.rs b/crates/metal2vulkan-runtime/src/tests/wrapped.rs index 3136a5220..c0204dcc4 100644 --- a/crates/metal2vulkan-runtime/src/tests/wrapped.rs +++ b/crates/metal2vulkan-runtime/src/tests/wrapped.rs @@ -11,7 +11,7 @@ use crate::sharing::Sharing; use crate::texture::wrapped::{check_layouts, wrap_plan, Transition, Wrapped, WrappedImage}; use crate::texture::Owner; use crate::texture_descriptor::{texture_usage, TextureDescriptor}; -use crate::tracker::{Access, UseRange}; +use crate::tracker::{Access, ImagePlace, UseRange}; use crate::{VkImageLayouts, WrappedImageProblem}; use ash::vk; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; @@ -656,6 +656,7 @@ fn a_transition_is_a_tracked_write_of_every_subresource() { aspects: vk::ImageAspectFlags::COLOR, levels: 0..2, layers: 0..3, + place: ImagePlace::WHOLE, } ); assert_eq!(used.read, Access::NONE); diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 01c1ccc7f..eef8887ab 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -117,7 +117,7 @@ use super::texture_descriptor::{ memoryless_two_plane_cube, texture_usage, TextureDescriptor, TextureLayout, TextureProblem, TextureSwizzleChannels, }; -use super::tracker::{Access, Use, UseRange}; +use super::tracker::{Access, ImagePlace, Use, UseRange}; use super::two_planes; use super::values::{ CpuCacheMode, HazardTrackingMode, Origin, Region, ResourceOptions, Size, StorageMode, @@ -1198,6 +1198,17 @@ impl Image { self.form.plan().unwrap_or(&self.plan) } + /// Where the image's uses lie in the memory of their key (`tracker::ImagePlace`): an + /// automatic or placement heap's texture's range of the heap's bytes, whose key the image + /// of one bound in the heap's memory shares with every resource of the heap (`texture/heap.rs`); + /// the whole of the key for any other. + pub(super) fn place(&self) -> ImagePlace { + match self.owner.heap_place() { + Some(place) => ImagePlace::bytes(place.offset..place.offset + place.size), + None => ImagePlace::WHOLE, + } + } + /// Whether it lies in lazily allocated memory: a memoryless texture's, where the device has /// such memory (`image_plan.rs`). MoltenVK runs such an image as Metal's memoryless storage, /// which keeps no texels past the render pass that renders them. @@ -6416,6 +6427,7 @@ impl Texture { aspects: texture_aspects(image.plan()), levels: record.base_level..record.base_level + record.level_count, layers: record.base_layer..record.base_layer + record.layer_count, + place: image.place(), }, read, write, @@ -6452,6 +6464,7 @@ impl Texture { aspects: texture_aspects(image.plan()), levels, layers, + place: image.place(), }; Ok(if write { Use::writes(identity.key, identity.tracked, range, access) diff --git a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs index df98d034f..2644e0a1d 100644 --- a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs +++ b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs @@ -201,7 +201,7 @@ use crate::render_values::LoadAction; use crate::resource::ResourceKey; use crate::texture::view_error; use crate::texture_descriptor::TextureDescriptor; -use crate::tracker::{Access, Use, UseRange}; +use crate::tracker::{Access, ImagePlace, Use, UseRange}; use crate::values::ResourceOptions; use crate::view_plan::ViewRecord; use ash::vk; @@ -225,8 +225,10 @@ pub(crate) struct AttachedColors([Option; MAX_COLOR_ATTACHMENTS]) /// A color attachment as [`AttachedColors`] holds it. #[derive(Clone)] struct AttachedColor { - /// The key of the image its texture renders. + /// The key of the image its texture renders, and where the image lies in that key's memory: + /// the images of a heap share its key, each at its own bytes (`tracker::ImagePlace`). image: ResourceKey, + place: ImagePlace, /// The level it renders. level: u32, /// The layers it renders. @@ -246,6 +248,7 @@ impl AttachedColors { let image = target.texture.image().ok()?; Some(AttachedColor { image: image.identity.key, + place: image.place(), level: target.level, layers: target.layer..target.layer + target.layers, clears: color.load == LoadAction::Clear, @@ -376,8 +379,9 @@ impl Texture { return None; } let mut rendering = (layout.colors.iter().flatten()).filter(|color| { - (color.target.texture.image()) - .is_ok_and(|other| other.identity.key == image.identity.key) + (color.target.texture.image()).is_ok_and(|other| { + other.identity.key == image.identity.key && other.place().meets(image.place()) + }) }); let color = rendering.next()?; let target = &color.target; @@ -473,7 +477,8 @@ impl Texture { /// The color attachments of `colors` that `keep` keeps that render the texture at a layer it /// presents, each by its index and the level it renders, counted from the texture's own first /// level: of its image, at one of its levels, and at one of its layers (any layer of a 3D - /// image's). + /// image's). An image placed in a heap apart from the attachment's, at bytes of its own, + /// presents none of it, though the heap's images share one key (`tracker::ImagePlace`). fn attached_levels<'s>( &'s self, colors: &'s AttachedColors, @@ -485,6 +490,7 @@ impl Texture { let layers = record.base_layer..record.base_layer + record.layer_count; let volume = image.is_some_and(|image| image.plan().image_type == ImageType::TYPE_3D); let key = image.map(|image| image.identity.key); + let place = image.map_or(ImagePlace::WHOLE, |image| image.place()); let colors = key.map(|_| colors.0.iter().enumerate()); (colors.into_iter().flatten()) .filter_map(|(index, color)| color.as_ref().map(|color| (index, color))) @@ -493,7 +499,8 @@ impl Texture { let rendered = &color.layers; let presented = volume || (rendered.start < layers.end && layers.start < rendered.end); - (Some(color.image) == key && levels.contains(&color.level) && presented) + let same = Some(color.image) == key && place.meets(color.place); + (same && levels.contains(&color.level) && presented) .then(|| (index, color.level - record.base_level)) }) } @@ -531,10 +538,9 @@ impl Texture { layout.colors.iter().enumerate().find_map(|(index, color)| { let color = color.as_ref()?; let target = &color.target; - let same = target - .texture - .image() - .is_ok_and(|other| other.identity.key == image.identity.key); + let same = (target.texture.image()).is_ok_and(|other| { + other.identity.key == image.identity.key && other.place().meets(image.place()) + }); let own = same && color.stand_in.is_none() && color.planes.is_none() diff --git a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs index 4f928ec4c..1acf93e94 100644 --- a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs +++ b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs @@ -1566,6 +1566,7 @@ impl Image { aspects: texture_aspects(self.plan()), levels: region.level..region.level + 1, layers, + place: self.place(), }; Use::writes(self.identity.key, self.identity.tracked, range, access) }) diff --git a/crates/metal2vulkan-runtime/src/texture/faces.rs b/crates/metal2vulkan-runtime/src/texture/faces.rs index e1bfca263..274a4b3ab 100644 --- a/crates/metal2vulkan-runtime/src/texture/faces.rs +++ b/crates/metal2vulkan-runtime/src/texture/faces.rs @@ -85,7 +85,7 @@ use crate::shadow::{Backing, ImageTruth, ShadowCopies, ShadowSource}; use crate::shadow_merge::ScratchSpares; use crate::shadow_standing::StandingAcross; use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; -use crate::tracker::{Summary, UseRange}; +use crate::tracker::{ImagePlace, Summary, UseRange}; use crate::values::StorageMode; use crate::Device; use ash::vk; @@ -502,6 +502,7 @@ fn face_copies(truth: &Arc, shadow: &Arc, extent: [u32; 3]) -> Sha aspects, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }; let layers = vk::ImageSubresourceLayers { aspect_mask: aspects, @@ -609,6 +610,7 @@ impl FaceFix { aspects: texture_aspects(image.plan()), levels: 0..1, layers: 0..1, + place: image.place(), }; let identity = image.identity; match writes { diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index fa7f8dc9f..1a1acba9d 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -12,14 +12,20 @@ //! coarser alignment, the default `HeapAnswerPolicy::Device` answers the larger of the two and //! the texture lies in that image ([`device_heap_answer`]): Metal's query is the device's own, //! and the Macs answer alignments from 128 bytes to 65536 (an AMD Radeon Pro 5300M), so a program -//! places a heap's resources by the query, not by Apple's numbers. The alignment it takes is at -//! most 64 KiB, and at most 4 KiB or the answer's size; where the route's image asks more (ANV's +//! places a heap's resources by the query, not by Apple's numbers. The alignment it takes is +//! the device's, at most the heap's memory's own ([`HEAP_BASE_ALIGNMENT`], 256 KiB: an image +//! aligned past it has no offset there to bind at) and at most 4 KiB or the answer's size; +//! where the route's image asks more (ANV's //! compressed image of a small texture: 64 KiB), the texture's image that a 4 KiB alignment //! holds (`Device::fitting_heap_image`) lies there in its place, the answer that one's. A //! `Shared` texture's answer also holds the linear image a heap over host pages binds for it -//! (`Device::host_route_extent`). A measured route's, a multisample texture's and a texture -//! whose image lies in memory of its own keep Metal's answer, and under -//! `HeapAnswerPolicy::Metal` (in `exact_answers`) every texture does, held to it as below. The +//! (`Device::host_route_extent`). A multisample texture takes it too, its image bound in the +//! heap's memory at its offset as any other's, in the driver's layout of its samples (a +//! `Private` heap's 4-sample render targets at 1920x1080 on ANV, whose images ask more than +//! Metal's answer, then render in place rather than as shadows whose every sample the encoders +//! move between the image and Metal's tiles). A measured route's and a texture whose image lies +//! in memory of its own keep Metal's answer, and under `HeapAnswerPolicy::Metal` (in +//! `exact_answers`) every texture does, held to it as below. The //! answer depends on the device, its policy and the descriptor alone, never on what was //! allocated. //! @@ -261,7 +267,7 @@ use crate::resource::{Identity, ResourceKey}; use crate::shadow::{Backing, ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{effective_usage, Creator, TextureLayout, TextureProblem}; -use crate::tracker::UseRange; +use crate::tracker::{ImagePlace, UseRange}; use crate::two_planes; use crate::values::{ResourceOptions, StorageMode}; use crate::Device; @@ -1593,12 +1599,6 @@ pub(crate) fn images_fit(images: SizeAndAlign, metal: SizeAndAlign) -> bool { images.size <= metal.size && images.align <= metal.align } -/// The coarsest alignment a heap texture's answer takes from its device's image under -/// `HeapAnswerPolicy::Device` ([`device_heap_answer`]): 64 KiB, the largest a Mac answers -/// (`heapTextureSizeAndAlignWithDescriptor:` on an AMD Radeon Pro 5300M; an Intel UHD Graphics 630 -/// answers 4096, Apple's GPUs 128 and, for arrays, 16384). -pub(crate) const DEVICE_ANSWER_MOST_ALIGN: u64 = 64 << 10; - /// The alignment a heap texture's answer takes from its device's image under /// `HeapAnswerPolicy::Device` whatever its size ([`device_heap_answer`]): 4096 bytes, what an /// Intel UHD Graphics 630 answers for every texture. A coarser one is taken only up to the @@ -1611,19 +1611,22 @@ pub(crate) const DEVICE_ANSWER_FREE_ALIGN: u64 = 4 << 10; /// took, and for a `Shared` texture the linear image a heap over host pages binds), each /// [`heap_extent`]. `None`, so Metal's answer holds as under `HeapAnswerPolicy::Metal`, where /// those images fit Metal's answer; where the texture's image does not bind into the heap's -/// memory (`shape.apart`, or `in_own_memory`: a shadow already) or it is a 4:2:2, one-plane YCbCr -/// or multisample texture; where Metal's answer is a measured route's (`measured_route`); and -/// where the answer would be aligned past [`DEVICE_ANSWER_MOST_ALIGN`], or past both its own size -/// and [`DEVICE_ANSWER_FREE_ALIGN`], so that a heap's padding before a texture is at most a page -/// or its own bytes (ANV's compressed image of a small texture asks 64 KiB for 16 KiB: the image -/// a 4 KiB alignment holds takes its place, `Device::heap_plan`). +/// memory (`shape.apart`, or `in_own_memory`: a shadow already) or it is a 4:2:2 or one-plane +/// YCbCr texture; where Metal's answer is a measured route's (`measured_route`); and +/// where the answer would be aligned past [`HEAP_BASE_ALIGNMENT`], the alignment of the heap's +/// memory, past which the image has no offset there to bind at (the device's own alignment +/// otherwise, an RX 7900 XTX's 256 KiB for a 4-sample render target included: the answer +/// describes the device, as Metal's query does, not a number inside the Macs' range), or past +/// both its own size and [`DEVICE_ANSWER_FREE_ALIGN`], so that a heap's padding before a texture +/// is at most a page or its own bytes (ANV's compressed image of a small texture asks 64 KiB for +/// 16 KiB: the image a 4 KiB alignment holds takes its place, `Device::heap_plan`). pub(crate) fn device_heap_answer( metal: SizeAndAlign, routes: &[SizeAndAlign], shape: HeapTextureShape, (measured_route, in_own_memory): (bool, bool), ) -> Option { - if shape.apart || shape.rows || shape.multisample || measured_route || in_own_memory { + if shape.apart || shape.rows || measured_route || in_own_memory { return None; } let need = routes @@ -1640,7 +1643,7 @@ pub(crate) fn device_heap_answer( align: need.align.max(metal.align), }; let padding = answer.align <= answer.size.max(DEVICE_ANSWER_FREE_ALIGN); - (answer.align <= DEVICE_ANSWER_MOST_ALIGN && padding).then_some(answer) + (answer.align <= HEAP_BASE_ALIGNMENT && padding).then_some(answer) } /// What a heap texture's descriptor and its planned images decide about holding it to Metal's @@ -1656,7 +1659,9 @@ pub(crate) struct HeapTextureShape { /// image lays them. pub(crate) rows: bool, /// More than one sample: no copy of rows shadows its image, which lies in memory of its own - /// instead, as one the heap's memory cannot hold. + /// instead, as one the heap's memory cannot hold, where the texture is held to Metal's answer + /// ([`held_to_metal`]); under `HeapAnswerPolicy::Device` it takes its device's answer as any + /// other ([`device_heap_answer`]), and lies in its image in the heap's memory. pub(crate) multisample: bool, } @@ -1865,9 +1870,9 @@ impl Device { /// runtime models it and the device's image fits it; the device's image's own footprint, with /// whole chunks of compression data where the driver writes them past an image's size, where /// the model has none. Where the image needs more than Metal's answer, the policy decides - /// (`DevicePolicy::heap_answers`): under the default `HeapAnswerPolicy::Device` a - /// single-sample texture whose image binds into the heap's memory answers the larger of the - /// two (its alignment at most 64 KiB, and at most 4 KiB or its size, else its image that a + /// (`DevicePolicy::heap_answers`): under the default `HeapAnswerPolicy::Device` a texture + /// whose image binds into the heap's memory (a multisample one too) answers the larger of the + /// two (its alignment at most 256 KiB, and at most 4 KiB or its size, else its image that a /// 4 KiB alignment holds answers); under `HeapAnswerPolicy::Metal`, Metal's answer, which an /// image that fits or a shadow of the heap's bytes holds, and the larger of the two only where /// neither does. A larger answer is announced `heap-texture-larger-than-metal`. The image of a @@ -4275,6 +4280,7 @@ impl Device { aspects: image_aspects(plan.format).into(), levels: 0..plan.levels, layers: 0..plan.layers, + place: ImagePlace::WHOLE, }; let identity = Identity { key: ResourceKey::new(), @@ -4380,6 +4386,7 @@ impl Device { aspects: image_aspects(plan.format).into(), levels: 0..1, layers: 0..planes.slices as u32, + place: ImagePlace::WHOLE, }; let identity = Identity { key: ResourceKey::new(), @@ -4462,6 +4469,7 @@ impl Device { aspects: image_aspects(plan.format).into(), levels: 0..plan.levels, layers: 0..plan.layers, + place: ImagePlace::WHOLE, }; let identity = Identity { key: ResourceKey::new(), diff --git a/crates/metal2vulkan-runtime/src/texture/held_depth.rs b/crates/metal2vulkan-runtime/src/texture/held_depth.rs index 7918bb7cd..a75583d3d 100644 --- a/crates/metal2vulkan-runtime/src/texture/held_depth.rs +++ b/crates/metal2vulkan-runtime/src/texture/held_depth.rs @@ -41,7 +41,7 @@ use super::super::key_hash::KeyMap; use super::super::resource::ResourceKey; -use super::super::tracker::{Access, Use, UseRange}; +use super::super::tracker::{Access, ImagePlace, Use, UseRange}; use super::super::Device; use super::image_aspects; use super::wrapped::Transition; @@ -134,6 +134,7 @@ impl HeldImage { aspects: self.aspects.into(), levels: 0..self.levels, layers: 0..self.layers, + place: ImagePlace::WHOLE, }, Access::new( vk::PipelineStageFlags2::ALL_COMMANDS, diff --git a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs index b0bfb5579..41b014d02 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs @@ -33,7 +33,7 @@ use super::super::resource::Identity; use super::super::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; use super::super::shadow_merge::ScratchSpares; use super::super::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; -use super::super::tracker::UseRange; +use super::super::tracker::{ImagePlace, UseRange}; use super::super::values::ResourceOptions; use super::super::view_plan::ViewRecord; use super::super::Device; @@ -161,6 +161,7 @@ impl Texture { aspects: aspect, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: texels.tracked(), drops_writes: false, diff --git a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs index 852a2359a..043811a44 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs @@ -61,7 +61,7 @@ use crate::linear_plan::{BufferLayout, LINEAR_ALIGNMENT}; use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; -use crate::tracker::UseRange; +use crate::tracker::{ImagePlace, UseRange}; use crate::view_plan::ViewRecord; use crate::ycbcr::IoSurfaceYCbCr; use crate::Device; @@ -233,6 +233,7 @@ impl Device { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: texels.tracked(), drops_writes: false, diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index ce6bc583a..7aeec5275 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -67,7 +67,7 @@ use crate::shadow_merge::ScratchSpares; use crate::shadow_standing::StandingAcross; use crate::texture::{copy_units, image_error, texture_aspects}; use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; -use crate::tracker::UseRange; +use crate::tracker::{ImagePlace, UseRange}; use crate::values::{ResourceOptions, StorageMode}; use crate::view_plan::{keeps_components, reinterpretation_refused, ViewRecord}; use crate::Device; @@ -415,6 +415,7 @@ impl Device { aspects, levels: view.base_level..view.base_level + view.level_count, layers: view.base_layer..view.base_layer + view.layer_count, + place: ImagePlace::WHOLE, }; let volume = texture.texture_type == TextureType::Type3D; let regions: Vec = (view.base_level..view.base_level + view.level_count) diff --git a/crates/metal2vulkan-runtime/src/texture/wrapped.rs b/crates/metal2vulkan-runtime/src/texture/wrapped.rs index 6dbd9441f..0e2f01c84 100644 --- a/crates/metal2vulkan-runtime/src/texture/wrapped.rs +++ b/crates/metal2vulkan-runtime/src/texture/wrapped.rs @@ -37,7 +37,7 @@ use super::super::resource::{Identity, ResourceKey}; use super::super::resource_ids::IdPlacement; use super::super::sharing::Sharing; use super::super::texture_descriptor::{texture_usage, TextureDescriptor}; -use super::super::tracker::{Access, Use, UseRange}; +use super::super::tracker::{Access, ImagePlace, Use, UseRange}; use super::super::values::StorageMode; use super::super::view_plan::ViewRecord; use super::super::Device; @@ -323,6 +323,7 @@ impl WrappedImage { aspects: self.aspects.into(), levels: 0..self.levels, layers: 0..self.layers, + place: ImagePlace::WHOLE, }, Access::new( vk::PipelineStageFlags2::ALL_COMMANDS, diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index 30c2e7699..9b3025314 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -34,7 +34,7 @@ use crate::resource::ResourceKey; use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource}; use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; -use crate::tracker::{Access, Use, UseRange}; +use crate::tracker::{Access, ImagePlace, Use, UseRange}; use crate::values::ResourceOptions; use crate::view_plan::ViewRecord; use crate::ycbcr::{YCbCrConversion, YCbCrWriteBack}; @@ -382,6 +382,7 @@ impl Device { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: texels.tracked(), // Metal drops a function's writes to the texture. @@ -707,6 +708,7 @@ impl Texture { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: texels.tracked(), drops_writes: false, @@ -883,6 +885,7 @@ impl Texture { aspects: vk::ImageAspectFlags::COLOR, levels: 0..1, layers: 0..1, + place: ImagePlace::WHOLE, }, tracked: texels.tracked(), drops_writes: false, diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index 0ce9d66d1..464d740db 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -154,14 +154,63 @@ pub(super) enum UseRange { /// Bytes `start..end`. Bytes(Range), /// Aspects, mip levels and array layers of an image. 3D depth slices are not separate, since - /// Vulkan's barriers cannot name them. + /// Vulkan's barriers cannot name them. `place` is where the image lies in the memory its key + /// names ([`ImagePlace`]). Image { aspects: vk::ImageAspectFlags, levels: Range, layers: Range, + place: ImagePlace, }, } +/// Where an image's uses lie in the memory of the key they name ([`UseRange::Image`]): the whole +/// of it ([`ImagePlace::WHOLE`]) for an image whose key is its own, or the bytes an image bound in +/// an automatic or placement heap takes of the heap's, whose key every resource of the heap shares +/// (`texture/heap.rs`), in the heap buffer's offsets (`Buffer::tracked`). +/// +/// Hazard tracking does not read it: Metal tracks a tracked heap's resources as one ("at the +/// granularity of the heap", `heap.rs`), and so do [`UseRange::overlaps`] and the tracker. What +/// asks whether two uses touch the same memory reads it ([`UseRange::shares_memory`]): a draw that +/// reads a texture placed apart from its attachment in the attachment's heap reads no memory the +/// attachment renders. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct ImagePlace { + start: u64, + end: u64, +} + +impl ImagePlace { + /// The whole of the key's memory: an image whose key is its own, or one whose place is not + /// known. + pub(super) const WHOLE: ImagePlace = ImagePlace { start: 0, end: 0 }; + + /// The bytes `bytes` of the key's memory; [`WHOLE`](Self::WHOLE) for an empty range. + pub(super) fn bytes(bytes: Range) -> ImagePlace { + match bytes.is_empty() { + true => ImagePlace::WHOLE, + false => ImagePlace { + start: bytes.start, + end: bytes.end, + }, + } + } + + /// Its bytes, where it names some. + fn range(self) -> Option> { + (self != ImagePlace::WHOLE).then_some(self.start..self.end) + } + + /// Whether an image here and one at `other`, of the same key, may share memory: always, but + /// for two placed at bytes that do not meet. + pub(super) fn meets(self, other: ImagePlace) -> bool { + match (self.range(), other.range()) { + (Some(a), Some(b)) => meet(&a, &b), + _ => true, + } + } +} + impl UseRange { /// The range every untracked use of a command that may touch untracked memory its uses do /// not name takes inside an encoder, and every untracked use's in the class all of them @@ -176,12 +225,15 @@ impl UseRange { aspects, levels, layers, + .. } => aspects.is_empty() || levels.is_empty() || layers.is_empty(), } } - /// Whether the two ranges share memory. Ranges of different kinds on one key are taken to - /// share it, which is always correct. + /// Whether the two ranges share memory, as hazard tracking orders them. Ranges of different + /// kinds on one key are taken to share it, which is always correct. An image's place is not + /// read: a heap's images, one key, order as one resource, as Metal tracks a tracked heap + /// ([`ImagePlace`]). pub(super) fn overlaps(&self, other: &UseRange) -> bool { match (self, other) { (UseRange::Bytes(a), UseRange::Bytes(b)) => meet(a, b), @@ -190,17 +242,44 @@ impl UseRange { aspects: a, levels: a_levels, layers: a_layers, + .. }, UseRange::Image { aspects: b, levels: b_levels, layers: b_layers, + .. }, ) => a.intersects(*b) && meet(a_levels, b_levels) && meet(a_layers, b_layers), _ => true, } } + /// Whether the two ranges, of one key, touch the same memory: as [`overlaps`](Self::overlaps) + /// answers, but that an image placed in a heap ([`ImagePlace`]) meets a range of the heap's + /// bytes, or another image placed at other bytes, only where their bytes meet. Two uses of + /// one image (the same place) meet where their aspects, levels and layers do; an image whose + /// place is not known meets every range of another kind. + pub(super) fn shares_memory(&self, other: &UseRange) -> bool { + let place = |range: &UseRange| match range { + UseRange::Image { place, .. } => place.range(), + UseRange::Bytes(_) => None, + }; + match (self, other) { + (UseRange::Image { place: a, .. }, UseRange::Image { place: b, .. }) if a != b => { + match (a.range(), b.range()) { + (Some(a), Some(b)) => meet(&a, &b), + _ => self.overlaps(other), + } + } + (image @ UseRange::Image { .. }, UseRange::Bytes(bytes)) + | (UseRange::Bytes(bytes), image @ UseRange::Image { .. }) => { + place(image).is_none_or(|placed| meet(&placed, bytes)) + } + _ => self.overlaps(other), + } + } + /// Whether this range holds all of `other`. pub(super) fn contains(&self, other: &UseRange) -> bool { match (self, other) { @@ -210,11 +289,13 @@ impl UseRange { aspects: a, levels: a_levels, layers: a_layers, + .. }, UseRange::Image { aspects: b, levels: b_levels, layers: b_layers, + .. }, ) => a.contains(*b) && within(a_levels, b_levels) && within(a_layers, b_layers), _ => false, @@ -230,16 +311,23 @@ impl UseRange { aspects: a, levels: a_levels, layers: a_layers, + place: a_place, }, UseRange::Image { aspects: b, levels: b_levels, layers: b_layers, + place: b_place, }, ) => Some(UseRange::Image { aspects: *a | *b, levels: hull(a_levels, b_levels), layers: hull(a_layers, b_layers), + // Two images' hull is of no one place. + place: match a_place == b_place { + true => *a_place, + false => ImagePlace::WHOLE, + }, }), _ => None, } @@ -254,11 +342,18 @@ impl fmt::Debug for UseRange { aspects, levels, layers, - } => write!( - f, - "Image {{ aspects: {:#x}, levels: {levels:?}, layers: {layers:?} }}", - aspects.as_raw() - ), + place, + } => { + write!( + f, + "Image {{ aspects: {:#x}, levels: {levels:?}, layers: {layers:?}", + aspects.as_raw() + )?; + match place.range() { + Some(bytes) => write!(f, ", place: {bytes:?} }}"), + None => write!(f, " }}"), + } + } } } } diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index 24305c927..e966cab61 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -145,6 +145,7 @@ fixture hlf_half_buffer: metal: Apple metal version 32023.921 (metalfe-32023.921 fixture hlf_half_dims: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture hlf_half_forms: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture hnq_half_layer_composite: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) +fixture hpr_reads: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture hrd_half_read: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture hrd_half_widen: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture hsw_storage_writes: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.air.ll new file mode 100644 index 000000000..a8c2bfcc4 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.air.ll @@ -0,0 +1,101 @@ +; Generated by scripts/regen-air-fixtures from hpr_reads.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +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" + +%struct._texture_2d_t = type opaque +%struct._sampler_t = type opaque + +; Function Attrs: argmemonly mustprogress nofree norecurse nosync nounwind readonly willreturn +define <4 x float> @hpr_one(<4 x float> %0, <4 x float> %1, <4 x float> addrspace(1)* nocapture noundef readonly "air-buffer-no-alias" %2) local_unnamed_addr #0 { + %4 = load <4 x float>, <4 x float> addrspace(1)* %2, align 16, !tbaa !35, !alias.scope !38 + %5 = fadd fast <4 x float> %4, %1 + ret <4 x float> %5 +} + +; Function Attrs: argmemonly mustprogress nofree norecurse nosync nounwind readonly willreturn +define <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> @hpr_five(<4 x float> %0, <4 x float> %1, <4 x float> addrspace(1)* nocapture noundef readonly "air-buffer-no-alias" %2) local_unnamed_addr #0 { + %4 = load <4 x float>, <4 x float> addrspace(1)* %2, align 16, !tbaa !35, !alias.scope !41 + %5 = fadd fast <4 x float> %4, %1 + %6 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> undef, <4 x float> %5, 0 + %7 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %6, <4 x float> %1, 1 + %8 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %7, <4 x float> %1, 2 + %9 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %8, <4 x float> %1, 3 + %10 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %9, <4 x float> %1, 4 + ret <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %10 +} + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind willreturn +define <4 x float> @hpr_level1_write(<4 x float> %0, <2 x float> %1, %struct._texture_2d_t addrspace(1)* nocapture readonly %2, %struct._sampler_t addrspace(2)* nocapture readonly %3, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %4) local_unnamed_addr #1 { + %6 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %2, %struct._sampler_t addrspace(2)* nocapture readonly %3, <2 x float> %1, i1 true, <2 x i32> zeroinitializer, i1 true, float 1.000000e+00, float 0.000000e+00, i32 0) #3, !alias.scope !44, !noalias !48 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + store <4 x float> %7, <4 x float> addrspace(1)* %4, align 16, !tbaa !35, !alias.scope !48, !noalias !44 + ret <4 x float> %7 +} + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)* nocapture readonly, <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #2 + +attributes #0 = { argmemonly mustprogress nofree norecurse nosync nounwind readonly willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { argmemonly convergent mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { argmemonly convergent mustprogress nofree nounwind readonly willreturn } +attributes #3 = { argmemonly convergent nounwind readonly willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.fragment = !{!9, !16, !23} +!air.compile_options = !{!29, !30, !31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{<4 x float> (<4 x float>, <4 x float>, <4 x float> addrspace(1)*)* @hpr_one, !10, !12} +!10 = !{!11} +!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!12 = !{!13, !14, !15} +!13 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!14 = !{i32 1, !"air.fragment_input", !"generated(4tintDv4_f)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"tint"} +!15 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"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", !"b"} +!16 = !{<{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> (<4 x float>, <4 x float>, <4 x float> addrspace(1)*)* @hpr_five, !17, !12} +!17 = !{!18, !19, !20, !21, !22} +!18 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c0"} +!19 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c1"} +!20 = !{!"air.render_target", i32 2, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c2"} +!21 = !{!"air.render_target", i32 3, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c3"} +!22 = !{!"air.render_target", i32 4, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c4"} +!23 = !{<4 x float> (<4 x float>, <2 x float>, %struct._texture_2d_t addrspace(1)*, %struct._sampler_t addrspace(2)*, <4 x float> addrspace(1)*)* @hpr_level1_write, !10, !24} +!24 = !{!13, !25, !26, !27, !28} +!25 = !{i32 1, !"air.fragment_input", !"generated(2uvDv2_f)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"} +!26 = !{i32 2, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!27 = !{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} +!28 = !{i32 4, !"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", !"w"} +!29 = !{!"air.compile.denorms_disable"} +!30 = !{!"air.compile.fast_math_enable"} +!31 = !{!"air.compile.framebuffer_fetch_enable"} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36, !36, i64 0} +!36 = !{!"omnipotent char", !37, i64 0} +!37 = !{!"Simple C++ TBAA"} +!38 = !{!39} +!39 = distinct !{!39, !40, !"air-alias-scope-arg(2)"} +!40 = distinct !{!40, !"air-alias-scopes(hpr_one)"} +!41 = !{!42} +!42 = distinct !{!42, !43, !"air-alias-scope-arg(2)"} +!43 = distinct !{!43, !"air-alias-scopes(hpr_five)"} +!44 = !{!45, !47} +!45 = distinct !{!45, !46, !"air-alias-scope-textures"} +!46 = distinct !{!46, !"air-alias-scopes(hpr_level1_write)"} +!47 = distinct !{!47, !46, !"air-alias-scope-samplers"} +!48 = !{!49} +!49 = distinct !{!49, !46, !"air-alias-scope-arg(4)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.ll b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.ll new file mode 100644 index 000000000..851550642 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.ll @@ -0,0 +1,98 @@ +; Generated by scripts/regen-air-fixtures from hpr_reads.metal (llvm-dis of hpr_reads.air). Do not edit. +; ModuleID = '' +source_filename = "-" +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" + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read) +define <4 x float> @hpr_one(<4 x float> %0, <4 x float> %1, ptr addrspace(1) noundef readonly captures(none) "air-buffer-no-alias" %2) local_unnamed_addr #0 { + %4 = load <4 x float>, ptr addrspace(1) %2, align 16, !tbaa !35, !alias.scope !38 + %5 = fadd fast <4 x float> %4, %1 + ret <4 x float> %5 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read) +define <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> @hpr_five(<4 x float> %0, <4 x float> %1, ptr addrspace(1) noundef readonly captures(none) "air-buffer-no-alias" %2) local_unnamed_addr #0 { + %4 = load <4 x float>, ptr addrspace(1) %2, align 16, !tbaa !35, !alias.scope !41 + %5 = fadd fast <4 x float> %4, %1 + %6 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> undef, <4 x float> %5, 0 + %7 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %6, <4 x float> %1, 1 + %8 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %7, <4 x float> %1, 2 + %9 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %8, <4 x float> %1, 3 + %10 = insertvalue <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %9, <4 x float> %1, 4 + ret <{ <4 x float>, <4 x float>, <4 x float>, <4 x float>, <4 x float> }> %10 +} + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) +define <4 x float> @hpr_level1_write(<4 x float> %0, <2 x float> %1, ptr addrspace(1) readonly captures(none) %2, ptr addrspace(2) readonly captures(none) %3, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %4) local_unnamed_addr #1 { + %6 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %2, ptr addrspace(2) readonly captures(none) %3, <2 x float> %1, i1 true, <2 x i32> zeroinitializer, i1 true, float 1.000000e+00, float 0.000000e+00, i32 0) #3, !alias.scope !44, !noalias !48 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + store <4 x float> %7, ptr addrspace(1) %4, align 16, !tbaa !35, !alias.scope !48, !noalias !44 + ret <4 x float> %7 +} + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2) readonly captures(none), <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #2 + +attributes #0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { convergent mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #3 = { convergent nounwind willreturn memory(argmem: read) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.fragment = !{!9, !16, !23} +!air.compile_options = !{!29, !30, !31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @hpr_one, !10, !12} +!10 = !{!11} +!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!12 = !{!13, !14, !15} +!13 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!14 = !{i32 1, !"air.fragment_input", !"generated(4tintDv4_f)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"tint"} +!15 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"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", !"b"} +!16 = !{ptr @hpr_five, !17, !12} +!17 = !{!18, !19, !20, !21, !22} +!18 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c0"} +!19 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c1"} +!20 = !{!"air.render_target", i32 2, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c2"} +!21 = !{!"air.render_target", i32 3, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c3"} +!22 = !{!"air.render_target", i32 4, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"c4"} +!23 = !{ptr @hpr_level1_write, !10, !24} +!24 = !{!13, !25, !26, !27, !28} +!25 = !{i32 1, !"air.fragment_input", !"generated(2uvDv2_f)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"} +!26 = !{i32 2, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!27 = !{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} +!28 = !{i32 4, !"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", !"w"} +!29 = !{!"air.compile.denorms_disable"} +!30 = !{!"air.compile.fast_math_enable"} +!31 = !{!"air.compile.framebuffer_fetch_enable"} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36, !36, i64 0} +!36 = !{!"omnipotent char", !37, i64 0} +!37 = !{!"Simple C++ TBAA"} +!38 = !{!39} +!39 = distinct !{!39, !40, !"air-alias-scope-arg(2)"} +!40 = distinct !{!40, !"air-alias-scopes(hpr_one)"} +!41 = !{!42} +!42 = distinct !{!42, !43, !"air-alias-scope-arg(2)"} +!43 = distinct !{!43, !"air-alias-scopes(hpr_five)"} +!44 = !{!45, !47} +!45 = distinct !{!45, !46, !"air-alias-scope-textures"} +!46 = distinct !{!46, !"air-alias-scopes(hpr_level1_write)"} +!47 = distinct !{!47, !46, !"air-alias-scope-samplers"} +!48 = !{!49} +!49 = distinct !{!49, !46, !"air-alias-scope-arg(4)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.metal b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.metal new file mode 100644 index 000000000..37926d62c --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/hpr_reads.metal @@ -0,0 +1,44 @@ +// Owned fixture: fragment functions that read or write a device buffer, for draws whose buffer +// may lie in the heap of their pass's attachments. `hpr_one` writes `b[0]` plus the varying `tint` +// to color 0; `hpr_five` writes it to color 0 and `tint` to colors 1 to 4, a pass of more colors +// than a device at Vulkan's floor draws at once (four), which the translation draws in groups; +// their vertex function is `color_groups`' `cg_cover`, whose interface they read. +// `hpr_level1_write` samples texture 0 through sampler 0 at the explicit level 1, as +// `alv_levels`' `alv_level1` does, returns it and writes it to `w[0]`; its vertex function is +// `alv_rect`. Loop-free. +#include +using namespace metal; + +struct CgPoint { + float4 position [[position]]; + float4 tint; +}; + +fragment float4 hpr_one(CgPoint in [[stage_in]], const device float4 *b [[buffer(0)]]) { + return b[0] + in.tint; +} + +struct HprFive { + float4 c0 [[color(0)]]; + float4 c1 [[color(1)]]; + float4 c2 [[color(2)]]; + float4 c3 [[color(3)]]; + float4 c4 [[color(4)]]; +}; + +fragment HprFive hpr_five(CgPoint in [[stage_in]], const device float4 *b [[buffer(0)]]) { + float4 t = in.tint; + return HprFive { b[0] + t, t, t, t, t }; +} + +struct AlvOut { + float4 position [[position]]; + float2 uv; +}; + +fragment float4 hpr_level1_write(AlvOut in [[stage_in]], texture2d t [[texture(0)]], + sampler s [[sampler(0)]], device float4 *w [[buffer(0)]]) { + float4 c = t.sample(s, in.uv, level(1.0f)); + w[0] = c; + return c; +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 0ac1a1ae8..6ce10c1b1 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 = 522; /// 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 = 2256; +pub const RUNTIME_VERSION: u32 = 2257; /// 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 diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index b8c3e01ea..08626edf3 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -307,15 +307,17 @@ pub enum HeapCompressionPolicy { /// Metal's query is the device's own: the Macs answer alignments from 128 bytes (an M3 Max) to /// 4096 (an Intel UHD Graphics 630) and 65536 (an AMD Radeon Pro 5300M), and every driver measured /// off MoltenVK aligns its optimal images coarser than Apple's 128 (1024 bytes on an RTX 5080 -/// Laptop, 65536 for ANV's compressed images, up to 64 KiB on a Radeon 780M). The runtime's choice -/// alone: no emitted code changes. +/// Laptop, 65536 for ANV's compressed images, up to 64 KiB on a Radeon 780M, and on an RX 7900 XTX +/// 128 KiB for a depth image and 256 KiB for a 4-sample render target past 128 texels a side). +/// The runtime's choice alone: no emitted code changes. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum HeapAnswerPolicy { /// The larger of Metal's answer and the device's image of the texture's first route (the - /// default), for a single-sample texture whose image binds into the heap's memory, where that - /// image's alignment is at most 64 KiB (the largest a Mac answers) and at most 4 KiB or its + /// default), for a texture whose image binds into the heap's memory (a multisample one too, + /// its samples in the driver's layout), where that image's alignment is at most 256 KiB (the + /// alignment of a heap's memory, past which no image binds there) and at most 4 KiB or its /// answer's size, so a heap's padding at most doubles a texture's bytes past a page: the /// texture lies in that image, its compression kept as `HeapCompressionPolicy` says, with no /// image put in its place to fit Metal's answer and no shadow of Metal's tiles. Where that @@ -323,10 +325,9 @@ pub enum HeapAnswerPolicy { /// optimal image of host-transfer usage, else its linear one) lies there in its place, the /// answer that image's. A `Shared` texture's answer also holds the linear image a heap over /// host pages binds there. A texture whose answer Metal measures apart from its image (4:2:2, - /// one-plane YCbCr, two-plane extended-range, `X32_Stencil8`, `BlockWritesOnly`), a - /// multisample one, one whose image lies in memory of its own and every other texture take - /// Metal's answer as under `Metal`. Announced `heap-texture-larger-than-metal` where the - /// answer is past Metal's. + /// one-plane YCbCr, two-plane extended-range, `X32_Stencil8`, `BlockWritesOnly`), one whose + /// image lies in memory of its own and every other texture take Metal's answer as under + /// `Metal`. Announced `heap-texture-larger-than-metal` where the answer is past Metal's. #[default] Device, /// Metal's answer wherever the runtime models it: a texture whose image needs more takes an diff --git a/docs/API.md b/docs/API.md index ecba8a392..007d91e2e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3573,8 +3573,8 @@ bound. - `metal2vulkan-degrade-heap-texture-larger-than-metal` (precision). `HeapTextureLargerThanMetal`: A heap texture sized or made (`heap_texture_size_and_align`, `Heap::new_texture`) whose images on the device need more bytes or a coarser alignment than Metal's answer, which the runtime models: under - the default `HeapAnswerPolicy::Device`, a single-sample texture whose image binds into the heap's - memory, which lies in that image; under `HeapAnswerPolicy::Metal`, one that no shadow of its bytes + the default `HeapAnswerPolicy::Device`, a texture whose image binds into the heap's memory, which + lies in that image; under `HeapAnswerPolicy::Metal`, one that no shadow of its bytes holds to Metal's answer: not a multisample texture, whose image lies in memory of its own, nor one whose planes or Metal's tiles fit its bytes. The answer is then the larger of the two, since no image binds at Metal's offsets. Every other such texture answers Metal's numbers and announces @@ -5434,11 +5434,12 @@ each item named states the rule in full. - **A heap texture answers Metal's size and alignment where the device's image fits them, else the device's** (`Device::heap_texture_size_and_align`, `DevicePolicy::heap_answers`). Under the - default `HeapAnswerPolicy::Device`, a single-sample texture whose image binds into the heap's - memory and needs more than Metal's answer answers the larger of the two and lies in that image: - no image is put in its place and no shadow holds it. The alignment it takes is at most 64 KiB - (an AMD Radeon Pro 5300M's answer on a Mac), and at most 4 KiB or its own size; where its image - asks more, its image that a 4 KiB alignment holds (host-transfer usage, else linear) takes its + default `HeapAnswerPolicy::Device`, a texture whose image binds into the heap's memory (a + multisample one too) and needs more than Metal's answer answers the larger of the two and lies + in that image: no image is put in its place and no shadow holds it. The alignment it takes is + the device's (on an RX 7900 XTX, 256 KiB for a 4-sample render target past 128 texels a side), at most a + heap's memory's own, 256 KiB, past which no image binds there, and at most 4 KiB or its own + size; where its image asks more, its image that a 4 KiB alignment holds (host-transfer usage, else linear) takes its place. A `Shared` texture's answer also holds the linear image a heap over host pages binds. Under `HeapAnswerPolicy::Metal` (in `exact_answers`), the answer is Metal's: an image that fits it takes the place of one that does not, else a shadow of the heap's bytes holds the texture diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 7c12ae822..847747b0a 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -34,7 +34,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X |---|---|---|---|---| | A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass and a multisampled one (an extended-range color's shadow holds per sample, from the pass's clear). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's | | A heap's colour texture that Metal keeps losslessly compressed (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, 16 texels or more a side), on a driver whose compressed images may keep their texels apart from the memory they are bound to (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), is the driver's compressed optimal image, its compression and fast clears kept. A texture Metal keeps uncompressed takes the uncompressed image under either value. The runtime's choice: no pipeline differs. | `heap_compression = HeapCompressionPolicy::Compressed` | `heap_compression = HeapCompressionPolicy::Uncompressed`: an image the driver keeps uncompressed in the heap's bytes, as for a texture Metal keeps uncompressed: host-transfer usage where the device enabled `hostImageCopy` (`heap-texture-host-transfer`), else a linear image (`heap-texture-linear`), else the optimal one (`heap-texture-hides-aliased-writes`) | A write through a buffer or another texture over the texture's bytes may leave its texels as they were or change them otherwise than as written, where Metal's texture reads opaque magenta (`0xffff00ff`) in every texel of drawn content the write covers and the written bytes where it held only a clear; the texture's own writes may show in those bytes compressed. Within Metal's contract: Metal documents such a texture's layout as its own (`allowGPUOptimizedContents` lets it "adjust the private layout"), so no write through another view over its bytes has a defined result there either. `HeapTextureCompressed` (`heap-texture-compressed`), announced once per device where such a texture is made; `runtime_lane::heap_textures` | ANV (Iris Xe of RPL-P; `heap_textures::heap_compression_costs`), a 2048x2048 `RGBA8Unorm` render target in a `Private` placement heap: a pass that clears it 26.9 us against 676.2-676.5 us; a copy into another such texture 647.7-649.1 us against 673.9-693.2 us. The compressed image lies in the heap only where the heap's answer holds it (`heap_answers = HeapAnswerPolicy::Device`, the next row). This 2048x2048 texture's does not under either answer policy, so it takes the linear image under either compression value: a clear 963.5 us against 958.4 us under `heap_answers = HeapAnswerPolicy::Metal`, 955.3 us against 971.4 us under the default, the copy 488-496 us | -| A heap texture whose image of the route the device takes for it needs more bytes or a coarser alignment of the heap than Metal's answer (each of a guest compositor's 22 heap shapes, `RGBA16Float` 2D arrays of one slice and 2D textures to 456x255: on ANV, whose compressed images align to 64 KiB; on the RTX 3090 at 1024; on the RX 7900 XTX at 256 to 64 KiB, where Metal answers 128 for each but the 299x299 array's 16 KiB): the size query (`heapTextureSizeAndAlign`) answers the larger of Metal's answer and that image's, and the texture lies in that image in the heap's bytes. A `Shared` texture's answer also holds the linear image a heap over host pages binds for it. Where that image's alignment is past 64 KiB, or past both 4 KiB and the texture's size, the texture's image that a 4 KiB alignment holds takes its place (host-transfer usage, else linear), the answer that one's; else Metal's answer, as under the switch. Metal's measured answers (4:2:2, one-plane YCbCr, two-plane extended-range, `X32_Stencil8`, `BlockWritesOnly` textures), multisample textures and textures whose image lies in memory of its own keep Metal's answer. The runtime's choice: no pipeline differs. | `heap_answers = HeapAnswerPolicy::Device` | `heap_answers = HeapAnswerPolicy::Metal`: Metal's answer; the texture lies in an image that fits it (host-transfer usage, else linear: `heap-texture-host-transfer`, `heap-texture-linear`), else is a shadow of the heap's bytes in Metal's tiles, copied in before and out after the commands that use it (`shadowed-texture`) | A heap holds fewer such textures than Metal's: of the 22 shapes, the small arrays answer 4096 bytes where Metal answers 128 to 2176 (on ANV and the XTX; the XTX's 1x1 answers 256), and the 22 answers take 3769962 bytes of heaps placed one after another on ANV and 4155498 on the XTX, against Metal's 3656426 (`heap_texture_images`, `HEAP-COUNT`). A program that places a heap's resources by sizes of its own rather than the query's may overlap the texture with its neighbour; Metal's answer differs by GPU too (65536 on an AMD Radeon Pro 5300M, 4096 on an Intel UHD 630, 128 on an M3). `HeapTextureLargerThanMetal` (`heap-texture-larger-than-metal`), announced once per device; `tests::heap`, `heap_shadow_costs::heap_texture_images` | Of the 22 shapes made in heaps under the switch (`heap_texture_images`), on ANV (Iris Xe of RPL-P) 14 lie in an image put in place of their first one and 7 are shadows in Metal's tiles; on the RX 7900 XTX (RADV) 1 and 8, every other answer Metal's; under the default none on either. ANV (`heap_shadow_costs::heap_texture_shadow_costs`), a 1x1 `RGBA16Float` array held as a shadow: a frame that clears it and blits it 34.7 us in the heap against 8.2 us outside | +| A heap texture whose image of the route the device takes for it needs more bytes or a coarser alignment of the heap than Metal's answer (each of a guest compositor's 22 heap shapes, `RGBA16Float` 2D arrays of one slice and 2D textures to 456x255: on ANV, whose compressed images align to 64 KiB; on the RTX 3090 at 1024; on the RX 7900 XTX at 256 to 64 KiB, where Metal answers 128 for each but the 299x299 array's 16 KiB): the size query (`heapTextureSizeAndAlign`) answers the larger of Metal's answer and that image's, and the texture lies in that image in the heap's bytes. A `Shared` texture's answer also holds the linear image a heap over host pages binds for it. Its alignment is the device's up to a heap's memory's own, 256 KiB, past which no image binds there (on the RX 7900 XTX, 128 KiB for a depth image and 256 KiB for a 4-sample render target past 128 texels a side). Where that image's alignment is past 256 KiB, or past both 4 KiB and the texture's size, the texture's image that a 4 KiB alignment holds takes its place (host-transfer usage, else linear), the answer that one's; else Metal's answer, as under the switch. A multisample texture takes it too and lies in its image in the heap's bytes, in the driver's layout of its samples, where under the switch it is a shadow of its samples in Metal's tiles (`heap_placed_targets`: a frame's 4-sample `RGBA16Float` and `Depth32Float` targets placed in a tracked `Private` heap). Metal's measured answers (4:2:2, one-plane YCbCr, two-plane extended-range, `X32_Stencil8`, `BlockWritesOnly` textures) and textures whose image lies in memory of its own keep Metal's answer. The runtime's choice: no pipeline differs. | `heap_answers = HeapAnswerPolicy::Device` | `heap_answers = HeapAnswerPolicy::Metal`: Metal's answer; the texture lies in an image that fits it (host-transfer usage, else linear: `heap-texture-host-transfer`, `heap-texture-linear`), else is a shadow of the heap's bytes in Metal's tiles, copied in before and out after the commands that use it (`shadowed-texture`) | A heap holds fewer such textures than Metal's: of the 22 shapes, the small arrays answer 4096 bytes where Metal answers 128 to 2176 (on ANV and the XTX; the XTX's 1x1 answers 256), and the 22 answers take 3769962 bytes of heaps placed one after another on ANV and 4155498 on the XTX, against Metal's 3656426 (`heap_texture_images`, `HEAP-COUNT`). A program that places a heap's resources by sizes of its own rather than the query's may overlap the texture with its neighbour; Metal's answer differs by GPU too (65536 on an AMD Radeon Pro 5300M, 4096 on an Intel UHD 630, 128 on an M3). `HeapTextureLargerThanMetal` (`heap-texture-larger-than-metal`), announced once per device; `tests::heap`, `tests::heap_placed_targets`, `heap_shadow_costs::heap_texture_images` | Of the 22 shapes made in heaps under the switch (`heap_texture_images`), on ANV (Iris Xe of RPL-P) 14 lie in an image put in place of their first one and 7 are shadows in Metal's tiles; on the RX 7900 XTX (RADV) 1 and 8, every other answer Metal's; under the default none on either. ANV (`heap_shadow_costs::heap_texture_shadow_costs`), a 1x1 `RGBA16Float` array held as a shadow: a frame that clears it and blits it 34.7 us in the heap against 8.2 us outside | | Batches of command buffers committed on one queue that the scheduler finds ready together (a backlog) go to the driver in one `vkQueueSubmit`, at most four, only the last signalling the queue's timeline, on a device whose own check finds a submission that signals nothing merged into the next (`submit_check.rs`, once per driver, release and kernel: one `vkQueueSubmit` of four empty infos against four calls of one, merged where the one costs at most 0.6 of the four; Mesa 26.2.6's RADV on the Radeon 780M, the RX 7900 XTX and the RX 550 at 0.33-0.38, ANV on the Iris Xe of RPL-P at 0.39, MoltenVK 1.4.2 on the M3 Max at 0.98; a device whose check has not answered, or that does not merge, takes the ungrouped form under either value of the switch): one kernel submission, where ANV on i915 lists every `VkDeviceMemory` in each (the consumer's guest drag on the Iris Xe: about 300 entries per execbuffer, 260 of them its host imports, at 112 to 128 execbuffers a frame). A batch's event signals ride to the group's end, which signals each event's semaphore to the highest index the batches held signal it to (an event's indices rise in commit order). A batch that signals a binary semaphore, takes a fence, binds a sparse update, does first work, names the caller's wrapped image, or waits for anything not seen complete (an event, another queue's work) goes alone, after the batches held: a batch with a wait leads a group, never joins one. So that checked command buffers (the consumer checks each) are found ready together, the submission checks of up to three batches right behind a line's head that goes run with the head's, in commit order, none committed after another queue's batch: such a check runs before the previous batch's `vkQueueSubmit` rather than after it, in the scheduler pass that submits its own batch. A pass that finds no batch ready sends the batches held, unless two or more earlier submissions of their `VkQueue` are not seen complete: the GPU runs those first in any case, so the batches stay held, and those committed meanwhile join them, until one submission is left in flight (a completion turn wakes the scheduler at its value), the group fills, a later batch sends it, a head waits for the GPU, or a thread waits for one of their command buffers' completion, which sends them at once; nor are they kept where the scheduler's thread runs next a submission handler of another queue's command buffer: they go first, as Metal schedules a queue's command buffers whatever another queue's handler does (an M3 Max, probe `cross_queue_handler_waits`); a batch that ends a command buffer with a switch of storage forms riding on it, which settles by its submission's outcome, is never kept so. A batch a committing thread submits (`CommandBuffer::commit_and_submit`) goes alone where its `VkQueue` runs at most one earlier submission not seen complete, as the pass that held it would send the group at once; where two or more run it is left to the scheduler's thread, which holds it. A held batch that ends its command buffer is `Scheduled` as it is held, its submission handlers run first, then its scheduled handlers, and its kernel end time set, as an M3 Max schedules a command buffer committed behind running work 0.04 to 0.18 ms after its commit. The runtime's: no pipeline differs. | `completion = CompletionPolicy::Grouped` | `completion = CompletionPolicy::Exact`: one submission per batch, each signalling its own values; each line's head checked alone | Each command buffer of a submission but the last is seen complete (status, completed handlers, waits), and the event values it signals are reached (by the GPU waits on other queues, the host's waits, value reads and listeners), once the last completed: late by the GPU time of at most three later batches (about 0.1 to 0.2 ms each in the consumer's compositor frames on the Iris Xe; about 20 ms behind a 20 ms batch), never early, in commit order. Metal's contract states no bound on when completion is seen (an M3 Max reports a command buffer complete, its handlers, status, waits and event listeners alike, 0.04 to 0.10 ms after its GPU end), and no member but the first waits, so no wait holds a member back: a valid program sees only later completion, as of slower GPU work. A batch kept while earlier work runs is seen complete within the same bound, and, where the one submission left in flight ends before its group reaches the GPU, late besides by that gap: at most a completion turn's reaction and the group's `vkQueueSubmit`. Commands, barriers and GPU times are unchanged. `GroupedCompletion` (`grouped-completion`), announced once per device at its first such submission; `runtime_lane::grouped_submissions` | ANV (Iris Xe of RPL-P; `frame_costs::frame_costs_over_imports`, the checked device, 67 command buffers a frame, GPU at 467-783 MHz), with 520 host imports live, where the Exact form's submissions fall behind the commits as the guest's do: 32.0-33.2 kernel submissions a frame against 67.0, 3.4-3.5 ms of execbuffer ioctl a frame against 6.9-7.9 ms, the scheduler thread's CPU 61-63 us a command buffer against 121-136 us, a frame through completion 4.7-5.9 ms against 8.6-9.7 ms; in the guest's shape with 520 (a second queue taking every 20th command buffer, each signalling a shared event, every 10th waiting for one): 26.2-26.7 kernel submissions a frame against 67.0, 2.8 ms of ioctl a frame against 6.9-7.0 ms, the scheduler 52-53 us a command buffer against 122-123 us, a frame through completion 6.0 ms against 8.7 ms; with 260, where it keeps up, 64.9-66.3 kernel submissions a frame against 67.0, the CPU and wall times alike. The cost (`grouped_submissions::grouped_completion_delays`, 8 command buffers of 0.3-0.5 ms of GPU work ready together): the host saw each but a group's last complete later by the later ones' GPU time, the last 0.1-0.3 ms later than alone (the completion turn's per-command-buffer work for the group, done at its end). Keeping a group while earlier work runs (UHD 770 of RPL-S, ANV, the guest's shape with 520 host imports, a submission handler on every command buffer and a 16 MiB fill ahead of each, about 1.3 ms of GPU each; the kept form against the batches sent as found): committed every 1 ms, 18.1-18.2 groups kept a frame, 24.9-25.0 kernel submissions a frame against 57.9, 2.18-2.90 ms of execbuffer ioctl a frame against 4.64-5.43 ms, the scheduler thread's CPU 67-82 us a command buffer against 113-118 us, the GPU idle within a frame's span 0.61 ms against 0.68-0.69 ms, a frame through completion 89.5-89.6 ms alike, completion seen later (GPU end to completed handler: mean 1.82-1.86 ms against 0.43-0.46 ms, p50 1.57-1.60 against 0.11-0.13, p99 4.35-4.37 against 4.09-4.11, max 4.52-4.55 against 4.18-4.23); committed at once, 18.0 kernel submissions a frame against 23.4; with no fill, 18.0 against 20.6, the GPU idle 0.59 ms against 0.58-0.66 ms. In the consumer's guest drag on the Iris Xe (i9-13900H; three passes each way): 24.4-27.5 kernel submissions a frame against 42.4-43.8, the scheduler thread 0.4-1.7 ms of CPU a frame less, 15.7-17.3 frames a second against 16.4-17.6: the frame rate alike within noise, as the scheduler thread does not bound that frame. A batch a committing thread submits alone (RADV, Mesa 26.2.6, RX 7900 XTX, whose check finds submissions merged; two rounds each against the form that left every batch that may wait in a group to the scheduler's thread, `tests::completion_latency`): a checked fill's `commit_and_submit` to its submission handler p50 30.4-32.8 us, p90 32.3-35.9, p99 48.8-57.8 against 36.2-55.7, 56.4-176.3 and 112.1-198.5, the call returning after its submission (32-34 us against 4-8); committed 2 ms apart between two shapes of `commit`, its commit to submission p50 31.9-36.1 us, p90 102.6-135.7 against 39.2-50.1 and 152.1-169.7, and the `commit`s beside it alike (p50 32.1-47.3 us against 38.9-46.7, the scheduler thread's wake p50 4.0-4.5 us against 4.1), as the committing thread wakes that thread after a batch it submitted alone, as the batch's hand-off to it would have. On lavapipe, whose check finds no merge, the two forms alike, the scheduler's thread woken alike (a checked fill's p50 12.5-13.4 us against 12.4-13.4). | | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps (not the host's view of how long it ran as its `VkQueue`'s oldest, which also holds its wait for the GPU to start it and the waiter's lateness to see it complete), or held its `VkQueue` for over 2 ms from the submission of a batch that waited on the GPU for another `VkQueue`'s work (an `MTLEvent`'s signal, the tracker's wait, new resources' first work) to its own GPU end, is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Under either value, as a queue is made, it takes the round robin's `VkQueue` the fewest live command queues hold, of those no unshared queue holds, in turn among equals, and an unshared queue one no command queue holds where one is free (one pass over the `VkQueue`s' counts; one that finds none shares the one the fewest hold, `WorkCounts::unshared_queues_sharing_a_vk_queue`). Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation; so does every queue of a device whose command buffers write no GPU timestamps it reads (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's), which does not share and is counted (`WorkCounts::queue_sharing_untimed`). The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation (the fewest live queues' as above), and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 26.4 to 30.1 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in those 6 runs (at most 5.6 to 9.7 ms); with 2 ms of draws between long command buffers, none over 10 ms in 3 runs (at most 5.7 to 9.8 ms) against 7, 0 and 0 under `PerQueue` (at most 6.9 to 11.2 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.4k to 28.0k (5 runs each); 8 threads with 1 in flight 47.0k to 50.1k against 13.9k to 14.3k (5); 2 threads with 3 in flight 28.0k to 53.7k against 21.4k to 28.0k (10 each, in turn, the default above `PerQueue` in each pair; no thread's queue marked long), and beside another process's 30 ms command buffers 5.1k to 6.7k against 4.0k to 4.1k (3 each; the host's view marked a thread's queue long in 1 of 3 runs, which then ran at `PerQueue`'s 4.1k); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms |