diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f2347ad..2378a74c40 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -12,15 +12,18 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +use victory_shader::emit::HEAP_GUARDS; pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, - /// Slots mirroring the title's; view heaps have `dynamic` more. + /// Slots mirroring the title's; view heaps have `dynamic` more, then + /// their guard slots ([`HostHeap::guard_slot`]). count: u32, - /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] - /// where the host takes them, else [`MIN_DYNAMIC`]. + /// Dynamic slots past `count` (none in sampler heaps): what + /// [`view_layout`] gives the heap past its title slots but its last + /// [`HEAP_GUARDS`]`.len()`, the guard slots. dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. @@ -35,29 +38,62 @@ pub(crate) struct HostHeap { next: Mutex<(u32, Vec)>, } -/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for -/// device-removed reports: a shader indexing a heap past its end faults. -static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); +/// A host heap's GPU range, for device-removed reports. +struct GpuRange { + start: u64, + bytes: u64, + /// Bytes per slot. + step: u64, + sampler: bool, + /// The slots mirroring the title's; dynamic ones follow. + title: u64, +} + +/// Host heaps' GPU ranges, for device-removed reports: a shader indexing a +/// heap past its end faults. +static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); /// For device-removed reports: where host GPU address `va` lies against /// the host descriptor heaps. pub(crate) fn near_heaps(va: u64) -> String { let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); let mut text = String::new(); - for &(start, bytes, step, sampler) in ranges.iter() { - let kind = if sampler { "sampler" } else { "view" }; - let place = if va < start { - format!("{:#x} below", start - va) - } else if va < start + bytes { - format!("inside, slot {}", (va - start) / step) + for r in ranges.iter() { + let (start, bytes) = (r.start, r.bytes); + let kind = if r.sampler { "sampler" } else { "view" }; + let guards = if r.sampler { + 0 } else { - format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + HEAP_GUARDS.len() as u64 }; + let place = place_in_heap(va, start, bytes, r.step, r.title, guards); text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } text } +/// Where `va` lies in a heap at `start` of `bytes`, `step` bytes a slot, +/// whose first `title` slots mirror the title's. Past them are dynamic +/// slots, and in a view heap its `guards` guard slots last. Translated +/// shaders bound their heap indices, so a fault in the dynamic slots is a +/// table's own read, and one in a guard slot an index they bounded. +fn place_in_heap(va: u64, start: u64, bytes: u64, step: u64, title: u64, guards: u64) -> String { + if va < start { + return format!("{:#x} below", start - va); + } + let slot = (va - start) / step; + if va >= start + bytes { + return format!("{:#x} past its end (slot {slot})", va - start - bytes); + } + if slot < title { + format!("inside, title slot {slot}") + } else if slot + guards >= bytes / step { + format!("inside, guard slot {slot}") + } else { + format!("inside, dynamic slot {} (slot {slot})", slot - title) + } +} + /// The host's limit for shader-visible view heaps on resource binding /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; @@ -69,10 +105,57 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// each a device removal shortly after; #59). const DYNAMIC: u32 = 1 << 18; -/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more -/// (a capped heap, NVIDIA): the title's slots keep their room first. +/// The fewest dynamic slots a heap gets whose host would not take +/// [`DYNAMIC`] more (a capped heap, NVIDIA) while the title's slots fit. const MIN_DYNAMIC: u32 = 1 << 16; +/// How a view heap the title made with `count` slots is laid out on the +/// host: the host heap `make` created, the title slots it mirrors and the +/// dynamic slots after them. `make` creates a shader-visible view heap of +/// the size it is given, or refuses it. +/// +/// A host that refuses `count` + [`DYNAMIC`] most likely caps view heaps at +/// [`PORTABLE_VIEWS`] (NVIDIA on binding tier 3 too): +/// +/// * the title's slots fit below it with at least [`MIN_DYNAMIC`] to +/// spare: they all stay and the dynamic range gets the rest; +/// * they do not fit below it, and the host takes them with +/// [`MIN_DYNAMIC`] more (its cap lies above the portable one): as +/// before, every title slot and the fewest dynamic ones; +/// * they do not fit and the host is capped at the portable limit: the +/// dynamic range keeps all of [`DYNAMIC`]. With 2^16 the world's fresh +/// tables ran out inside every submission and most of its draws were +/// dropped; its tables past the smaller title range are made fresh +/// instead (#747). +/// +/// Anything else (a host capped lower) gets every title slot and +/// [`MIN_DYNAMIC`], as before, or no heap. +fn view_layout(count: u32, mut make: impl FnMut(u32) -> Option) -> Option<(H, u32, u32)> { + if let Some(heap) = make(count.saturating_add(DYNAMIC)) { + return Some((heap, count, DYNAMIC)); + } + if count <= PORTABLE_VIEWS - MIN_DYNAMIC { + let dynamic = (PORTABLE_VIEWS - count).min(DYNAMIC); + // `DYNAMIC` was just refused; `MIN_DYNAMIC` is tried below. + if MIN_DYNAMIC < dynamic + && dynamic < DYNAMIC + && let Some(heap) = make(count + dynamic) + { + return Some((heap, count, dynamic)); + } + } else if let Some(heap) = make(count.saturating_add(MIN_DYNAMIC)) { + return Some((heap, count, MIN_DYNAMIC)); + } else { + let heap = make(PORTABLE_VIEWS)?; + // shortcut: descriptors past the host's limit are left out; a + // title that reaches them needs remapping. + tracing::warn!(count, "host view heap capped at {PORTABLE_VIEWS}"); + return Some((heap, PORTABLE_VIEWS - DYNAMIC, DYNAMIC)); + } + let heap = make(count + MIN_DYNAMIC)?; + Some((heap, count, MIN_DYNAMIC)) +} + impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { let host = host()?; @@ -93,8 +176,8 @@ impl HostHeap { }) } }; - // The larger dynamic range only where the host takes it on top of - // every title slot; else the smaller one, and the cap after that. + // Sampler heaps as the title made them; view heaps with dynamic + // slots after the title's (`view_layout`). let (heap, count, extra) = if sampler { match make(count) { Ok(heap) => (heap, count, 0), @@ -103,22 +186,15 @@ impl HostHeap { return None; } } - } else if let Ok(heap) = make(count + DYNAMIC) { - (heap, count, DYNAMIC) } else { - match make(count + MIN_DYNAMIC) { - Ok(heap) => (heap, count, MIN_DYNAMIC), - Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left - // out; a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC) - } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } + let mut refused = None; + let Some(layout) = view_layout(count, |n| make(n).map_err(|e| refused = Some(e)).ok()) + else { + let error = refused.map(|e| e.to_string()).unwrap_or_default(); + tracing::warn!(error, count, sampler, "no host descriptor heap"); + return None; + }; + layout }; // SAFETY: a live heap. let (cpu, step) = unsafe { @@ -130,22 +206,31 @@ impl HostHeap { tracing::debug!(count, sampler, "host descriptor heap"); // SAFETY: a live shader-visible heap. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; - GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( - gpu, - u64::from(count + extra) * u64::from(step), - u64::from(step), - sampler, - )); + GPU_RANGES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(GpuRange { + start: gpu, + bytes: u64::from(count + extra) * u64::from(step), + step: u64::from(step), + sampler, + title: u64::from(count), + }); let h = HostHeap { heap, cpu, step, count, - dynamic: extra, + // A view heap's last slots are its guards: never given to a + // table, so they keep the null views made below. + dynamic: extra.saturating_sub(HEAP_GUARDS.len() as u32), sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; extra as usize])), + next: Mutex::new(( + 0, + vec![false; extra.saturating_sub(HEAP_GUARDS.len() as u32) as usize], + )), }; // 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 @@ -155,6 +240,11 @@ impl HostHeap { if let Err(e) = h.fill_null(kind, count + extra) { tracing::warn!(error = %e, "host descriptor heap not made null"); } + if !sampler { + for (i, &guard) in HEAP_GUARDS.iter().enumerate() { + null_guard(guard, h.cpu(h.guard_slot() + i as u32)); + } + } tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); Some(h) } @@ -248,8 +338,18 @@ impl HostHeap { } } let Some(first) = found else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + // Counted, not warned about once: the world ran out inside every + // submission while the log showed one line (#747). + static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let failed = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if failed.is_power_of_two() { + tracing::warn!( + n, + failed, + dynamic = self.dynamic, + "no free dynamic descriptor slots: a table is not made" + ); + } return None; }; taken[first..first + n].fill(true); @@ -263,6 +363,21 @@ impl HostHeap { self.count } + /// The slot translated shaders read in place of a heap index they + /// compute at or past it (or, read straight from a view heap, at or + /// past [`HostHeap::count`]): in a view heap the first of its guard + /// slots after the dynamic ones, one null view of each kind of + /// [`HEAP_GUARDS`] (a read takes its kind's), never given to a table; + /// in a sampler heap its last slot (any sampler reads safely). The + /// scheme is #483's. + pub(crate) fn guard_slot(&self) -> u32 { + if self.sampler { + self.count.saturating_sub(1) + } else { + self.count + self.dynamic + } + } + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// @@ -895,6 +1010,123 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +/// The null view of `kind` (one of [`HEAP_GUARDS`]: a DXIL resource kind, +/// `0x1000` for a UAV) at `at`: what a translated shader reads in place of +/// a heap index out of bounds. A null view reads zero and drops writes +/// only where the shader reads it as the kind it is (D3D12 binding spec, +/// "NULL Descriptors"), so a 2D texture SRV will not do for every read. +fn null_guard(kind: u32, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let uav = kind & 0x1000 != 0; + let kind = kind & 0xFF; + // SAFETY: a slot of our heap; a null resource is allowed with a desc, + // a null constant buffer view with none. + unsafe { + if kind == 13 { + host.device.CreateConstantBufferView(None, at); + return; + } + if uav { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ..Default::default() + }; + desc.ViewDimension = match kind { + 1 => D3D12_UAV_DIMENSION_TEXTURE1D, + 4 => { + desc.Anonymous.Texture3D.WSize = u32::MAX; + D3D12_UAV_DIMENSION_TEXTURE3D + } + 6 => { + desc.Anonymous.Texture1DArray.ArraySize = 1; + D3D12_UAV_DIMENSION_TEXTURE1DARRAY + } + 7 => { + desc.Anonymous.Texture2DArray.ArraySize = 1; + D3D12_UAV_DIMENSION_TEXTURE2DARRAY + } + 10..=12 => { + desc.Anonymous.Buffer.NumElements = 1; + if kind == 11 { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else if kind == 12 { + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.Anonymous.Buffer.StructureByteStride = 4; + } + D3D12_UAV_DIMENSION_BUFFER + } + _ => D3D12_UAV_DIMENSION_TEXTURE2D, + }; + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + at, + ); + return; + } + let mut desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + let a = &mut desc.Anonymous; + desc.ViewDimension = match kind { + 1 => { + a.Texture1D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE1D + } + 3 => D3D12_SRV_DIMENSION_TEXTURE2DMS, + 4 => { + a.Texture3D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE3D + } + 5 => { + a.TextureCube.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURECUBE + } + 6 => { + a.Texture1DArray.MipLevels = 1; + a.Texture1DArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE1DARRAY + } + 7 => { + a.Texture2DArray.MipLevels = 1; + a.Texture2DArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE2DARRAY + } + 8 => { + a.Texture2DMSArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY + } + 9 => { + a.TextureCubeArray.MipLevels = 1; + a.TextureCubeArray.NumCubes = 1; + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY + } + 10..=12 => { + a.Buffer.NumElements = 1; + desc.Format = DXGI_FORMAT_R32_UINT; + if kind == 11 { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + a.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else if kind == 12 { + desc.Format = DXGI_FORMAT_UNKNOWN; + a.Buffer.StructureByteStride = 4; + } + D3D12_SRV_DIMENSION_BUFFER + } + _ => { + a.Texture2D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE2D + } + }; + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at); + } +} + /// A view that reads zeros, for slots whose view the host cannot make. /// shortcut: slots with no view at all (kind unknown) get this null 2D /// view; null buffer views there did not stop the world's low-address @@ -973,4 +1205,216 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// The view heap the world makes (#747). + const WORLD_VIEWS: u32 = 1_245_184; + + /// [`view_layout`] on a host that takes view heaps up to `cap` slots: + /// (total, title slots, dynamic slots). + fn layout_on(cap: u32, count: u32) -> Option<(u32, u32, u32)> { + view_layout(count, |n| (n <= cap).then_some(n)) + } + + /// A host without a cap (AMD, WARP) keeps every title slot and the full + /// dynamic range. + #[test] + fn uncapped_view_heaps_keep_every_title_slot() { + for count in [4, 737_856, 934_464, WORLD_VIEWS] { + assert_eq!( + layout_on(u32::MAX, count), + Some((count + DYNAMIC, count, DYNAMIC)), + "{count}" + ); + } + } + + /// On a heap capped at 1,000,000 (NVIDIA) the world's heap keeps the + /// full dynamic range: with 2^16 its fresh tables ran out inside every + /// submission and most world draws were dropped (#747). + #[test] + fn capped_view_heaps_keep_the_full_dynamic_range() { + assert_eq!( + layout_on(PORTABLE_VIEWS, WORLD_VIEWS), + Some((PORTABLE_VIEWS, PORTABLE_VIEWS - DYNAMIC, DYNAMIC)) + ); + } + + /// A capped heap that has room for the title's slots keeps all of them + /// and gives the dynamic range the rest; title slots are only given up + /// where the title's heap does not fit anyway. + #[test] + fn capped_view_heaps_give_title_slots_up_only_past_the_cap() { + let cap = PORTABLE_VIEWS; + assert_eq!( + layout_on(cap, 700_000), + Some((700_000 + DYNAMIC, 700_000, DYNAMIC)) + ); + assert_eq!(layout_on(cap, 900_000), Some((cap, 900_000, 100_000))); + assert_eq!( + layout_on(cap, cap - MIN_DYNAMIC), + Some((cap, cap - MIN_DYNAMIC, MIN_DYNAMIC)) + ); + for count in (0..=2_000_000).step_by(997) { + let (total, title, dynamic) = layout_on(cap, count).unwrap(); + assert!(total <= cap && title + dynamic == total, "{count}"); + assert!((MIN_DYNAMIC..=DYNAMIC).contains(&dynamic), "{count}"); + assert!(title <= count, "{count}"); + assert!( + title == count || dynamic == DYNAMIC, + "{count}: title slots lost" + ); + } + } + + /// The split before #747, as reference: `count` + [`DYNAMIC`], else + /// `count` + [`MIN_DYNAMIC`], else (past the portable limit) the + /// portable limit with [`MIN_DYNAMIC`] dynamic slots. + fn before_747(cap: u32, count: u32) -> Option<(u32, u32)> { + let takes = |n: u32| n <= cap; + if takes(count.saturating_add(DYNAMIC)) { + Some((count, DYNAMIC)) + } else if takes(count.saturating_add(MIN_DYNAMIC)) { + Some((count, MIN_DYNAMIC)) + } else if count.saturating_add(MIN_DYNAMIC) > PORTABLE_VIEWS && takes(PORTABLE_VIEWS) { + Some((PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)) + } else { + None + } + } + + /// On every host cap the split gives no fewer title slots and no fewer + /// dynamic slots than before, except where #747 trades them: where the + /// title's heap was cut to the portable limit before, the cut keeps the + /// full dynamic range now. A host that takes the title's heap with the + /// fewest dynamic slots (1.31M views were reported on an RTX 4060 + /// Laptop, #735) keeps every title slot. + #[test] + fn view_heap_split_is_never_worse_than_before() { + let caps = [900_000, PORTABLE_VIEWS, 1_310_720, 1_400_000, u32::MAX]; + for cap in caps { + for count in (0..=2_000_000).step_by(991).chain([WORLD_VIEWS]) { + let new = layout_on(cap, count).map(|(_, t, d)| (t, d)); + let old = before_747(cap, count); + let cut = Some((PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)); + let traded = count > PORTABLE_VIEWS - MIN_DYNAMIC && old == cut; + match (old, new) { + (None, None) => {} + (Some((t0, d0)), Some((t, d))) if traded => { + assert_eq!((t0, d0), (PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)); + assert_eq!((t, d), (PORTABLE_VIEWS - DYNAMIC, DYNAMIC)); + } + (Some((t0, d0)), Some((t, d))) => { + assert!(t >= t0 && d >= d0, "cap {cap}, count {count}"); + } + _ => panic!("cap {cap}, count {count}: {old:?} before, {new:?} now"), + } + } + } + // The world's heap on a host capped above the portable limit. + assert_eq!( + layout_on(1_400_000, WORLD_VIEWS), + Some((WORLD_VIEWS + MIN_DYNAMIC, WORLD_VIEWS, MIN_DYNAMIC)) + ); + } + + /// The world's view heap on the real device: uncapped or capped at the + /// portable limit (NVIDIA), it holds the full dynamic range, and every + /// dynamic slot up to the heap's last can be taken and written. + /// CPU-side descriptor writes only; nothing is submitted. + #[test] + fn world_view_heap_has_the_full_dynamic_range_on_the_host() { + if host().is_none() { + return; // no host GPU + } + let heap = HostHeap::new(false, WORLD_VIEWS).expect("the world's view heap"); + // The dynamic slots end below the guard slots, the heap's last. + let total = heap.count + heap.dynamic; + let span = heap.dynamic + HEAP_GUARDS.len() as u32; + assert_eq!(heap.guard_slot(), total); + eprintln!( + "world view heap: {} title slots, {} dynamic, guard {}", + heap.count, + heap.dynamic, + heap.guard_slot() + ); + if heap.count == WORLD_VIEWS && span == MIN_DYNAMIC { + // A host capped between the two: the split before #747. + eprintln!("host capped above the portable limit; the full range is not checked"); + } else { + assert_eq!(span, DYNAMIC); + assert!(heap.count == WORLD_VIEWS || heap.count + span == PORTABLE_VIEWS); + } + let dynamic = heap.dynamic; + // Tables of 140 slots (the world's large ones, #747) until full. + const TABLE: u32 = 140; + let mut tables = 0; + while let Some(first) = heap.dynamic(TABLE) { + assert_eq!(first, heap.count + tables * TABLE); + tables += 1; + } + assert_eq!(tables, dynamic / TABLE); + // Exhausted: what is left at the end is given out, nothing more, + // and no run is taken in part. + let left = dynamic % TABLE; + assert_eq!(heap.dynamic(left + 1), None); + assert_eq!(heap.dynamic(left), Some(total - left)); + assert_eq!(heap.dynamic(1), None); + // A table given back (its list reset) is taken again, and only it. + let fifth = heap.count + 5 * TABLE; + heap.release(fifth, TABLE); + assert_eq!(heap.dynamic(TABLE + 1), None); + assert_eq!(heap.dynamic(TABLE), Some(fifth)); + let last = heap.count + heap.dynamic - 1; + heap.make_null(last); + let host = host().unwrap(); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + // Device-removed reports tell title slots from dynamic ones. + // SAFETY: a live shader-visible heap. + let start = unsafe { heap.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + let at = |slot: u32| start + u64::from(slot) * u64::from(heap.step); + let title = format!("inside, title slot {}", heap.count - 1); + assert!(near_heaps(at(heap.count - 1)).contains(&title)); + let dynamic = format!("inside, dynamic slot 0 (slot {})", heap.count); + assert!(near_heaps(at(heap.count)).contains(&dynamic)); + let guard = format!("inside, guard slot {total}"); + assert!(near_heaps(at(total)).contains(&guard)); + } + + /// Every dynamic slot a heap hands out lies below its guard slots (the + /// heap's last): taking them all never reaches one, so no table is made + /// there. + #[test] + fn the_guard_slot_is_never_given_to_a_table() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + assert_eq!(heap.guard_slot(), 4 + heap.dynamic); + let mut highest = 0; + while let Some(first) = heap.dynamic(1) { + highest = highest.max(first); + } + assert_eq!(highest, heap.guard_slot() - 1); + // The guards are the heap's last slots. + let kept = heap.kept.lock().unwrap_or_else(|e| e.into_inner()); + assert_eq!(kept.len(), (heap.guard_slot() as usize) + HEAP_GUARDS.len()); + } + + /// Where an address lies against a view heap of 10 slots of 32 bytes, + /// the first 6 the title's and the last 2 its guards; a sampler heap + /// has no guard of its own past its slots. + #[test] + fn device_removed_reports_name_title_dynamic_and_guard_slots() { + let place = |va| place_in_heap(va, 0x1000, 320, 32, 6, 2); + assert_eq!(place(0xf00), "0x100 below"); + assert_eq!(place(0x1000), "inside, title slot 0"); + assert_eq!(place(0x1000 + 5 * 32 + 31), "inside, title slot 5"); + assert_eq!(place(0x1000 + 6 * 32), "inside, dynamic slot 0 (slot 6)"); + assert_eq!(place(0x1000 + 7 * 32), "inside, dynamic slot 1 (slot 7)"); + assert_eq!(place(0x1000 + 8 * 32), "inside, guard slot 8"); + assert_eq!(place(0x1000 + 9 * 32), "inside, guard slot 9"); + assert_eq!(place(0x1000 + 10 * 32), "0x0 past its end (slot 10)"); + let sampler = place_in_heap(0x1000 + 9 * 32, 0x1000, 320, 32, 10, 0); + assert_eq!(sampler, "inside, title slot 9"); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc4ad..0491795235 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -296,6 +296,24 @@ impl State { }; } + /// The value of user-data dword `u` of a translated shader: a root + /// argument, or a bound heap's bound (`Lower::heap_bound`): its guard + /// slot (dword 0), a view heap's title slots (dword 1). + fn user_dword(&self, compute: bool, u: &victory_shader::emit::UserData) -> u32 { + let heap = |samplers: bool| { + let h = self.heaps[usize::from(samplers)]; + (h != 0) + .then(|| crate::descriptor::heap(h as This).host()) + .flatten() + }; + match (u.root, u.dword) { + (RootType::ResourceHeap, 0) => heap(false).map_or(0, |h| h.guard_slot()), + (RootType::ResourceHeap, _) => heap(false).map_or(0, |h| h.count()), + (RootType::SamplerHeap, _) => heap(true).map_or(0, |h| h.guard_slot()), + _ => self.user_value(compute, u.slot, u.root, u.dword), + } + } + /// The user-data value of a root argument, as translated shaders read /// it: a table's byte offset in its heap, a constant's value. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { @@ -479,7 +497,7 @@ impl State { .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, - None => self.user_value(compute, u.slot, u.root, u.dword), + None => self.user_dword(compute, u), }; } // SAFETY: an open list; `values` covers the parameter. @@ -567,7 +585,7 @@ impl State { let t = stage.translated(); let _ = write!(text, " | {}:", stage.shader.hash); for u in &t.host.user_data { - let v = self.user_value(compute, u.slot, u.root, u.dword); + let v = self.user_dword(compute, u); let _ = write!(text, " u{}={v:#x}", u.index); let index = if u.root == RootType::Table { v / 32 } else { v }; if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa10c..40695322d1 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -665,3 +665,85 @@ fn root_signature( Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A stage's user data as [`HostPipeline::new`] binds it: root + /// constants, one dword of the root signature each. + fn constants(dwords: u32, visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER1 { + D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + } + } + + /// A root CBV as [`HostPipeline::new`] binds one: two dwords. + fn root_cbv(visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER1 { + D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_CBV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + } + } + + /// The host takes a root signature of up to 64 dwords and refuses one + /// of 65, whatever they are made of (the D3D12 limit); a pipeline whose + /// stages' user data and root views pass it is refused (#747: the + /// heap bounds' user data must not push one over). + #[test] + fn root_signatures_hold_64_dwords() { + let Some(host) = host() else { + return; // no host GPU + }; + let (vs, ps) = ( + D3D12_SHADER_VISIBILITY_VERTEX, + D3D12_SHADER_VISIBILITY_PIXEL, + ); + let cases: [(&str, Vec, bool); 5] = [ + ( + "63: 32 + 31", + vec![constants(32, vs), constants(31, ps)], + true, + ), + ( + "64: 32 + 32", + vec![constants(32, vs), constants(32, ps)], + true, + ), + ( + "64: 30 + 32 + root CBV", + vec![constants(30, vs), constants(32, ps), root_cbv(ps)], + true, + ), + ( + "65: 32 + 31 + root CBV", + vec![constants(32, vs), constants(31, ps), root_cbv(ps)], + false, + ), + ( + "65: 33 + 32", + vec![constants(33, vs), constants(32, ps)], + false, + ), + ]; + for (label, params, takes) in cases { + let made = root_signature(&host.device, ¶ms, &[], false).is_ok(); + assert_eq!(made, takes, "{label}"); + } + } +} diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index fdc02aa119..53710815dc 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -706,6 +706,8 @@ fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec { (RootType::Table, 3) => 5 * 32, // The typed views of `raw` (compute) from 9. (RootType::Table, 6) => 9 * 32, + // Heap bounds: every view these tests bind is in range. + (RootType::ResourceHeap | RootType::SamplerHeap, _) => u32::MAX, other => panic!("unexpected user data {other:?}"), }; } @@ -1031,6 +1033,7 @@ fn float_semantics_are_the_consoles() { views: &views, samplers: &[], groups: [1, 1, 1], + placed: None, }, ) .unwrap(); @@ -1171,6 +1174,7 @@ fn translated_compute_matches_pc() { views: &views, samplers: &samplers, groups: [2, 2, 1], + placed: None, }; let mut failures = Vec::new(); let only = std::env::var("VICTORY_DIFF_ONLY").ok(); diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4dc5..992e705988 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -947,6 +947,191 @@ pub struct Dispatch<'a> { pub views: &'a [View<'a>], pub samplers: &'a [D3D12_SAMPLER_DESC], pub groups: [u32; 3], + /// Where the views go: `None` in order from slot 0, with the guard + /// slots after them ([`bound`]); else the view heap's size and each + /// view's slot, the guard slots last, every other slot null. + pub placed: Option<(u32, &'a [u32])>, +} + +/// The user-data value of a translated shader's heap bound entry (root +/// type `ResourceHeap` or `SamplerHeap`, see `Lower::heap_bound`) for a +/// [`Host::dispatch`] with `views` views in order and `samplers` samplers: +/// the first guard slot after the views, as many title slots as views, +/// the last sampler. `None` for other entries. +#[cfg(test)] +pub fn bound(u: &super::UserData, views: usize, samplers: usize) -> Option { + use crate::native::RootType; + match u.root { + RootType::ResourceHeap => Some(views as u32), + RootType::SamplerHeap => Some(samplers.saturating_sub(1) as u32), + _ => None, + } +} + +/// Makes the slots of view heap `heap` from `first` on the host's guard +/// slots: one null view of each kind of [`super::HEAP_GUARDS`], as +/// `victory-gpu` makes them (`descriptor::host::null_guard`). +#[cfg(test)] +fn null_guards(dev: &ID3D12Device, heap: &ID3D12DescriptorHeap, first: u32) { + let heap_kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: slots inside a live heap; null resources with descriptions, + // a null constant buffer view with none. + unsafe { + let step = dev.GetDescriptorHandleIncrementSize(heap_kind) as usize; + let start = heap.GetCPUDescriptorHandleForHeapStart(); + for (i, &guard) in super::HEAP_GUARDS.iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (first as usize + i) * step, + }; + let (uav, kind) = (guard & 0x1000 != 0, guard & 0xFF); + if kind == 13 { + dev.CreateConstantBufferView(None, at); + } else if uav { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ..Default::default() + }; + desc.ViewDimension = match kind { + 1 => D3D12_UAV_DIMENSION_TEXTURE1D, + 4 => { + desc.Anonymous.Texture3D.WSize = u32::MAX; + D3D12_UAV_DIMENSION_TEXTURE3D + } + 6 => { + desc.Anonymous.Texture1DArray.ArraySize = 1; + D3D12_UAV_DIMENSION_TEXTURE1DARRAY + } + 7 => { + desc.Anonymous.Texture2DArray.ArraySize = 1; + D3D12_UAV_DIMENSION_TEXTURE2DARRAY + } + 10..=12 => { + desc.Anonymous.Buffer.NumElements = 1; + if kind == 11 { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else if kind == 12 { + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.Anonymous.Buffer.StructureByteStride = 4; + } + D3D12_UAV_DIMENSION_BUFFER + } + _ => D3D12_UAV_DIMENSION_TEXTURE2D, + }; + dev.CreateUnorderedAccessView(None, None, Some(&desc), at); + } else { + let mut desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + let a = &mut desc.Anonymous; + desc.ViewDimension = match kind { + 1 => { + a.Texture1D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE1D + } + 3 => D3D12_SRV_DIMENSION_TEXTURE2DMS, + 4 => { + a.Texture3D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE3D + } + 5 => { + a.TextureCube.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURECUBE + } + 6 => { + a.Texture1DArray.MipLevels = 1; + a.Texture1DArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE1DARRAY + } + 7 => { + a.Texture2DArray.MipLevels = 1; + a.Texture2DArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE2DARRAY + } + 8 => { + a.Texture2DMSArray.ArraySize = 1; + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY + } + 9 => { + a.TextureCubeArray.MipLevels = 1; + a.TextureCubeArray.NumCubes = 1; + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY + } + 10..=12 => { + a.Buffer.NumElements = 1; + desc.Format = DXGI_FORMAT_R32_UINT; + if kind == 11 { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + a.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else if kind == 12 { + desc.Format = DXGI_FORMAT_UNKNOWN; + a.Buffer.StructureByteStride = 4; + } + D3D12_SRV_DIMENSION_BUFFER + } + _ => { + a.Texture2D.MipLevels = 1; + D3D12_SRV_DIMENSION_TEXTURE2D + } + }; + dev.CreateShaderResourceView(None, Some(&desc), at); + } + } + } +} + +/// Makes `n` slots of view heap `heap` from `first` on null, as the host +/// makes its empty slots (a null 2D texture view): one block made, then +/// copied. +#[cfg(test)] +fn null_views(dev: &ID3D12Device, heap: &ID3D12DescriptorHeap, first: u32, n: u32) { + const BLOCK: u32 = 1 << 16; + if n == 0 { + return; + } + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + // SAFETY: slots inside live heaps; the CPU-side block outlives the + // copies. + unsafe { + let step = dev.GetDescriptorHandleIncrementSize(kind) as usize; + let block: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK.min(n), + ..Default::default() + }) + .expect("a CPU descriptor heap"); + let start = block.GetCPUDescriptorHandleForHeapStart(); + for i in 0..BLOCK.min(n) as usize { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i * step, + }; + dev.CreateShaderResourceView(None, Some(&desc), at); + } + let to = heap.GetCPUDescriptorHandleForHeapStart(); + let mut done = 0; + while done < n { + let k = BLOCK.min(n - done); + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: to.ptr + (first + done) as usize * step, + }; + dev.CopyDescriptorsSimple(k, at, start, kind); + done += k; + } + } } #[cfg(test)] @@ -1071,7 +1256,27 @@ impl Host { b.Unmap(0, None); Ok(b) }; - let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.views.len())?; + // In order with a null guard slot after the views (see + // [`bound`]), or placed in a heap whose other slots are null. + let (view_slots, slot_of): (u32, Box usize>) = match d.placed { + None => ( + (d.views.len() + super::HEAP_GUARDS.len()) as u32, + Box::new(|i| i), + ), + Some((size, at)) => { + assert_eq!(at.len(), d.views.len(), "a slot for every view"); + let guards = super::HEAP_GUARDS.len() as u32; + assert!( + at.iter().all(|&s| s < size - guards), + "slots inside the heap, below its guard slots" + ); + (size, Box::new(move |i| at[i] as usize)) + } + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, view_slots as usize)?; + null_views(dev, &views, 0, view_slots); + // The guard slots, one null view of each kind, end the heap. + null_guards(dev, &views, view_slots - super::HEAP_GUARDS.len() as u32); let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.len())?; let view_size = dev .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) @@ -1083,7 +1288,7 @@ impl Host { let mut uavs = Vec::new(); for (i, v) in d.views.iter().enumerate() { let mut at = views.GetCPUDescriptorHandleForHeapStart(); - at.ptr += i * view_size; + at.ptr += slot_of(i) * view_size; match *v { View::Texture(..) | View::Cube(..) => { let (w, h, texels, faces) = match *v { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd804b0..c23ec95c75 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -65,9 +65,63 @@ enum Stop { } pub(crate) fn lower(parts: &Parts) -> Result { + // The host's heap bounds go past every user-data dword the program + // reads (`Lower::heap_bound`). Placed past the whole layout first, + // which is always safe; where the program reads less of it, lowered + // again with them right past its last read (lowered twice, then kept + // in the shader cache), so they cost no more + // host root-signature space than they need (64 dwords for all stages). + let layout_end = parts + .native + .layout + .iter() + .map(|p| u32::from(p.user_data) + p.sgprs) + .max() + .unwrap_or(0); + let wide = lower_at(parts, layout_end)?; + let is_bound = |u: &&UserData| matches!(u.root, RootType::ResourceHeap | RootType::SamplerHeap); + if !wide.user_data.iter().any(|u| is_bound(&u)) { + return Ok(wide); + } + let read_end = |l: &Lowered| { + l.user_data + .iter() + .filter(|u| !is_bound(u)) + .map(|u| u.index + 1) + .max() + .unwrap_or(0) + }; + let end = read_end(&wide); + if end >= layout_end { + return Ok(wide); + } + // Only a saving: whatever stops it, the first result stands. + let Ok(tight) = lower_at(parts, end) else { + return Ok(wide); + }; + // The same reads, and no bound on a dword the program reads. + let reads = |l: &Lowered| -> Vec { + let mut r: Vec = l + .user_data + .iter() + .filter(|u| !is_bound(u)) + .map(|u| u.index) + .collect(); + r.sort_unstable(); + r + }; + if reads(&tight) == reads(&wide) && read_end(&tight) <= end { + Ok(tight) + } else { + Ok(wide) + } +} + +/// [`lower`] with the heap bounds from user-data dword `bounds_at` on. +fn lower_at(parts: &Parts, bounds_at: u32) -> Result { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad).run() { + match Lower::new(parts, &bad, bounds_at).run() { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -222,6 +276,13 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// The host's heap bounds ([`Lower::heap_bound`]), read once each: the + /// view heap's guard slot, the sampler heap's, and the view heap's + /// title slots. + heap_bounds: [Option; 3], + /// The user-data dword the first heap bound the program reads goes to; + /// the others follow in the order they are read. + bounds_at: u32, } /// Iterations after which a loop is left (per entry into it), unless @@ -343,7 +404,7 @@ fn unsupported(offset: usize, what: Why) -> Stop { } impl<'a> Lower<'a> { - fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { + fn new(x: &'a Parts<'a>, bad: &'a HashMap, bounds_at: u32) -> Self { let p = x.p; let mut phi_at = HashMap::new(); for (b, block) in p.blocks.iter().enumerate() { @@ -515,6 +576,8 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + heap_bounds: [None; 3], + bounds_at, } } @@ -1158,6 +1221,11 @@ impl<'a> Lower<'a> { dword, }, ); + Val::I32(self.user_dword(index)) + } + + /// Dword `index` of the user-data buffer, read in the entry block. + fn user_dword(&mut self, index: u32) -> V { self.s.user_data = self.s.user_data.max(index + 1); let h = match self.user_data { Some(h) => h, @@ -1177,7 +1245,7 @@ impl<'a> Lower<'a> { 59, &[h, row], ); - Val::I32(self.s.m.extract(entry, r, index % 4)) + self.s.m.extract(entry, r, index % 4) } /// A dword of a lane mask as a number: the ballot of the lanes' bits, @@ -3306,13 +3374,20 @@ impl<'a> Lower<'a> { sampler: bool, props: (u32, u32), ) -> Result { + // Which guard slot an index out of bounds reads: one of this read's + // kind (`HEAP_GUARDS`). + let guard = if sampler { + 0 + } else { + super::shader::heap_guard(props.0) + }; match src { Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props.0); if let Some(&h) = self.handles.get(&key) { return Ok(h); } - let index = self.heap_index(*load, *first, sampler)?; + let index = self.heap_index(*load, *first, sampler, guard)?; // A waterfall loop's load at the first lane's offset reads // each lane's own entry (see `resource::Waterfall`). let per_lane = self.x.res.waterfall.loads.contains(load); @@ -3380,7 +3455,7 @@ impl<'a> Lower<'a> { }; 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); + let index = self.heap_index(*load, *first, sampler, guard); self.cur = here; incoming.push((index?, at)); } @@ -3402,8 +3477,8 @@ impl<'a> Lower<'a> { Val::Bit(x) => x, _ => return Err("SCC without a value"), }; - let set = self.heap_index(a, fa, sampler)?; - let clear = self.heap_index(b, fb, sampler)?; + let set = self.heap_index(a, fa, sampler, guard)?; + let clear = self.heap_index(b, fb, sampler, guard)?; let index = self.s.m.select(self.cur, cond, set, clear); Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) } @@ -3411,7 +3486,7 @@ impl<'a> Lower<'a> { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. - let index = self.lane_heap_index(src, sampler)?; + let index = self.lane_heap_index(src, sampler, guard)?; Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) } } @@ -3420,10 +3495,10 @@ impl<'a> Lower<'a> { /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). - fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + fn lane_heap_index(&mut self, src: &Source, sampler: bool, guard: u32) -> Result { match src { - Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), - Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler), + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler, guard), + Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler, guard), Source::Lanes { mask, args } | Source::Select { scc: mask, args } => { let [a, b] = &args[..] else { return Err("a descriptor chosen per lane"); @@ -3442,8 +3517,8 @@ impl<'a> Lower<'a> { _ => return Err("SCC without a value"), } }; - let set = self.lane_heap_index(a, sampler)?; - let clear = self.lane_heap_index(b, sampler)?; + let set = self.lane_heap_index(a, sampler, guard)?; + let clear = self.lane_heap_index(b, sampler, guard)?; Ok(self.s.m.select(self.cur, cond, set, clear)) } Source::LanePhi { block, args } => { @@ -3464,7 +3539,7 @@ impl<'a> Lower<'a> { let index = match arg { Some(arg) => { let here = std::mem::replace(&mut self.cur, at); - let index = self.lane_heap_index(arg, sampler); + let index = self.lane_heap_index(arg, sampler, guard); self.cur = here; index? } @@ -3483,16 +3558,23 @@ impl<'a> Lower<'a> { /// The heap index of the descriptor at dword `first` of what the global /// load at `load` reads, in each lane: its address (base plus offsets) /// over the descriptor size. - fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + fn fetched_index( + &mut self, + load: Site, + first: u8, + sampler: bool, + guard: u32, + ) -> Result { const WHY: Why = "a per-lane descriptor load"; let a = *self .scalar .get(&load) .ok_or("an untracked descriptor load")?; - match self.x.native.layout.get(a.param).map(|p| p.root) { - Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + let direct = match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table) => false, + Some(RootType::ResourceHeap | RootType::SamplerHeap) => true, _ => return Err("a descriptor outside the heaps"), - } + }; let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; let Fields::Flat { addr: Some(Operand::Vector { reg, .. }), @@ -3519,20 +3601,22 @@ impl<'a> Lower<'a> { .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first))); at = self.s.m.bin(c, Bin::Add, at, k); let shift = self.s.m.i32(if sampler { 4 } else { 5 }); - Ok(self.s.m.bin(c, Bin::LShr, at, shift)) + let index = self.s.m.bin(c, Bin::LShr, at, shift); + Ok(self.heap_bound(index, sampler, direct, guard)) } /// The heap index of the descriptor at dword `first` of what the scalar /// load at `load` reads, computed in the current block. - fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + fn heap_index(&mut self, load: Site, first: u8, sampler: bool, guard: u32) -> Result { let a = *self .scalar .get(&load) .ok_or("an untracked descriptor load")?; - match self.x.native.layout.get(a.param).map(|p| p.root) { - Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + let direct = match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table) => false, + Some(RootType::ResourceHeap | RootType::SamplerHeap) => true, _ => return Err("a descriptor outside the heaps"), - } + }; let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; let Fields::Smem { base, @@ -3559,7 +3643,74 @@ impl<'a> Lower<'a> { addr = self.s.m.bin(c, Bin::Add, addr, so); } let shift = self.s.m.i32(if sampler { 4 } else { 5 }); - Ok(self.s.m.bin(c, Bin::LShr, addr, shift)) + let index = self.s.m.bin(c, Bin::LShr, addr, shift); + Ok(self.heap_bound(index, sampler, direct, guard)) + } + + /// `index` where the host has a slot for it, else the heap's guard + /// slot. A heap index is an address the title's data computes; on the + /// console a wrong one reads some memory as a descriptor, but on the + /// host an index past the heap is undefined (NVIDIA wraps it onto + /// another slot, AMD loses the device), and one inside the host's + /// dynamic slots reads a descriptor another draw made there. The + /// host passes its bounds in user data, past every other dword the + /// program reads (`bounds_at`, see [`lower`]), in the order it reads + /// them (the guard dword's scheme is #483's): + /// + /// * the guard slot (root type `ResourceHeap` / `SamplerHeap`, dword + /// 0): null in a view heap, any sampler in a sampler heap; indices + /// at or above it read it; + /// * for a view heap read directly (`direct`: through the heap, not a + /// table), its title slots (`ResourceHeap`, dword 1): the slots past + /// them hold the host's tables of other draws, so such indices read + /// the guard slot too. A table's indices may lie there (a table the + /// host made afresh), so they are bounded by the guard only. + fn heap_bound(&mut self, index: V, sampler: bool, direct: bool, kind: u32) -> V { + let guard = self.heap_bound_dword(if sampler { 1 } else { 0 }); + let limit = if direct && !sampler { + self.heap_bound_dword(2) + } else { + guard + }; + let c = self.cur; + // The guard slot of the read's kind (`HEAP_GUARDS`): a view heap + // keeps one null view of each kind from its guard slot on. + let target = if kind == 0 { + guard + } else { + let k = self.s.m.i32(kind); + self.s.m.bin(c, Bin::Add, guard, k) + }; + let inside = self.s.m.cmp(c, pred::IULT, index, limit); + self.s.m.select(c, inside, index, target) + } + + /// Heap bound `k` ([`Lower::heap_bound`]): 0 the view heap's guard slot, + /// 1 the sampler heap's, 2 the view heap's title slots. + fn heap_bound_dword(&mut self, k: usize) -> V { + if let Some(v) = self.heap_bounds[k] { + return v; + } + // In the order the program reads them, from `bounds_at` on (past + // every dword it reads otherwise: see `lower`). + let index = self.bounds_at + self.heap_bounds.iter().flatten().count() as u32; + let (root, dword) = match k { + 0 => (RootType::ResourceHeap, 0), + 1 => (RootType::SamplerHeap, 0), + _ => (RootType::ResourceHeap, 1), + }; + self.user_reads.insert( + index, + UserData { + index, + slot: 0, + root, + dword, + }, + ); + let v = self.user_dword(index); + self.heap_bounds[k] = Some(v); + v } fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { @@ -7240,6 +7391,35 @@ mod tests { } } + /// Per-lane descriptors loaded with `global_load` (`fetched_index`) + /// are bounded like those loaded with `s_load`: in this program only + /// the image comes from the view heap, so its guard entry is there + /// only if that path bounds it; the sampler (an `s_load`) has its own. + /// Read through tables, neither needs the title bound. + #[test] + fn per_lane_heap_indices_are_bounded_too() { + use crate::resource::tests::{WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64}; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + let mut bounds: Vec<_> = l + .user_data + .iter() + .filter(|u| matches!(u.root, RootType::ResourceHeap | RootType::SamplerHeap)) + .map(|u| (u.root, u.dword)) + .collect(); + bounds.sort_unstable_by_key(|b| (b.0 == RootType::SamplerHeap, b.1)); + assert_eq!( + bounds, + [(RootType::ResourceHeap, 0), (RootType::SamplerHeap, 0)], + "wave64 {wave64}" + ); + } + } + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { let (layout, mut used) = texture_tables(); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da8f1..51bfe2b630 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -13,7 +13,19 @@ //! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16 //! for sampler tables (the console's descriptor sizes; the code adds //! offsets in those units). The heap bases of dynamic resources are 0 -//! and not listed. +//! and not listed. Past every other dword the program reads come the +//! host's heap bounds, root type `ResourceHeap` (`SamplerHeap`): +//! dword 0 is the bound view (sampler) heap's first guard slot, and a +//! heap index the code computes at or above it reads a guard slot +//! instead (an index past a heap hangs some GPUs): in a view heap the +//! one of the read's kind, `guard + heap_guard(kind)` (the host keeps a +//! null view of each kind of [`HEAP_GUARDS`] there, as a null view is +//! defined only when read as its own kind), in a sampler heap the guard +//! itself (any sampler will do). Dword 1 of `ResourceHeap` is the view +//! heap's title slots, the bound of a descriptor read straight from the +//! heap rather than through a table (past them the host keeps its own +//! tables of other draws). The host gives no table a slot at or above +//! the guard. The guard scheme is #483's. //! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and //! `SamplerDescriptorHeap[]`, at the index the console address gives, so //! the host heaps keep the title's descriptor order. The root signature @@ -97,7 +109,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use shader::{HEAP_GUARDS, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, heap_guard}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -179,7 +191,8 @@ pub struct UserData { pub index: u32, /// Root parameter index in the title's root signature. pub slot: u8, - /// `Constants` or `Table` (see the module notes for the value). + /// `Constants` or `Table`, or `ResourceHeap` / `SamplerHeap` for a + /// heap bound (see the module notes for the value). pub root: RootType, /// Dword within the parameter. pub dword: u32, diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index dd2eb75135..e6525516c1 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -13,6 +13,29 @@ pub const SAMPLER_SPACE: u32 = 0; /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// The views a view heap's guard slots hold, from its guard slot on (see +/// the module notes), as the first word of the DXIL resource properties a +/// heap read is annotated with: the resource kind, `0x1000` for a UAV. A +/// null view reads as zero and drops writes only where it is of the kind +/// the shader reads (D3D12 binding spec, "NULL Descriptors"; GPU-based +/// validation reports any other), so each kind has its own: SRVs of every +/// texture kind and of typed, raw and structured buffers, UAVs of the +/// kinds a UAV can be, and a constant buffer. +pub const HEAP_GUARDS: [u32; 21] = [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, // SRVs + 0x1001, 0x1002, 0x1004, 0x1006, 0x1007, 0x100A, 0x100B, 0x100C, // UAVs + 13, // constant buffer +]; + +/// Which of [`HEAP_GUARDS`] a heap read annotated with `props0` reads in +/// place of an index out of bounds: its own kind's, else the 2D texture +/// SRV's. +pub fn heap_guard(props0: u32) -> u32 { + let kind = props0 & 0x10FF; + let at = |k| HEAP_GUARDS.iter().position(|&g| g == k); + at(kind).or_else(|| at(2)).unwrap_or(0) as u32 +} + /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; @@ -663,3 +686,28 @@ impl Shader { Some(self.m.md_node(list)) } } + +#[cfg(test)] +mod tests { + use super::{HEAP_GUARDS, heap_guard}; + + /// Every kind of heap read the lowering annotates (resource kinds 1-13, + /// `0x1000` for a UAV) has a guard slot of its own kind, so an index out + /// of bounds reads a null view of the kind the shader reads. + #[test] + fn every_heap_read_has_a_guard_of_its_kind() { + let srvs = [1, 2, 4, 5, 6, 7, 10, 11, 12]; + let uavs = [1, 2, 4, 6, 7, 10, 11, 12].map(|k| k | 0x1000); + for props in srvs.into_iter().chain(uavs).chain([13]) { + assert_eq!(HEAP_GUARDS[heap_guard(props) as usize], props, "{props:#x}"); + } + // Flags beyond the kind and the UAV bit do not change it. + assert_eq!(HEAP_GUARDS[heap_guard(0x8000 | 2) as usize], 2); + // A kind with no guard of its own reads the 2D texture SRV's. + assert_eq!(HEAP_GUARDS[heap_guard(0x1005) as usize], 2); + // Each guard once. + for (i, g) in HEAP_GUARDS.iter().enumerate() { + assert_eq!(heap_guard(*g) as usize, i, "{g:#x}"); + } + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d778..b8898d6a98 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -81,7 +81,15 @@ fn build_valu_cs(body: &[u32]) -> HostShader { words.extend_from_slice(body); words.extend_from_slice(&buffer_store_dword(0, 8, 0)); words.push(S_ENDPGM); + lower_cs(&words, RootType::Table, 0) +} +/// Lowers `words` as a 1-thread compute program with [`build_valu_cs`]'s +/// layout: 4 root constants in `s0..s3`, in `s4` the address of a table +/// holding a UAV (`heap`: `Table`) or of the view heap itself +/// (`ResourceHeap`: a descriptor read straight from the heap); then +/// `unread` more root constants (`s5` on) the program does not read. +fn lower_cs(words: &[u32], heap: RootType, unread: u8) -> HostShader { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -97,17 +105,27 @@ fn build_valu_cs(body: &[u32]) -> HostShader { slot: 0, }, RootParam { - root: RootType::Table, + root: heap, table_offset_dwords: 0, sgprs: 1, base_register: 0, user_data: 4, slot: 1, }, - ], + ] + .into_iter() + .chain((unread > 0).then_some(RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: u32::from(unread), + base_register: 1, + user_data: 5, + slot: 2, + })) + .collect(), used: vec![UsedResource { kind: ResourceType::Uav, - root: RootType::Table, + root: heap, table_offset_dwords: 0, lower_bound: 0, stride: 0, @@ -116,7 +134,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + rsrc2: u32::from(5 + unread) << 1, // user SGPRs: s0..s4, then the unread ones threads: [1, 1, 1], }), code, @@ -190,7 +208,8 @@ fn run_cases( ud[u.index as usize] = match (u.root, u.slot) { (RootType::Constants, 0) => inputs[u.dword as usize], (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), + _ => super::host::bound(u, 1, 0) + .unwrap_or_else(|| panic!("unexpected user data {u:?}")), }; } let out = host @@ -202,6 +221,7 @@ fn run_cases( views: &[View::RawUav(1)], samplers: &[], groups: [1, 1, 1], + placed: None, }, ) .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); @@ -937,3 +957,250 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// The view heap of a host capped at 1,000,000 views with the world's heap +/// (#747): title slots below [`TITLE`], dynamic slots (tables the host +/// makes per draw) up to the guard slots, the heap's last (one null view +/// of each kind, see [`super::HEAP_GUARDS`]; [`GUARD`] the first). +const CAPPED: u32 = 1_000_000; +const TITLE: u32 = 737_856; +const GUARD: u32 = CAPPED - super::HEAP_GUARDS.len() as u32; +/// UAVs at the slots around the bounds: the last title slot, then slots +/// that hold tables of other draws. +const PLACED: [u32; 5] = [TITLE - 1, TITLE, 934_463, 934_464, GUARD - 1]; + +/// A 1-thread program that loads a UAV descriptor at heap address `s4` + +/// (`s0` << 5), as bindless code adds an index it computes, and stores +/// `s1` through it. +fn heap_read_program(heap: RootType) -> HostShader { + let words = [ + s_mov_b32(5, 0x80), // s5 = 0 + sop2(0x1E, 6, 0, 0x85), // s_lshl_b32 s6, s0, 5: the index from data + // s_load_dwordx4 s[8:11], s[4:5], s6 + s_load_dwordx4(8, 4)[0], + 6 << 25, + vop1(0x001, 0, sgpr(1)), // v_mov_b32 v0, s1 + buffer_store_dword(0, 8, 0)[0], + buffer_store_dword(0, 8, 0)[1], + S_ENDPGM, + ]; + lower_cs(&words, heap, 0) +} + +/// Runs [`heap_read_program`] on every SM 6.6 device, in the [`CAPPED`] +/// heap with UAVs at [`PLACED`], for each case (index, table base slot), +/// with the host's `bounds` (guard slot, title slots) in the user data. +/// Per device: for each case, which placed UAV got the case's marker +/// (none: the read went to the null guard slot). +fn heap_reads( + heap: RootType, + bounds: (u32, u32), + cases: &[(u32, u32)], +) -> Vec<(&'static str, Vec>)> { + let shader = heap_read_program(heap); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut devices = Vec::new(); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut reads = Vec::new(); + for (i, &(index, base)) in cases.iter().enumerate() { + let marker = 0x1000 + i as u32; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot, u.dword) { + (RootType::Constants, 0, 0) => index, + (RootType::Constants, 0, 1) => marker, + (RootType::Constants, 0, _) => 0, + (RootType::Table, 1, _) => base * 32, + (RootType::ResourceHeap, _, 0) => bounds.0, + (RootType::ResourceHeap, _, _) => bounds.1, + other => panic!("unexpected user data {other:?}"), + }; + } + let views: Vec = PLACED.iter().map(|_| View::RawUav(1)).collect(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + placed: Some((CAPPED, &PLACED)), + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + let hit: Vec = (0..PLACED.len()).filter(|&j| out[j][0] == marker).collect(); + assert!( + hit.len() <= 1, + "{label}: index {index}: written through {hit:?}" + ); + assert!( + out.iter().all(|o| o[0] == 0 || o[0] == marker), + "{label}: index {index}: a UAV holds another case's value" + ); + reads.push(hit.first().copied()); + } + devices.push((label, reads)); + } + assert!( + !devices.is_empty(), + "neither hardware nor WARP SM 6.6 device available" + ); + devices +} + +/// A descriptor read straight from the view heap (bindless) at a title +/// index the host has a slot for reads the title's descriptor; one at an +/// index past the title slots (a capped heap leaves those out, and the +/// host's tables of other draws lie there), the guard slot itself, past +/// the heap or the last index an address gives reads the null guard: the +/// store goes nowhere. +#[test] +fn direct_heap_reads_past_the_title_slots_read_the_guard() { + let cases = [ + (TITLE - 1, 0), + (TITLE, 0), + (934_463, 0), + (934_464, 0), + (GUARD - 1, 0), + (GUARD, 0), + (999_999, 0), + (CAPPED, 0), + (1 << 25, 0), + (0x07FF_FFFF, 0), + ]; + for (label, reads) in heap_reads(RootType::ResourceHeap, (GUARD, TITLE), &cases) { + for (&(index, _), read) in cases.iter().zip(reads) { + let want = (index == TITLE - 1).then_some(0); + assert_eq!(read, want, "{label}: direct index {index}"); + } + } +} + +/// A table the host made afresh lies in the dynamic slots; reads through +/// it reach every slot below the guard (its own entries), and stop at the +/// guard like any other read. A title table reads the title's slots. +#[test] +fn table_reads_reach_the_dynamic_slots_up_to_the_guard() { + let cases = [ + (0, TITLE), + (196_607, TITLE), + (196_608, TITLE), + (GUARD - 1 - TITLE, TITLE), + (GUARD - TITLE, TITLE), + (999_999 - TITLE, TITLE), + (CAPPED - TITLE, TITLE), + (0, TITLE - 1), + ]; + let want = [ + Some(1), + Some(2), + Some(3), + Some(4), + None, + None, + None, + Some(0), + ]; + for (label, reads) in heap_reads(RootType::Table, (GUARD, TITLE), &cases) { + for ((&(k, base), read), want) in cases.iter().zip(reads).zip(want) { + assert_eq!(read, want, "{label}: table at {base}, entry {k}"); + } + } +} + +/// The negative control: with one bound for every read (the guard, as +/// #483 bounds them) or none (as before), a direct read at a title index +/// past the title slots reaches whatever table another draw has there. +/// Only indices inside the heap are run unbounded. +#[test] +fn without_a_title_bound_direct_reads_reach_other_draws_tables() { + let inside = [ + (TITLE - 1, 0), + (TITLE, 0), + (934_463, 0), + (934_464, 0), + (GUARD - 1, 0), + ]; + let want = [Some(0), Some(1), Some(2), Some(3), Some(4)]; + for bounds in [(GUARD, GUARD), (u32::MAX, u32::MAX)] { + for (label, reads) in heap_reads(RootType::ResourceHeap, bounds, &inside) { + assert_eq!(reads, want, "{label}: bounds {bounds:?}"); + } + } + // One bound still keeps reads off slots past the heap. + let past = [(GUARD, 0), (999_999, 0), (CAPPED, 0), (1 << 25, 0)]; + for (label, reads) in heap_reads(RootType::ResourceHeap, (GUARD, GUARD), &past) { + assert_eq!(reads, [None, None, None, None], "{label}"); + } +} + +/// The heap bounds' user-data entries of `s`: (dword, root type, which). +fn heap_bound_entries(s: &HostShader) -> Vec<(u32, RootType, u32)> { + let mut b: Vec<_> = s + .user_data + .iter() + .filter(|u| matches!(u.root, RootType::ResourceHeap | RootType::SamplerHeap)) + .map(|u| (u.index, u.root, u.dword)) + .collect(); + b.sort_unstable_by_key(|b| b.0); + b +} + +/// Where the bounds go: right past every other user-data dword the +/// program reads, in the order it reads them. Read straight from the +/// heap it reads s0 and s1 (the heap's base is 0, no dword): the view +/// guard, then the title slots. Through the table at s4: the guard only. +#[test] +fn heap_bounds_are_user_data_past_the_reads() { + assert_eq!( + heap_bound_entries(&heap_read_program(RootType::ResourceHeap)), + [ + (2, RootType::ResourceHeap, 0), + (3, RootType::ResourceHeap, 1) + ] + ); + assert_eq!( + heap_bound_entries(&heap_read_program(RootType::Table)), + [(5, RootType::ResourceHeap, 0)] + ); +} + +/// The host root signature holds 64 dwords for all of a pipeline's +/// stages, each stage's user data rounded up to a row of 4. Past a +/// layout of 31 user SGPRs (the most a console stage has) of which the +/// program reads a few, the bounds would take 32 dwords more; right past +/// the reads they fit in the row the reads already take. +#[test] +fn heap_bounds_cost_no_more_than_the_reads_need() { + let words = [ + s_mov_b32(5, 0x80), + sop2(0x1E, 6, 0, 0x85), + s_load_dwordx4(8, 4)[0], + 6 << 25, + vop1(0x001, 0, sgpr(1)), + buffer_store_dword(0, 8, 0)[0], + buffer_store_dword(0, 8, 0)[1], + S_ENDPGM, + ]; + // (heap, user-data dwords the reads take without bounds, with them) + for (heap, reads, dwords) in [(RootType::ResourceHeap, 2, 4), (RootType::Table, 5, 8)] { + let narrow = lower_cs(&words, heap, 0); + let wide = lower_cs(&words, heap, 26); + assert_eq!(wide.user_data, narrow.user_data, "{heap:?}"); + assert_eq!(wide.user_data_dwords(), dwords, "{heap:?}"); + assert_eq!( + u32::next_multiple_of(reads, 4), + dwords, + "{heap:?}: no row more" + ); + } +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 104fc6d0c0..a464f421df 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -124,8 +124,11 @@ fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { // Both tables start at heap index 0. let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { - assert_eq!(u.root, RootType::Table, "{u:?}"); - ud[u.index as usize] = 0; + ud[u.index as usize] = match u.root { + RootType::Table => 0, + _ => super::host::bound(u, views.len(), samplers.len()) + .unwrap_or_else(|| panic!("unexpected user data {u:?}")), + }; } let words = host .dispatch( @@ -136,6 +139,7 @@ fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { views, samplers: &samplers, groups: [1, 1, 1], + placed: None, }, ) .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));