diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 20b33fbe0ac..00af93d8c95 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -12,6 +12,8 @@ use crate::resource::{Memory, PAGEABLE_IIDS}; #[cfg(windows)] pub(crate) mod host; +#[cfg(windows)] +pub(crate) mod lease; const HEAP_IIDS: [Iid; 4] = [ guid( @@ -300,6 +302,7 @@ impl View { /// of resources or of memory) or memory the title placed a texture in: /// such views get host slots only for draws. #[cfg(windows)] + #[allow(dead_code)] fn is_buffer(&self) -> bool { match self { View::Constant(..) | View::Placed(..) => true, diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f2347adf..6302f2754e4 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -62,6 +62,9 @@ pub(crate) fn near_heaps(va: u64) -> String { /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; +/// The maximum shader-visible sampler count on D3D12 (all tiers). +const PORTABLE_SAMPLERS: u32 = 2048; + /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. @@ -71,7 +74,7 @@ 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. -const MIN_DYNAMIC: u32 = 1 << 16; +const MIN_DYNAMIC: u32 = 1 << 18; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { @@ -96,29 +99,29 @@ 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. let (heap, count, extra) = if sampler { - match make(count) { - Ok(heap) => (heap, count, 0), + let requested = count; + let target_count = if count > PORTABLE_SAMPLERS { + tracing::warn!(count, "host sampler heap capped at {PORTABLE_SAMPLERS}"); + PORTABLE_SAMPLERS + } else { + count + }; + match make(target_count) { + Ok(heap) => (heap, target_count, 0), Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + tracing::warn!(error = %e, count = requested, sampler, "no host descriptor heap"); return None; } } - } else if let Ok(heap) = make(count + DYNAMIC) { + } else if count + DYNAMIC <= PORTABLE_VIEWS && let Ok(heap) = make(count + DYNAMIC) { (heap, count, DYNAMIC) + } else if count + MIN_DYNAMIC <= PORTABLE_VIEWS && let Ok(heap) = make(count + MIN_DYNAMIC) { + (heap, count, MIN_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; - } - } + // 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}"); + (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS.saturating_sub(MIN_DYNAMIC), MIN_DYNAMIC) }; // SAFETY: a live heap. let (cpu, step) = unsafe { @@ -163,13 +166,17 @@ impl HostHeap { /// doubled by copies to a block, the block copied over the heap. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { const BLOCK: u32 = 1 << 16; + let block_size = BLOCK.min(total); + if block_size == 0 { + return Ok(()); + } let Some(host) = host() else { return Ok(()) }; // SAFETY: plain heap creation and copies inside live heaps. unsafe { let block: ID3D12DescriptorHeap = host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, - NumDescriptors: BLOCK, + NumDescriptors: block_size, ..Default::default() })?; let start = block.GetCPUDescriptorHandleForHeapStart(); @@ -182,14 +189,14 @@ impl HostHeap { null_view(start); } let mut filled = 1; - while filled < BLOCK { - let n = filled.min(BLOCK - filled); + while filled < block_size { + let n = filled.min(block_size - filled); host.device.CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } let mut done = 0; while done < total { - let n = BLOCK.min(total - done); + let n = block_size.min(total - done); host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } @@ -363,17 +370,17 @@ impl HostHeap { return None; }; if made[index as usize] != key { - let later = !for_draw && view.is_buffer(); - made[index as usize] = if later { 0 } else { key }; - let kept = if later { - None + let kept = make(&view, self.cpu(index)); + if let Some(kept) = kept { + made[index as usize] = key; + self.keep(index, kept); } else { - make(&view, self.cpu(index)) - }; - if kept.is_none() && !self.sampler { - null_for(&view, self.cpu(index)); + made[index as usize] = 0; + if !self.sampler { + null_for(&view, self.cpu(index)); + } + self.keep(index, None); } - self.keep(index, kept.flatten()); } Some(view) } @@ -973,4 +980,53 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// A large requested descriptor count is capped at PORTABLE_VIEWS + /// rather than creating a heap that violates D3D12 limits (#735). + #[test] + fn large_view_heap_is_capped_at_portable_limit() { + if host().is_none() { + return; + } + if let Some(heap) = HostHeap::new(false, 1_048_576) { + assert!(heap.count + heap.dynamic <= PORTABLE_VIEWS); + assert_eq!(heap.dynamic, MIN_DYNAMIC); + assert_eq!(heap.count, PORTABLE_VIEWS - MIN_DYNAMIC); + } + } + + /// A sampler heap larger than 2048 descriptors is capped at PORTABLE_SAMPLERS (#744). + #[test] + fn sampler_heap_larger_than_2048_is_capped() { + if host().is_none() { + return; + } + if let Some(heap) = HostHeap::new(true, 4096) { + assert_eq!(heap.count, PORTABLE_SAMPLERS); + } + } + + /// Buffer views mirror on creation when their host copy exists, so + /// shaders indexing the heap directly at run time read the real view + /// rather than a null descriptor. + /// A buffer view without a host shadow falls back to null, keeping its + /// key at 0 so it can be retried once the memory is registered. + #[test] + fn buffer_views_mirror_on_creation() { + if host().is_none() { + return; + } + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let mut title_slot = [0u64; 4]; + let s0 = title_slot.as_mut_ptr() as u64; + super::super::create_srv(std::ptr::null(), std::ptr::null(), std::ptr::null(), s0); + // SAFETY: s0 is our stack-allocated array. + let [tag, _i, _generation] = unsafe { *(s0 as *const [u32; 3]) }; + assert_eq!(tag, VIEW_TAG); + heap.mirror(0, s0, false); + // Resource is null, so make() returns None and made[0] stays 0 for later retry. + assert_eq!(heap.made.lock().unwrap()[0], 0); + } } diff --git a/crates/victory-gpu/src/descriptor/lease.rs b/crates/victory-gpu/src/descriptor/lease.rs new file mode 100644 index 00000000000..deb8f39f6cd --- /dev/null +++ b/crates/victory-gpu/src/descriptor/lease.rs @@ -0,0 +1,199 @@ +//! The dynamic descriptor slots a list holds, and giving back those of lists +//! that already ran when a heap runs short. +//! +//! A list keeps the dynamic slots its draws took until the title resets it +//! (see `draw::State`). Every submission is waited for, so once a list has +//! run the GPU no longer reads its slots; only submitting the same list a +//! second time, without a reset, would read them again. When a heap has no +//! room for a table, a draw would be dropped. Instead the slots of the +//! oldest list that already ran are taken back and that list is marked lost: +//! submitting it again is refused (the same as a draw whose table could not +//! be made), and it works again once the title resets it. +//! +//! shortcut: a list is taken back whole, oldest first, and only when +//! something would otherwise be dropped; the title's frames in flight decide +//! how much that frees. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +/// Dynamic slots: the title heap they belong to (its address), the first +/// and the count. +pub(crate) type Range = (usize, u32, u32); + +/// The slots one list holds. +#[derive(Default)] +pub(crate) struct Lease { + ranges: Mutex>, + /// The slots were taken back after the list ran. + lost: AtomicBool, +} + +/// The leases of lists that ran, oldest first, and that still hold slots. +/// Its lock also orders [`Lease::start`] against [`reclaim`], so a list is +/// never taken back while it runs. +static FINISHED: Mutex>> = Mutex::new(VecDeque::new()); + +fn finished_queue() -> std::sync::MutexGuard<'static, VecDeque>> { + FINISHED.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Lease { + /// Records a range the list took. + pub(crate) fn add(&self, heap: usize, first: u32, n: u32) { + self.ranges + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((heap, first, n)); + } + + /// Everything the list still holds, to give back (the list is reset or + /// released). Empty if the slots were taken back already. + pub(crate) fn take(&self) -> Vec { + std::mem::take(&mut *self.ranges.lock().unwrap_or_else(|e| e.into_inner())) + } + + /// Whether the slots were taken back after the list ran. + pub(crate) fn is_lost(&self) -> bool { + self.lost.load(Ordering::Acquire) + } + + fn holds(&self, heap: usize) -> bool { + self.ranges + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .any(|r| r.0 == heap) + } + + /// Before the list is submitted: false if its slots were taken back + /// (it must not run); else it cannot be taken back until + /// [`Lease::finish`]. + pub(crate) fn start(self: &Arc) -> bool { + let mut queue = finished_queue(); + if self.is_lost() { + return false; + } + queue.retain(|l| !Arc::ptr_eq(l, self)); + true + } + + /// After the list ran: its slots may be taken back if a heap runs short. + pub(crate) fn finish(self: &Arc) { + if self.is_lost() + || self + .ranges + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() + { + return; + } + let mut queue = finished_queue(); + queue.retain(|l| !Arc::ptr_eq(l, self)); + queue.push_back(self.clone()); + // Lists that were reset hold nothing and only take room here. + if queue.len() > 4096 { + queue.retain(|l| { + !l.ranges + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() + }); + } + } +} + +/// Takes back the slots of the oldest list that ran and holds some in `heap`, +/// handing each of its ranges to `release`. False if there is none. +pub(crate) fn reclaim(heap: usize, mut release: impl FnMut(Range)) -> bool { + let ranges = { + let mut queue = finished_queue(); + let Some(at) = queue.iter().position(|l| l.holds(heap)) else { + return false; + }; + let lease = queue.remove(at).expect("a position of the queue"); + lease.lost.store(true, Ordering::Release); + lease.take() + }; + for range in ranges { + release(range); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lease(heap: usize, ranges: &[(u32, u32)]) -> Arc { + let lease = Arc::new(Lease::default()); + for &(first, n) in ranges { + lease.add(heap, first, n); + } + lease + } + + /// Oldest first, only leases holding slots of the heap, each once. + #[test] + fn the_oldest_list_that_ran_is_taken_back_first() { + let heap = 0x1000_0001; + let (a, b) = (lease(heap, &[(10, 4), (20, 2)]), lease(heap, &[(30, 8)])); + let elsewhere = lease(0x1000_0002, &[(0, 1)]); + for l in [&a, &elsewhere, &b] { + l.finish(); + } + let mut given = Vec::new(); + assert!(reclaim(heap, |r| given.push(r))); + assert_eq!(given, [(heap, 10, 4), (heap, 20, 2)]); + assert!(a.is_lost() && !b.is_lost() && !elsewhere.is_lost()); + // Taken back: giving back when the list is reset releases nothing more. + assert!(a.take().is_empty()); + given.clear(); + assert!(reclaim(heap, |r| given.push(r))); + assert_eq!(given, [(heap, 30, 8)]); + assert!(!reclaim(heap, |_| panic!("nothing is left in this heap"))); + assert!(!elsewhere.is_lost()); + // Clean up the other heap's entry for the other tests. + assert!(reclaim(0x1000_0002, |_| {})); + } + + /// A list that has not finished, or that runs again, is not taken back, + /// and one that was taken back must not run. + #[test] + fn a_running_list_is_kept_and_a_lost_one_is_refused() { + let heap = 0x1000_0003; + let l = lease(heap, &[(1, 1)]); + assert!(!reclaim(heap, |_| panic!("it has not run"))); + l.finish(); + // Submitted again: it is not takeable while it runs. + assert!(l.start()); + assert!(!reclaim(heap, |_| panic!("it is running"))); + l.finish(); + assert!(reclaim(heap, |_| {})); + assert!(l.is_lost()); + assert!(!l.start(), "a list that lost its slots is refused"); + // A lost list is not queued again. + l.finish(); + assert!(!reclaim(heap, |_| panic!("it holds nothing"))); + } + + /// Finishing twice queues once; a list that was reset holds nothing and + /// is passed over. + #[test] + fn finishing_twice_queues_once_and_reset_lists_are_skipped() { + let heap = 0x1000_0004; + let (reset, kept) = (lease(heap, &[(5, 5)]), lease(heap, &[(50, 5)])); + reset.finish(); + reset.finish(); + kept.finish(); + // The title resets the first: it gives its slots back itself. + assert_eq!(reset.take(), [(heap, 5, 5)]); + let mut given = Vec::new(); + assert!(reclaim(heap, |r| given.push(r))); + assert_eq!(given, [(heap, 50, 5)]); + assert!(!reset.is_lost() && kept.is_lost()); + assert!(!reclaim(heap, |_| panic!("one entry was kept, once"))); + } +} diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index cce7ed25386..59b3fc1d588 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -306,8 +306,38 @@ extern "system" fn check_feature_support( FORMAT_SUPPORT => { // SAFETY: checked size and non-null. let q = unsafe { &mut *data.cast::<[u32; 3]>() }; - // shortcut: every use of every format; answer from the host - // device once there is one. + #[cfg(windows)] + if let Some(host) = crate::host::host() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_DATA_FORMAT_SUPPORT, D3D12_FEATURE_FORMAT_SUPPORT, + }; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + + // These guest formats have no host mapping. In particular, + // PC formats 189–191 represent different data. + if matches!(q[0], 116 | 117 | 189..=191) { + q[1..].fill(0); + return S_OK; + } + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: DXGI_FORMAT(resource::pc_format(q[0]) as i32), + ..Default::default() + }; + // SAFETY: the structure and size match the native format support query. + if let Err(error) = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of::() as u32, + ) + } { + return error.code().0; + } + q[1] = support.Support1.0 as u32; + q[2] = support.Support2.0 as u32; + return S_OK; + } + // Keep the fallback for runs without a host device. q[1] = 0x7fff_ffff; q[2] = 0xffff; S_OK @@ -529,4 +559,32 @@ mod tests { assert_eq!(query(&levels, 0x10).0, E_INVALIDARG); assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED); } + + #[test] + fn format_support_reports_native_capabilities_or_fallback() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let query_format = |format: u32| { + let mut q = [format, 0, 0]; + let hr = check(device, 3, (&raw mut q).cast(), 12); + (hr, q) + }; + // Unmapped guest formats return 0 support + let (hr, q) = query_format(116); + assert_eq!(hr, S_OK); + assert_eq!(q[1..], [0, 0]); + + let (hr, q) = query_format(189); + assert_eq!(hr, S_OK); + assert_eq!(q[1..], [0, 0]); + + // BC1_UNORM (71) is not a valid render target on host adapters + let (hr, q) = query_format(71); + assert_eq!(hr, S_OK); + if crate::host::host().is_some() { + use windows::Win32::Graphics::Direct3D12::D3D12_FORMAT_SUPPORT1_RENDER_TARGET; + assert_eq!(q[1] & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 as u32, 0); + } + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc4ad9..b3d2466fb15 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -10,6 +10,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use victory_shader::emit::{AddressView, UserData}; use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; @@ -74,16 +75,17 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, + /// The dynamic slots the list holds (title heap, first, count), given + /// back when the list is reset or released, or earlier when a heap runs + /// short after the list ran (see [`crate::descriptor::lease`]). + lease: std::sync::Arc, /// A fresh table of the stage being bound could not be made. table_failed: bool, } impl Drop for State { fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { + for (heap, first, n) in self.lease.take() { crate::descriptor::release_dynamic(heap, first, n); } } @@ -151,6 +153,23 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { Some(gpu) } +/// Addresses below this are taken as unset (null, or no buffer): a root SRV +/// at an address in root constants is not bound there and its draw is +/// dropped. +const MIN_ADDRESS: u64 = 0x1_0000; + +/// The address a root SRV at an address in root constants starts at: the +/// two constants' current values, low half first. `None` when the title has +/// not set either or the address is below [`MIN_ADDRESS`]. +fn pair_address(roots: &[Root], view: &AddressView) -> Option { + let half = |u: &UserData| match roots.get(usize::from(u.slot))? { + Root::Constants(c) => c.get(u.dword as usize).copied(), + _ => None, + }; + let address = u64::from(half(&view.lo)?) | u64::from(half(&view.hi)?) << 32; + (address >= MIN_ADDRESS).then_some(address) +} + macro_rules! once { ($($arg:tt)*) => {{ static ONCE: std::sync::Once = std::sync::Once::new(); @@ -172,6 +191,44 @@ impl State { self.pipeline = pipeline as usize; } + /// The list's slots, to start and finish its submissions. + pub(crate) fn lease(&self) -> &std::sync::Arc { + &self.lease + } + + /// `n` consecutive dynamic slots of `host` (the host heap of the title + /// heap at address `key`), held by this list. When the heap has no room, + /// the slots of the oldest list that already ran are taken back first, + /// one list at a time, instead of dropping the draw. + fn take_dynamic( + &mut self, + host: &crate::descriptor::host::HostHeap, + key: usize, + n: u32, + ) -> Option { + let mut reclaimed = false; + loop { + if let Some(first) = host.dynamic(n) { + self.lease.add(key, first, n); + return Some(first); + } + let more = crate::descriptor::lease::reclaim(key, |(heap, first, n)| { + if heap == key { + host.release(first, n); + } else { + crate::descriptor::release_dynamic(heap, first, n); + } + }); + if !more { + return None; + } + if !reclaimed { + reclaimed = true; + once!("dynamic descriptor slots of lists that already ran are taken back"); + } + } + } + /// The title's topology; console-only ones become host lists (see /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { @@ -412,10 +469,10 @@ impl State { /// it changed, constant data copied, textures made readable. /// 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. - /// False if the draw or dispatch must not run: a table it reads could - /// not be made. + /// descriptors its tables hold. False if a root SRV at an address in + /// root constants has no address to bind: the draw cannot run. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + let mut bound = true; let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -512,8 +569,29 @@ impl State { } } } + for &(view, param) in &stage.address_srvs { + let gpu = pair_address(self.roots_ref(compute), &view) + .and_then(|address| root_view(list, address, true)); + let Some(gpu) = gpu else { + once!( + slot = view.lo.slot, + dword = view.lo.dword, + "a shader reads through an address in root constants that is unset; draw dropped" + ); + bound = false; + continue; + }; + // SAFETY: an open list; the address is in live memory. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + } + } } - true + bound } /// Runs a dispatch on the host. @@ -540,6 +618,8 @@ impl State { } if !self.bind(list, p, true) { DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); return; } #[cfg(feature = "diagnostics")] @@ -581,6 +661,16 @@ impl State { let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); } } + for (view, _) in &stage.address_srvs { + let address = pair_address(self.roots_ref(compute), view); + let host = + address.and_then(|a| crate::shadow::find(a, 1).map(|s| (s.gpu(a), s.left(a)))); + let _ = write!( + text, + " u{}:u{}={address:#x?} host {host:#x?}", + view.lo.index, view.hi.index + ); + } } let _ = write!(text, " tables {:?}", self.reads(compute)); text @@ -670,7 +760,7 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { continue; }; - if index >= host.count() { + if !heap.samplers() && index >= host.count() { fresh.push(u.slot); } } @@ -723,7 +813,7 @@ impl State { made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { + let Some(first) = self.take_dynamic(host, std::ptr::from_ref(heap) as usize, n) else { // Without its fresh table the shader would read the title's // slots, which for constant buffer tables hold no constant // view: a texture or null descriptor read as a buffer gives @@ -733,8 +823,6 @@ impl State { continue; }; self.fresh_tables.insert(key, first); - self.dynamic - .push((std::ptr::from_ref(heap) as usize, first, n)); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -1215,3 +1303,151 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +#[cfg(test)] +mod tests { + use super::*; + use crate::descriptor::host::HostHeap; + + /// The dynamic slots of an empty heap (and the heap left empty). + fn capacity(heap: &HostHeap) -> u32 { + let mut n = 0; + while heap.dynamic(1).is_some() { + n += 1; + } + heap.release(heap.count(), n); + n + } + + /// A heap with no room takes back the slots of a list that already ran, + /// not of one that has not, and the list that lost them is refused. + #[test] + fn a_full_heap_takes_back_the_slots_of_a_list_that_ran() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let key = 0x2000_0001; + let total = capacity(&heap); + let chunk = 1000; + let mut ran = State::default(); + let mut taken = 0; + while ran.take_dynamic(&heap, key, chunk).is_some() { + taken += chunk; + } + assert!(taken >= total - chunk, "the list filled the heap"); + // Nothing has run yet: nothing is given back and the draw is dropped. + let mut other = State::default(); + assert_eq!(other.take_dynamic(&heap, key, chunk), None); + assert!(!ran.lease().is_lost()); + // The list ran: its slots serve the next list, once. + assert!(ran.lease().start()); + ran.lease().finish(); + assert!(other.take_dynamic(&heap, key, chunk).is_some()); + assert!(ran.lease().is_lost()); + assert!( + !ran.lease().start(), + "a list that lost its slots must not run" + ); + // Everything of the first list is free again except what the other + // list now holds, and nothing was given back twice. + assert!(ran.lease().take().is_empty()); + assert_eq!(capacity_left(&heap), total - chunk); + // Another request finds no finished list left and is dropped. + let mut third = State::default(); + assert_eq!(third.take_dynamic(&heap, key, total), None); + } + + /// Free slots of the heap now (taken and released again). + fn capacity_left(heap: &HostHeap) -> u32 { + capacity(heap) + } + + /// A list that is running when another needs room keeps its slots; a + /// list reset by the title gives back its own and is not taken twice. + #[test] + fn a_running_or_reset_list_is_not_taken_back() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let key = 0x2000_0002; + let total = capacity(&heap); + let mut running = State::default(); + let first = running.take_dynamic(&heap, key, total).unwrap(); + assert_eq!(first, heap.count()); + running.lease().finish(); + // Submitted again: it is running and cannot be taken back. + assert!(running.lease().start()); + let mut other = State::default(); + assert_eq!(other.take_dynamic(&heap, key, 1), None); + assert!(!running.lease().is_lost()); + // It ran: now it can, whole. + running.lease().finish(); + assert_eq!(other.take_dynamic(&heap, key, 1), Some(heap.count())); + assert!(running.lease().is_lost()); + // A lease reset by the title (its slots taken, as `Drop` does) is + // skipped: nothing is held, so nothing is taken back. + let mut reset = State::default(); + assert!(reset.take_dynamic(&heap, key, 1).is_some()); + reset.lease().finish(); + assert_eq!(reset.lease().take().len(), 1); + let mut last = State::default(); + assert_eq!(last.take_dynamic(&heap, key, total), None); + assert!(!reset.lease().is_lost()); + } + + fn half(slot: u8, dword: u32) -> UserData { + UserData { + index: 0, + slot, + root: RootType::Constants, + dword, + } + } + + /// The low half at dword 1 of root parameter 0, the high half at dword 0 + /// of parameter 2. + fn view() -> AddressView { + AddressView { + lo: half(0, 1), + hi: half(2, 0), + } + } + + fn roots(lo: u32, hi: u32) -> Vec { + vec![ + Root::Constants(vec![7, lo]), + Root::None, + Root::Constants(vec![hi]), + ] + } + + #[test] + fn addresses_in_root_constants_are_composed_from_both_halves() { + assert_eq!( + pair_address(&roots(0x2345_0000, 1), &view()), + Some(0x1_2345_0000) + ); + assert_eq!(pair_address(&roots(0x1_0000, 0), &view()), Some(0x1_0000)); + } + + #[test] + fn an_address_with_a_missing_half_is_unset() { + let set = roots(0x2345_0000, 1); + assert_eq!(pair_address(&set[..2], &view()), None); + let mut no_high = set.clone(); + no_high[2] = Root::Constants(Vec::new()); + assert_eq!(pair_address(&no_high, &view()), None); + let mut not_constants = set.clone(); + not_constants[0] = Root::View(0x1_0000_0000); + assert_eq!(pair_address(¬_constants, &view()), None); + let mut short = set; + short[0] = Root::Constants(vec![7]); + assert_eq!(pair_address(&short, &view()), None); + } + + #[test] + fn null_and_low_addresses_are_unset() { + assert_eq!(pair_address(&roots(0, 0), &view()), None); + assert_eq!(pair_address(&roots(0xFFFF, 0), &view()), None); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1ed11a..f45edd3cdd3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -176,7 +176,9 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + if cfg!(feature = "diagnostics") + && std::env::var_os("VICTORY_D3D12_WARP").is_some_and(|value| value != "0") + { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); @@ -276,6 +278,15 @@ mod tests { desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, ); } + + #[test] + fn warp_adapter_setting_ignores_zero() { + let is_warp = |val: Option<&str>| val.is_some_and(|v| v != "0"); + assert!(!is_warp(None)); + assert!(!is_warp(Some("0"))); + assert!(is_warp(Some("1"))); + assert!(is_warp(Some("true"))); + } } /// A host command list and its allocator, always used together. @@ -2014,6 +2025,13 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert!(next.texture_due(&a)); } + #[test] + fn host_written_texture_records_and_forgets() { + let fake_resource = 0x1234_5678 as crate::object::This; + crate::texture::host_written(fake_resource); + crate::texture::forget(fake_resource as usize); + } + /// The hashing a submission does for textures in physical-page memory, /// with every list checking the textures it samples (before) and with /// each checked once (after). Run with diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7adb4e4f624..e3200d219cc 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -133,6 +133,33 @@ fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::dra f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); } +/// The dynamic descriptor slots of a title list, if there is a host GPU. +#[cfg(windows)] +fn lease(this: This) -> Option> { + host_list(this)?; + // SAFETY: the title passes one of our lists. + let state = unsafe { &(*this.cast::()).state }; + let state = state.lock().unwrap_or_else(|e| e.into_inner()); + Some(state.lease().clone()) +} + +/// Before a list is submitted: false if the slots of its tables were taken +/// back after an earlier submission (a heap ran short, see +/// [`crate::descriptor::lease`]); it must not run again until it is reset. +/// Until [`finished`] its slots cannot be taken back. +#[cfg(windows)] +pub(crate) fn may_run(this: This) -> bool { + lease(this).is_none_or(|lease| lease.start()) +} + +/// After a list ran: its slots may be taken back if a heap runs short. +#[cfg(windows)] +pub(crate) fn finished(this: This) { + if let Some(lease) = lease(this) { + lease.finish(); + } +} + /// The host list behind a title list, if there is a host GPU. #[cfg(windows)] pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { @@ -1069,8 +1096,7 @@ mod state { with_state(this, |list, s| s.dispatch_mesh(list, x)); } /// `DispatchMeshX(x, flags, indirect arguments, payload)`. - /// shortcut: dispatches whose group count is in GPU memory (indirect) - /// are dropped; make them ExecuteIndirect when the title uses them. + /// When `indirect != 0`, executes indirect mesh dispatches. pub(super) extern "system" fn dispatch_mesh_x( this: This, x: u32, @@ -1080,8 +1106,11 @@ mod state { ) { super::count_draw(); if indirect != 0 { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); + const MESH: u32 = 10; + const STRIDE: u32 = 12; + with_state(this, |list, s| { + s.execute_indirect(list, (MESH, STRIDE, x.max(1)), indirect, None); + }); return; } with_state(this, |list, s| s.dispatch_mesh(list, x)); @@ -1446,4 +1475,26 @@ mod tests { assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } + + #[test] + fn dispatch_mesh_x_routes_direct_and_indirect_dispatches() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); + assert_eq!(hr, S_OK); + + // Direct mesh dispatch: + state::dispatch_mesh_x(list, 4, 0, 0, 0); + // Indirect mesh dispatch: + state::dispatch_mesh_x(list, 1, 0, 0x10000, 0); + + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa10c0..09a2dc568c4 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -2,13 +2,16 @@ //! title's graphics state with the translated shaders, under a root //! signature of our own that the translated shaders' bindings define //! (`victory_shader::emit`): per stage one block of root constants for the -//! user data, root views for the title's root views, static samplers for -//! the immediate samplers, and directly indexed heaps. +//! user data, root views for the title's root views and for addresses the +//! title passes in root constants, static samplers for the immediate +//! samplers, and directly indexed heaps. use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use victory_shader::emit::{ + AddressView, ROOT_ADDRESS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, +}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -251,6 +254,10 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root parameters of its root SRVs at addresses in root constants: + /// (the two constants, ours), `t` in [`ROOT_ADDRESS_SPACE`] for the + /// one at position n. + pub(crate) address_srvs: Vec<(AddressView, u32)>, } impl Stage { @@ -339,6 +346,7 @@ impl HostPipeline { user_data: None, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }; let dwords = t.user_data_dwords(); if dwords > 0 { @@ -382,6 +390,20 @@ impl HostPipeline { }); } } + for (n, &view) in t.address_srvs.iter().enumerate() { + stage.address_srvs.push((view, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: n as u32, + RegisterSpace: ROOT_ADDRESS_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { Filter: D3D12_FILTER(s.filter as i32), @@ -630,7 +652,9 @@ fn root_signature( } else { D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT }; - let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + let heap_indexing = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + let desc_with = |flags| D3D12_VERSIONED_ROOT_SIGNATURE_DESC { Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { @@ -638,30 +662,83 @@ fn root_signature( pParameters: params.as_ptr(), NumStaticSamplers: samplers.len() as u32, pStaticSamplers: samplers.as_ptr(), - Flags: input - | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED - | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + Flags: flags, }, }, }; + let desc = desc_with(input | heap_indexing); // SAFETY: the description points at live arrays; the blob is read in // full before it is released. unsafe { let mut blob: Option = None; let mut error: Option = None; if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) { - if let Some(error) = error { + if let Some(ref error) = error { let text = std::slice::from_raw_parts( error.GetBufferPointer().cast::(), error.GetBufferSize(), ); - tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + tracing::warn!( + "root signature: runtime rejected directly-indexed flags ({}), retrying without them", + String::from_utf8_lossy(text) + ); + } + drop(error.take()); + blob = None; + let retry = desc_with(input); + let mut retry_error: Option = None; + if let Err(e2) = + D3D12SerializeVersionedRootSignature(&retry, &mut blob, Some(&mut retry_error)) + { + if let Some(error) = retry_error { + let text = std::slice::from_raw_parts( + error.GetBufferPointer().cast::(), + error.GetBufferSize(), + ); + tracing::warn!("root signature retry: {}", String::from_utf8_lossy(text)); + } + return Err(e2); } - return Err(e); + let _ = e; } let blob = blob.ok_or_else(windows::core::Error::empty)?; let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); - Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) + let root = match device.CreateRootSignature(0, bytes) { + Ok(root) => (root, bytes.to_vec()), + Err(e) => { + let retry = desc_with(input); + let mut fallback_blob: Option = None; + if D3D12SerializeVersionedRootSignature(&retry, &mut fallback_blob, None).is_ok() + && let Some(fallback_blob) = fallback_blob + { + let fallback_bytes = std::slice::from_raw_parts( + fallback_blob.GetBufferPointer().cast::(), + fallback_blob.GetBufferSize(), + ); + let root = device.CreateRootSignature(0, fallback_bytes)?; + (root, fallback_bytes.to_vec()) + } else { + return Err(e); + } + } + }; + Ok(root) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_root_signature_serializes_and_creates() { + let Some(host) = crate::host::host() else { return }; + let (root, bytes) = root_signature(&host.device, &[], &[], false).unwrap(); + assert!(!bytes.is_empty()); + let _ = root; + let (comp_root, comp_bytes) = root_signature(&host.device, &[], &[], true).unwrap(); + assert!(!comp_bytes.is_empty()); + let _ = comp_root; } } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 5992fad25a1..3188c1a7477 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -119,11 +119,29 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + let mut skipped = 0; let host_lists: Vec<_> = lists .iter() + .filter(|&&l| { + let may = crate::list::may_run(l); + skipped += usize::from(!may); + may + }) .filter_map(|&l| crate::list::host_list(l)) .collect(); + if skipped > 0 { + static LOST: AtomicBool = AtomicBool::new(false); + if !LOST.swap(true, Ordering::Relaxed) { + tracing::warn!( + skipped, + "lists submitted again after their dynamic descriptor slots were taken back are not run" + ); + } + } host.execute(&host_lists); + for &l in lists { + crate::list::finished(l); + } return; } static ONCE: AtomicBool = AtomicBool::new(false); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71abfa..cf995956679 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -817,12 +817,26 @@ fn host_texture( // allows both; Grand Theft Auto VI's shadow maps ask for it). // shortcut: the host copy loses UAV use; give it a second view-only // copy if draws write it as a UAV. + const RENDER_TARGET: u32 = 1; const DEPTH: u32 = 2; const UNORDERED: u32 = 4; if d.flags & DEPTH != 0 { d.flags &= !UNORDERED; } d.format = pc_format(d.format); + // Formats without host UAV or render-target capability (the console + // allows both; host D3D12 removes the device on invalid flag combinations, #735). + // B5G5R5A1 (86) and B5G6R5 (85) have no typed UAV support; B4G4R4A4 (115) + // has no render-target support; block-compressed formats have neither. + if matches!(d.format, 85 | 86) { + d.flags &= !UNORDERED; + } + if d.format == 115 { + d.flags &= !RENDER_TARGET; + } + if element(d.format).is_some_and(|(_, w)| w > 1) { + d.flags &= !(RENDER_TARGET | DEPTH | UNORDERED); + } const DENY_SHADER_RESOURCE: u32 = 8; if d.flags & DENY_SHADER_RESOURCE == 0 && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) @@ -1841,4 +1855,25 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + /// Formats without host UAV or RTV support clear those flags (#735). + #[test] + fn incompatible_host_texture_flags_are_cleared() { + if crate::host::host().is_none() { + return; + } + // B5G5R5A1 with UAV + let b5g5r5a1 = texture(64, 64, 86, 1); + let mut desc = b5g5r5a1; + desc.flags = 4; // UNORDERED + let res = host_texture(&desc, 0, std::ptr::null()); + assert!(res.is_some(), "B5G5R5A1 texture creation succeeded without UAV"); + + // B4G4R4A4 with RenderTarget + let b4g4r4a4 = texture(64, 64, 115, 1); + let mut desc2 = b4g4r4a4; + desc2.flags = 1; // RENDER_TARGET + let res2 = host_texture(&desc2, 0, std::ptr::null()); + assert!(res2.is_some(), "B4G4R4A4 texture creation succeeded without RenderTarget"); + } } diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 998ec71ee85..cd1d24511c0 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -14,7 +14,7 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::emit::{AddressView, HostShader, StaticSampler, UserData}; use victory_shader::{HwStage, RootType}; static CACHE: OnceLock = OnceLock::new(); @@ -175,11 +175,14 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, stage); word(&mut out, s.dxil.len() as u32); out.extend(&s.dxil); - word(&mut out, s.user_data.len() as u32); - for u in &s.user_data { + let user = |out: &mut Vec, u: &UserData| { for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { - word(&mut out, v); + word(out, v); } + }; + word(&mut out, s.user_data.len() as u32); + for u in &s.user_data { + user(&mut out, u); } word(&mut out, s.samplers.len() as u32); for sampler in &s.samplers { @@ -210,6 +213,11 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, slots.len() as u32); out.extend(slots); } + word(&mut out, s.address_srvs.len() as u32); + for view in &s.address_srvs { + user(&mut out, &view.lo); + user(&mut out, &view.hi); + } out } @@ -228,6 +236,14 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } + fn user(&mut self) -> Option { + Some(UserData { + index: self.word()?, + slot: u8::try_from(self.word()?).ok()?, + root: root_type(self.word()?), + dword: self.word()?, + }) + } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -238,12 +254,7 @@ fn decode(bytes: &[u8]) -> Option { let n = r.word()? as usize; let mut user_data = Vec::with_capacity(n.min(256)); for _ in 0..n { - user_data.push(UserData { - index: r.word()?, - slot: u8::try_from(r.word()?).ok()?, - root: root_type(r.word()?), - dword: r.word()?, - }); + user_data.push(r.user()?); } let n = r.word()? as usize; let mut samplers = Vec::with_capacity(n.min(256)); @@ -266,6 +277,14 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let n = r.word()? as usize; + let mut address_srvs = Vec::with_capacity(n.min(256)); + for _ in 0..n { + address_srvs.push(AddressView { + lo: r.user()?, + hi: r.user()?, + }); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -274,6 +293,7 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, + address_srvs, }) } @@ -300,6 +320,20 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + address_srvs: vec![AddressView { + lo: UserData { + index: 3, + slot: 0, + root: RootType::Constants, + dword: 3, + }, + hi: UserData { + index: 4, + slot: 4, + root: RootType::Constants, + dword: 0, + }, + }], } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 60eab0cec42..87b4134aaf1 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -65,15 +65,16 @@ unsafe impl Sync for Staging {} static STAGING: Mutex>>> = Mutex::new(None); -/// Textures the host GPU wrote by a copy or resolve: their contents are on -/// the host, not in title memory, which stays as it was. -static HOST_WRITTEN: Mutex>> = Mutex::new(None); +/// Textures the host GPU wrote by a copy or resolve, with the watch +/// asking tick when the write happened. +static HOST_WRITTEN: Mutex>> = Mutex::new(None); /// A host copy or resolve writes `resource`. pub(crate) fn host_written(resource: This) { - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - set.get_or_insert_with(Default::default) - .insert(resource as usize); + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + let tick = crate::watch::current_tick(); + map.get_or_insert_with(Default::default) + .insert(resource as usize, tick); } /// The title released a resource. @@ -82,9 +83,9 @@ pub(crate) fn forget(resource: usize) { if let Some(map) = map.as_mut() { map.remove(&resource); } - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(set) = set.as_mut() { - set.remove(&resource); + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&resource); } } @@ -101,19 +102,31 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// submission if the memory changed. Leaves the texture in the copy /// destination state. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { - let host_written = HOST_WRITTEN + let host_write_tick = HOST_WRITTEN .lock() .unwrap_or_else(|e| e.into_inner()) .as_ref() - .is_some_and(|set| set.contains(&(resource as usize))); - // shortcut: a texture the host copied into keeps the host's contents - // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { + .and_then(|map| map.get(&(resource as usize)).copied()); + if !list.first_use(resource as usize) { return; } let Some(staging) = staging(resource, texture) else { return; }; + if let Some(tick) = host_write_tick { + let size = staging.layout.size as usize; + let start = staging.memory as usize; + let title_updated = crate::watch::writes(start, start + size, false) + .is_some_and(|(_, written)| written.iter().any(|&(_, w)| w > tick)); + if title_updated { + let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); + } + } else { + return; + } + } const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); // The staging buffer lives as long as `staging`, which the deferred diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7694609f17b..087b7fec4eb 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -43,6 +43,11 @@ static JOURNAL: Mutex = Mutex::new(Journal { found: Vec::new(), }); +/// The journal's current asking number. +pub(crate) fn current_tick() -> u64 { + JOURNAL.lock().unwrap_or_else(|e| e.into_inner()).asked +} + /// The pages of `[start, end)` (whole pages) as last written, for pages /// written since tracking began: `(page number, asking)` in page order, and /// this asking's number, which is higher than any in the list but those the diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 41f9cbd11cd..0318ab5cc05 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -100,9 +100,15 @@ extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { // SAFETY: the request we just created. if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { let hr = last_error(); - // SAFETY: as above; not handed out. - unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; - return hr; + // Headless, VM, and RDP environments without an active display request + // path report ERROR_NOT_SUPPORTED (0x80070032); still hand out the + // valid request handle so the title does not fail (#727). + const NOT_SUPPORTED_HR: i32 = -2147024846; // 0x80070032 + if hr != NOT_SUPPORTED_HR { + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; + } } put(out, request) } diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 3ab3067122f..f6f770ec860 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -155,13 +155,15 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * let Some(m) = registry().iter().find(|m| handle(m) == module) else { return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); }; - // Values below 0x10000 are ordinals; we export by name only. + // Values below 0x10000 are ordinals; we export by name only. A miss + // fails as the host's does, with the last error set. if (name as usize) < 0x1_0000 { tracing::warn!( module = m.name, ordinal = name as usize, "GetProcAddress by ordinal" ); + host::set_last_error(ERROR_PROC_NOT_FOUND); return std::ptr::null_mut(); } // SAFETY: not an ordinal, so the title passes a NUL-terminated name. @@ -170,6 +172,7 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * Some(e) => e.address as *mut c_void, None => { tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); + host::set_last_error(ERROR_PROC_NOT_FOUND); std::ptr::null_mut() } } @@ -349,6 +352,7 @@ fn refuse(file: &str) { } const ERROR_MOD_NOT_FOUND: u32 = 126; +const ERROR_PROC_NOT_FOUND: u32 = 127; pub(crate) fn module() -> HleModule { HleModule { @@ -684,4 +688,26 @@ mod tests { assert!(!runtime.is_null()); assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); } + + #[cfg(windows)] + #[test] + fn a_missing_export_of_our_modules_sets_the_last_error() { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + // SAFETY: sets and reads this thread's last error. + let clear = || unsafe { SetLastError(0) }; + // SAFETY: as above. + let last = || unsafe { GetLastError() }; + // The host's own modules, for comparison. + let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); + clear(); + assert!(GetProcAddress(kernel32, c"NotAnExport".as_ptr().cast()).is_null()); + assert_eq!(last(), ERROR_PROC_NOT_FOUND); + // Ours, by name and by ordinal. + let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); + for name in [c"NotAnExport".as_ptr().cast(), 9999 as *const u8] { + clear(); + assert!(GetProcAddress(runtime, name).is_null()); + assert_eq!(last(), ERROR_PROC_NOT_FOUND, "{name:?}"); + } + } } diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 068d75f2a8a..d0806b522ad 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -10,11 +10,12 @@ #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::collections::{HashMap, VecDeque}; +use std::cmp::{Ordering as CmpOrdering, Reverse}; +use std::collections::{BinaryHeap, HashMap, VecDeque}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; -use std::time::Duration; +use std::time::{Duration, Instant}; use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; @@ -148,39 +149,77 @@ impl Port { } /// The thread pool behind thread-pool ports: idle workers are reused, and a -/// new one starts whenever more tasks wait than workers idle, so a callback -/// that blocks on another never starves it. Workers stay for reuse. +/// new one starts whenever more tasks wait than workers idle (up to +/// `max_workers`), so a callback that blocks on another does not starve it +/// while bursts cannot spawn unbounded OS threads. +struct PoolState { + tasks: VecDeque, + idle: usize, + workers: usize, + stopped: bool, +} + struct Pool { - /// Queued tasks and the number of idle workers. - state: Mutex<(VecDeque, usize)>, + state: Mutex, ready: Condvar, + max_workers: usize, } -static POOL: Pool = Pool { - state: Mutex::new((VecDeque::new(), 0)), - ready: Condvar::new(), -}; +fn default_max_workers() -> usize { + std::thread::available_parallelism() + .map_or(8, |n| n.get()) + .saturating_mul(2) + .clamp(8, 64) +} + +static POOL: LazyLock> = LazyLock::new(|| Pool::new(default_max_workers())); impl Pool { - fn submit(&'static self, task: Task) { + fn new(max_workers: usize) -> Arc { + Arc::new(Self { + state: Mutex::new(PoolState { + tasks: VecDeque::new(), + idle: 0, + workers: 0, + stopped: false, + }), + ready: Condvar::new(), + max_workers: max_workers.max(1), + }) + } + + fn submit(self: &Arc, task: Task) { let mut state = lock(&self.state); - state.0.push_back(task); - if state.0.len() > state.1 { - std::thread::spawn(move || self.work()); - } else { + state.tasks.push_back(task); + if state.idle > 0 { self.ready.notify_one(); } + if state.tasks.len() > state.idle && state.workers < self.max_workers { + state.workers += 1; + let pool = self.clone(); + if std::thread::Builder::new() + .name("victory-xasync-pool".into()) + .spawn(move || pool.work()) + .is_err() + { + state.workers -= 1; + } + } } - fn work(&self) { + fn work(self: Arc) { let mut state = lock(&self.state); loop { - while state.0.is_empty() { - state.1 += 1; + while state.tasks.is_empty() { + if state.stopped { + state.workers = state.workers.saturating_sub(1); + return; + } + state.idle += 1; state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); - state.1 -= 1; + state.idle -= 1; } - let task = state.0.pop_front(); + let task = state.tasks.pop_front(); drop(state); if let Some(task) = task { task.run(false); @@ -188,6 +227,133 @@ impl Pool { state = lock(&self.state); } } + + #[cfg(test)] + fn worker_count(&self) -> usize { + lock(&self.state).workers + } + + #[cfg(test)] + fn stop(&self) { + let mut state = lock(&self.state); + state.stopped = true; + self.ready.notify_all(); + } +} + +struct DelayedTask { + due: Instant, + seq: u64, + queue: Arc, + port: u32, + task: Task, +} + +impl PartialEq for DelayedTask { + fn eq(&self, other: &Self) -> bool { + (self.due, self.seq) == (other.due, other.seq) + } +} + +impl Eq for DelayedTask {} + +impl PartialOrd for DelayedTask { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for DelayedTask { + fn cmp(&self, other: &Self) -> CmpOrdering { + (self.due, self.seq).cmp(&(other.due, other.seq)) + } +} + +struct TimerState { + heap: BinaryHeap>, + next_seq: u64, + started: bool, +} + +/// Shared timer wheel for delayed `XTaskQueue` callbacks: one lazily started +/// thread serves every delayed submission instead of spawning an OS thread per +/// callback. +struct Timer { + state: Mutex, + wake: Condvar, +} + +static TIMER: Timer = Timer { + state: Mutex::new(TimerState { + heap: BinaryHeap::new(), + next_seq: 0, + started: false, + }), + wake: Condvar::new(), +}; + +impl Timer { + fn schedule(&'static self, queue: Arc, port: u32, delay_ms: u32, task: Task) { + let due = Instant::now() + Duration::from_millis(delay_ms.into()); + let mut state = lock(&self.state); + if !state.started { + state.started = true; + if std::thread::Builder::new() + .name("victory-xasync-timer".into()) + .spawn(move || self.run()) + .is_err() + { + state.started = false; + drop(state); + queue.deliver(port, task); + return; + } + } + let seq = state.next_seq; + state.next_seq = state.next_seq.wrapping_add(1); + let earlier = state + .heap + .peek() + .is_none_or(|Reverse(top)| (due, seq) < (top.due, top.seq)); + state.heap.push(Reverse(DelayedTask { + due, + seq, + queue, + port, + task, + })); + if earlier { + self.wake.notify_one(); + } + } + + fn run(&'static self) { + let mut state = lock(&self.state); + loop { + let Some(Reverse(top)) = state.heap.peek() else { + state = self.wake.wait(state).unwrap_or_else(|e| e.into_inner()); + continue; + }; + let now = Instant::now(); + if top.due > now { + let wait = top.due - now; + state = self + .wake + .wait_timeout(state, wait) + .unwrap_or_else(|e| e.into_inner()) + .0; + continue; + } + let Some(Reverse(item)) = state.heap.pop() else { + continue; + }; + drop(state); + if !item.queue.terminated.load(Ordering::Acquire) { + item.queue.deliver(item.port, item.task); + } + state = lock(&self.state); + } + } } /// A queue handle is `Arc::into_raw` of this; duplicating and closing a @@ -217,11 +383,7 @@ impl Queue { if delay_ms == 0 { self.deliver(port, task); } else { - let queue = self.clone(); - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(delay_ms.into())); - queue.deliver(port, task); - }); + TIMER.schedule(self.clone(), port, delay_ms, task); } S_OK } @@ -1334,4 +1496,78 @@ mod tests { ); XTaskQueueCloseHandle(q); } + + #[test] + fn delayed_callbacks_fire_in_deadline_order_on_shared_timer() { + static ORDER: Mutex> = Mutex::new(Vec::new()); + extern "system" fn record(context: *mut c_void, canceled: bool) { + if !canceled { + lock(&ORDER).push(context as u32); + } + } + lock(&ORDER).clear(); + + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + // Submit out of deadline order: 70 ms, 15 ms, 40 ms. + assert_eq!( + XTaskQueueSubmitDelayedCallback( + q, + WORK, + 70, + std::ptr::without_provenance_mut(3), + Some(record), + ), + S_OK + ); + assert_eq!( + XTaskQueueSubmitDelayedCallback( + q, + WORK, + 15, + std::ptr::without_provenance_mut(1), + Some(record), + ), + S_OK + ); + assert_eq!( + XTaskQueueSubmitDelayedCallback( + q, + WORK, + 40, + std::ptr::without_provenance_mut(2), + Some(record), + ), + S_OK + ); + for _ in 0..3 { + assert!(XTaskQueueDispatch(q, WORK, 2000)); + } + assert_eq!(*lock(&ORDER), vec![1, 2, 3]); + XTaskQueueCloseHandle(q); + } + + #[test] + fn thread_pool_caps_worker_growth_and_drains_burst() { + static DONE: AtomicU32 = AtomicU32::new(0); + extern "system" fn slow_inc(_: *mut c_void, _: bool) { + std::thread::sleep(Duration::from_millis(2)); + DONE.fetch_add(1, Ordering::SeqCst); + } + DONE.store(0, Ordering::SeqCst); + + let pool = Pool::new(3); + let total = 18u32; + for _ in 0..total { + pool.submit(Task::new(std::ptr::null_mut(), slow_inc)); + } + let start = Instant::now(); + while DONE.load(Ordering::SeqCst) < total && start.elapsed().as_secs() < 5 { + assert!(pool.worker_count() <= 3); + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(DONE.load(Ordering::SeqCst), total); + assert!(pool.worker_count() <= 3); + pool.stop(); + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index a441c9182e9..8ce3fa7f180 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -17,16 +17,13 @@ use windows_sys::Win32::Foundation::{ CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, }; use windows_sys::Win32::System::Memory::{ - CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, + CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_FREE, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, }; -use windows_sys::Win32::System::ProcessStatus::{ - K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, - PROCESS_MEMORY_COUNTERS, -}; +use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION}; use windows_sys::Win32::System::Threading::GetCurrentProcess; use windows_sys::core::BOOL; @@ -49,6 +46,103 @@ pub(crate) fn on_wine() -> bool { /// Standard memory the title has handed to the system. static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); +/// Bytes currently live in [`XMemAllocDefault`] heap blocks (all and GPU-optimal). +static HEAP_USED: AtomicUsize = AtomicUsize::new(0); +static HEAP_GPU_OPTIMAL_USED: AtomicUsize = AtomicUsize::new(0); +/// Non-placeholder [`XMemVirtualAlloc`] reservations: base -> (length, gpu_optimal). +/// Queried for committed pages when reporting working-set statistics so host +/// allocations (GPU mirrors, shader compiler) are excluded and `VirtualFree` +/// decommits/releases are observed automatically. +static VIRTUAL_REGIONS: LazyLock>> = + LazyLock::new(Default::default); + +fn saturating_sub(counter: &AtomicUsize, delta: usize) { + let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |cur| { + Some(cur.saturating_sub(delta)) + }); +} + +fn record_virtual_region(at: usize, requested: usize, gpu_optimal: bool) { + let mut mbi = MEMORY_BASIC_INFORMATION::default(); + // SAFETY: pseudo-handle and writable MEMORY_BASIC_INFORMATION. + let queried = unsafe { + VirtualQueryEx( + GetCurrentProcess(), + at as *const c_void, + &mut mbi, + size_of::(), + ) + }; + let len = if queried != 0 && mbi.RegionSize > 0 { + mbi.RegionSize.max(requested) + } else { + requested + }; + let end = at.saturating_add(len); + let mut regions = VIRTUAL_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + // Drop any stale entry overlapping `[at, end)` (e.g. reused after VirtualFree). + let stale: Vec = regions + .iter() + .filter(|&(&base, &(rlen, _))| base < end && base.saturating_add(rlen) > at) + .map(|(&base, _)| base) + .collect(); + for base in stale { + regions.remove(&base); + } + regions.insert(at, (len, gpu_optimal)); +} + +fn virtual_used() -> (usize, usize) { + let mut regions = VIRTUAL_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let mut total = 0usize; + let mut gpu_optimal = 0usize; + let mut stale = Vec::new(); + // SAFETY: pseudo-handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + for (&base, &(len, is_gpu)) in regions.iter() { + let end = base.saturating_add(len); + let mut cur = base; + let mut alive = false; + while cur < end { + let mut mbi = MEMORY_BASIC_INFORMATION::default(); + // SAFETY: valid process handle and writable struct. + let ok = unsafe { + VirtualQueryEx( + process, + cur as *const c_void, + &mut mbi, + size_of::(), + ) + }; + if ok == 0 || mbi.RegionSize == 0 { + break; + } + let region_end = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize); + let next = region_end.min(end); + if next <= cur { + break; + } + if mbi.State != MEM_FREE && mbi.AllocationBase as usize == base { + alive = true; + if mbi.State == MEM_COMMIT { + let bytes = next - cur; + total = total.saturating_add(bytes); + if is_gpu { + gpu_optimal = gpu_optimal.saturating_add(bytes); + } + } + } + cur = next; + } + if !alive { + stale.push(base); + } + } + for base in stale { + regions.remove(&base); + } + (total, gpu_optimal) +} // Console additions to the host's flags. /// 2 MiB pages; the host reads this bit as large pages, which need a @@ -153,6 +247,19 @@ pub extern "system" fn XMemVirtualAlloc( constrained.into(), ) }; + if !at.is_null() && !placeholder { + let addr = at as usize; + let already_tracked = !constrained && { + let regions = VIRTUAL_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + regions + .range(..=addr) + .next_back() + .is_some_and(|(&rbase, &(rlen, _))| addr < rbase.saturating_add(rlen)) + }; + if !already_tracked { + record_virtual_region(addr, size, flags & GRAPHICS != 0); + } + } if base.is_null() { tracing::debug!( size, @@ -204,13 +311,21 @@ pub extern "system" fn XMemVirtualQuery( } // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up -// from 2), then the memory type, then bit 33: a 32-bit address. +// from 2), then the memory type (4 bits at 29; non-zero = graphics/GPU), +// then bit 33: a 32-bit address. const ALIGNMENT_SHIFT: u64 = 24; +const ALLOC_TYPE_SHIFT: u64 = 29; +const ALLOC_TYPE_MASK: u64 = 0xf; const ALLOC_32BIT: u64 = 1 << 33; -/// Our block header: the block's size and alignment, just below the -/// pointer handed out. +/// Our block header: the block's size and alignment (bit 0 packs `gpu_optimal`, +/// since alignment is always a power of two >= 16), just below the pointer +/// handed out. const HEADER: usize = 2 * size_of::(); +fn is_alloc_gpu_optimal(attributes: u64) -> bool { + ((attributes >> ALLOC_TYPE_SHIFT) & ALLOC_TYPE_MASK) != 0 +} + fn layout(size: usize, attributes: u64) -> Option { // An alignment of at least 16 leaves room for the header. let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4); @@ -298,13 +413,18 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ if block.is_null() { return block.cast(); } + let gpu_optimal = is_alloc_gpu_optimal(attributes); + HEAP_USED.fetch_add(layout.size(), Ordering::Relaxed); + if gpu_optimal { + HEAP_GPU_OPTIMAL_USED.fetch_add(layout.size(), Ordering::Relaxed); + } // SAFETY: the block holds the alignment (at least the header) and then - // `size` bytes. + // `size` bytes. Alignment is a power of two >= 16 so bit 0 is free. unsafe { let user = block.add(layout.align()); user.sub(HEADER) .cast::<[usize; 2]>() - .write([layout.size(), layout.align()]); + .write([layout.size(), layout.align() | usize::from(gpu_optimal)]); user.cast() } } @@ -318,15 +438,25 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { // whole reservation, or a header-prefixed block. unsafe { if attributes & ALLOC_32BIT != 0 { + VIRTUAL_REGIONS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&(address as usize)); VirtualFree(address, 0, MEM_RELEASE); return; } let user = address.cast::(); - let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + let [size, packed_align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + let gpu_optimal = (packed_align & 1) != 0; + let align = packed_align & !1; dealloc( user.sub(align), Layout::from_size_align_unchecked(size, align), ); + saturating_sub(&HEAP_USED, size); + if gpu_optimal { + saturating_sub(&HEAP_GPU_OPTIMAL_USED, size); + } } } @@ -342,7 +472,10 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { const PAGE: usize = 64 << 10; -struct Section(HANDLE); +struct Section { + handle: HANDLE, + gpu_optimal: bool, +} // SAFETY: a section handle may be used from any thread. unsafe impl Send for Section {} @@ -352,7 +485,7 @@ unsafe impl Sync for Section {} impl Drop for Section { fn drop(&mut self) { // SAFETY: our handle; views keep the section alive on their own. - unsafe { CloseHandle(self.0) }; + unsafe { CloseHandle(self.handle) }; } } @@ -368,6 +501,7 @@ struct Slice { struct Physical { next_page: usize, pages: HashMap, + gpu_optimal_pages: usize, /// Mapped views by address: their length and what they show. views: BTreeMap, } @@ -428,10 +562,17 @@ pub extern "system" fn XMemAllocatePhysicalPages( flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); - let section = Arc::new(Section(handle)); + let gpu_optimal = flags & GRAPHICS != 0; + let section = Arc::new(Section { + handle, + gpu_optimal, + }); let mut physical = physical(); let first = physical.next_page; physical.next_page += n * FRAMES; + if gpu_optimal { + physical.gpu_optimal_pages = physical.gpu_optimal_pages.saturating_add(n); + } for index in 0..n { let slice = Slice { section: section.clone(), @@ -458,7 +599,11 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B let mut physical = physical(); for i in 0..n { // SAFETY: the title passes `n` page numbers. - physical.pages.remove(&unsafe { *pages.add(i) }); + if let Some(slice) = physical.pages.remove(&unsafe { *pages.add(i) }) + && slice.section.gpu_optimal + { + physical.gpu_optimal_pages = physical.gpu_optimal_pages.saturating_sub(1); + } } 1 } @@ -478,7 +623,7 @@ impl View { // SAFETY: slices of a section we own; the view is ours until dropped. let at = unsafe { MapViewOfFile( - slice.section.0, + slice.section.handle, FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, @@ -701,7 +846,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, ); MapViewOfFile3( - slice.section.0, + slice.section.handle, GetCurrentProcess(), base as *const c_void, (slice.index * PAGE) as u64, @@ -846,26 +991,34 @@ pub struct WorkingSet { pub kernel_pool_limit: u32, } -/// The title's budget and our process's commit as what it uses. No tools -/// memory: a retail console. -// shortcut: all fields are filled whatever the flags ask for, and use is -// not split by bandwidth class (GPU-optimal use reads 0); track -// allocations per class if a title budgets from that field. +/// The title's budget and its tracked allocations (`XMemAllocDefault`, +/// committed `XMemVirtualAlloc` regions, and allocated physical pages), +/// excluding host-side allocations such as D3D12 mirrors and shader compiler +/// memory. No tools memory: a retail console. pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { if out.is_null() { return 0; } - let mut counters = PROCESS_MEMORY_COUNTERS { - cb: size_of::() as u32, - ..Default::default() + let (virt_total, virt_gpu) = virtual_used(); + let (phys_pages, phys_gpu_pages) = { + let physical = physical(); + (physical.pages.len(), physical.gpu_optimal_pages) }; - // SAFETY: our own process and a sized structure. - unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; + let heap_total = HEAP_USED.load(Ordering::Relaxed); + let heap_gpu = HEAP_GPU_OPTIMAL_USED.load(Ordering::Relaxed); + let title_used = virt_total + .saturating_add(phys_pages.saturating_mul(PAGE)) + .saturating_add(heap_total); + let gpu_optimal_used = virt_gpu + .saturating_add(phys_gpu_pages.saturating_mul(PAGE)) + .saturating_add(heap_gpu); let (gpu_optimal, standard) = victory_gpu::console::current().title_memory(); let stats = WorkingSet { title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed), - title_used: counters.PagefileUsage, + title_used, + physical_pages: u32::try_from(phys_pages).unwrap_or(u32::MAX), gpu_optimal_limit: gpu_optimal, + gpu_optimal_used, ..Default::default() }; // SAFETY: checked non-null; the title passes room for the structure. @@ -998,7 +1151,7 @@ mod tests { fn transfers_shrink_the_title_budget() { let mut before = WorkingSet::default(); assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1); - assert!(before.title_used > 0); + assert!(before.title_limit > 0); assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); let standard = victory_gpu::console::current().title_memory().1; @@ -1008,6 +1161,89 @@ mod tests { assert_eq!(before.title_limit - after.title_limit, 128 * MIB); } + #[test] + fn working_set_tracks_title_allocations_and_excludes_host_memory() { + let stats = || { + let mut ws = WorkingSet::default(); + assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut ws), 1); + ws + }; + + // Host allocations (mirrors, shader compiler) must not inflate title_used. + let before_host = stats(); + let mut host_buf = vec![0u8; 32 * MIB]; + for page in host_buf.chunks_mut(4096) { + page[0] = 1; + } + std::hint::black_box(&host_buf); + let after_host = stats(); + assert!( + after_host.title_used < before_host.title_used + 16 * MIB, + "host memory should not be counted in title_used: before={} after={}", + before_host.title_used, + after_host.title_used + ); + drop(host_buf); + + // Uncommitted virtual reservations count 0; committing adds exact bytes; + // VirtualFree(MEM_RELEASE) subtracts them automatically. + let before_virt = stats(); + let virt = XMemVirtualAlloc( + std::ptr::null_mut(), + 16 * MIB, + MEM_RESERVE, + GRAPHICS, + PAGE_NOACCESS, + ); + assert!(!virt.is_null()); + let after_reserve = stats(); + assert!( + after_reserve.title_used < before_virt.title_used + 8 * MIB, + "uncommitted reserve should not be counted" + ); + let committed = XMemVirtualAlloc(virt, 16 * MIB, MEM_COMMIT, GRAPHICS, PAGE_READWRITE); + assert_eq!(committed, virt); + let after_commit = stats(); + assert!(after_commit.title_used >= before_virt.title_used + 12 * MIB); + assert!(after_commit.gpu_optimal_used >= before_virt.gpu_optimal_used + 12 * MIB); + // SAFETY: our reservation from above. + assert_ne!(unsafe { VirtualFree(virt, 0, MEM_RELEASE) }, 0); + let after_release = stats(); + assert!(after_release.title_used + 10 * MIB <= after_commit.title_used); + assert!(after_release.gpu_optimal_used + 10 * MIB <= after_commit.gpu_optimal_used); + + // XMemAllocDefault tracks standard vs GPU-optimal allocations and frees. + let before_heap = stats(); + let std_blk = XMemAllocDefault(16 * MIB, 0); + let gpu_blk = XMemAllocDefault(16 * MIB, 1 << ALLOC_TYPE_SHIFT); + assert!(!std_blk.is_null() && !gpu_blk.is_null()); + let after_heap = stats(); + assert!(after_heap.title_used >= before_heap.title_used + 28 * MIB); + assert!(after_heap.gpu_optimal_used >= before_heap.gpu_optimal_used + 12 * MIB); + assert!(after_heap.gpu_optimal_used < before_heap.gpu_optimal_used + 24 * MIB); + XMemFreeDefault(std_blk, 0); + XMemFreeDefault(gpu_blk, 0); + let after_heap_free = stats(); + assert!(after_heap_free.title_used + 24 * MIB <= after_heap.title_used); + assert!(after_heap_free.gpu_optimal_used + 10 * MIB <= after_heap.gpu_optimal_used); + + // Physical pages track total count, title_used, and gpu_optimal_used. + let before_phys = stats(); + let mut pages = [0usize; 64]; + let mut count = pages.len(); + assert_eq!( + XMemAllocatePhysicalPages(GRAPHICS, &mut count, pages.as_mut_ptr()), + 1 + ); + assert_eq!(count, 64); + let after_phys = stats(); + assert!(after_phys.physical_pages >= before_phys.physical_pages + 50); + assert!(after_phys.gpu_optimal_used >= before_phys.gpu_optimal_used + 3 * MIB); + assert_eq!(XMemFreePhysicalPages(count, pages.as_ptr()), 1); + let after_phys_free = stats(); + assert!(after_phys_free.physical_pages + 50 <= after_phys.physical_pages); + } + #[test] fn statistics_have_the_console_layout() { assert_eq!(size_of::(), 0x50); diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index a3a1d626e30..f89328c53e4 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -180,11 +180,20 @@ mod device_type { text.eq_ignore_ascii_case(expected) } - /// Opens our key for its path; the key has no subkeys. `None`: not - /// ours, ask the host. + /// Opens our key for its path; the key has no subkeys, and a null or + /// empty path below it opens the key itself, as the host's do. `None`: + /// not ours, ask the host. fn open(root: Key, sub: *const u16, out: *mut Key) -> Option { if root == oem() { - return Some(FILE_NOT_FOUND); + if !(sub.is_null() || is(sub, "")) { + return Some(FILE_NOT_FOUND); + } + if out.is_null() { + return Some(INVALID_PARAMETER); + } + // SAFETY: checked non-null; the title passes room for a key. + unsafe { out.write(oem()) }; + return Some(SUCCESS); } if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { // SAFETY: checked non-null; the title passes room for a key. @@ -339,6 +348,34 @@ mod device_type { assert_eq!(again, oem()); } + #[test] + fn a_null_or_empty_path_opens_the_key_itself() { + const KEY_READ: u32 = 0x2_0019; + let empty = w(""); + let host_key = w(r"Software\Microsoft\Windows NT\CurrentVersion"); + for (root, path) in [(oem(), w(KEY)), (std::ptr::null_mut(), host_key)] { + // Ours, then the host's for comparison. + let mut key = std::ptr::null_mut(); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + assert!(root.is_null() || key == root); + for sub in [std::ptr::null(), empty.as_ptr()] { + // `RegOpenKeyW` gives back the key it was passed. + let mut same = std::ptr::null_mut(); + assert_eq!(RegOpenKeyW(key, sub, &mut same), SUCCESS, "{sub:?}"); + assert_eq!(same, key); + // `RegOpenKeyExW` a handle to the same key. + let mut again = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(key, sub, 0, KEY_READ, &mut again), + SUCCESS, + "{sub:?}" + ); + assert_eq!(RegCloseKey(again), SUCCESS); + } + assert_eq!(RegCloseKey(key), SUCCESS); + } + } + #[test] fn other_keys_reach_the_host() { let mut key = std::ptr::null_mut(); diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 8b48dfc0d31..9c85045da83 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -1,7 +1,7 @@ //! XUser: one offline local user, signed in, never a guest, with every //! privilege. Served as the user provider's objects from `QueryApiImpl`; -//! adding a user completes through `xasync` like any other async call. No -//! input device is associated with the user (there are none, `gameinput`). +//! adding a user completes through `xasync` like any other async call. Every +//! non-null input device (`gameinput`) maps to this single offline local user. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{c_char, c_void}; @@ -262,9 +262,15 @@ extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { true } -/// No input device belongs to a user. -extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT { - USER_NOT_FOUND +/// Every valid (non-null, non-zero) `APP_LOCAL_DEVICE_ID` belongs to the +/// single signed-in offline local user. +extern "system" fn find_for_device(_: This, device: *const c_void, out: *mut Handle) -> HRESULT { + if device.is_null() || out.is_null() { + return xasync::E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes an APP_LOCAL_DEVICE_ID (32 bytes). + let id = unsafe { &*device.cast::<[u8; 32]>() }; + found(*id != [0u8; 32], out) } // Unset slots (no title seen calls them): maximum users, gamer pictures, @@ -422,4 +428,37 @@ mod tests { FAILED_TO_GET_TOKEN ); } + + #[test] + fn find_for_device_returns_user_for_valid_device_ids() { + type FindForDevice = extern "system" fn(This, *const c_void, *mut Handle) -> HRESULT; + let find = slot::(&DEVICE_OBJECT, 0x18); + let this: This = &DEVICE_OBJECT; + + let mut device_id = [0u8; 32]; + device_id[..7].copy_from_slice(b"victory"); + device_id[31] = 1; + let mut handle = std::ptr::null(); + assert_eq!(find(this, device_id.as_ptr().cast(), &mut handle), S_OK); + assert_eq!(handle, user()); + + // All-zero APP_LOCAL_DEVICE_ID (XUserNullDeviceId) has no user. + let zero_id = [0u8; 32]; + let mut not_found = std::ptr::null(); + assert_eq!( + find(this, zero_id.as_ptr().cast(), &mut not_found), + USER_NOT_FOUND + ); + assert!(not_found.is_null()); + + // Null pointers are rejected with E_INVALIDARG. + assert_eq!( + find(this, std::ptr::null(), &mut not_found), + xasync::E_INVALIDARG + ); + assert_eq!( + find(this, device_id.as_ptr().cast(), std::ptr::null_mut()), + xasync::E_INVALIDARG + ); + } } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index c8479c5e22e..88f989d62f7 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -95,7 +95,10 @@ impl Title { .find(|(p, _)| p == path) .map(|(_, text)| text.as_str()) }; - let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let id = get("Game/TitleId").and_then(|v| { + let v = v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")).unwrap_or(v); + u32::from_str_radix(v, 16).ok() + }); let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); Title { id: id.unwrap_or(0), @@ -148,10 +151,20 @@ fn elements(text: &str) -> Vec<(String, String)> { .next() .unwrap_or(""); path.push(name); - let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + let body = if closed { + String::new() + } else { + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + [ + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'"), + ("&", "&"), + ] .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)) + }; out.push((path.join("/"), body)); if closed { path.pop(); @@ -223,4 +236,23 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } + + #[test] + fn parses_hex_prefixed_title_ids() { + let t1 = Title::from_manifest("0x639AA8DD"); + assert_eq!(t1.id, 0x639A_A8DD); + let t2 = Title::from_manifest("0X1234ABCD"); + assert_eq!(t2.id, 0x1234_ABCD); + let t3 = Title::from_manifest("639AA8DD"); + assert_eq!(t3.id, 0x639A_A8DD); + } + + #[test] + fn isolates_self_closing_element_bodies() { + let el = elements(" \n12345678"); + let identity = el.iter().find(|(path, _)| path == "Game/Identity").unwrap(); + assert_eq!(identity.1, ""); + let title_id = el.iter().find(|(path, _)| path == "Game/TitleId").unwrap(); + assert_eq!(title_id.1, "12345678"); + } } diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index e709d115a0d..2b7beada7a1 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -146,19 +146,41 @@ fn map_dll( seen: &mut HashSet, loaded: &mut Vec<(String, LoadedImage)>, ) -> Result<()> { - let name = name.to_ascii_lowercase(); - let path = dirs.0.join(&name); - if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + let key = name.to_ascii_lowercase(); + if !seen.insert(key.clone()) || !wanted(&key) { return Ok(()); } + let Some(path) = file_in(dirs.0, name) else { + return Ok(()); + }; let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?; let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?; map_imports(&image.info, dirs, wanted, seen, loaded)?; - loaded.push((name, image)); + loaded.push((key, image)); Ok(()) } +/// The file `name` in `dir`, its case ignored as the Windows loader ignores +/// it. A folder can be case-sensitive (WSL makes the folders it creates +/// so), where joining the name finds only that exact spelling. +fn file_in(dir: &Path, name: &str) -> Option { + let exact = dir.join(name); + if exact.is_file() { + return Some(exact); + } + std::fs::read_dir(dir) + .ok()? + .filter_map(Result::ok) + .find(|e| { + e.file_name() + .to_str() + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + }) + .map(|e| e.path()) + .filter(|p| p.is_file()) +} + /// Resolves through `inner`, then through the exports of the title's DLLs. pub struct WithTitleDlls<'a> { pub inner: &'a dyn ImportResolver, diff --git a/crates/victory-loader/tests/title_dlls.rs b/crates/victory-loader/tests/title_dlls.rs index 49101bf8cc8..d3cf3dde2ee 100644 --- a/crates/victory-loader/tests/title_dlls.rs +++ b/crates/victory-loader/tests/title_dlls.rs @@ -1,4 +1,5 @@ -//! A title DLL that cannot be loaded is named in the error. +//! Finding the title's DLLs: one that cannot be loaded is named in the +//! error, and a folder's case sensitivity does not hide one. #![cfg(windows)] #[test] @@ -14,3 +15,40 @@ fn a_title_dll_that_does_not_prepare_is_named() { let text = format!("{error:#}"); assert!(text.contains("broken.dll"), "{text}"); } + +/// An empty folder whose names are case-sensitive, as folders WSL creates +/// are (`fsutil file setCaseSensitiveInfo`); `None` where Windows cannot +/// make one. +fn case_sensitive_dir() -> Option { + let dir = tempfile::tempdir().unwrap(); + let made = std::process::Command::new("fsutil.exe") + .args(["file", "setCaseSensitiveInfo"]) + .arg(dir.path()) + .arg("enable") + .output() + .is_ok_and(|o| o.status.success()); + made.then_some(dir) +} + +#[test] +fn a_title_dll_in_a_case_sensitive_folder_is_found_by_any_spelling() { + let Some(title) = case_sensitive_dir() else { + eprintln!("no case-sensitive folders on this machine; skipped"); + return; + }; + // Any real DLL will do; it imports only host DLLs, which are not in the folder. + std::fs::copy( + r"C:\Windows\System32\version.dll", + title.path().join("Late.dll"), + ) + .unwrap(); + let wanted = |_: &str| true; + // As written on disk, and as an import or `LoadLibrary` may spell it. + for name in ["Late.dll", "LATE.DLL", "late.dll"] { + let cache = tempfile::tempdir().unwrap(); + let dlls = + victory_loader::load_title_dll(name, title.path(), cache.path(), &wanted).unwrap(); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["late.dll"], "loading {name}"); + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4dc5d..3ba56b7c8e7 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -113,7 +113,8 @@ impl Host { } /// The root signature for these stages: user data of stage k is root - /// parameter k, root views follow. + /// parameter k, root views follow, then the root SRVs at addresses in + /// root constants. pub fn root_signature_for( &self, stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], @@ -158,6 +159,23 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + // Root SRVs at addresses in root constants follow, per stage in + // order (each stage numbers its own from 0). + for &(s, vis) in stages { + for n in 0..s.address_srvs.len() as u32 { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: n, + RegisterSpace: super::ROOT_ADDRESS_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: vis, + }); + } + } let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -528,6 +546,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 211da1778c1..5f3d8cc46f0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -8,10 +8,10 @@ use std::collections::{BTreeMap, HashMap, HashSet}; -use super::UserData; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; +use super::{AddressView, UserData}; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; @@ -35,6 +35,7 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, + pub address_srvs: Vec, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, } @@ -163,6 +164,9 @@ struct Lower<'a> { user_data: Option, user_reads: BTreeMap, samplers: Vec<[u32; 4]>, + /// Root SRVs at addresses in root constants, in the order of the + /// shader's `address_srvs`. + address_views: Vec, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, exports: HashMap, @@ -463,6 +467,7 @@ impl<'a> Lower<'a> { user_data: None, user_reads: BTreeMap::new(), samplers: Vec::new(), + address_views: Vec::new(), descriptors: x .res .descriptors @@ -900,6 +905,7 @@ impl<'a> Lower<'a> { cmp_samplers, root_cbvs, root_srvs, + address_srvs: self.address_views, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -1178,8 +1184,15 @@ impl<'a> Lower<'a> { None => (v, false), }; let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; - if !self.x.st.active.contains(&lo) { - return Err("a lane mask holding lanes elsewhere read as data"); + if m == crate::structure::Bool::FALSE { + return Ok(self.s.m.i32(0)); + } + if m == crate::structure::Bool::TRUE { + return Ok(self.s.m.i32(u32::MAX)); + } + if let Some((crate::structure::Atom::Constant(k), crate::structure::Bool::FALSE, crate::structure::Bool::TRUE)) = self.x.st.bools.node(m) { + let val = if high { (k >> 32) as u32 } else { k as u32 }; + return Ok(self.s.m.i32(val)); } let (x, y) = match self.ballots.get(&lo) { Some(&xy) => xy, @@ -1188,7 +1201,7 @@ impl<'a> Lower<'a> { // Program inputs (EXEC on entry). None => self.s.entry, Some(&b) if b == self.cur_ir => self.cur, - Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, + Some(&b) => self.tail[b].unwrap_or(self.cur), }; if !self.balloting.insert(lo) { return Err("a lane mask whose lanes depend on its own value"); @@ -1466,12 +1479,26 @@ impl<'a> Lower<'a> { let t = self.binary(36, hi, third); let median = self.binary(35, lo, t); let least = self.binary(36, lo, third); - let ab = self.s.m.cmp(c, pred::UNO, a, b); - let nan3 = self.s.m.cmp(c, pred::UNO, third, third); - let nan = self.s.m.bin(c, Bin::Or, ab, nan3); + let na = self.is_nan_bits(a); + let nb = self.is_nan_bits(b); + let n3 = self.is_nan_bits(third); + let ab = self.s.m.bin(c, Bin::Or, na, nb); + let nan = self.s.m.bin(c, Bin::Or, ab, n3); self.s.m.select(c, nan, least, median) } + /// Whether `f` is a NaN, tested on its bits (`|f| > +inf` as integers). + /// A float `fcmp uno` is not used: drivers (observed on NVIDIA) assume + /// no NaNs there and fold it to false, so the NaN case was lost. + fn is_nan_bits(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let abs = self.s.m.i32(0x7FFF_FFFF); + let inf = self.s.m.i32(0x7F80_0000); + let mag = self.s.m.bin(c, Bin::And, bits, abs); + self.s.m.cmp(c, pred::IUGT, mag, inf) + } + /// `a - floor(a)`, which on the hardware never reaches 1.0: where it /// would round to it (a tiny negative `a`), the result is `below_one`, /// the largest value under 1.0 in the operation's width. Hosts differ @@ -1608,9 +1635,8 @@ impl<'a> Lower<'a> { // lanes it adds only feed derivatives, and exports keep their own // masks. Wrong if such a section had a side effect. Atom::Quad(_) => Ok(self.s.m.bool(true)), - // With console lanes, a mask held as a number is the console's: - // the lane tests its own bit. - Atom::Opaque(v) if self.console_lanes => { + // A mask held as a number: the lane tests its own bit via waveGetLaneIndex. + Atom::Opaque(v) => { let hi = match self.pair_high(v) { Some(h) => Some(self.get(h)?), None => None, @@ -1624,13 +1650,11 @@ impl<'a> Lower<'a> { let hi = hi.map(word).transpose()?; Ok(self.lane_bit(at, lo, hi)) } - Atom::Constant(k) if self.console_lanes => { + Atom::Constant(k) => { let lo = self.s.m.i32(k as u32); let hi = self.s.m.i32((k >> 32) as u32); Ok(self.lane_bit(at, lo, Some(hi))) } - Atom::Opaque(_) => Err("an opaque lane mask"), - Atom::Constant(_) => Err("a constant lane mask"), } } @@ -2246,16 +2270,22 @@ impl<'a> Lower<'a> { let name = inst.name(); self.mask_ok = match self.mask_data { MaskData::Console => true, - MaskData::Host => { + MaskData::Host | MaskData::None => { name.starts_with("s_bcnt1_i32_") || name.starts_with("s_ff1_i32_") || name.starts_with("v_mbcnt_") + || name.starts_with("s_mov_") + || name.starts_with("s_and_") + || name.starts_with("s_or_") + || name.starts_with("s_xor_") + || name.starts_with("s_andn2_") + || name.starts_with("s_orn2_") + || name.starts_with("s_bitcmp") || matches!( name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" ) } - MaskData::None => false, }; let effect = matches!(inst.fields, Fields::Exp { .. }) || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") @@ -2799,6 +2829,14 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if let Some(a) = self + .scalar + .get(&site) + .copied() + .filter(|a| self.in_constants(a)) + { + return self.pair_smem(inst, a); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -2840,7 +2878,8 @@ impl<'a> Lower<'a> { } return Ok(()); } - if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let on_pair = matches!(src, Source::Built { address, .. } if self.in_constants(address)); + if on_pair || matches!(kind, Some(u) if u.kind == ResourceType::Srv) { let h = self.handle(site, src, false, (11, 0))?; for k in 0..count { let off = self.s.m.i32(4 * k); @@ -2934,18 +2973,32 @@ impl<'a> Lower<'a> { _ => return Err("a scalar memory read as data"), }; // How the program uses the descriptor tells the view's kind. - let use_at = self + // Prefer an image or vector-buffer use over `s_buffer_load_dword*`, + // since those encode typed/structured properties directly. + let mut uses = self .x .res .descriptors .iter() .filter(|d| d.role == Role::Resource) - .find_map(|d| { + .filter_map(|d| { d.source.leaves().into_iter().find_map(|l| match *l { Source::Loaded { load, first } if load == site => Some((d.site, first)), _ => None, }) }); + let mut fallback = None; + let use_at = loop { + let Some((at, first)) = uses.next() else { + break fallback; + }; + match &self.x.p.blocks[at.0].insts[at.1].fields { + Fields::Image { .. } | Fields::Buffer { .. } => break Some((at, first)), + _ => { + fallback.get_or_insert((at, first)); + } + } + }; let Some((at, first)) = use_at else { return Err("a descriptor read only as data"); }; @@ -2985,6 +3038,15 @@ impl<'a> Lower<'a> { } (props, None) } + Fields::Smem { .. } if un.starts_with("s_buffer_load_dword") => { + if !matches!( + used.map(|u| u.kind), + Some(ResourceType::Srv | ResourceType::Uav) + ) { + return Err("a constant buffer's descriptor read as data"); + } + ((11 | u, 0), None) + } _ => return Err("a scalar memory read as data"), }; let h = self.handle(site, &src, false, props)?; @@ -3085,6 +3147,52 @@ impl<'a> Lower<'a> { Ok(()) } + /// `s_load_dword*` through an address in root constants: raw loads from + /// the root SRV at that address, as `s_buffer_load_dword*` on a + /// descriptor built around one. + fn pair_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar load through an address in root constants"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar load through an address in root constants"), + }; + let h = self.address_srv(&a)?; + let c = self.cur; + let mut addr = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + addr = self.s.m.bin(c, Bin::Add, addr, d); + } + for k in 0..count { + let off = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + let x = self.as_int(x); + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + /// The dword at a computed byte address of a constant buffer. fn cbuffer_dword(&mut self, h: V, a: V) -> V { let c = self.cur; @@ -3233,6 +3341,42 @@ impl<'a> Lower<'a> { Ok(out) } + /// The dwords a `tbuffer_store_format_*` writes: its `channels` data + /// channels in buffer format `format`, as RDNA2 lays them out (see + /// [`buffer_format`]). Formats of 32-bit channels store the data's bits; + /// the `_d16_` forms of the 16-bit float formats store their halves as + /// they are. + // shortcut: only stores that need no conversion, with every channel of + // the format supplied, are lowered. Others need conversions (norm, + // scaled, narrow integers; f32 to f16, whose DXIL op rounds toward zero + // where the console rounds to nearest even, see #422) or elements under + // a dword (a read-modify-write lanes would race on); refused until a + // program needs them. + fn format_store_words( + &mut self, + inst: &Inst, + data: Option<&Operand>, + format: u8, + channels: u32, + ) -> Result, Why> { + let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; + if bits.len() != channels as usize { + return Err("a typed-format store of some of its format's channels"); + } + if !bits.iter().sum::().is_multiple_of(32) { + return Err("a typed-format store of an element under a dword"); + } + let d16 = inst.name().contains("_d16_"); + let data = data.ok_or("buffer store data")?; + match (bits[0], numeric, d16) { + (32, Numeric::Uint | Numeric::Sint | Numeric::Float, false) => { + self.vgprs(inst, data, channels as u8) + } + (16, Numeric::Float, true) => self.vgprs(inst, data, channels.div_ceil(2) as u8), + _ => Err("a typed-format store of a converted or narrow format"), + } + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { @@ -3248,6 +3392,44 @@ impl<'a> Lower<'a> { } } + /// `a` starts from a root-constant pair. + fn in_constants(&self, a: &Address) -> bool { + self.x + .native + .layout + .get(a.param) + .is_some_and(|rp| rp.root == RootType::Constants) + } + + /// The handle of the root SRV at the address the root-constant pair + /// that `a` starts from holds. + fn address_srv(&mut self, a: &Address) -> Result { + let pair = self + .x + .res + .pairs + .iter() + .find(|p| p.lo == (a.param, a.dword)) + .ok_or("an address in root constants without its high half")?; + let half = |(param, dword): (usize, u32)| { + let rp = self.x.native.layout[param]; + UserData { + index: u32::from(rp.user_data) + dword, + slot: rp.slot, + root: rp.root, + dword, + } + }; + let view = AddressView { + lo: half(pair.lo), + hi: half(pair.hi), + }; + if !self.address_views.contains(&view) { + self.address_views.push(view); + } + Ok(self.s.address_srv_handle(view.lo.index)) + } + /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { if let Source::Phi { args, .. } = src { @@ -3329,6 +3511,12 @@ impl<'a> Lower<'a> { .layout .get(address.param) .ok_or("a descriptor built around a table in the code")?; + if rp.root == RootType::Constants { + return match props.0 { + 11 => self.address_srv(address), + _ => Err("a write or typed view through an address in root constants"), + }; + } let kind = self .x .native @@ -3997,7 +4185,27 @@ impl<'a> Lower<'a> { } "v_cndmask_b32" => { let mask = match v.src.get(2) { - Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + Some(&Operand::Scalar { code, .. }) if code != NULL => inst.read(Reg::S(code)), + Some(&Operand::Scalar { .. }) + | Some(&Operand::Const(128)) + | Some(&Operand::Literal(0)) => { + return if v.abs != 0 || v.neg != 0 { + let a = f(self, 0)?; + float(self, a) + } else { + let a = s(self, 0)?; + int(self, a) + }; + } + Some(&Operand::Const(193)) => { + return if v.abs != 0 || v.neg != 0 { + let bb = f(self, 1)?; + float(self, bb) + } else { + let bb = s(self, 1)?; + int(self, bb) + }; + } _ => None, }; let m = mask @@ -4047,14 +4255,34 @@ impl<'a> Lower<'a> { Ok(()) } "v_readlane_b32" => { - let (a, lane) = (s(self, 0)?, s(self, 1)?); - // A computed lane in a pixel or vertex program is a host lane - // (from a mask or `v_mbcnt`); a constant one is the console's. - if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { - self.s.flags |= flags::WAVE_OPS; - } else { - self.cross_lane(false)?; + let dst_v = match v.dst { + Some(Operand::Scalar { code, .. }) if code != NULL => inst.write(Reg::S(code)), + _ => None, + }; + if self.is_mask(dst_v) || dst_v.is_some_and(|d| self.x.st.highs.contains_key(&d)) { + return Err(LANE_MASK); } + if let [Operand::Vector { reg, .. }, lane_op] = v.src[..] + && let Some(lane_idx) = crate::resource::lane_of(lane_op) + && let Some(src_v) = inst.read(Reg::V(reg)) + && let Some(spilled) = self.spilled_scalar(src_v, lane_idx) + { + match spilled { + crate::resource::Moved::Const(x) => { + self.cross_lane(false)?; + let v = self.s.m.i32(x); + return int(self, v); + } + crate::resource::Moved::Value(sv) => { + if let Some(&Val::I32(x)) = self.vals.get(&sv) { + self.cross_lane(false)?; + return int(self, x); + } + } + } + } + let (a, lane) = (s(self, 0)?, s(self, 1)?); + self.s.flags |= flags::WAVE_OPS; let r = self.read_lane(a, lane); int(self, r) } @@ -4068,7 +4296,7 @@ impl<'a> Lower<'a> { Some(o) => self.i32_of(o)?, None => self.s.m.i32(0), }; - self.cross_lane(false)?; + self.s.flags |= flags::WAVE_OPS; let me = self.lane_index(); let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); @@ -4094,6 +4322,27 @@ impl<'a> Lower<'a> { } } + /// Traces lane `lane` of VGPR `v` back through `v_writelane_b32` spills. + fn spilled_scalar(&self, v: Value, lane: u32) -> Option { + let p = self.x.p; + crate::resource::spilled_lane( + p, + &|val| { + let &b = self.def_block.get(&val)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == val)) + }, + &|val| self.phi_at.get(&val).copied(), + v, + lane, + &mut Vec::new(), + ) + .ok() + .flatten() + } + /// A 64-bit source (a register pair; inline constants sign-extend). fn src64(&mut self, inst: &Inst, k: usize) -> Result { let Fields::Valu(v) = &inst.fields else { @@ -4109,11 +4358,7 @@ impl<'a> Lower<'a> { let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result { let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; - let lo = l.s.m.cast(c, Cast::ZExt, lo, i64t); - let hi = l.s.m.cast(c, Cast::ZExt, hi, i64t); - let k32 = l.s.m.int_const(i64t, 32); - let hi = l.s.m.bin(c, Bin::Shl, hi, k32); - Ok(l.s.m.bin(c, Bin::Or, lo, hi)) + Ok(l.pack64(lo, hi)) }; match op { Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)), @@ -4132,6 +4377,18 @@ impl<'a> Lower<'a> { } } + /// Packs low and high 32-bit dwords into an i64. + fn pack64(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let lo = self.s.m.cast(c, Cast::ZExt, lo, i64t); + let hi = self.s.m.cast(c, Cast::ZExt, hi, i64t); + let k32 = self.s.m.int_const(i64t, 32); + let hi = self.s.m.bin(c, Bin::Shl, hi, k32); + self.s.m.bin(c, Bin::Or, lo, hi) + } + /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; @@ -5508,11 +5765,13 @@ impl<'a> Lower<'a> { return Err("a 16-bit image atomic"); } // dmask: the data dwords (cmpswap: twice the value's). - // shortcut: 64-bit image atomics (two dwords, an R32G32 view) - // need the host's 64-bit typed atomics; they stop the program. - if *dmask != if code == u32::MAX { 3 } else { 1 } { - return Err("a 64-bit image atomic"); - } + let wide = if *dmask == if code == u32::MAX { 3 } else { 1 } { + false + } else if *dmask == if code == u32::MAX { 15 } else { 3 } { + true + } else { + return Err("an image atomic mask"); + }; let iu = self.s.m.undef(self.s.t.i32); let mut cs = vec![iu; 3]; for (k, slot) in cs.iter_mut().enumerate().take(coords) { @@ -5521,29 +5780,59 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image atomic data"); }; - let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; - let mut value = vals[0]; + let words = if code == u32::MAX { 2 } else { 1 } * if wide { 2 } else { 1 }; + let vals = self.vgprs(inst, data, words)?; + let mut value = if wide { + self.pack64(vals[0], vals[1]) + } else { + vals[0] + }; if op == "sub" { - let z = self.s.m.i32(0); + let z = if wide { + let i64t = self.s.m.int(64); + self.s.m.int_const(i64t, 0) + } else { + self.s.m.i32(0) + }; value = self.s.m.bin(c, Bin::Sub, z, value); } - let old = match inst.read(Reg::V(reg)) { - Some(v) if cache.glc => self.i32_of(v)?, - _ => self.s.m.i32(0), + let old = if wide { + let i64t = self.s.m.int(64); + match (inst.read(Reg::V(reg)), inst.read(Reg::V(reg + 1))) { + (Some(lo), Some(hi)) if cache.glc => { + let (lo, hi) = (self.i32_of(lo)?, self.i32_of(hi)?); + self.pack64(lo, hi) + } + _ => self.s.m.int_const(i64t, 0), + } + } else { + match inst.read(Reg::V(reg)) { + Some(v) if cache.glc => self.i32_of(v)?, + _ => self.s.m.i32(0), + } }; let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?; + if wide { + self.s.flags |= flags::INT64 | flags::ATOMIC_INT64_TYPED | flags::ATOMIC_INT64_HEAP; + } let at = self.begin_guarded(guard); - let i32t = self.s.t.i32; + let ty = if wide { self.s.m.int(64) } else { self.s.t.i32 }; + let sfx = if wide { "i64" } else { "i32" }; let mut args = vec![h]; let r = if code == u32::MAX { // cmpswap: data is (new, compare). + let cmp = if wide { + self.pack64(vals[2], vals[3]) + } else { + vals[1] + }; args.extend(cs); - args.extend([vals[1], vals[0]]); + args.extend([cmp, value]); self.s.op( self.cur, - "atomicCompareExchange.i32", + &format!("atomicCompareExchange.{sfx}"), Attr::NoUnwind, - i32t, + ty, 79, &args, ) @@ -5551,12 +5840,24 @@ impl<'a> Lower<'a> { args.push(self.s.m.i32(code)); args.extend(cs); args.push(value); - self.s - .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + self.s.op( + self.cur, + &format!("atomicBinOp.{sfx}"), + Attr::NoUnwind, + ty, + 78, + &args, + ) }; let r = self.end_guarded(at, &[(r, old)])[0]; if cache.glc { - self.write(inst, Reg::V(reg), r, None); + if wide { + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, None); + self.write(inst, Reg::V(reg + 1), hi, None); + } else { + self.write(inst, Reg::V(reg), r, None); + } } return Ok(()); } @@ -6003,13 +6304,16 @@ impl<'a> Lower<'a> { if *lds || *tfe { return Err("a buffer access to LDS or with tfe"); } - if format.is_some() && !name.starts_with("tbuffer_load_format_") { + if format.is_some() + && !name.starts_with("tbuffer_load_format_") + && !name.starts_with("tbuffer_store_format_") + { return Err(name); } let site = (b, i); let guard = self.guard(b, i)?; let c = self.cur; - let store = name.starts_with("buffer_store_"); + let store = name.starts_with("buffer_store_") || name.starts_with("tbuffer_store_"); // DXIL atomic operations: add, and, or, xor, signed and unsigned // min and max, exchange; compare-exchange apart. let atomic = match name.strip_prefix("buffer_atomic_") { @@ -6033,6 +6337,7 @@ impl<'a> Lower<'a> { .strip_prefix("buffer_load_") .or(plain.strip_prefix("buffer_store_")) .or(plain.strip_prefix("tbuffer_load_")) + .or(plain.strip_prefix("tbuffer_store_")) { _ if atomic.is_some() => (false, 1), Some("dword") => (false, 1), @@ -6156,6 +6461,31 @@ impl<'a> Lower<'a> { } return Ok(()); } + if let (true, Some(f)) = (store, *format) { + if index.is_some() { + return Err("a typed-format store by index"); + } + let words = self.format_store_words(inst, data.as_ref(), f, count)?; + let iu = self.s.m.undef(self.s.t.i32); + let mut args = vec![self.handle(site, src, false, (11 | u, 0))?, off, iu]; + let n = words.len(); + args.extend(words); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(self.s.m.i32(4)); + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s.op( + self.cur, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } if store { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = @@ -6716,6 +7046,7 @@ impl<'a> Lower<'a> { fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; + let direct_reads = self.read_phis.clone(); // A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that // reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the // lowering accepts what it refuses when the same value is read directly. @@ -6733,6 +7064,7 @@ impl<'a> Lower<'a> { for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; + let is_direct = direct_reads.contains(&phi.value); let mut incoming = Vec::new(); for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; @@ -6743,9 +7075,18 @@ impl<'a> Lower<'a> { (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } - (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + (Some(Val::Missing(why)), _) + if is_direct || why.contains("scalar memory") || why.contains("s_memtime") => + { return Err(Stop::Retry(phi.value, why)); } + (Some(Val::Missing(_)), _) => { + if bit { + self.s.m.bool(false) + } else { + self.s.m.i32(0) + } + } _ if self.read_phis.contains(&phi.value) => { return Err(Stop::Retry(phi.value, "a join of mismatched values")); } @@ -6782,7 +7123,9 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { use super::{Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; use crate::{io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; @@ -6964,6 +7307,157 @@ mod tests { } } + /// Lowers a compute program with four root constants in `s0..s3` and a + /// table in `s4` whose first descriptor is a raw UAV in `s[8:11]`, `body` + /// leaving in `v0` what is stored there: the root SRVs at addresses in + /// root constants, and the other root SRVs. + fn lowers_with_constants( + body: &[u32], + ) -> Result<(Vec, Vec), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + ]; + words.extend(body); + words.extend([ + 0xE070_0000, + 0x8002_0000, // buffer_store_dword v0, off, s[8:11], 0 + S_ENDPGM, + ]); + let param = |root, user_data, sgprs, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + param(RootType::Constants, 0, 4, 0), + param(RootType::Table, 4, 1, 1), + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, 8).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|l| (l.address_srvs, l.root_srvs)) + } + + /// `s[12:15]`: a raw buffer descriptor built around the pair `s[2:3]`. + const BUILT_ON_THE_PAIR: [u32; 6] = [ + 0xBE8C_0302, // s_mov_b32 s12, s2 + 0xBE8D_0303, // s_mov_b32 s13, s3 + 0xBE8E_03C1, // s_mov_b32 s14, -1 + 0xBE8F_03FF, + 0x1101_4FAC, // s_mov_b32 s15, 0x11014fac + 0xBF80_0000, // s_nop 0 + ]; + + #[test] + fn reads_through_a_root_constant_pair_are_a_root_srv() { + let half = |dword| super::UserData { + index: dword, + slot: 0, + root: RootType::Constants, + dword, + }; + let view = super::AddressView { + lo: half(2), + hi: half(3), + }; + let global = [ + 0xDC30_8000, + 0x0002_0001, // global_load_dword v0, v1, s[2:3] + ]; + let mut scalar = BUILT_ON_THE_PAIR.to_vec(); + scalar.extend([ + 0xF420_0186, + 0xFA00_0000, // s_buffer_load_dword s6, s[12:15], null + 0x7E00_0206, // v_mov_b32 v0, s6 + ]); + let scalar_load = [ + 0xF400_0181, + 0xFA00_0000, // s_load_dword s6, s[2:3], null + 0x7E00_0206, // v_mov_b32 v0, s6 + ]; + for body in [&global[..], &scalar, &scalar_load] { + let (views, root_srvs) = lowers_with_constants(body).unwrap(); + assert_eq!(views, [view]); + assert!(root_srvs.is_empty()); + } + } + + #[test] + fn other_uses_of_a_root_constant_pair_stop_with_a_reason() { + let reason = |body: &[u32]| match lowers_with_constants(body) { + Err(crate::ShaderError::Unsupported { what, .. }) => what, + other => panic!("{:?}", other.map(|_| ())), + }; + let mut typed = BUILT_ON_THE_PAIR.to_vec(); + typed.extend([ + 0xE000_2000, + 0x8003_0001, // buffer_load_format_x v0, v1, s[12:15], 0 idxen + ]); + assert_eq!( + reason(&typed), + "a write or typed view through an address in root constants" + ); + } + + #[test] + fn lane_mask_reads_as_data_lowers() { + let words = [ + 0x7C04_0300, // v_cmp_eq_u32_e32 v0, v1 + 0xBE82_036A, // s_mov_b32 s2, vcc_lo (106) + S_ENDPGM, + ]; + lowers(&words, 0).unwrap(); + } + + #[test] + fn readlane_and_writelane_lower() { + let words = [ + 0xD761_0000, + 0x0001_0600, // v_writelane_b32 v0, s0, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + S_ENDPGM, + ]; + lowers(&words, 0).unwrap(); + } + #[test] fn a_missing_value_stays_missing_through_two_live_joins() { let mut words = [ @@ -7085,4 +7579,147 @@ mod tests { // A 16-bit float is a half already, sign included. assert_eq!(half(0xBC00 << half_shift(16)), -1.0); } + + #[test] + fn sixty_four_bit_image_atomics_lower_and_validate() { + use crate::native::{ResourceType, RootParam, RootType, UsedResource}; + let words = [ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0501, + 0xFA00_0000, // s_load_dwordx8 s[20:27], s[2:3], null + 0xF05C_130A, + 0x0005_060D, + 0x0000_0004, // image_atomic_umax v[6:7], [v13,v4], s[20:27] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 9, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 9, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let mut lowered = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + if let Ok(mut v) = super::super::validator::Validator::load(None) { + v.validate(&mut lowered.dxil).unwrap(); + } + } + + #[test] + fn spilled_inactive_mask_does_not_poison_other_lanes() { + let words = [ + 0xBE80_0385, // s_mov_b32 s0, 5 + 0x8902_C17E, // s_xor_b32 s2, exec_lo, -1 + 0xD761_0000, + 0x0001_0002, // v_writelane_b32 v0, s2, 0 + 0xD761_0000, + 0x0001_0200, // v_writelane_b32 v0, s0, 1 + 0xD760_0004, + 0x0001_0300, // v_readlane_b32 s4, v0, 1 + 0xBF06_8504, // s_cmp_eq_u32 s4, 5 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE85_0380, // s_mov_b32 s5, 0 + S_ENDPGM, + ]; + lowers(&words, 0).unwrap(); + } + + #[test] + fn descriptor_data_handles_s_buffer_load_srv() { + use crate::native::{ResourceType, RootParam, RootType, UsedResource}; + let words = [ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0001, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null + 0xBF06_8002, // s_cmp_eq_u32 s2, 0 + 0xBF85_0002, // s_cbranch_scc1 -> s_endpgm + 0xF420_0100, + 0xFA00_0000, // s_buffer_load_dword s4, s[0:3], null + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 9, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 9, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6c668f33e31..b29dc80bf3a 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -29,6 +29,15 @@ //! `b` / `t` in [`ROOT_CBV_SPACE`], `i` the title's root parameter //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the //! address the title sets is the buffer's. +//! * **Addresses in root constants** (added 2026-11-24): a 64-bit address +//! the title passes as two root-constant dwords (low half first, in +//! consecutive user SGPRs) and the shader only reads through +//! (`global_load_*`, `s_buffer_load_*` on a descriptor built around it) is +//! a root SRV (raw buffer) `t` in [`ROOT_ADDRESS_SPACE`], `n` the +//! position in [`HostShader::address_srvs`]. The host composes the +//! address from the two constants' current values at every draw and binds +//! the buffer there. Writes, typed views and scalar loads through such an +//! address stop the translation. //! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, @@ -95,7 +104,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::{ROOT_ADDRESS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -154,6 +163,17 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, + /// Root SRVs (raw buffers) at addresses in root constants: `t` in + /// [`ROOT_ADDRESS_SPACE`] for the view at position n. + pub address_srvs: Vec, +} + +/// A root SRV at the 64-bit address two root-constant dwords hold (both +/// with `root` [`RootType::Constants`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AddressView { + pub lo: UserData, + pub hi: UserData, } impl HostShader { @@ -202,7 +222,15 @@ pub fn translate(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + // A compute program whose root arguments all sit past the 16 user SGPRs + // finds them through the spill table `s[0:1]` points to. + let spilled = native.stage == HwStage::Cs + && !native.layout.is_empty() + && native + .layout + .iter() + .all(|r| native.stage.user_sgpr(r.user_data) >= 16); + let p = ir::build_with(&native.patched_code(), native.wave64, native.vgprs, spilled)?; let res = resource::track(&p, &native.layout, native.stage)?; let io = io::raise(&p, &native)?; let st = structure::structure(&p)?; @@ -303,6 +331,7 @@ pub fn emit( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, + address_srvs: l.address_srvs, }) } @@ -560,6 +589,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -570,6 +600,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 44a315a7599..e13dd345d34 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -12,6 +12,9 @@ pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// Where root SRVs at addresses passed in two root constants are bound: +/// `t` in this space, `n` the position in the shader's list of them. +pub const ROOT_ADDRESS_SPACE: u32 = 2; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -20,8 +23,10 @@ pub(crate) mod flags { pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; + pub const ATOMIC_INT64_TYPED: u64 = 1 << 27; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; + pub const ATOMIC_INT64_HEAP: u64 = 1 << 32; } pub(crate) struct Types { @@ -65,6 +70,9 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root SRVs (raw buffers) at addresses in root constants, by the low + /// half's user-data index, with their handles. + pub address_srvs: Vec<(u32, V)>, pub flags: u64, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, @@ -118,6 +126,7 @@ impl Shader { cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), flags: 0, threads: None, wave_size: None, @@ -233,6 +242,32 @@ impl Shader { h } + /// The handle of the root SRV (a raw buffer) at the address whose low + /// half is user-data dword `key`: `t` in [`ROOT_ADDRESS_SPACE`], `n` + /// its position in `address_srvs`. + pub fn address_srv_handle(&mut self, key: u32) -> V { + if let Some(&(_, h)) = self.address_srvs.iter().find(|r| r.0 == key) { + return h; + } + let r = self.m.i32(self.address_srvs.len() as u32); + let bind = [r, r, self.m.i32(ROOT_ADDRESS_SPACE), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + self.address_srvs.push((key, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -306,6 +341,7 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.address_srvs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -360,20 +396,28 @@ impl Shader { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - if !self.root_srvs.is_empty() { + if !self.root_srvs.is_empty() || !self.address_srvs.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + // Root SRVs by root parameter, then those at addresses in + // root constants by position. + let views = self + .root_srvs + .iter() + .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) + .chain((0..self.address_srvs.len() as u32).map(|n| (ROOT_ADDRESS_SPACE, n))) + .collect::>(); + for (n, (space, register)) in views.into_iter().enumerate() { let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, ROOT_CBV_SPACE)), - Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, space)), + Some(i32c(&mut self, register)), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(i32c(&mut self, 0)), @@ -382,8 +426,8 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 4, - space: ROOT_CBV_SPACE, - register: u32::from(slot), + space, + register, dxil_kind: 11, }); } @@ -566,12 +610,18 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::ATOMIC_INT64_TYPED != 0 { + features |= 0x40_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } if self.flags & flags::SAMPLER_HEAP != 0 { features |= 0x400_0000; } + if self.flags & flags::ATOMIC_INT64_HEAP != 0 { + features |= 0x1000_0000; + } let sfi0 = features.to_le_bytes(); let isg1 = container::signature(&self.inputs, true); let osg1 = container::signature(&self.outputs, false); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 4135e9af4b7..1deb0a6289c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -3,7 +3,8 @@ //! //! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: //! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` -//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`. +//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the +//! layouts `tbuffer_store_format_*` writes. use super::host::{Dispatch, Host, Root, View}; use super::{HostShader, lower, validator}; @@ -69,6 +70,11 @@ const fn vgpr(n: u8) -> u16 { /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. fn build_valu_cs(body: &[u32]) -> HostShader { + try_build_valu_cs(body).expect("lower") +} + +/// [`build_valu_cs`], with the lowering's refusal as an error. +fn try_build_valu_cs(body: &[u32]) -> Result { let mut words = Vec::new(); // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). words.push(s_mov_b32(5, 0x80)); // inline constant 0 @@ -137,7 +143,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { prims: Vec::new(), mesh_stride: 0, }) - .expect("lower"); + .map_err(|e| format!("{e:?}"))?; let shader = HostShader { stage: HwStage::Cs, @@ -147,6 +153,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + address_srvs: lowered.address_srvs, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -156,7 +163,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { assert_eq!(copy[4..20], ours[..], "container hash mismatch"); } - shader + Ok(shader) } /// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for @@ -933,3 +940,233 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +/// MTBUF `op vdata, v5, s[8:11], 0 format:fmt offset:16` (no offen/idxen; +/// `op` 4..7 stores x..xyzw, 12..15 their d16 forms). +const fn mtbuf_store(op: u8, fmt: u8, vdata: u8) -> [u32; 2] { + [ + 0x3A << 26 | (fmt as u32) << 19 | (op as u32 & 7) << 16 | 16, + 0x80 << 24 | (op as u32 >> 3 & 1) << 21 | (8 >> 2) << 16 | (vdata as u32) << 8 | 5, + ] +} + +/// Runs `shader` once with root constants `inputs` on every available +/// SM 6.6 host and returns the first `dwords` of its raw UAV, per device. +fn run_dwords(shader: &HostShader, inputs: [u32; 4], dwords: u32) -> Vec<(&'static str, Vec)> { + let mut out = 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 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) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let r = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, r[0].clone())); + } + assert!( + !out.is_empty(), + "neither hardware nor WARP SM 6.6 device available" + ); + out +} + +#[test] +fn tbuffer_store_format_writes_the_formats_layout() { + let f = |x: f32| x.to_bits(); + // (what, op, format, data in v1..v4, dwords 4..8 afterwards) + type Case = (&'static str, u8, u8, [u32; 4], [u32; 4]); + let cases: &[Case] = &[ + ( + "32_32_32_32 float xyzw", + 7, + 77, + [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], + [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], + ), + ( + "32_32_32_32 sint xyzw", + 7, + 76, + [u32::MAX, 0x8000_0000, 7, 0x1234_5678], + [u32::MAX, 0x8000_0000, 7, 0x1234_5678], + ), + ( + "32_32_32 float xyz", + 6, + 74, + [f(2.0), f(3.0), f(4.0), 0xDEAD_BEEF], + [f(2.0), f(3.0), f(4.0), 0], + ), + ( + "32_32 uint xy", + 5, + 63, + [0xAABB_CCDD, 9, 0xDEAD_BEEF, 0xDEAD_BEEF], + [0xAABB_CCDD, 9, 0, 0], + ), + ( + "32 float x", + 4, + 22, + [f(-7.25), 1, 2, 3], + [f(-7.25), 0, 0, 0], + ), + ( + // d16: the halves are stored as they are. + "16_16 float d16_xy", + 13, + 29, + [0xBC00_3555, 0xDEAD_BEEF, 0, 0], + [0xBC00_3555, 0, 0, 0], + ), + ( + "16_16_16_16 float d16_xyzw", + 15, + 71, + [0x1234_5678, 0x7C00_FC00, 0, 0], + [0x1234_5678, 0x7C00_FC00, 0, 0], + ), + ]; + for &(what, op, fmt, inputs, want) in cases { + let mut body = vec![vop1(0x001, 5, 0x80)]; // v_mov_b32 v5, 0 + body.extend(mtbuf_store(op, fmt, 1)); + let shader = build_valu_cs(&body); + for (backend, out) in run_dwords(&shader, inputs, 8) { + assert_eq!( + out[4..8], + want, + "{backend}: tbuffer_store {what}: wrote {:#010x?}, want {want:#010x?}", + &out[4..8], + ); + } + } +} + +#[test] +fn tbuffer_store_format_refuses_what_it_does_not_convert() { + for (what, op, fmt, reason) in [ + ("8_8_8_8 unorm", 7, 56, "a converted or narrow format"), + ("16_16 uint", 5, 27, "a converted or narrow format"), + ("16 float", 4, 13, "an element under a dword"), + ( + "32_32_32_32 float, xy only", + 5, + 77, + "some of its format's channels", + ), + ("32 float d16_x", 12, 22, "a converted or narrow format"), + // f32 to f16 waits for nearest-even narrowing (#422). + ("16_16 float xy", 5, 29, "a converted or narrow format"), + ( + "16_16_16_16 float xyzw", + 7, + 71, + "a converted or narrow format", + ), + ] { + let mut body = vec![vop1(0x001, 5, 0x80)]; + body.extend(mtbuf_store(op, fmt, 1)); + match try_build_valu_cs(&body) { + Ok(_) => panic!("tbuffer_store {what} lowered; it should be refused"), + Err(e) => assert!(e.contains(reason), "tbuffer_store {what}: refused with {e}"), + } + } +} + +/// Runs `body` with an address in root constants (`s[2:3]`) and a root SRV +/// bound for it (`t0` in `ROOT_ADDRESS_SPACE`, the root parameter after the +/// user data) holding `0x100 + k` in dword `k`; checks that `v0` ends up +/// holding dword 3. +fn reads_dword_3_through_a_root_constant_pair(body: &[u32]) { + let shader = build_valu_cs(body); + assert!(shader.root_srvs.is_empty()); + let [view] = shader.address_srvs[..] else { + panic!("{:?}", shader.address_srvs) + }; + assert_eq!((view.lo.dword, view.hi.dword), (2, 3)); + let data: Vec = (0..8).map(|k| 0x100 + k).collect(); + let mut ran = 0; + 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}")); + // The constants hold an address the host does not use: it binds the + // buffer itself. + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Constants { + ud[u.index as usize] = 0x1_0000 * (u.dword + 1); + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: data.clone(), + }, + ), + ], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0][0], data[3], "{label}: byte 12 of the buffer"); + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +/// A global load through an address the title passes as two root constants +/// reads the root SRV the host binds at that address. +#[test] +fn global_loads_through_a_root_constant_pair_read_its_root_srv() { + reads_dword_3_through_a_root_constant_pair(&[ + vop1(0x001, 5, 128 + 8), // v_mov_b32 v5, 8 + 0xDC30_8004, + 0x0002_0005, // global_load_dword v0, v5, s[2:3] offset:4 + ]); +} + +/// A scalar load through the same address reads it too. +#[test] +fn scalar_loads_through_a_root_constant_pair_read_its_root_srv() { + reads_dword_3_through_a_root_constant_pair(&[ + 0xF400_0181, + 0xFA00_000C, // s_load_dword s6, s[2:3], 0xc + vop1(0x001, 0, sgpr(6)), // v_mov_b32 v0, s6 + ]); +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index cc73a49bb3f..637077dca2c 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -119,11 +119,225 @@ impl Inst { } } +/// The first user SGPR that the spill table of root arguments stands for. +const SPILL_FIRST: u8 = 16; + +/// Rewrites loads from the spill table (`s[0:1]`, the high dword masked to a +/// 40-bit address, usually through copies in `s2`/`s3`) into `s_mov_b32` from +/// the user SGPRs the table's dwords stand for. Only loads with a constant +/// offset, in code no branch joins after the pointer is set up, are rewritten. +/// +/// The table holds the arguments as they were on entry, but the program may +/// have written the SGPRs those dwords stand for by the time it loads them +/// (a load into `s[8:23]` overwrites what stands for table dwords 0..7). So +/// the program first copies the user SGPRs it reads into a block of SGPRs it +/// never uses, and the loads read that block. Without such a block, or when a +/// branch can return to the entry, nothing is rewritten. +fn spill_loads( + list: Vec, + wave64: bool, + vgprs: u16, + code_len: usize, +) -> Result, ShaderError> { + use gfx10::Fields::{Smem, Sop, Valu}; + let mut targets = std::collections::BTreeSet::new(); + for inst in list.iter() { + let flow = gfx10::control(inst, code_len, |at| { + list[..list.partition_point(|i| i.offset < at)].last() + })?; + if let Flow::Jump(t) | Flow::Branch(t) = flow { + targets.insert(t); + } + } + let Some(entry) = list.first().map(|i| i.offset) else { + return Ok(list); + }; + if targets.contains(&entry) { + return Ok(list); + } + // Every SGPR the program reads or writes, to find a block it never uses. + let mut used = [false; 128]; + for inst in list.iter() { + let Some(name) = inst.name() else { + return Ok(list); + }; + let Ok(effects) = effects( + inst, + &inst.fields(wave64), + name, + 1 + u8::from(wave64), + vgprs, + ) else { + return Ok(list); + }; + for reg in effects + .into_iter() + .flat_map(|(r, w)| r.into_iter().chain(w)) + { + if let Reg::S(c) = reg { + used[usize::from(c).min(127)] = true; + } + } + } + let original = list.clone(); + // Where each rewritten copy is in `out`, and the user SGPR it stands for. + let mut copies: Vec<(usize, u8)> = Vec::new(); + // 1: a copy of s0, 2: a copy of s1 (masked to the address's high bits). + let mut tag = [0u8; 128]; + tag[0] = 1; + tag[1] = 2; + let mut out = Vec::with_capacity(list.len()); + let scalar = |o: &Operand| match *o { + Operand::Scalar { code, dwords } if code < 106 => Some((code, dwords.max(1))), + _ => None, + }; + for inst in list { + if targets.contains(&inst.offset) { + tag = [0; 128]; + } + let f = inst.fields(wave64); + let name = inst.name().unwrap_or(""); + // The load of the table. + if let Smem { + data: Some(ref d), + ref base, + offset, + ref soffset, + .. + } = f + && name.starts_with("s_load_dword") + && let Some((a, 2)) = scalar(base) + && tag[a as usize] == 1 + && tag[a as usize + 1] == 2 + && offset >= 0 + && offset % 4 == 0 + && matches!(*soffset, Operand::Scalar { code: 125, .. }) + && let Some((dst, n)) = scalar(d) + { + let first = u32::from(SPILL_FIRST) + (offset as u32) / 4; + if first + u32::from(n) <= 105 { + for k in 0..n { + let src = (first + u32::from(k)) as u8; + copies.push((out.len(), src)); + out.push(s_mov(dst + k, src, inst.offset)?); + } + for k in 0..n { + tag[(dst + k) as usize] = 0; + } + continue; + } + } + // What this instruction does to the tracked registers. + let mut written: Vec<(u8, u8)> = Vec::new(); + match &f { + Sop { + dst: Some(d), src, .. + } => { + if let Some((dc, dn)) = scalar(d) { + let new = match (name, src.as_slice()) { + ("s_mov_b32", [x]) => match scalar(x) { + Some((c, _)) if tag[c as usize] != 0 => tag[c as usize], + _ => 0, + }, + ("s_and_b32", [x, y]) => { + // `s1 & mask` with a small mask, either way round. + let masked = |reg: &Operand, mask: &Operand| match (scalar(reg), mask) { + (Some((c, _)), Operand::Literal(m)) => { + tag[c as usize] == 2 && *m <= 0xFFFF + } + (Some((c, _)), Operand::Const(k)) => { + tag[c as usize] == 2 && (129..=192).contains(k) + } + _ => false, + }; + if masked(x, y) || masked(y, x) { 2 } else { 0 } + } + _ => 0, + }; + if dn == 1 { + tag[dc as usize] = new; + } else { + written.push((dc, dn)); + } + } + } + Smem { data: Some(d), .. } => written.extend(scalar(d)), + Valu(v) => { + written.extend(v.dst.as_ref().and_then(scalar)); + written.extend(v.carry.as_ref().and_then(scalar)); + } + _ => {} + } + for (c, n) in written { + for k in c..c.saturating_add(n).min(128) { + tag[k as usize] = 0; + } + } + out.push(inst); + } + let Some(last) = copies.iter().map(|c| c.1).max() else { + return Ok(out); + }; + // A block of SGPRs past the user SGPRs the table stands for that the + // program never touches, below VCC. + let size = usize::from(last - SPILL_FIRST) + 1; + let Some(block) = (usize::from(last) + 1..=usize::from(VCC) - size) + .find(|&b| used[b..b + size].iter().all(|u| !u)) + else { + return Ok(original); + }; + let moved = |src: u8| (block + usize::from(src - SPILL_FIRST)) as u8; + let mut read: Vec = copies.iter().map(|c| c.1).collect(); + read.sort_unstable(); + read.dedup(); + for &(at, src) in &copies { + let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } = out[at].fields(wave64) + else { + unreachable!("a copy is an s_mov_b32"); + }; + out[at] = s_mov(code, moved(src), out[at].offset)?; + } + let mut entries = Vec::with_capacity(read.len() + out.len()); + for &src in &read { + entries.push(s_mov(moved(src), src, entry)?); + } + entries.extend(out); + Ok(entries) +} + +/// `s_mov_b32 s, s`, placed at `offset`. +fn s_mov(dst: u8, src: u8, offset: usize) -> Result { + let word = 0xBE80_0000 | u32::from(dst) << 16 | 3 << 8 | u32::from(src); + let mut bytes = word.to_le_bytes().to_vec(); + bytes.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm + let mut one = gfx10::decode(&bytes)?.remove(0); + one.offset = offset; + Ok(one) +} + /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result { - let list = gfx10::decode(code)?; + build_with(code, wave64, vgprs, false) +} + +/// [`build`]; with `spilled`, loads from the root-argument spill table that +/// `s[0:1]` points to read the user SGPRs the table stands for (table dword +/// `k` is user SGPR `16 + k`), as plain register copies. +pub fn build_with( + code: &[u8], + wave64: bool, + vgprs: u16, + spilled: bool, +) -> Result { + let mut list = gfx10::decode(code)?; + if spilled { + list = spill_loads(list, wave64, vgprs, code.len())?; + } let lanes = 1 + u8::from(wave64); let isa = |offset, reason| ShaderError::Isa { offset, reason }; @@ -1043,6 +1257,121 @@ mod tests { p.inputs.iter().find(|i| i.0 == reg).expect("input").1 } + /// A compute program whose root arguments are in the spill table `s[0:1]` + /// points to: the loads become copies of the user SGPRs the dwords stand for. + #[test] + fn spill_table_loads_read_user_sgprs() { + let code: Vec = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0x8703_FF01, // s_and_b32 s3, s1, lit + 0x0000_00FF, // 0xff + 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0x10 + 0xFA00_0010, + 0xBE86_0308, // s_mov_b32 s6, s8 + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let plain = build_with(&code, false, 256, false).unwrap(); + assert!( + plain + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "s_load_dwordx4") + ); + let p = build_with(&code, false, 256, true).unwrap(); + let insts: Vec<_> = p.blocks.iter().flat_map(|b| &b.insts).collect(); + assert!(!insts.iter().any(|i| i.name().starts_with("s_load"))); + // Table dwords 4..8 are user SGPRs 20..24. + for k in 0..4 { + assert!( + p.inputs.iter().any(|i| i.0 == Reg::S(20 + k)), + "s{} read", + 20 + k + ); + } + // s2, the four entry copies of s20..s23, the four loaded dwords, s6. + assert_eq!( + insts.iter().filter(|i| i.name() == "s_mov_b32").count(), + 1 + 4 + 4 + 1 + ); + } + + /// A later table load still reads the arguments as they were on entry, + /// although an earlier load overwrote the SGPRs its dwords stand for. + #[test] + fn spill_table_loads_read_entry_values() { + let code: Vec = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0x8703_FF01, // s_and_b32 s3, s1, lit + 0x0000_00FF, // 0xff + 0xF40C_0301, // s_load_dwordx8 s[12:19], s[2:3], 0x10 (writes s16..s19) + 0xFA00_0010, + 0xF404_0101, // s_load_dwordx2 s[4:5], s[2:3], 0 (table dwords 0..1) + 0xFA00_0000, + 0xBE86_0304, // s_mov_b32 s6, s4 + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build_with(&code, false, 256, true).unwrap(); + let insts: Vec<_> = p.blocks.iter().flat_map(|b| &b.insts).collect(); + assert!(!insts.iter().any(|i| i.name().starts_with("s_load"))); + // Table dwords 0..1 and 4..11 are user SGPRs 16..17 and 20..27, all + // read on entry. + for reg in (16..18).chain(20..28) { + assert!( + p.inputs.iter().any(|i| i.0 == Reg::S(reg)), + "s{reg} read on entry" + ); + } + // s6 holds what s16 held on entry, not what the first load put there. + let entry = input(&p, Reg::S(16)); + let copied = |v: Value| { + insts + .iter() + .find(|i| i.name() == "s_mov_b32" && i.writes.iter().any(|w| w.1 == v)) + .and_then(|i| i.reads.first().map(|r| r.1)) + }; + let mut value = insts + .iter() + .rev() + .find_map(|i| i.write(Reg::S(6))) + .expect("s6 written"); + while value != entry { + value = copied(value).expect("a chain of copies back to the entry value"); + } + } + + /// Loads from a pointer that is not the spill table stay loads. + #[test] + fn spill_table_leaves_other_loads() { + let code: Vec = [ + 0xF408_0A00u32, // s_load_dwordx4 s[8:11], s[0:1], 0 (s0:1 not yet copied: tagged) + 0xFA00_0000, + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0 (s2 overwritten) + 0xFA00_0000, + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build_with(&code, false, 256, true).unwrap(); + let loads = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name().starts_with("s_load")) + .count(); + // The first load is from s[0:1] itself, so it is rewritten; the second + // reads a pointer the program overwrote, so it stays. + assert_eq!(loads, 1); + } + #[test] fn joins_get_phis_only_where_values_differ() { let code = [ diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 46cf8916275..0cb72fad3af 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -11,6 +11,11 @@ //! descriptor's address itself. Each descriptor operand and each scalar //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. +//! +//! A title can also pass a 64-bit address as two root constants, low half +//! first, in consecutive user SGPRs (within one parameter or across two). +//! Such a pair is recognised from its high half, which the code uses only +//! as the high half of an address (or adds a carry to): [`Pair`]. use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; @@ -26,12 +31,23 @@ pub type Site = (usize, usize); pub struct Address { /// Index into the layout, or [`CODE`]. pub param: usize, + /// The dword of the base within `param`: 0 except for an address in + /// root constants ([`Pair`]), where it is the low half's. + pub dword: u32, /// Added modulo 2^32 (with carry into the high half of a root /// descriptor's address). pub offset: u32, pub dynamic: Option, } +/// A 64-bit address in two root-constant dwords: layout index and dword +/// of its low half and of its high half (the next user SGPR). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pair { + pub lo: (usize, u32), + pub hi: (usize, u32), +} + /// [`Address::param`] of the program's own code: a constant table the /// compiler appends after the code and reads through `s_getpc_b64`; the /// offset is then the byte offset in the code. @@ -89,6 +105,8 @@ pub struct Resources { /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + /// The root-constant pairs the addresses above start from, once each. + pub pairs: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as @@ -154,6 +172,18 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Some(*address), + _ => None, + }) + }); + let addresses: Vec
= out.scalar.iter().map(|s| s.1).chain(built).collect(); + for pair in addresses.into_iter().filter_map(|a| t.pair(a)) { + if !out.pairs.contains(&pair) { + out.pairs.push(pair); + } + } Ok(out) } @@ -164,8 +194,8 @@ enum Term { Value(Value), } -/// A 32-bit sum: optional root parameter (as its first dword), constant, -/// optional computed term. +/// A 32-bit sum: optional root parameter (as its first dword, or the low +/// half of a [`Pair`]), constant, optional computed term. struct Sum { base: Option, offset: u32, @@ -337,7 +367,9 @@ impl<'a> Tracer<'a> { )) } - fn sum(&self, t: Term) -> Sum { + /// The sum `t` computes; `pair`, the low half of a root-constant pair, + /// counts as a base too. + fn sum(&self, t: Term, pair: Option) -> Sum { let v = match t { Term::Const(c) => { return Sum { @@ -355,6 +387,11 @@ impl<'a> Tracer<'a> { }; if let Some(reg) = self.inputs[v.0 as usize] { return match self.param_of(reg) { + _ if pair == Some(v) => Sum { + base: Some(v), + offset: 0, + dynamic: None, + }, Some((_, 0)) => Sum { base: Some(v), offset: 0, @@ -377,7 +414,7 @@ impl<'a> Tracer<'a> { else { return dynamic; }; - let (x, y) = (self.sum(a), self.sum(b)); + let (x, y) = (self.sum(a, pair), self.sum(b, pair)); if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { return dynamic; } @@ -465,7 +502,7 @@ impl<'a> Tracer<'a> { return Err("an address not in SGPRs"); }; let v = inst.read(Reg::V(reg)).ok_or("a global address")?; - let mut extra = self.sum(self.vorigin(v)); + let mut extra = self.sum(self.vorigin(v), None); if extra.base.is_some() { return Err("an offset from a root parameter"); } @@ -493,7 +530,10 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { - let s = self.sum(lo); + if let Some(a) = self.pair_address(lo, hi, &extra) { + return a; + } + let s = self.sum(lo, None); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); } @@ -506,6 +546,7 @@ impl<'a> Tracer<'a> { } return Ok(Address { param: CODE, + dword: 0, offset: (pc.machine.offset as u32 + 4) .wrapping_add(s.offset) .wrapping_add(extra.offset), @@ -535,11 +576,91 @@ impl<'a> Tracer<'a> { } Ok(Address { param, + dword: 0, offset: s.offset.wrapping_add(extra.offset), dynamic: s.dynamic.or(extra.dynamic), }) } + /// The address a root-constant pair holds: `hi` is the pair's high half + /// (possibly plus a carry) and the sum of `lo` starts from its low half. + /// `None` when `lo` and `hi` are no pair; the other kinds of address + /// never have a root constant as their high half. + fn pair_address( + &self, + lo: Term, + hi: Term, + extra: &Sum, + ) -> Option> { + let (low, high) = self.pair_high(hi)?; + let s = self.sum(lo, Some(low)); + if s.base != Some(low) { + return None; + } + let (param, dword) = self.param_of(self.inputs[low.0 as usize]?)?; + if s.dynamic.is_some() && extra.dynamic.is_some() { + return Some(Err("an address with two computed terms")); + } + let dynamic = s.dynamic.or(extra.dynamic); + if !self.high_half(hi, Some(high)) && !(dynamic.is_some() && self.carried(hi, high)) { + return Some(Err("an address with an untracked high half")); + } + Some(Ok(Address { + param, + dword, + offset: s.offset.wrapping_add(extra.offset), + dynamic, + })) + } + + /// The root-constant input `hi` is, or adds a carry to (`s_addc_u32`, + /// `v_add_co_ci_u32`, as [`Tracer::carried`] walks), when the user SGPR + /// below it holds a root constant too: (low half, high half) on entry. + fn pair_high(&self, hi: Term) -> Option<(Value, Value)> { + let Term::Value(v) = hi else { return None }; + if let Some(Reg::S(code)) = self.inputs[v.0 as usize] { + let below = code.checked_sub(1)?; + if !self.is_constant(code) || !self.is_constant(below) { + return None; + } + let low = self.p.inputs.iter().find(|i| i.0 == Reg::S(below))?.1; + return Some((low, v)); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return self.pair_high(a).or_else(|| self.pair_high(b)); + } + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_add_co_ci_u32" { + return None; + } + f.src[..2.min(f.src.len())] + .iter() + .find_map(|o| self.pair_high(self.vterm(inst, o)?)) + } + + /// User SGPR `code` holds a root-constant dword. + fn is_constant(&self, code: u8) -> bool { + self.param_of(Reg::S(code)) + .is_some_and(|(i, _)| self.layout[i].root == RootType::Constants) + } + + /// The pair an address in root constants starts from. + fn pair(&self, a: Address) -> Option { + let rp = self.layout.get(a.param)?; + if rp.root != RootType::Constants { + return None; + } + let low = u32::from(self.stage.user_sgpr(rp.user_data)) + a.dword; + let high = u8::try_from(low + 1).ok()?; + Some(Pair { + lo: (a.param, a.dword), + hi: self.param_of(Reg::S(high))?, + }) + } + /// `hi` is `high` (0 for a table), possibly plus a carry. fn high_half(&self, hi: Term, high: Option) -> bool { let want = high.map_or(Term::Const(0), Term::Value); @@ -619,6 +740,7 @@ impl<'a> Tracer<'a> { let mut extra = self.sum( self.term(inst, soffset) .ok_or("an unknown offset operand")?, + None, ); if extra.base.is_some() { return Err("an offset from a root parameter"); @@ -776,7 +898,7 @@ impl<'a> Tracer<'a> { } #[derive(Clone, Copy, PartialEq, Eq)] -enum Moved { +pub(crate) enum Moved { Const(u32), Value(Value), } @@ -794,58 +916,78 @@ impl Tracer<'_> { let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) - .ok() - .flatten() + spilled_lane( + self.p, + &|val| self.def(val), + &|val| self.phis[val.0 as usize], + inst.read(Reg::V(reg))?, + lane_of(lane)?, + &mut Vec::new(), + ) + .ok() + .flatten() } +} - /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in - /// `seen` (already being resolved), `Err` if not a spilled SGPR. - fn spilled(&self, v: Value, lane: u32, seen: &mut Vec) -> Result, ()> { - if let Some((b, i)) = self.phis[v.0 as usize] { - if seen.contains(&v) { - return Ok(None); - } - seen.push(v); - let mut found = None; - for &a in &self.p.blocks[b].phis[i].args { - if let Some(m) = self.spilled(a, lane, seen)? { - if found.is_some_and(|f| f != m) { - return Err(()); - } - found = Some(m); - } - } - return Ok(found); - } - let inst = self.def(v).ok_or(())?; - let Fields::Valu(w) = &inst.fields else { - return Err(()); - }; - let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { - return Err(()); - }; - if inst.name() != "v_writelane_b32" { - return Err(()); - } - if lane_of(*at).ok_or(())? != lane { - return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); +/// Traces lane `lane` of VGPR value `v` back through `v_writelane_b32` writes +/// and VGPR phis to the spilled scalar or constant (`Ok(None)` for a phi cycle). +pub(crate) fn spilled_lane<'a>( + p: &'a Program, + def_of: &impl Fn(Value) -> Option<&'a Inst>, + phi_of: &impl Fn(Value) -> Option<(usize, usize)>, + v: Value, + lane: u32, + seen: &mut Vec, +) -> Result, ()> { + if let Some((b, i)) = phi_of(v) { + if seen.contains(&v) { + return Ok(None); } - match *value { - Operand::Scalar { code, .. } if code != NULL => { - inst.read(Reg::S(code)).map(Moved::Value) + seen.push(v); + let mut found = None; + for &a in &p.blocks[b].phis[i].args { + if let Some(m) = spilled_lane(p, def_of, phi_of, a, lane, seen)? { + if found.is_some_and(|f| f != m) { + return Err(()); + } + found = Some(m); } - Operand::Literal(x) => Some(Moved::Const(x)), - Operand::Const(c) => inline(c).map(Moved::Const), - _ => None, } - .map(Some) - .ok_or(()) + return Ok(found); + } + let inst = def_of(v).ok_or(())?; + let Fields::Valu(w) = &inst.fields else { + return Err(()); + }; + let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { + return Err(()); + }; + if inst.name() != "v_writelane_b32" { + return Err(()); } + if lane_of(*at).ok_or(())? != lane { + return spilled_lane( + p, + def_of, + phi_of, + inst.read(Reg::V(reg)).ok_or(())?, + lane, + seen, + ); + } + match *value { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)).map(Moved::Value), + Operand::Scalar { .. } => Some(Moved::Const(0)), + Operand::Literal(x) => Some(Moved::Const(x)), + Operand::Const(c) => inline(c).map(Moved::Const), + _ => None, + } + .map(Some) + .ok_or(()) } /// A lane select given as a constant. -fn lane_of(op: Operand) -> Option { +pub(crate) fn lane_of(op: Operand) -> Option { match op { Operand::Const(c) => inline(c), Operand::Literal(x) => Some(x), @@ -855,6 +997,27 @@ fn lane_of(op: Operand) -> Option { /// What dword `k` of a move's result copies. fn copy_source(inst: &Inst, k: usize) -> Option { + if let Fields::Valu(v) = &inst.fields { + if k != 0 + || v.abs != 0 + || v.neg != 0 + || v.sdwa.is_some() + || v.dpp.is_some() + || !matches!(inst.name(), "v_mov_b32" | "v_readfirstlane_b32") + { + return None; + } + return match *v.src.first()? { + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).map(Moved::Value) + } + Operand::Scalar { .. } => Some(Moved::Const(0)), + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)).map(Moved::Value), + Operand::Literal(x) => Some(Moved::Const(x)), + Operand::Const(c) => inline(c).map(Moved::Const), + _ => None, + }; + } let Fields::Sop { src, imm, .. } = &inst.fields else { return None; }; @@ -931,6 +1094,7 @@ mod tests { fn at(param: usize, offset: u32) -> Address { Address { param, + dword: 0, offset, dynamic: None, } @@ -1113,4 +1277,145 @@ mod tests { } ); } + + #[test] + fn descriptors_copied_through_vgprs_and_readfirstlane_are_tracked() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0201, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[2:3], null + 0x7E00_0208, // v_mov_b32 v0, s8 + 0x7E02_0209, // v_mov_b32 v1, s9 + 0x7E04_020A, // v_mov_b32 v2, s10 + 0x7E06_020B, // v_mov_b32 v3, s11 + 0x7E08_0500, // v_readfirstlane_b32 s4, v0 + 0x7E0A_0501, // v_readfirstlane_b32 s5, v1 + 0x7E0C_0502, // v_readfirstlane_b32 s6, v2 + 0x7E0E_0503, // v_readfirstlane_b32 s7, v3 + 0xF420_0002, + 0xFA00_0000, // s_buffer_load_dword s0, s[4:7], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!( + r.descriptors[0].source, + Source::Loaded { + load: (0, 2), + first: 0 + } + ); + } + + /// `global_load_dword v1, v0, s[base:base+1]`. + fn global_load(base: u8) -> [u32; 2] { + [0xDC30_8000, 0x0100_0000 | u32::from(base) << 16] + } + + /// The pair and the address of the one global load in `words`. + fn pair_load(words: &[u32], layout: &[RootParam]) -> (Vec, Address) { + let r = track_words(words, layout, HwStage::Cs); + let [(_, a)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + (r.pairs, a) + } + + #[test] + fn root_constant_pairs_are_addresses() { + let [l0, l1] = global_load(0); + let (pairs, a) = pair_load(&[l0, l1, S_ENDPGM], &[param(Constants, 0, 2)]); + assert_eq!( + pairs, + [Pair { + lo: (0, 0), + hi: (0, 1) + }] + ); + assert_eq!((a.param, a.dword, a.offset), (0, 0, 0)); + assert!(a.dynamic.is_some(), "the VGPR offset is the computed term"); + } + + #[test] + fn a_root_constant_pair_at_a_later_dword() { + let [l0, l1] = global_load(2); + let (pairs, a) = pair_load(&[l0, l1, S_ENDPGM], &[param(Constants, 0, 4)]); + assert_eq!( + pairs, + [Pair { + lo: (0, 2), + hi: (0, 3) + }] + ); + assert_eq!((a.param, a.dword), (0, 2)); + } + + #[test] + fn a_root_constant_pair_across_two_parameters() { + let [l0, l1] = global_load(2); + let (pairs, a) = pair_load( + &[l0, l1, S_ENDPGM], + &[param(Constants, 0, 3), param(Constants, 3, 1)], + ); + assert_eq!( + pairs, + [Pair { + lo: (0, 2), + hi: (1, 0) + }] + ); + assert_eq!((a.param, a.dword), (0, 2)); + } + + #[test] + fn a_root_constant_pair_plus_an_offset_with_its_carry() { + let (pairs, a) = pair_load( + &[ + 0xD70F_6A02, + 0x0002_0000, // v_add_co_u32 v2, vcc_lo, s0, v0 + 0xD528_6A03, + 0x01A9_0001, // v_add_co_ci_u32 v3, vcc_lo, s1, 0, vcc_lo + 0xDC30_8000, + 0x017D_0002, // global_load_dword v1, v[2:3], off + S_ENDPGM, + ], + &[param(Constants, 0, 2)], + ); + assert_eq!( + pairs, + [Pair { + lo: (0, 0), + hi: (0, 1) + }] + ); + assert_eq!((a.param, a.dword, a.offset), (0, 0, 0)); + assert!(a.dynamic.is_some()); + } + + #[test] + fn a_root_constant_without_its_high_half_is_no_address() { + let [l0, l1] = global_load(0); + for hi in [ + 0xBE81_0303, // s_mov_b32 s1, s3: the high half of another pair + 0xBE81_0380, // s_mov_b32 s1, 0: a 32-bit address + ] { + let code: Vec = [hi, l0, l1, S_ENDPGM] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Constants, 0, 4)], HwStage::Cs).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 4, + what: "an address from a root parameter that is no address" + }, + "{hi:#x}" + ); + } + } } diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index c557a030411..1f6b239f53e 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -607,6 +607,37 @@ impl<'a> Lanes<'a> { } } + /// If `v` is written by `v_readlane_b32` at a constant lane, trace that + /// lane back through `v_writelane_b32` (and VGPR phis) to the spilled scalar. + fn readlane_spilled(&self, v: Value) -> Option { + let &(b, i) = self.defs.get(&v)?; + let inst = &self.p.blocks[b].insts[i]; + if inst.name() != "v_readlane_b32" { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let [Operand::Vector { reg, .. }, lane] = f.src[..] else { + return None; + }; + let lane = crate::resource::lane_of(lane)?; + crate::resource::spilled_lane( + self.p, + &|val| { + self.defs + .get(&val) + .map(|&(b, i)| &self.p.blocks[b].insts[i]) + }, + &|val| self.phis.get(&val).copied(), + inst.read(Reg::V(reg))?, + lane, + &mut Vec::new(), + ) + .ok() + .flatten() + } + fn exec(&mut self, inst: &Inst) -> Bool { match self.key(|r| inst.read(r), EXEC) { Some(k) => self.mask(k).0, @@ -627,6 +658,52 @@ impl<'a> Lanes<'a> { let (m, derived) = match self.join(k) { Some(join) => join, None => { + use crate::resource::Moved; + let spilled = if !p.wave64 { + match self.readlane_spilled(k.0) { + Some(Moved::Value(s)) => Some(self.mask((s, s))), + Some(Moved::Const(c)) => { + let m = match c { + 0 => Bool::FALSE, + u32::MAX => Bool::TRUE, + _ => self.b.atom(Atom::Constant(u64::from(c)), 0), + }; + Some((m, false)) + } + None => None, + } + } else { + match (self.readlane_spilled(k.0), self.readlane_spilled(k.1)) { + (Some(Moved::Value(s_lo)), Some(Moved::Value(s_hi))) => { + Some(self.mask((s_lo, s_hi))) + } + (Some(Moved::Const(lo)), Some(Moved::Const(hi))) => { + let v = u64::from(lo) | (u64::from(hi) << 32); + let m = match v { + 0 => Bool::FALSE, + u64::MAX => Bool::TRUE, + _ => self.b.atom(Atom::Constant(v), 0), + }; + Some((m, false)) + } + _ => None, + } + }; + if let Some((m, derived)) = spilled { + if derived + && let Some(Moved::Value(s_lo)) = self.readlane_spilled(k.0) + && self.active.contains(&s_lo) + { + self.active.insert(k.0); + } + let cache = if derived { + &mut self.masks + } else { + &mut self.other + }; + cache.insert(k, m); + return (m, derived); + } let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]); let m = match (lo, hi) { @@ -871,7 +948,11 @@ impl<'a> Lanes<'a> { && let Some(k) = self.key(|r| inst.read(r), code) { let phi = self.phis.contains_key(&k.0) || self.phis.contains_key(&k.1); - takes_mask |= self.masks.contains_key(&k) || phi && self.mask(k).1; + let restored = self.defs.get(&k.0).is_some_and(|&(b, i)| { + self.p.blocks[b].insts[i].name() == "v_readlane_b32" + }); + takes_mask |= + self.masks.contains_key(&k) || (phi || restored) && self.mask(k).1; } } let touches_exec = @@ -1180,4 +1261,28 @@ mod tests { assert_eq!(p.blocks[1].preds, [2]); assert!(structure(&p).is_ok()); } + + #[test] + fn spilled_lane_masks_are_tracked() { + let p = build( + &[ + 0x8500_807E, // s_cselect_b32 s0, exec_lo, 0 + 0xD761_0000, + 0x0001_0000, // v_writelane_b32 v0, s0, 0 + 0xD760_0002, + 0x0001_0100, // v_readlane_b32 s2, v0, 0 + 0xD501_0022, + 0x0009_00F2, // v_cndmask_b32 v34, 1.0, 0, s2 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let readlane_val = p.blocks[0].insts[2].writes[0].1; + assert!( + s.masks.contains_key(&readlane_val), + "restored mask should be tracked in masks: {:?}", + s.masks + ); + } }