diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9ae83bdd24..f09b847ca3 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -704,6 +704,209 @@ mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + #[cfg(windows)] + #[test] + fn runtime_stride_reads_the_exact_structured_srv_window() { + use victory_shader::native::{ComputeIo, StageIo}; + use victory_shader::{ + Container, HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, + }; + let Some(host) = crate::host::host() else { + eprintln!("Skipping structured SRV readback because D3D12 is unavailable"); + return; + }; + let words = [ + 0xBE85_0380u32, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // read the SRV record + 0xF408_0302, + 0xFA00_0020, // read the UAV record + 0x7E00_0281, // element 1 + 0x7E02_0284, // byte offset 4 into that element + 0xE030_3000, + 0x8002_0200, // buffer_load_dword v2, v[0:1], s[8:11], 0 idxen offen + 0x7E00_0200, // output byte offset from s0 + 0xE070_1000, + 0x8003_0200, // buffer_store_dword v2, v0, s[12:15], 0 offen + 0xBF81_0000, + ]; + let param = |root, sgprs, user_data, slot| RootParam { + root, + sgprs, + user_data, + slot, + base_register: 0, + table_offset_dwords: 0, + }; + let used = |kind, table_offset_dwords| UsedResource { + kind, + table_offset_dwords, + root: RootType::Table, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 4, + layout: vec![ + param(RootType::Constants, 4, 0, 0), + param(RootType::Table, 1, 4, 1), + ], + used: vec![used(ResourceType::Srv, 0), used(ResourceType::Uav, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.into_iter().flat_map(u32::to_le_bytes).collect(), + }; + let p = victory_shader::ir::build(&native.code, false, native.vgprs).unwrap(); + let res = victory_shader::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = victory_shader::io::raise(&p, &native).unwrap(); + let st = victory_shader::structure::structure(&p).unwrap(); + let c = Container { + digest: [0; 16], + version: (1, 0), + parts: Vec::new(), + }; + let shader = victory_shader::emit::emit(&c, &native, &p, &st, &io, &res).unwrap(); + assert_eq!(shader.stride_table, [(1, 0)]); + let pipeline = crate::pipeline::test_compute_pipeline(shader, native.used); + let null = std::ptr::null(); + let mut heap_obj = null; + assert_eq!( + create( + HeapDesc { + kind: 0, + count: 2, + flags: 1, + nodes: 0 + }, + Placement { + address: 0, + size: 0 + }, + &mut heap_obj + ), + S_OK + ); + let heap = heap(heap_obj); + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + let allocate = || { + // SAFETY: allocate a write-watched page for shadow refresh and copy-back. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 64 << 10, + MEM_RESERVE | MEM_COMMIT | 0x20_0000, + PAGE_READWRITE, + ) + }; + assert!(!p.is_null()); + p as u64 + }; + let src = allocate(); + let dst = allocate(); + crate::shadow::register(src as usize, src, 64); + crate::shadow::register(dst as usize, dst, 64); + for i in 0..16 { + // SAFETY: the 16 initialized dwords are within the allocation. + unsafe { (src as *mut u32).add(i).write(100 + i as u32) }; + } + let mut resource = [0; 14]; + resource[0] = 1; // BUFFER + resource[4] = 64; + let mut srv = [0; 16]; + srv[1] = 1; // BUFFER SRV + srv[2] = 5768; // default component mapping + srv[4] = 1; // FirstElement + srv[6] = 2; // NumElements + srv[7] = 16; // StructureByteStride + srv[10] = src as u32; + srv[11] = (src >> 32) as u32; + create_placed_srv(null, &resource, &srv, heap.start); + let mut uav = [0; 16]; + uav[0] = 39; // R32_TYPELESS + uav[1] = 1; // BUFFER UAV + uav[4] = 16; // NumElements + uav[8] = 1; // RAW + uav[10] = dst as u32; + uav[11] = (dst >> 32) as u32; + create_placed_uav(null, &resource, &uav, heap.start + 32); + + let list = host.new_list().unwrap(); + let mut state = crate::draw::State::default(); + state.set_pipeline(pipeline); + state.set_heaps(&[heap_obj]); + state.set_table(true, 1, heap.start); + // Leave one dynamic descriptor available. A structured view starting + // at byte four cannot form a raw SRV and must return that lease. + let host_heap = heap.host().unwrap(); + let all_slots = 1 << 16; + let first = host_heap.dynamic(all_slots).unwrap(); + let last = first + all_slots - 1; + host_heap.release(last, 1); + let mut unaligned = srv; + unaligned[7] = 4; + create_placed_srv(null, &resource, &unaligned, heap.start); + state.set_constants(true, 0, &[16], 0); + state.dispatch(&list, 1, 1, 1); + assert_eq!( + host_heap.dynamic(1), + Some(last), + "a rejected alias bind must release its unsubmitted lease" + ); + host_heap.release(first, all_slots); + create_placed_srv(null, &resource, &srv, heap.start); + + state.set_constants(true, 0, &[20], 0); + state.dispatch(&list, 1, 1, 1); + + // Record another alias of the original slot before the list runs. + // The first dispatch must retain its original nonzero FirstElement. + srv[4] = 0; + create_placed_srv(null, &resource, &srv, heap.start); + state.set_constants(true, 0, &[24], 0); + state.dispatch(&list, 1, 1, 1); + assert_eq!(view(heap.start), Some(View::Placed(false, resource, srv))); + // A legal raw input retains the stride-four behavior of the original PR. + let mut raw = srv; + raw[0] = 39; // R32_TYPELESS + raw[6] = 16; // NumElements + raw[7] = 0; + raw[8] = 1; // RAW + create_placed_srv(null, &resource, &raw, heap.start); + state.set_constants(true, 0, &[28], 0); + state.dispatch(&list, 1, 1, 1); + list.close(); + host.execute(&[&list]); + // SAFETY: dword 4 is in the output range and was never dispatched. + assert_eq!(unsafe { (dst as *const u32).add(4).read() }, 0); + // SAFETY: dword 5 is within the registered output range. + assert_eq!(unsafe { (dst as *const u32).add(5).read() }, 109); + // SAFETY: dword 6 is within the registered output range. + assert_eq!(unsafe { (dst as *const u32).add(6).read() }, 105); + // SAFETY: dword 7 is within the registered output range. + assert_eq!(unsafe { (dst as *const u32).add(7).read() }, 102); + assert_eq!(view(heap.start), Some(View::Placed(false, resource, raw))); + eprintln!("Structured SRV generation and raw SRV readbacks passed"); + drop(state); + release(heap_obj); + slot:: u32>(pipeline, 0x10)(pipeline); + crate::shadow::unregister(src as usize, src); + crate::shadow::unregister(dst as usize, dst); + // SAFETY: both ranges came from VirtualAlloc above and are retired. + unsafe { + VirtualFree(src as *mut _, 0, MEM_RELEASE); + VirtualFree(dst as *mut _, 0, MEM_RELEASE); + } + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 1244766710..2d889ad13f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -30,63 +30,6 @@ pub(crate) struct HostHeap { /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, - /// Per-slot element byte stride (`u32`) for structured buffers whose - /// stride shader analysis could not recover statically. - strides: Option, -} - -struct StrideTable { - _resource: ID3D12Resource, - ptr: usize, - gpu: u64, - len: u32, -} - -impl StrideTable { - fn new(device: &ID3D12Device, len: u32) -> Option { - let bytes = (u64::from(len) * 4).max(4); - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: bytes, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let mut resource: Option = None; - let mut p = std::ptr::null_mut(); - // SAFETY: plain committed upload buffer creation and persistent CPU map. - let gpu = unsafe { - device - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, - ..Default::default() - }, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - &mut resource, - ) - .ok()?; - let res = resource.as_ref()?; - res.Map(0, None, Some(&mut p)).ok()?; - std::ptr::write_bytes(p.cast::(), 0, bytes as usize); - res.GetGPUVirtualAddress() - }; - Some(Self { - _resource: resource?, - ptr: p as usize, - gpu, - len, - }) - } } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -175,11 +118,6 @@ impl HostHeap { u64::from(step), sampler, )); - let strides = if sampler { - None - } else { - StrideTable::new(&host.device, count + extra) - }; let h = HostHeap { heap, cpu, @@ -189,7 +127,6 @@ impl HostHeap { made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), - strides, }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -339,7 +276,42 @@ impl HostHeap { null_for(view, self.cpu(index)); } self.keep(index, kept.flatten()); - self.set_stride(index, if ok { view_stride(view) } else { 0 }); + } + + /// Makes a separately leased raw SRV over a structured or raw buffer view. + pub(crate) fn structured_read_alias( + &self, + index: u32, + view: &View, + list: &crate::host::HostList, + ) -> Option<[u32; 4]> { + let (address, len, words) = match view { + View::Shader(resource, Some(words)) => { + let (base, len) = crate::resource::buffer_bytes(*resource as crate::object::This)?; + (base as u64, len, words) + } + View::Placed(false, resource, desc) if resource[0] == 1 => ( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + desc[..10].try_into().ok()?, + ), + _ => return None, + }; + let shadow = crate::shadow::find(address, len)?; + let (raw, start, bytes, stride, count) = + raw_read_window(&srv_desc(words), shadow.offset(address), len)?; + let refresh_at = address.checked_add(start)?; + shadow.refresh(list, refresh_at, u64::from(bytes)); + let host = host()?; + // SAFETY: the alias occupies a leased dynamic slot, and its extent + // is entirely inside the live backing buffer. + unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&raw), self.cpu(index)); + } + list.keep(&shadow.buffer); + self.keep(index, Some(shadow.buffer.clone())); + Some([index, stride, bytes, count]) } /// Makes slot `index` read nothing: a null view, or a plain sampler. @@ -350,7 +322,6 @@ impl HostHeap { null_view(self.cpu(index)); } self.keep(index, None); - self.set_stride(index, 0); } /// Slot `index` now views `resource` (or nothing of the host's). @@ -361,25 +332,10 @@ impl HostHeap { } } - fn set_stride(&self, index: u32, stride: u32) { - if let Some(t) = &self.strides - && index < t.len - { - // SAFETY: `t.ptr` points to a live mapped UPLOAD buffer of `t.len` dwords. - unsafe { *(t.ptr as *mut u32).add(index as usize) = stride }; - } - } - - /// GPU virtual address of the per-slot element byte stride table. - pub(crate) fn stride_table_gpu(&self) -> Option { - self.strides.as_ref().map(|t| t.gpu) - } - /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { self.keep(index, None); - self.set_stride(index, 0); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -445,7 +401,6 @@ impl HostHeap { null_for(&view, self.cpu(index)); } self.keep(index, kept.flatten()); - self.set_stride(index, if ok { view_stride(&view) } else { 0 }); } Some(view) } @@ -563,26 +518,6 @@ fn uav_element_size(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { } } -/// Element byte stride of `view` for the runtime stride table (`0` for -/// non-buffer views or descriptors without a known element size). -fn view_stride(view: &View) -> u32 { - let bytes = match view { - View::Shader(_, Some(desc)) => element_size(&srv_desc(desc)), - View::Placed(false, resource, desc) if resource[0] == 1 => desc[..10] - .try_into() - .ok() - .map_or(0, |w: &[u32; 10]| element_size(&srv_desc(w))), - View::Unordered(_, _, Some(desc)) => uav_element_size(&uav_desc(desc)).unwrap_or(0), - View::Placed(true, resource, desc) if resource[0] == 1 => desc[..10] - .try_into() - .ok() - .and_then(|w: &[u32; 10]| uav_element_size(&uav_desc(w))) - .unwrap_or(0), - _ => 0, - }; - u32::try_from(bytes).unwrap_or(0) -} - /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); @@ -627,6 +562,52 @@ fn buffer_srv( Some(Some(shadow.buffer.clone())) } +/// Raw descriptor and exact byte window of a buffer view. +fn raw_read_window( + desc: &D3D12_SHADER_RESOURCE_VIEW_DESC, + host_offset: u64, + len: u64, +) -> Option<(D3D12_SHADER_RESOURCE_VIEW_DESC, u64, u32, u32, u32)> { + if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { + return None; + } + // SAFETY: the descriptor dimension was checked above. + let buffer = unsafe { desc.Anonymous.Buffer }; + let stride = match (desc.Format, buffer.Flags, buffer.StructureByteStride) { + (DXGI_FORMAT_UNKNOWN, D3D12_BUFFER_SRV_FLAG_NONE, stride) + if stride > 0 && stride.is_multiple_of(4) => + { + stride + } + (DXGI_FORMAT_R32_TYPELESS, D3D12_BUFFER_SRV_FLAG_RAW, 0) => 4, + _ => return None, + }; + let count = buffer.NumElements; + let start = buffer.FirstElement.checked_mul(u64::from(stride))?; + let bytes = count.checked_mul(stride)?; + let first = host_offset.checked_add(start)?; + if bytes == 0 + || start.checked_add(u64::from(bytes))? > len + || !first.is_multiple_of(u64::from(D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) + { + return None; + } + let raw = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first / 4, + NumElements: bytes / 4, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + Some((raw, start, bytes, stride, count)) +} + /// An unordered access view of title buffer memory at `address` (`len` /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be /// written by shaders (upload memory). diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 0d9c642cd1..0af793c852 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -347,7 +347,9 @@ impl State { ); return false; } - self.bind(list, p, false); + if !self.bind(list, p, false) { + return false; + } let l = &list.list; // Vertex buffers the input layout reads. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; @@ -406,7 +408,7 @@ impl State { /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -447,6 +449,7 @@ impl State { list.keep(&p.pso); list.keep(&p.root); } + let mut alias_leases = Vec::new(); for stage in &p.stages { let t = stage.translated(); let made = self.tables(list, &t.used, compute); @@ -492,24 +495,68 @@ impl State { } } if let Some(param) = stage.stride_table { - let gpu = (self.heaps[0] != 0) - .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) - .flatten() - .and_then(|h| h.stride_table_gpu()); - if let Some(gpu) = gpu { - // SAFETY: an open list; the stride table buffer lives with the host heap. - unsafe { - if compute { - l.SetComputeRootShaderResourceView(param, gpu); - } else { - l.SetGraphicsRootShaderResourceView(param, gpu); - } + let Some((gpu, lease)) = + self.structured_read_aliases(list, &t.host.stride_table, compute) + else { + for (heap, first, count) in alias_leases { + crate::descriptor::release_dynamic(heap, first, count); + } + once!("cannot bind a runtime-stride structured SRV"); + return false; + }; + alias_leases.push(lease); + // SAFETY: this immutable table lives until the list retires. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); } - } else { - once!("a shader reads the runtime stride table without a host view heap"); } } } + self.dynamic.extend(alias_leases); + true + } + + fn structured_read_aliases( + &self, + list: &HostList, + entries: &[(u8, u32)], + compute: bool, + ) -> Option<(u64, (usize, u32, u32))> { + let address = self.heaps[0]; + if address == 0 { + return None; + } + let heap = crate::descriptor::heap(address as This); + let host = heap.host()?; + let n = u32::try_from(entries.len()).ok()?; + let (gpu, ptr) = list.scratch(u64::from(n) * 16)?; + let views = entries + .iter() + .map(|&(slot, dword)| { + let Root::Table(table) = *self.roots_ref(compute).get(usize::from(slot))? else { + return None; + }; + let handle = table.checked_add(u64::from(dword) * 4)?; + if !std::ptr::eq(heap, self.heap_of(handle)?) { + return None; + } + crate::descriptor::view(handle) + }) + .collect::>>()?; + let first = host.dynamic(n)?; + for (i, view) in views.iter().enumerate() { + let Some(row) = host.structured_read_alias(first + i as u32, view, list) else { + // No command references this lease until every row is bound. + host.release(first, n); + return None; + }; + // SAFETY: allocated four dwords for each entry above. + unsafe { ptr.cast::<[u32; 4]>().add(i).write(row) }; + } + Some((gpu, (std::ptr::from_ref(heap) as usize, first, n))) } /// Runs a dispatch on the host. @@ -534,7 +581,10 @@ impl State { once!("a dispatch with a graphics pipeline"); return; } - self.bind(list, p, true); + if !self.bind(list, p, true) { + DROPPED.fetch_add(1, Ordering::Relaxed); + return; + } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. @@ -1009,10 +1059,7 @@ impl State { DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => { - self.bind(list, p, true); - true - } + Some(p) if p.compute => self.bind(list, p, true), _ => false, }, _ => false, diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index d488d03430..fe9be0c463 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -501,6 +501,28 @@ pub fn save_pipeline_cache() { library::save(true); } +#[cfg(all(test, windows))] +pub(crate) fn test_compute_pipeline( + host: victory_shader::emit::HostShader, + used: Vec, +) -> This { + let hash = blake3::hash(&host.dxil).to_hex()[..16].to_owned(); + let translated = OnceLock::new(); + let _ = translated.set(Some(Translated { host, used })); + let shader = Arc::new(Shader { + stage: "compute", + hash, + container: Vec::new(), + translated, + }); + let mut out = std::ptr::null(); + assert_eq!( + hand_out(vec![shader], None, &PIPELINE_IIDS[0], &mut out), + crate::object::S_OK + ); + out +} + #[cfg(test)] mod tests { #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 81169d6988..b33155ca1f 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -393,7 +393,7 @@ impl HostPipeline { }); } } - if t.stride_table { + if !t.stride_table.is_empty() { stage.stride_table = Some(params.len() as u32); params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 1071c78627..3029e0ce93 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -131,7 +131,7 @@ fn cached( (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH2"; +const MAGIC: &[u8; 4] = b"VSH3"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -210,7 +210,11 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, slots.len() as u32); out.extend(slots); } - word(&mut out, u32::from(s.stride_table)); + word(&mut out, s.stride_table.len() as u32); + for &(slot, dword) in &s.stride_table { + word(&mut out, u32::from(slot)); + word(&mut out, dword); + } out } @@ -267,7 +271,16 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; - let stride_table = r.word()? != 0; + let count = r.word()?; + let mut stride_table = Vec::new(); + for _ in 0..count { + let slot = u8::try_from(r.word()?).ok()?; + let dword = r.word()?; + if !dword.is_multiple_of(8) || stride_table.contains(&(slot, dword)) { + return None; + } + stride_table.push((slot, dword)); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -303,7 +316,7 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], - stride_table: true, + stride_table: vec![(0, 8)], } } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 930efb1ac2..095180fd4a 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -158,7 +158,7 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } - if stages.iter().any(|(s, _)| s.stride_table) { + if stages.iter().any(|(s, _)| !s.stride_table.is_empty()) { params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -541,7 +541,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - stride_table: false, + stride_table: Vec::new(), } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e133659ed9..e93cd49c91 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -35,7 +35,7 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, - pub stride_table: bool, + pub stride_table: Vec<(u8, u32)>, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, } @@ -152,6 +152,7 @@ struct Lower<'a> { user_reads: BTreeMap, samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, + runtime_srvs: Vec<(u8, u32)>, scalar: HashMap, exports: HashMap, interps: HashMap, @@ -457,6 +458,7 @@ impl<'a> Lower<'a> { .iter() .map(|d| ((d.site, d.role == Role::Sampler), &d.source)) .collect(), + runtime_srvs: Vec::new(), scalar: x.res.scalar.iter().copied().collect(), exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), @@ -883,13 +885,12 @@ impl<'a> Lower<'a> { self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); - let stride_table = self.s.stride_table.is_some(); let cmp_samplers = self.s.cmp_samplers; Ok(Lowered { cmp_samplers, root_cbvs, root_srvs, - stride_table, + stride_table: self.runtime_srvs, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -2884,6 +2885,29 @@ impl<'a> Lower<'a> { || un.contains("atomic") || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; + if let Fields::Buffer { + idxen: true, + format: None, + .. + } = ui.fields + && !uav + && un.starts_with("buffer_load") + && !un.starts_with("buffer_load_format") + && used.is_some_and(|u| { + u.kind == ResourceType::Srv && (u.stride < 4 || !u.stride.is_multiple_of(4)) + }) + { + let [_, _, _, records] = self.runtime_srv_row(&src)?; + for k in 0..count { + let reg = Reg::S(code + k as u8); + if k == u32::from(first) + 2 { + self.write(inst, reg, records, None); + } else if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + } + } + return Ok(()); + } let (props, image) = match &ui.fields { Fields::Image { dim, .. } => { let kind = match dim { @@ -3293,48 +3317,37 @@ impl<'a> Lower<'a> { } } - /// The view-heap slot of `src` when it comes from a descriptor table or - /// heap (`Loaded` or `Phi` of `Loaded`). - fn heap_slot(&mut self, src: &Source, sampler: bool) -> Result { - match src { - Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), - Source::Phi { block, args } => { - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); - } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - Ok(phi) - } - _ => Err("a descriptor outside the heaps"), + /// Resolve a runtime-stride read against an exact SRV entry. The host + /// snapshots its independently leased raw alias and extent for this draw. + fn runtime_srv_row(&mut self, src: &Source) -> Result<[V; 4], Why> { + let why = "a structured buffer of unknown stride"; + let Source::Loaded { load, first } = src else { + return Err(why); + }; + let a = self.scalar.get(load).ok_or(why)?; + let r = self.used_kind(src).ok_or(why)?; + if a.dynamic.is_some() + || !a.offset.is_multiple_of(4) + || r.kind != ResourceType::Srv + || r.table_offset_dwords != (a.offset / 4) + u32::from(*first) + || !r.table_offset_dwords.is_multiple_of(8) + { + return Err(why); } - } - - /// Byte offset `index * stride + off` for a structured buffer whose - /// stride was not recovered statically, reading `stride` from the host's - /// runtime stride table (`t0`, [`super::STRIDE_SPACE`]). - fn runtime_stride_offset(&mut self, src: &Source, index: V, off: V) -> Result { - let slot = self - .heap_slot(src, false) - .map_err(|_| "a structured buffer of unknown stride")?; + let binding = (r.slot, r.table_offset_dwords); + let row = self + .runtime_srvs + .iter() + .position(|v| *v == binding) + .unwrap_or_else(|| { + self.runtime_srvs.push(binding); + self.runtime_srvs.len() - 1 + }); let c = self.cur; let table = self.s.stride_table_handle(); - let four = self.s.m.i32(4); - let addr = self.s.m.bin(c, Bin::Mul, slot, four); - let iu = self.s.m.undef(self.s.t.i32); - let mask = self.s.m.i8(1); + let addr = self.s.m.i32((row as u32) * 16); + let undef = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(15); let align = self.s.m.i32(4); let res = self.s.op( c, @@ -3342,12 +3355,24 @@ impl<'a> Lower<'a> { Attr::ReadOnly, self.s.t.res_ret, 139, - &[table, addr, iu, mask, align], + &[table, addr, undef, mask, align], ); - let stride_f = self.s.m.extract(c, res, 0); - let stride = self.as_int(stride_f); - let elem_off = self.s.m.bin(c, Bin::Mul, index, stride); - Ok(self.s.m.bin(c, Bin::Add, elem_off, off)) + Ok([0, 1, 2, 3].map(|field| { + let v = self.s.m.extract(c, res, field); + self.as_int(v) + })) + } + + fn runtime_srv_load(&mut self, src: &Source, index: V, off: V) -> Result<(V, V), Why> { + let [alias, stride, len, count] = self.runtime_srv_row(src)?; + let c = self.cur; + let base = self.s.m.bin(c, Bin::Mul, index, stride); + let byte = self.s.m.bin(c, Bin::Add, base, off); + let bad_index = self.s.m.cmp(c, pred::IUGE, index, count); + let overflow = self.s.m.cmp(c, pred::IULT, byte, base); + let bad = self.s.m.bin(c, Bin::Or, bad_index, overflow); + let byte = self.s.m.select(c, bad, len, byte); + Ok((self.s.heap_handle(c, alias, false, (11, 0)), byte)) } /// The heap index of the descriptor at dword `first` of what the scalar @@ -5970,8 +5995,7 @@ impl<'a> Lower<'a> { [index, off, iu], ) } else { - let byte = self.runtime_stride_offset(src, index, off)?; - (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu]) + return Err("a structured buffer of unknown stride"); } } None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]), @@ -6055,9 +6079,7 @@ impl<'a> Lower<'a> { args.push(self.handle(site, src, false, (12 | u, stride))?); args.extend([index, off]); } else { - let byte = self.runtime_stride_offset(src, index, off)?; - args.push(self.handle(site, src, false, (11 | u, 0))?); - args.extend([byte, iu]); + return Err("a structured buffer of unknown stride"); } } None => { @@ -6126,8 +6148,7 @@ impl<'a> Lower<'a> { &[h, index, off, mask, align], ) } else { - let byte = self.runtime_stride_offset(src, index, off)?; - let h = self.handle(site, src, false, (11 | u, 0))?; + let (h, byte) = self.runtime_srv_load(src, index, off)?; self.s.op( c, "rawBufferLoad.f32", diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index faf4a73efd..ea7be38cd0 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -154,9 +154,9 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, - /// True when the shader reads the runtime stride table (`t0` in - /// [`STRIDE_SPACE`]). - pub stride_table: bool, + /// Guest table slot and dword for each immutable runtime stride row + /// read from `t0` in [`STRIDE_SPACE`]. + pub stride_table: Vec<(u8, u32)>, } impl HostShader { @@ -494,7 +494,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - stride_table: false, + stride_table: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -505,7 +505,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), - stride_table: false, + stride_table: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -609,21 +609,13 @@ mod tests { 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 0xF408_0302, 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 - 0x7E00_0282, // v_mov_b32 v0, 2 + 0x7E00_0281, // v_mov_b32 v0, 1 0x7E02_0284, // v_mov_b32 v1, 4 0xE030_3000, 0x8002_0200, // buffer_load_dword v2, v[0:1], s[8:11], 0 idxen offen - 0x7E00_0281, // v_mov_b32 v0, 1 - 0x7E02_0288, // v_mov_b32 v1, 8 - 0xE070_3000, - 0x8003_0200, // buffer_store_dword v2, v[0:1], s[12:15], 0 idxen offen - 0x7E00_0282, // v_mov_b32 v0, 2 - 0x7E02_0280, // v_mov_b32 v1, 0 - 0x7E06_028A, // v_mov_b32 v3, 10 - 0xE0C8_3000, - 0x8003_0300, // buffer_atomic_add v3, v[0:1], s[12:15], 0 idxen offen - 0xE0C8_3000, - 0x8003_0300, // buffer_atomic_add v3, v[0:1], s[12:15], 0 idxen offen + 0x7E00_0200, // v_mov_b32 v0, s0 + 0xE070_1000, + 0x8003_0200, // buffer_store_dword v2, v0, s[12:15], 0 offen 0xBF81_0000, // s_endpgm ]; let native = super::NativeProgram { @@ -676,23 +668,56 @@ mod tests { }), code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; - let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); - let st = crate::structure::structure(&p).unwrap(); - let l = super::lower::lower(&super::lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - }) - .unwrap(); - assert!(l.stride_table); + let lower = |native: &super::NativeProgram| { + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = crate::io::raise(&p, native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + super::lower::lower(&super::lower::Parts { + native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + }; + let l = lower(&native).unwrap(); + assert_eq!(l.stride_table, [(1, 0)]); + + let mut with_write = native; + let mut body = words[..words.len() - 4].to_vec(); + body.extend_from_slice(&[ + 0x7E00_0281, // v_mov_b32 v0, 1 + 0x7E02_0288, // v_mov_b32 v1, 8 + 0xE070_3000, + 0x8003_0200, // indexed store + 0xBF81_0000, + ]); + with_write.code = body.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + lower(&with_write), + Err(crate::ShaderError::Unsupported { + what: "a structured buffer of unknown stride", + .. + }) + )); + let op = body.len() - 3; + body[op] = 0xE0C8_3000; // indexed atomic add + with_write.code = body.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + lower(&with_write), + Err(crate::ShaderError::Unsupported { + what: "a structured buffer of unknown stride", + .. + }) + )); + with_write.used[1].stride = 12; + assert!(lower(&with_write).is_ok()); + let mut dxil = l.dxil; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( @@ -720,12 +745,12 @@ mod tests { &pso, &super::host::Dispatch { roots: vec![ - (0, super::host::Root::Constants(vec![0, 0, 0, 0, 0])), + (0, super::host::Root::Constants(vec![20, 0, 0, 0, 0])), ( 1, super::host::Root::View { srv: true, - data: vec![12, 12], + data: vec![0, 12, 48, 4], }, ), ], @@ -741,8 +766,7 @@ mod tests { }, ) .unwrap(); - assert_eq!(out[0][5], 107); - assert_eq!(out[0][6], 20); + assert_eq!(out[0][5], 104); } } } diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index b9e0d33e36..210b87c08b 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -239,8 +239,8 @@ impl Shader { } /// The handle of the host's runtime stride table (`t0` in - /// [`STRIDE_SPACE`], a raw buffer of `u32` byte strides indexed by - /// view-heap slot). + /// [`STRIDE_SPACE`], a raw buffer of fixed rows for the shader's + /// exact table bindings). pub fn stride_table_handle(&mut self) -> V { if let Some(h) = self.stride_table { return h;