diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index e5fb5b0fa..ccce44187 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -96,6 +96,10 @@ pub(crate) struct AtBindViews { slots: [AtomicU64; VIEW_STAGES.len()], /// The device's view base alignment (`BindState::view_base_alignment_of`). alignment: u32, + /// Whether the device reads every uniform view at its residual + /// (`pipeline::reads_views_at_bind`), which a bind state states + /// (`BindState::uniform_views_at_residual`). + at_residual: bool, /// The slots of its tables the state's bind state holds ([`ReadSlots`]). read: ReadSlots, } @@ -116,6 +120,7 @@ impl AtBindViews { AtBindViews { slots: VIEW_STAGES.map(|stage| AtomicU64::new(interface.uniform_view_buffers(stage))), alignment: BindState::view_base_alignment_of(limits), + at_residual: !crate::pipeline::reads_views_at_bind(device), read, } } @@ -133,6 +138,14 @@ impl AtBindViews { self.alignment } + /// Whether the device reads every uniform view at its residual, which a bind state states + /// (`BindState::uniform_views_at_residual`): every key its draws and dispatches take is then + /// its residual form (`RenderVariant::plan`, `Variant::keyed_regions`), so instantiation may + /// bind a uniform view over a range its bind offsets share. + pub(crate) fn at_residual(&self) -> bool { + self.at_residual + } + /// Whether `stage`'s slots are `slots` (none for a stage it does not keep): a table read under /// them that binds the same offsets leaves the same out ([`ArgumentTable::at_bind_views`]), /// as it left out its own as it was read. diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 9f8503264..c53c3c0cf 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1867,6 +1867,7 @@ impl DispatchTables<'_> { let mut state = BindState::default(); state.stages.insert(Stage::Kernel, table); state.view_base_alignment = views.alignment(); + state.uniform_views_at_residual = views.at_residual(); if self.pipeline.imageblock_cell_bytes().is_some() { state.imageblock_size = self.imageblock; } diff --git a/crates/metal2vulkan-runtime/src/compute/live.rs b/crates/metal2vulkan-runtime/src/compute/live.rs index 11be46e3e..15f342e33 100644 --- a/crates/metal2vulkan-runtime/src/compute/live.rs +++ b/crates/metal2vulkan-runtime/src/compute/live.rs @@ -193,6 +193,7 @@ impl LiveDispatch { let views = pipeline.at_bind_views(); let state = &mut self.state; reshape.field(&mut state.view_base_alignment, views.alignment()); + state.uniform_views_at_residual = views.at_residual(); let moved = crate::buffer::host_cells_moved(); let same = self.read_from.reads(pipeline, maps, moved); // The state's used resources are what the encoder made resident still where the residency diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 21004477f..5aa3be8af 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -6865,6 +6865,7 @@ impl RenderLowering { let state = &mut live.state; let views = pipeline.at_bind_views(); reshape.field(&mut state.view_base_alignment, views.alignment()); + state.uniform_views_at_residual = views.at_residual(); let tables = [ (Stage::Vertex, pass_start.or(Stage::Vertex, &self.vertex)), (Stage::Fragment, &self.fragment), diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index 65485b950..87566185c 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -852,6 +852,7 @@ impl RenderLowering { let mut bind = BindState::default(); bind.stages.insert(Stage::Kernel, stage_table.clone()); bind.view_base_alignment = views.alignment(); + bind.uniform_views_at_residual = views.at_residual(); bind.imageblock_size = ImageblockSize::new(tile[0], tile[1]); bind.render_area = area; // The planner refuses a layered pass's dispatch (`NotImplemented(TileShading)`). diff --git a/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs b/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs index 02848ffa5..a073f9a6b 100644 --- a/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs +++ b/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs @@ -15,7 +15,8 @@ //! //! A device test: 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 those of the owned -//! fixture `validation/fixtures/public/engine/ubo_bind_offsets.ll` (`llvm-as`). +//! fixture `validation/fixtures/public/engine/ubo_bind_offsets.ll` (`llvm-as`), and, for draws +//! moved along a buffer, of `cof_offsets.ll` beside it. use super::blit_holds::{device, Scratch, WAIT}; use crate::{ @@ -379,6 +380,152 @@ fn constants_bound_at_moving_offsets_keep_one_shape() { ); } +/// The render state of the owned fixture `cof_offsets.metal` that `runtime_lane::constant_offsets` +/// draws: a triangle placed by the vertex function's constant reference `q` at buffer 0 (corner +/// `q.xy`, legs `q.zw`), in the colour of the fragment function's constant reference at buffer 0, +/// one `RGBA8Unorm` target. +fn moved_state(device: &Device) -> RenderPipelineState { + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/engine/cof_offsets.ll"); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); + let library = device.new_library_with_compile_library(library); + let vertex = library.new_function_with_name("cof_constant").unwrap(); + let fragment = library.new_function_with_name("cof_flat").unwrap(); + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); + descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A vertex constant slot moved along one buffer draw by draw in one encoder, with no other call +/// between draws (the shape `runtime_lane::constant_offsets` measures), on a device that reads +/// every uniform view at its residual (`pipeline::reads_views_at_bind`), binds one descriptor +/// range at every offset (`BindState::uniform_views_at_residual`, +/// `bind::instantiate::shared_range`): each draw is moved (`WorkCounts::draws_moved`), and where +/// its set 0 is pushed it pushes no write of it, only the slot's residual; each reads its own +/// bytes, a triangle over its own pixel alone, so every pixel takes the fragment constant's colour +/// once each draw read its own. A first pass through the offsets settles the slot's shape; the +/// second is counted (in a build with debug assertions every second draw again takes every step, +/// `render/draw_again.rs`). Where the range started at the bind offset, every draw of it pushed +/// set 0 again. +#[test] +fn constants_moved_along_one_buffer_keep_their_set_zero() { + let scratch = Scratch::new("uniform-moved-set-zero"); + let device = device(&scratch.0); + if crate::pipeline::reads_views_at_bind(&device) { + eprintln!("SKIPPED: the device reads uniform views at their bind offsets"); + return; + } + let queue = device.new_command_queue().unwrap(); + let state = moved_state(&device); + // Draw `p`'s triangle at byte 256 p, its corner 1/8 below and left of its pixel's centre in + // normalized device coordinates (a pixel is 2 / SIDE wide, y up), its legs 1/2 long: it covers + // that centre (1/8 + 1/8 from the corner) and no other (each 2 / SIDE away). The colour: codes + // 9, 99, 199 and 255, each `code / 255`. + let pixels = SIDE * SIDE; + let floats = |values: [f32; 4]| values.map(f32::to_le_bytes).concat(); + let mut places = vec![0u8; (256 * pixels) as usize]; + for p in 0..pixels { + let side = SIDE as f32; + let x = -1.0 + (2 * (p % SIDE) + 1) as f32 / side; + let y = 1.0 - (2 * (p / SIDE) + 1) as f32 / side; + let at = (256 * p) as usize; + places[at..at + 16].copy_from_slice(&floats([x - 0.125, y - 0.125, 0.5, 0.5])); + } + let codes = [9u8, 99, 199, 255]; + let colour = floats(codes.map(|code| f32::from(code) / 255.0)); + let shared = ResourceOptions::shared(); + let places = device.new_buffer_with_bytes(&places, shared).unwrap(); + let per = SIDE * SIDE * 4; + let (pass, target) = pass(&device); + let back = device.new_buffer(per, shared).unwrap(); + 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_bytes(&colour, 0).unwrap(); + let mut counts = Vec::new(); + for _ in 0..2 { + counts.push(device.work_counts()); + for p in 0..pixels { + encoder + .set_vertex_buffer(Some(&places), 256 * p, 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + } + } + counts.push(device.work_counts()); + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &back, + 0, + SIDE * 4, + per, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + for (p, pixel) in bytes_of(&back).chunks(4).enumerate() { + assert_eq!(pixel, codes, "pixel {p}"); + } + let (second, after) = (&counts[1], &counts[2]); + if after.draws_pushing_set_zero > second.draws_pushing_set_zero { + assert_eq!( + after.set_zero_writes_pushed - second.set_zero_writes_pushed, + 0, + "set-0 writes pushed on the second pass" + ); + } + // What the second pass's draws did besides, where some were not moved. + let besides = |c: &crate::WorkCounts| { + [ + ("rebound", c.draws_rebound), + ("as before", c.draws_as_before), + ("unkept", c.draws_unkept), + ("unlike kept", c.draws_unlike_kept), + ("none kept", c.draws_none_kept), + ("rebind stopped", c.draws_rebind_stopped), + ( + "stopped reshaped", + c.draws_rebind_stopped_arguments_reshaped, + ), + ( + "stopped unsettled", + c.draws_rebind_stopped_arguments_unsettled, + ), + ("stopped slots", c.draws_rebind_stopped_arguments_slots), + ("stopped other", c.draws_rebind_stopped_arguments_other), + ("reshaped by offset", c.draws_rebind_reshaped_buffer_offset), + ("settled", c.draws_settled), + ] + }; + let deltas: Vec<_> = (besides(after).into_iter().zip(besides(second))) + .map(|((name, a), (_, b))| (name, a - b)) + .filter(|&(_, delta)| delta > 0) + .collect(); + // Every draw of the second pass draws its kept draw again, moved, but every second one from + // the first, which takes every step in a build with debug assertions. + assert_eq!( + after.draws_moved - second.draws_moved, + super::draw_again::drawn_alone(pixels), + "draws moved on the second pass; besides: {deltas:?}" + ); +} + /// A state's creation makes its predicted key's residual form, each slot read at its residual /// (`pipeline/render/residual.rs`). With the device's pool held, so that a draw waiting for a /// making there could not complete, a draw binding both slots at offset 0, which every device's diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index e966cab61..ac459fa84 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -41,6 +41,7 @@ fixture cfb_tile_shadows: metal: Apple metal version 32023.921 (metalfe-32023.92 fixture cfit_fragment_tile_memory: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture cfit_tile_imageblock: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture cfit_tile_memory: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture cof_offsets: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture color_groups: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture color_groups_fetch: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture compute_thread_limit: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.air.ll new file mode 100644 index 000000000..e38397917 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.air.ll @@ -0,0 +1,107 @@ +; Generated by scripts/regen-air-fixtures from cof_offsets.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" + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x float> }> @cof_constant(i32 noundef %0, <4 x float> addrspace(2)* nocapture noundef readonly align 16 dereferenceable(16) "air-buffer-no-alias" %1) local_unnamed_addr #0 { + %3 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !alias.scope !31 + %4 = shufflevector <4 x float> %3, <4 x float> poison, <2 x i32> + %5 = icmp eq i32 %0, 1 + %6 = select fast i1 %5, float 1.000000e+00, float 0.000000e+00 + %7 = insertelement <2 x float> undef, float %6, i64 0 + %8 = icmp eq i32 %0, 2 + %9 = select fast i1 %8, float 1.000000e+00, float 0.000000e+00 + %10 = insertelement <2 x float> %7, float %9, i64 1 + %11 = shufflevector <4 x float> %3, <4 x float> poison, <2 x i32> + %12 = fmul fast <2 x float> %11, %10 + %13 = fadd fast <2 x float> %12, %4 + %14 = shufflevector <2 x float> %13, <2 x float> poison, <4 x i32> + %15 = shufflevector <4 x float> %14, <4 x float> , <4 x i32> + %16 = insertvalue <{ <4 x float> }> undef, <4 x float> %15, 0 + ret <{ <4 x float> }> %16 +} + +; Function Attrs: argmemonly mustprogress nofree norecurse nosync nounwind readonly willreturn +define <{ <4 x float> }> @cof_device(i32 noundef %0, i32 noundef %1, <4 x float> addrspace(1)* nocapture noundef readonly "air-buffer-no-alias" %2) local_unnamed_addr #1 { + %4 = zext i32 %1 to i64 + %5 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %2, i64 %4 + %6 = load <4 x float>, <4 x float> addrspace(1)* %5, align 16, !tbaa !34, !alias.scope !37 + %7 = shufflevector <4 x float> %6, <4 x float> poison, <2 x i32> + %8 = icmp eq i32 %0, 1 + %9 = select fast i1 %8, float 1.000000e+00, float 0.000000e+00 + %10 = insertelement <2 x float> undef, float %9, i64 0 + %11 = icmp eq i32 %0, 2 + %12 = select fast i1 %11, float 1.000000e+00, float 0.000000e+00 + %13 = insertelement <2 x float> %10, float %12, i64 1 + %14 = shufflevector <4 x float> %6, <4 x float> poison, <2 x i32> + %15 = fmul fast <2 x float> %14, %13 + %16 = fadd fast <2 x float> %15, %7 + %17 = shufflevector <2 x float> %16, <2 x float> poison, <4 x i32> + %18 = shufflevector <4 x float> %17, <4 x float> , <4 x i32> + %19 = insertvalue <{ <4 x float> }> undef, <4 x float> %18, 0 + ret <{ <4 x float> }> %19 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x float> @cof_flat(<4 x float> %0, <4 x float> addrspace(2)* nocapture noundef readonly align 16 dereferenceable(16) "air-buffer-no-alias" %1) local_unnamed_addr #2 { + %3 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !34, !alias.scope !40 + ret <4 x float> %3 +} + +attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "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 mustprogress nofree norecurse nosync nounwind readonly willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "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 = { mustprogress nofree norecurse nosync nounwind readnone 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" } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !15} +!air.fragment = !{!19} +!air.compile_options = !{!25, !26, !27} +!llvm.ident = !{!28} +!air.version = !{!29} +!air.language_version = !{!30} + +!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> }> (i32, <4 x float> addrspace(2)*)* @cof_constant, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13, !14} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} +!14 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"q"} +!15 = !{<{ <4 x float> }> (i32, i32, <4 x float> addrspace(1)*)* @cof_device, !10, !16} +!16 = !{!13, !17, !18} +!17 = !{i32 1, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"} +!18 = !{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", !"q"} +!19 = !{<4 x float> (<4 x float>, <4 x float> addrspace(2)*)* @cof_flat, !20, !22} +!20 = !{!21} +!21 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!22 = !{!23, !24} +!23 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!24 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"} +!25 = !{!"air.compile.denorms_disable"} +!26 = !{!"air.compile.fast_math_enable"} +!27 = !{!"air.compile.framebuffer_fetch_enable"} +!28 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!29 = !{i32 2, i32 8, i32 0} +!30 = !{!"Metal", i32 4, i32 0, i32 0} +!31 = !{!32} +!32 = distinct !{!32, !33, !"air-alias-scope-arg(1)"} +!33 = distinct !{!33, !"air-alias-scopes(cof_constant)"} +!34 = !{!35, !35, i64 0} +!35 = !{!"omnipotent char", !36, i64 0} +!36 = !{!"Simple C++ TBAA"} +!37 = !{!38} +!38 = distinct !{!38, !39, !"air-alias-scope-arg(2)"} +!39 = distinct !{!39, !"air-alias-scopes(cof_device)"} +!40 = !{!41} +!41 = distinct !{!41, !42, !"air-alias-scope-arg(1)"} +!42 = distinct !{!42, !"air-alias-scopes(cof_flat)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.ll b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.ll new file mode 100644 index 000000000..81c9d35d0 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.ll @@ -0,0 +1,107 @@ +; Generated by scripts/regen-air-fixtures from cof_offsets.metal (llvm-dis of cof_offsets.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(none) +define <{ <4 x float> }> @cof_constant(i32 noundef %0, ptr addrspace(2) noundef readonly align 16 captures(none) dereferenceable(16) "air-buffer-no-alias" %1) local_unnamed_addr #0 { + %3 = load <4 x float>, ptr addrspace(2) %1, align 16, !alias.scope !31 + %4 = shufflevector <4 x float> %3, <4 x float> poison, <2 x i32> + %5 = icmp eq i32 %0, 1 + %6 = select fast i1 %5, float 1.000000e+00, float 0.000000e+00 + %7 = insertelement <2 x float> undef, float %6, i64 0 + %8 = icmp eq i32 %0, 2 + %9 = select fast i1 %8, float 1.000000e+00, float 0.000000e+00 + %10 = insertelement <2 x float> %7, float %9, i64 1 + %11 = shufflevector <4 x float> %3, <4 x float> poison, <2 x i32> + %12 = fmul fast <2 x float> %11, %10 + %13 = fadd fast <2 x float> %12, %4 + %14 = shufflevector <2 x float> %13, <2 x float> poison, <4 x i32> + %15 = shufflevector <4 x float> %14, <4 x float> , <4 x i32> + %16 = insertvalue <{ <4 x float> }> undef, <4 x float> %15, 0 + ret <{ <4 x float> }> %16 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read) +define <{ <4 x float> }> @cof_device(i32 noundef %0, i32 noundef %1, ptr addrspace(1) noundef readonly captures(none) "air-buffer-no-alias" %2) local_unnamed_addr #1 { + %4 = zext i32 %1 to i64 + %5 = getelementptr inbounds <4 x float>, ptr addrspace(1) %2, i64 %4 + %6 = load <4 x float>, ptr addrspace(1) %5, align 16, !tbaa !34, !alias.scope !37 + %7 = shufflevector <4 x float> %6, <4 x float> poison, <2 x i32> + %8 = icmp eq i32 %0, 1 + %9 = select fast i1 %8, float 1.000000e+00, float 0.000000e+00 + %10 = insertelement <2 x float> undef, float %9, i64 0 + %11 = icmp eq i32 %0, 2 + %12 = select fast i1 %11, float 1.000000e+00, float 0.000000e+00 + %13 = insertelement <2 x float> %10, float %12, i64 1 + %14 = shufflevector <4 x float> %6, <4 x float> poison, <2 x i32> + %15 = fmul fast <2 x float> %14, %13 + %16 = fadd fast <2 x float> %15, %7 + %17 = shufflevector <2 x float> %16, <2 x float> poison, <4 x i32> + %18 = shufflevector <4 x float> %17, <4 x float> , <4 x i32> + %19 = insertvalue <{ <4 x float> }> undef, <4 x float> %18, 0 + ret <{ <4 x float> }> %19 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x float> @cof_flat(<4 x float> %0, ptr addrspace(2) noundef readonly align 16 captures(none) dereferenceable(16) "air-buffer-no-alias" %1) local_unnamed_addr #2 { + %3 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !34, !alias.scope !40 + ret <4 x float> %3 +} + +attributes #0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "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 = { mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="64" "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 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "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" } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !15} +!air.fragment = !{!19} +!air.compile_options = !{!25, !26, !27} +!llvm.ident = !{!28} +!air.version = !{!29} +!air.language_version = !{!30} + +!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 @cof_constant, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13, !14} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} +!14 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"q"} +!15 = !{ptr @cof_device, !10, !16} +!16 = !{!13, !17, !18} +!17 = !{i32 1, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"} +!18 = !{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", !"q"} +!19 = !{ptr @cof_flat, !20, !22} +!20 = !{!21} +!21 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!22 = !{!23, !24} +!23 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!24 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"} +!25 = !{!"air.compile.denorms_disable"} +!26 = !{!"air.compile.fast_math_enable"} +!27 = !{!"air.compile.framebuffer_fetch_enable"} +!28 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!29 = !{i32 2, i32 8, i32 0} +!30 = !{!"Metal", i32 4, i32 0, i32 0} +!31 = !{!32} +!32 = distinct !{!32, !33, !"air-alias-scope-arg(1)"} +!33 = distinct !{!33, !"air-alias-scopes(cof_constant)"} +!34 = !{!35, !35, i64 0} +!35 = !{!"omnipotent char", !36, i64 0} +!36 = !{!"Simple C++ TBAA"} +!37 = !{!38} +!38 = distinct !{!38, !39, !"air-alias-scope-arg(2)"} +!39 = distinct !{!39, !"air-alias-scopes(cof_device)"} +!40 = !{!41} +!41 = distinct !{!41, !42, !"air-alias-scope-arg(1)"} +!42 = distinct !{!42, !"air-alias-scopes(cof_flat)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.metal b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.metal new file mode 100644 index 000000000..5b80ac001 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/cof_offsets.metal @@ -0,0 +1,40 @@ +// Owned fixture: the functions the runtime lane's `constant_offsets` cost run draws with, a small +// triangle placed by a float4 at buffer 0 that each draw binds at another offset of one buffer. +// The vertex function reads it through a constant reference (`cof_constant`) or through a device +// pointer at an index it cannot bound (`cof_device`), the two forms whose per-draw rebinds the run +// compares; the fragment function's colour is a constant reference too. Written for this +// repository; no third-party source. Loop-free. +#include +using namespace metal; + +struct CofVertex { + float4 position [[position]]; +}; + +// The corner of vertex `vid` of a right triangle of unit legs: (0, 0), (1, 0) and (0, 1). +static float2 cof_corner(uint vid) { + return float2(vid == 1u ? 1.0 : 0.0, vid == 2u ? 1.0 : 0.0); +} + +// The triangle at q.xy, its legs q.zw long, its q a constant reference. +vertex CofVertex cof_constant(uint vid [[vertex_id]], constant float4 &q [[buffer(0)]]) { + CofVertex out; + out.position = float4(q.xy + cof_corner(vid) * q.zw, 0.0, 1.0); + return out; +} + +// The same triangle, its q read through a device pointer at the instance's element: an index the +// function cannot bound, so the slot's window runs to the end of the bound buffer. Drawn as one +// instance from instance 0, it reads q[0]. +vertex CofVertex cof_device(uint vid [[vertex_id]], uint iid [[instance_id]], + const device float4 *q [[buffer(0)]]) { + float4 r = q[iid]; + CofVertex out; + out.position = float4(r.xy + cof_corner(vid) * r.zw, 0.0, 1.0); + return out; +} + +// The colour c. +fragment float4 cof_flat(CofVertex in [[stage_in]], constant float4 &c [[buffer(0)]]) { + return c; +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index d513bd5f8..2e172b7df 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -349,6 +349,8 @@ mod compute_inherited_buffers; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod compute_threadgroups; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod constant_offsets; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod copied_surfaces; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod coverage_alpha_rounding; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/constant_offsets.rs b/crates/metal2vulkan-validation/src/runtime_lane/constant_offsets.rs new file mode 100644 index 000000000..dddaf11c9 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/constant_offsets.rs @@ -0,0 +1,319 @@ +//! What a stream of draws that each bind vertex buffer 0 at the next offset of one buffer costs the +//! thread that encodes them, by how the vertex function reads the slot: through a constant +//! reference (`constant float4 &`, `cof_constant`) or a device pointer at an index it cannot bound +//! (`const device float4 *`, `cof_device`, both of `cof_offsets.metal`), on the device the cfg +//! selects, without the validation layer: report only, in release builds. +//! +//! The stream is a guest's small draws as a consumer that stages each draw's `setVertexBytes` in +//! upload chunks sends them: each draw of 3 vertices binds a chunk of [`CHUNK`] bytes at vertex +//! index 0, at the next [`STEP`]-byte offset of the chunk, the next of [`CHUNKS`] chunks once one +//! is used up; the fragment function's colour is bound once a pass (`setFragmentBytes`). The +//! chunks are shared buffers, or no-copy buffers over host pages, as a guest's memory is +//! (`over pages`; a device that imports no host memory runs no such shape, and says so). A +//! command buffer is one render pass of [`DRAWS`] draws into a `RGBA8Unorm` target of +//! [`TARGET_SIDE`] square, committed and waited for. Each shape runs [`WARM`] command buffers +//! untimed, then [`TIMED`], printed as a `CONSTANT-OFFSETS` line (the medians of the encoding +//! thread's CPU time a draw, from the encoder's creation through `end_encoding`) and a +//! `CONSTANT-OFFSETS-MOVED` line (every work count the timed command buffers moved, a draw, by +//! name: the draws moved and moved inside, and the set-0 writes pushed, among them). +//! +//! `constant_offsets` measures every shape in turn; `constant_offsets_profiled_constant` and +//! `constant_offsets_profiled_device` encode [`PROFILED`] command buffers of one form over host +//! pages alone (shared chunks where the device imports none), for a profiler. +//! +//! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`, in a +//! build with `--cfg m2v_system_alloc`, whose lib test binary keeps the system allocator as a +//! consumer's process does. + +use super::draw_costs::{percentiles, thread_cpu}; +use super::host_memory::{host_page, no_copy, not_importable, Mapping}; +use super::{validated_device_with, Messages, ScratchCache, WAIT}; +use crate::air_library::AirLibrary; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + Buffer, CommandBufferStatus, CommandQueue, Device, DeviceOptions, LoadAction, PipelineOptions, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, StoreAction, Texture, + TextureDescriptor, +}; +use std::time::Duration; + +/// The untimed and the timed command buffers of each shape. +const WARM: usize = 3; +const TIMED: usize = 9; +/// The command buffers a profiled run encodes. +const PROFILED: usize = 40; +/// The draws of a command buffer's pass. +const DRAWS: usize = 10_000; +/// The bytes of an upload chunk, the offset step between two draws' bytes in it, and the chunks +/// the draws take in turn. +const CHUNK: u64 = 64 * 1024; +const STEP: u64 = 256; +const CHUNKS: usize = 4; +/// The target's side. +const TARGET_SIDE: u64 = 256; + +/// How the vertex function reads its float4 (the module docs). +#[derive(Clone, Copy, Debug)] +enum Form { + Constant, + Device, +} + +impl Form { + fn name(self) -> &'static str { + match self { + Form::Constant => "constant reference", + Form::Device => "device pointer", + } + } + + fn function(self) -> &'static str { + match self { + Form::Constant => "cof_constant", + Form::Device => "cof_device", + } + } +} + +/// The chunks of a [`Workload`], over host pages where the device imports them. +struct Chunks { + shared: Vec, + over_pages: Option>, + /// The host pages the chunks over pages lie in, which outlive them (`Workload`'s order). + _pages: Vec, +} + +/// The device, its queue, the pipeline state of each form, the chunks and the target. +struct Workload { + queue: CommandQueue, + /// The constant reference's pipeline state, and the device pointer's. + pipelines: [RenderPipelineState; 2], + chunks: Chunks, + target: Texture, + device: Device, +} + +/// Chunk `n`'s bytes: at each step a small triangle's float4, one of a grid over the target. +fn chunk_bytes(n: usize) -> Vec { + let per_chunk = (CHUNK / STEP) as usize; + let mut bytes = vec![0u8; CHUNK as usize]; + for slot in 0..per_chunk { + let at = n * per_chunk + slot; + let (x, y) = ((at % 32) as f32, ((at / 32) % 32) as f32); + let q = [x / 16.0 - 1.0, y / 16.0 - 1.0, 1.0 / 16.0, 1.0 / 16.0]; + let words: Vec = q.iter().flat_map(|v| v.to_le_bytes()).collect(); + let start = slot * STEP as usize; + bytes[start..start + words.len()].copy_from_slice(&words); + } + bytes +} + +impl Workload { + fn new(device: Device) -> Workload { + let ll = engine_dir().join("cof_offsets.ll"); + let library = device + .new_library_with_air(&llvm_assemble(&ll).unwrap()) + .unwrap(); + let function = |name| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let pipeline = |form: Form| { + let mut descriptor = RenderPipelineDescriptor::new(function(form.function())); + descriptor.fragment = Some(function("cof_flat")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() + }; + let shared = (0..CHUNKS) + .map(|n| super::buffer_with(&device, &chunk_bytes(n)).unwrap()) + .collect(); + let len = (CHUNK as usize).next_multiple_of(host_page()); + let pages: Vec = (0..CHUNKS).map(|_| Mapping::anonymous(len)).collect(); + let over_pages = (pages.iter().enumerate()) + .map(|(n, mapping)| { + mapping.write(0, &chunk_bytes(n)); + // SAFETY: the pages are this process's, mapped read and write, and outlive the + // buffer (`Chunks`' order). + unsafe { + no_copy( + &device, + mapping.pointer(), + len, + ResourceOptions::shared(), + None, + ) + } + }) + .collect::, _>>(); + let over_pages = match over_pages { + Ok(buffers) => Some(buffers), + Err(error) if not_importable(&error) => None, + Err(error) => panic!("chunks over host pages: {error:?}"), + }; + let mut target = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, TARGET_SIDE, TARGET_SIDE, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + Workload { + queue: device.new_command_queue().unwrap(), + pipelines: [pipeline(Form::Constant), pipeline(Form::Device)], + chunks: Chunks { + shared, + over_pages, + _pages: pages, + }, + target: device.new_texture(&target).unwrap(), + device, + } + } + + /// The chunks over host pages where `over_pages` and the device imports them, else the shared + /// ones; `None` for chunks over pages the device does not import. + fn chunks(&self, over_pages: bool) -> Option<&[Buffer]> { + match over_pages { + true => self.chunks.over_pages.as_deref(), + false => Some(&self.chunks.shared), + } + } + + /// Encode one command buffer of `form` over `chunks`, commit it and wait for it: the encoding + /// thread's CPU time its encoding took. + fn run(&self, form: Form, chunks: &[Buffer]) -> Duration { + let command_buffer = self.queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(self.target.clone()); + color.load_action = LoadAction::DontCare; + color.store_action = StoreAction::Store; + let cpu_start = thread_cpu(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + let pipeline = match form { + Form::Constant => &self.pipelines[0], + Form::Device => &self.pipelines[1], + }; + encoder.set_render_pipeline_state(pipeline).unwrap(); + let colour = [0.25f32, 0.5, 0.75, 1.0].map(f32::to_le_bytes).concat(); + encoder.set_fragment_bytes(&colour, 0).unwrap(); + let per_chunk = (CHUNK / STEP) as usize; + for draw in 0..DRAWS { + let chunk = &chunks[(draw / per_chunk) % chunks.len()]; + let offset = (draw % per_chunk) as u64 * STEP; + encoder.set_vertex_buffer(Some(chunk), offset, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + } + encoder.end_encoding().unwrap(); + let cpu = thread_cpu().saturating_sub(cpu_start); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + cpu + } +} + +/// The workload on the cfg's device, as a consumer opens it: no layer, no execution records, +/// the default policy. +fn workload(cache: &ScratchCache, messages: &Messages) -> Workload { + let device = validated_device_with(TEST_DEVICE, messages, cache.path(), |options| { + options.layers.clear(); + options.record_executions = false; + options.policy = DeviceOptions::default().policy; + }) + .unwrap(); + Workload::new(device) +} + +/// A shape's name: its form, and where its chunks lie. +fn shape_name(form: Form, over_pages: bool) -> String { + match over_pages { + true => format!("{} over pages", form.name()), + false => form.name().to_owned(), + } +} + +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn constant_offsets() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let work = workload(&cache, &messages); + let name = work.device.name().to_owned(); + eprintln!( + "CONSTANT-OFFSETS {name}: {DRAWS} draws a pass, each binding vertex buffer 0 at the next \ + {STEP}-byte offset of a {CHUNK}-byte chunk ({CHUNKS} in turn), {WARM} untimed and \ + {TIMED} timed command buffers a shape" + ); + let shapes = [ + (Form::Constant, false), + (Form::Device, false), + (Form::Constant, true), + (Form::Device, true), + ]; + for (form, over_pages) in shapes { + let shape = shape_name(form, over_pages); + let Some(chunks) = work.chunks(over_pages) else { + eprintln!("CONSTANT-OFFSETS {name} {shape}: the device imports no host memory"); + continue; + }; + for _ in 0..WARM { + work.run(form, chunks); + } + let before = work.device.work_counts(); + let runs: Vec = (0..TIMED) + .map(|_| work.run(form, chunks).as_secs_f64() * 1e9 / DRAWS as f64) + .collect(); + let after = work.device.work_counts(); + let [low, cpu, high] = percentiles(runs); + eprintln!( + "CONSTANT-OFFSETS {name} {shape}: {cpu:.1} ns of the thread's CPU a draw (p10 \ + {low:.1}, p90 {high:.1})" + ); + let moved = super::video_frames::moved_per_frame(&before, &after, TIMED * DRAWS); + eprintln!("CONSTANT-OFFSETS-MOVED {name} {shape}: a draw: {moved}"); + } +} + +/// Encode [`PROFILED`] command buffers of `form` over host pages alone (shared chunks where the +/// device imports none), for a profiler. +fn profiled(form: Form) { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let work = workload(&cache, &messages); + let over_pages = work.chunks(true).is_some(); + let chunks = work.chunks(over_pages).unwrap(); + for _ in 0..WARM { + work.run(form, chunks); + } + let runs: Vec = (0..PROFILED) + .map(|_| work.run(form, chunks).as_secs_f64() * 1e9 / DRAWS as f64) + .collect(); + let [_, cpu, _] = percentiles(runs); + eprintln!( + "CONSTANT-OFFSETS {} {} profiled: {cpu:.1} ns of the thread's CPU a draw", + work.device.name(), + shape_name(form, over_pages) + ); +} + +#[test] +#[ignore = "a profiling run, not a check: run by name with --run-ignored all"] +fn constant_offsets_profiled_constant() { + profiled(Form::Constant); +} + +#[test] +#[ignore = "a profiling run, not a check: run by name with --run-ignored all"] +fn constant_offsets_profiled_device() { + profiled(Form::Device); +} diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 6af0aab9b..62984f8be 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -650,9 +650,11 @@ fn residuals_ranges_extents_and_holes_follow_the_state() { }; let c = instantiate(&t, &s, &d).expect("instantiate"); assert_eq!(c.descriptor_ranges.len(), 1); + // A bounded storage window binds the range its bind offsets share, the buffer from its start + // (`bind::instantiate::shared_range`), the bind offset its residual. let r = c.descriptor_ranges[0].range; - assert_eq!((r.offset, r.range), (64, 112)); - assert_eq!(push_words(&c.regions[0])[8], 36, "residual 100 - 64"); + assert_eq!((r.offset, r.range), (0, 4096)); + assert_eq!(push_words(&c.regions[0])[8], 100, "residual 100 - 0"); assert_eq!(c.extents.len(), 1); assert_eq!( c.push_holes, diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 4c9f09356..503dadd63 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -5266,9 +5266,10 @@ fn rebind_with( // An unbound slot has no residual: its `SlotBindOffset` reads 0. let mut residual = 0; if let (Some((place, key)), Some(_)) = (entry.place, bound) { + let views = state.uniform_views_at_residual; let (range, slot_residual) = - crate::bind::instantiate::planned_range(pb, bind_offset, length).map_err(|e| { - match e { + crate::bind::instantiate::planned_range(pb, bind_offset, length, views).map_err( + |e| match e { RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { slot: pb.slot, needed, @@ -5277,8 +5278,8 @@ fn rebind_with( RangeError::Empty => BindError::Unsupported( Unsupported::not_representable(Feature::BufferRange), ), - } - })?; + }, + )?; let Some(written) = (out.descriptor_ranges.get_mut(place)).filter(|r| (r.set, r.binding) == key) else { diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index 7c838ef94..f55df74ac 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -530,29 +530,107 @@ pub(crate) fn descriptor_range( )) } +/// The descriptor range and the `SlotBindOffset` residual of a slot of `window` read at its +/// residual, bound at `bind_offset` of an allocation of `length` bytes (padded to 16), for the +/// descriptor base alignment `alignment` (at least 4 used) and the view's maximum range +/// `max_range`: a range that a run of bind offsets of the allocation shares, so a draw or dispatch +/// that moves only the slot's offset binds the same descriptor (and keeps its set 0) and moves +/// only its residual. For a `Bounded` window, `M` the smaller of `max_range` and `2^32` (a `u32` +/// residual and offset reach no further): the padded allocation whole where it fits `M`, from 0, +/// its residual the bind offset; else the block of `h` bytes the window's first byte lies in (`h` +/// the largest power of two at most half of `M`, a multiple of the alignment), to `M` past the +/// block's start or the padded end. A window of at most `M - h` bytes (at least half of `M`) that +/// starts in a block ends before `M` past the block's start, so it never straddles its block's +/// range; a longer one takes no block. Like [`descriptor_range`]'s, the range starts at a multiple of the +/// alignment, holds at least 16 bytes inside the padded allocation, and holds each byte `m` of +/// the window inside the allocation at `residual + m` (modulo `2^32`). `None` where no such range +/// holds the window (a `Whole` one, one at or past the padded end, one longer than its block +/// allows): the caller takes [`descriptor_range`]'s. +pub(crate) fn shared_range( + bind_offset: u64, + length: u64, + window: Window, + alignment: u64, + max_range: u64, +) -> Option<(BufferRange, u32)> { + let Window::Bounded { start, len } = window else { + return None; + }; + let end = i128::from(padded(length)); + let b = i128::from(bind_offset); + if b >= end { + return None; + } + let first = (b + i128::from(start)).max(0); + let last = (b + i128::from(start) + i128::from(len)).min(end); + // No range past `2^32` bytes: a `u32` residual and offset reach no further. + let max_range = max_range.min(1 << 32); + let (lo, hi) = if end <= i128::from(max_range) { + (0, end) + } else { + let a = alignment.max(4); + let block = 1u64 << (max_range / 2).checked_ilog2()?; + // The window's size limit: starting in the block, it ends inside the block's range. + if block < a || !block.is_multiple_of(a) || len > max_range - block { + return None; + } + let block = i128::from(block); + let lo = first - first.rem_euclid(block); + (lo, (lo + i128::from(max_range)).min(end)) + }; + debug_assert!(last <= hi, "a window past its shared range"); + let residual = b - lo; + if first >= hi || hi - lo < 16 || residual.abs() >= 1 << 32 { + return None; + } + // `0 <= lo < hi <= end <= 2^64`: both fit `u64`. + let range = BufferRange { + offset: lo as u64, + range: (hi - lo) as u64, + }; + Some((range, residual.rem_euclid(1 << 32) as u32)) +} + /// The descriptor range and the `SlotBindOffset` residual of planned buffer slot `pb` bound at -/// `bind_offset` of an allocation of `length` bytes: a storage view of a `Whole` window takes its -/// range from the start of the bound buffer's space (offset 0) to the padded end, its residual the -/// bind offset, so every bind offset of one buffer binds one descriptor and a draw or dispatch that -/// moves only the offset keeps its set 0 (a dynamic one's offset moves with the space alone). -/// Its function reads byte `residual + m` of the range for the Metal offset `m`, the byte it read -/// of the range from the bind offset; the bytes before the bind offset, which the window does not -/// state, are reachable as Metal's own memory is. Every other slot, and one whose range from 0 -/// would exceed the view's `max_range` or reach past `2^32` (a `u32` residual and offset), or whose -/// bind offset lies at or past the padded end, takes [`descriptor_range`]'s range. +/// `bind_offset` of an allocation of `length` bytes, where `views_at_residual` says the consumer +/// reads every uniform view at its residual (`BindState::uniform_views_at_residual`). Its function +/// reads byte `residual + m` of the range for the Metal offset `m`, the byte it read of the range +/// from the bind offset, so a slot read at its residual binds a range its bind offsets share: +/// +/// - a storage view of a `Whole` window takes its range from the start of the bound buffer's +/// space (offset 0) to the padded end, its residual the bind offset, so every bind offset of one +/// buffer binds one descriptor and a draw or dispatch that moves only the offset keeps its set 0 +/// (a dynamic one's offset moves with the space alone); the bytes before the bind offset, which +/// the window does not state, are reachable as Metal's own memory is. Where that range would +/// exceed the view's `max_range` or reach past `2^32` (a `u32` residual and offset), or the bind +/// offset lies at or past the padded end, it takes [`descriptor_range`]'s range; +/// - a storage view of a `Bounded` window, which every function reads at its residual, and a +/// uniform view of one where `views_at_residual` (no function reads it at its bind offset +/// alone, `SpecKey::RangeAtBindOffset`), take [`shared_range`]'s, where it holds the window; +/// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down +/// to the descriptor base alignment: a uniform view's key may read it at its bind offset alone, +/// where its residual is 0. pub(crate) fn planned_range( pb: &PlannedBuffer, bind_offset: u64, length: u64, + views_at_residual: bool, ) -> Result<(BufferRange, u32), RangeError> { let end = padded(length); + let storage = pb.form == BufferForm::Descriptor(DescriptorView::Storage); let from_start = pb.window == Window::Whole - && pb.form == BufferForm::Descriptor(DescriptorView::Storage) + && storage && bind_offset < end && end <= pb.max_range && end <= 1 << 32; if !from_start { - return descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range); + let shared = (storage || (views_at_residual && pb.form.uniform_view())) + .then(|| shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range)) + .flatten(); + return match shared { + Some(shared) => Ok(shared), + None => descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), + }; } // `bind_offset < end <= 2^32`: the residual is the bind offset. let range = BufferRange { @@ -708,8 +786,9 @@ pub(crate) fn bind_buffers( }; match (pb.form, pb.binding) { (BufferForm::Descriptor(_), Some((set, binding))) => { + let views = state.uniform_views_at_residual; let (range, residual) = - planned_range(pb, bind_offset, length).map_err(|e| match e { + planned_range(pb, bind_offset, length, views).map_err(|e| match e { RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { slot: pb.slot, needed, diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs index aba5557ba..e11f39b52 100644 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ b/crates/metal2vulkan/src/bind/instantiate/tests.rs @@ -222,8 +222,8 @@ fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { let pb = planned(Window::Whole, DescriptorView::Storage, alignment, MAX); for bind_offset in (0..LENGTH).step_by(4).chain([1, 15, LENGTH - 1]) { let what = format!("{alignment} {bind_offset}"); - let (range, residual) = - planned_range(&pb, bind_offset, LENGTH).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let (range, residual) = planned_range(&pb, bind_offset, LENGTH, false) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); let whole = BufferRange { offset: 0, range: LENGTH, @@ -246,21 +246,23 @@ fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { // A buffer of 2^32 bytes, bound at its last word: the residual still fits. let pb = planned(Window::Whole, DescriptorView::Storage, 16, MAX); let last = (1 << 32) - 4; - let (range, residual) = planned_range(&pb, last, 1 << 32).unwrap(); + let (range, residual) = planned_range(&pb, last, 1 << 32, false).unwrap(); assert_eq!( (range.offset, range.range, residual), (0, 1 << 32, u32::MAX - 3) ); } -/// Every other slot takes `descriptor_range`'s range: a range from 0 past the view's limit or -/// past `2^32`, a bind offset at or past the padded end, a uniform view, a bounded window. A limit -/// the range from the bind offset meets binds; one it does not is refused as before. +/// Every other slot takes `descriptor_range`'s range: a storage view's range from 0 past the +/// view's limit or past `2^32`, a bind offset at or past the padded end, a uniform view where the +/// consumer may read it at its bind offset alone (`views_at_residual` false), a bounded window no +/// shared range holds. A limit the range from the bind offset meets binds; one it does not is +/// refused as before. #[test] fn other_slots_bind_the_range_from_their_bind_offset() { let same = |pb: &PlannedBuffer, bind_offset: u64, length: u64| { assert_eq!( - planned_range(pb, bind_offset, length), + planned_range(pb, bind_offset, length, false), descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), "{:?} {:?} {bind_offset} {length}", pb.window, @@ -273,16 +275,16 @@ fn other_slots_bind_the_range_from_their_bind_offset() { let limited = storage(1 << 16); let length = 1 << 20; same(&limited, length - 4096, length); - assert!(planned_range(&limited, length - 4096, length).is_ok()); + assert!(planned_range(&limited, length - 4096, length, false).is_ok()); same(&limited, 64, length); assert_eq!( - planned_range(&limited, 64, length), + planned_range(&limited, 64, length, false), Err(RangeError::TooLarge { needed: length - 64 }) ); // At the limit exactly, from 0. - let (range, _) = planned_range(&storage(length), 64, length).unwrap(); + let (range, _) = planned_range(&storage(length), 64, length, false).unwrap(); assert_eq!(range.offset, 0); // Past 2^32 bytes: a residual and an offset of 32 bits could not state the bind offset. for length in [(1 << 32) + 16, 1 << 33] { @@ -290,27 +292,195 @@ fn other_slots_bind_the_range_from_their_bind_offset() { same(&storage(MAX), bind_offset, length); } } - // At or past the padded end, where the range is widened down into the allocation. + // At or past the padded end, where the range is widened down into the allocation, a whole + // window's or a bounded one's. for bind_offset in [4096, 4100, 8192, MAX] { same(&storage(MAX), bind_offset, 4096); same(&storage(MAX), bind_offset, 4090); + let bounded = Window::Bounded { start: 0, len: 16 }; + same( + &planned(bounded, DescriptorView::Storage, 64, MAX), + bind_offset, + 4096, + ); } - // A uniform view, whose `RangeAtBindOffset` reads a range from the bind offset; a bounded - // window of a storage view. + // A uniform view a key may read at its bind offset alone (`RangeAtBindOffset`), of a whole + // window or a bounded one. for bind_offset in (0..4096).step_by(4) { for view in [DescriptorView::UniformWords, DescriptorView::UniformVec4] { same(&planned(Window::Whole, view, 256, MAX), bind_offset, 4096); + let bounded = Window::Bounded { start: 0, len: 64 }; + same(&planned(bounded, view, 256, 1 << 16), bind_offset, 4096); } - for window in [ - Window::Bounded { start: 0, len: 64 }, - Window::Bounded { start: -8, len: 40 }, - ] { - same( - &planned(window, DescriptorView::Storage, 64, MAX), - bind_offset, - 4096, - ); + } +} + +/// The contract every shared range meets where it is given, as `descriptor_range`'s does: an +/// aligned start, at least 16 bytes, inside the padded allocation and the view's limit, and every +/// byte of the window inside the allocation at `residual + m` inside the range. +fn check_shared(bind_offset: u64, length: u64, window: Window, a: u64, max_range: u64) { + let Some((r, residual)) = shared_range(bind_offset, length, window, a, max_range) else { + return; + }; + let what = format!("{bind_offset} {length} {window:?} {a} {max_range}"); + let end = padded(length); + assert_eq!(r.offset % a.max(4), 0, "{what}: aligned start"); + assert!(r.range >= 16, "{what}: at least 16 bytes"); + assert!( + r.offset + r.range <= end, + "{what}: inside the padded allocation" + ); + assert!( + r.range <= max_range.min(1 << 32), + "{what}: inside the view's limit and 4 GiB" + ); + let Window::Bounded { start, len } = window else { + panic!("{what}: a shared range of a whole window"); + }; + let (start, len) = (i128::from(start), i128::from(len)); + for m in [start, start + len / 2, start + len - 1] { + if len <= 0 { + break; } + let abs = i128::from(bind_offset) + m; + if abs < 0 || abs >= i128::from(end) { + continue; + } + let rel = (i128::from(residual) + m).rem_euclid(1 << 32); + let expect = abs - i128::from(r.offset); + assert_eq!(rel, expect.rem_euclid(1 << 32), "{what}: byte {m}"); + assert!( + expect >= 0 && expect < i128::from(r.range), + "{what}: byte {m} inside [{}, +{})", + r.offset, + r.range + ); + } +} + +#[test] +fn shared_ranges_hold_every_window_byte_at_the_residual() { + let offsets = [ + 0, + 4, + 16, + 255, + 256, + 32 * 1024 - 16, + 32 * 1024, + 65520, + 65536, + (1 << 20) - 16, + (1 << 32) - 4, + (1 << 32) + 4, + MAX - 4095, + ]; + let lengths = [1, 16, 4096, 65536, 65537, 1 << 20, 1 << 33, MAX - 64]; + let windows = [ + Window::Bounded { start: 0, len: 16 }, + Window::Bounded { start: 0, len: 1 }, + Window::Bounded { start: -8, len: 40 }, + Window::Bounded { + start: 256, + len: 16, + }, + Window::Bounded { + start: 0, + len: 40000, + }, + Window::Bounded { + start: i64::MIN, + len: MAX, + }, + Window::Bounded { + start: 1 << 32, + len: 64, + }, + ]; + for &b in &offsets { + for &len in &lengths { + for &w in &windows { + for a in [4, 16, 64, 256] { + for max_range in [64, 65536, 1 << 27, MAX] { + check_shared(b, len, w, a, max_range); + } + } + } + } + } +} + +/// A slot read at its residual binds one range at every bind offset of a buffer that fits the +/// view's limit, from 0, its residual the bind offset: a storage view of a bounded window always, +/// a uniform view where the consumer reads every view at its residual. Past the limit, the bind +/// offsets of one block of half the limit share one; the next block binds the next. +#[test] +fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { + const CHUNK: u64 = 64 * 1024; + let bounded = Window::Bounded { start: 0, len: 16 }; + let uniform = planned(bounded, DescriptorView::UniformVec4, 64, CHUNK); + let storage = planned(bounded, DescriptorView::Storage, 64, 1 << 27); + let whole = BufferRange { + offset: 0, + range: CHUNK, + }; + for bind_offset in (0..CHUNK).step_by(256) { + let shared = (whole, bind_offset as u32); + assert_eq!( + planned_range(&uniform, bind_offset, CHUNK, true), + Ok(shared), + "uniform {bind_offset}" + ); + assert_eq!( + planned_range(&storage, bind_offset, CHUNK, false), + Ok(shared), + "storage {bind_offset}" + ); + // A uniform view a key may read at its bind offset alone: the range starts there. + let (range, residual) = planned_range(&uniform, bind_offset, CHUNK, false).unwrap(); + assert_eq!((range.offset, residual), (bind_offset, 0), "{bind_offset}"); + } + // A buffer of 1 MiB, past the uniform view's limit: blocks of 32 KiB. + let length = 1 << 20; + let block = CHUNK / 2; + for bind_offset in (0..length).step_by(256) { + let base = bind_offset - bind_offset % block; + let (range, residual) = planned_range(&uniform, bind_offset, length, true).unwrap(); + assert_eq!( + (range.offset, range.range, u64::from(residual)), + (base, CHUNK.min(length - base), bind_offset - base), + "{bind_offset}" + ); + } + // A window never straddles its block's range: one of half the limit, starting in a block's + // last 16 bytes, ends inside the block's range; a longer one takes no block, and binds from + // its bind offset. + for start in [0, block - 16, 3 * block - 16] { + let half = Window::Bounded { + start: 0, + len: block, + }; + let (range, residual) = shared_range(start, length, half, 64, CHUNK).unwrap(); + assert_eq!(range.offset, start - start % block, "{start}"); + assert!( + u64::from(residual) + block <= range.range, + "{start}: the window inside its block's range" + ); + let longer = Window::Bounded { + start: 0, + len: block + 16, + }; + assert_eq!( + shared_range(start, length, longer, 64, CHUNK), + None, + "{start}" + ); + let pb = planned(longer, DescriptorView::UniformVec4, 64, CHUNK); + assert_eq!( + planned_range(&pb, start, length, true), + descriptor_range(start, length, longer, 64, CHUNK), + "{start}" + ); } } diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 3a9c8c9ee..7c1858469 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -186,6 +186,20 @@ pub struct BindState { /// as it is under any other value the plan does not find its own. #[cfg_attr(feature = "serde", serde(default))] pub view_base_alignment: u32, + /// Whether the consumer reads every uniform view at its residual: it draws and dispatches + /// with each plan's key at every `SpecKey::RangeAtBindOffset` 0, its residual form, as the + /// runtime does on a device whose driver loads no uniform read at a constant offset ahead of + /// the shader. A uniform view's descriptor range then need not start at its bind offset, and + /// instantiation binds one that a run of bind offsets of the bound buffer shares (the buffer + /// from its start where it fits the view's maximum range), its `SlotBindOffset` residual the + /// rest: a command that moves only such a slot's offset binds the same descriptor, keeps its + /// set 0 and pushes only its residual. False, the default, starts each uniform view's range at + /// its bind offset aligned down to the view base alignment, which a key reading it at its bind + /// offset alone (`RangeAtBindOffset` 1) needs. Either reads the same bytes. Only the descriptor + /// ranges and residuals a command's instantiation writes depend on it, so it is not part of + /// the shape. + #[cfg_attr(feature = "serde", serde(default))] + pub uniform_views_at_residual: bool, /// The render encoder's viewport count (`setViewports:count:`): a vertex function's /// `[[viewport_array_index]]` at or past it draws through viewport 0, as Metal's does /// (`PushField::ViewportCount`). Metal's default is one viewport; 0, the default here, and 1 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index b087729ef..0990a1346 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 = 523; /// 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 = 2338; +pub const RUNTIME_VERSION: u32 = 2339; /// 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/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 7ef6621e4..c545f1ede 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -1001,6 +1001,7 @@ mod bind_serde_round_trips { round_trip(&BindState { stages, view_base_alignment: 64, + uniform_views_at_residual: true, used_resources: vec![UsedResource { class: ResourceClass::Heap, gpu_address: Some(0x2_0000_0000), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 48bbf9fdb..ca21c9acd 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3858,6 +3858,7 @@ field metal2vulkan::bind::BindState.stages pub stages: BTreeMap field metal2vulkan::bind::BindState.vertex_amplification pub vertex_amplification: VertexAmplification diff --git a/docs/API.md b/docs/API.md index 2a553bbbb..e791ef419 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1438,7 +1438,11 @@ for dependency in &pipeline.dependencies { take it). A buffer bound at any other offset, or at a slot left out, takes the other form, a pipeline of its own: leave out a slot bound at offsets that move, so that its draws keep one shape and one pipeline (the runtime leaves out each slot of a state once it finds one bound at - an offset the alignment does not divide). + an offset the alignment does not divide). A consumer that draws and dispatches every key at its + residual form (each `RangeAtBindOffset` at 0, as the runtime does on every device whose driver + is not measured to load such reads ahead of the shader) says so with + `state.uniform_views_at_residual = true`: its uniform views then bind ranges their bind offsets + share (below), as a bounded storage view's do. - A two-plane YCbCr texture whose planes a function may read in place states them in its facts (`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes; the runtime states one on a device whose memory is the host's, `DeviceProfile::reads_ycbcr_planes_in_place`: an integrated @@ -1584,8 +1588,21 @@ to 16 bytes, whatever its bind offset, which its `SlotBindOffset` push field hol dispatches that bind one buffer at other offsets write the same descriptors, and only push data differs. Where that range would pass the view's `maxStorageBufferRange` or 4 GiB, or the offset lies at or past the padded end, the range starts at the bind offset aligned down to the -descriptor base alignment, as every other descriptor-form slot's does. An access that reaches -back before the bind offset, inside the buffer, reads the buffer's bytes there, as Metal's does. +descriptor base alignment. An access that reaches back before the bind offset, inside the buffer, +reads the buffer's bytes there, as Metal's does. + +A slot of a bounded window read at its residual -- a storage view's always, a uniform view's +where the state says `uniform_views_at_residual` -- takes a range its bind offsets share in the +same way: the buffer from 0 to its padded end where that fits the view's maximum range (a uniform +view's is `maxUniformBufferRange` capped at 64 KiB) and 4 GiB, else the block of half that +maximum (rounded down to a power of two) its window starts in, to the maximum past the block's +start. A window of at most half the maximum starting in a block ends inside its block's range; a +longer one, or one at or past the padded end, takes the range from its bind offset, as every +other descriptor-form slot does. So draws that move such a slot's offset along one buffer (a +consumer's staged `setVertexBytes`, a constant reference bound at the next offset of an upload +chunk) write the same descriptor, keep set 0 and push only the slot's `SlotBindOffset`. Each read +inside the window reads the bytes it read before; one outside it, which Metal leaves undefined, +reads the buffer's bytes inside the range. `instantiate_draw_into` writes the same commands over a `DrawCommands` you keep, in the storage its vectors already hold: keep one from draw to draw (`DrawCommands::default()` to start) and the @@ -5188,8 +5205,10 @@ each item named states the rule in full. makes its predicted key's general form: each specialization constant with an arm that serves every binding exactly at that arm. Every constant buffer slot read through a uniform view is read at the slot's residual (`RangeAtBindOffset` 0), which reads the same bytes at every bind offset: - the binder writes the slot's descriptor range and residual from the bind offset alone, whichever - form the pipeline takes, and the residual is 0 wherever the range starts at the bind offset. A + the binder writes the slot's descriptor range and residual from the bind offset alone, and the + residual is 0 wherever the range starts at the bind offset (a bind state that says + `uniform_views_at_residual`, whose keys are all their residual forms, binds a range its bind + offsets share instead, the residual the rest). A slot bound to nothing is read at its residual too (0), so a draw that leaves such slots unbound takes the creation's pipeline itself. On MoltenVK a texture slot a function converts to `half` has its `UnmeasuredTexels`, which no instruction reads, at 0 (a class whose `half` conversion is