From 66ed287e6ed119d403aec52ae160216a19557660 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:28:24 -0500 Subject: [PATCH 1/2] Recompiler: direct DXIL reads heap memory windows without a branch With heap windows (XCL_HEAP_WINDOWS=1), every read of the direct DXIL translator was a branch on `w < windows` (and the lane guard) around the heap lookup, and a phi per value at the join. On NVIDIA the driver's compile time follows the block count, and the reads of a large compute program make thousands of blocks. XCL_HEAP_FLAT=1 (with heap windows; new flag HEAP_FLAT in the windows count, so the caches keep the forms apart) reads in one path: the lane loads from window `w`, or window 0 when `w` is outside the windows or the lane is not active, and those lanes take 0, as the guarded form and root UAVs give. All with_mem_i32s callers only load (raw, SMEM, unaligned, format and BVH node reads). Stores and atomics keep their branch. Compute programs only (kernel and CS entries, kernel::reads_heap_flat): mesh, GS, vertex and pixel programs keep the guarded form. The HLSL path ignores the flag. The one-path form is the idea #1695 brings to the HLSL heap form. xcl shaders (--precompile, --export-hlsl, --measure-pso) takes its windows from pso::windows_for, as pso::mem_windows does, instead of its own copy of the rule, which had no HEAP_FLAT: with XCL_HEAP_FLAT=1 the precompile made the guarded form's entries, not the ones the runtime looks up (found by bielfreedom). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/gpu/dxil/kernel.rs | 24 ++++++++- crates/xcl/src/gpu/dxil/lower.rs | 2 + crates/xcl/src/gpu/dxil/lower_mem.rs | 23 ++++++++ crates/xcl/src/gpu/recomp/mod.rs | 7 ++- crates/xcl/src/gpu/recomp/pso.rs | 16 +++++- crates/xcl/src/gpu/recomp/tests.rs | 78 ++++++++++++++++++++++++++++ crates/xcl/src/shaders.rs | 42 ++++++++++++--- 7 files changed, 180 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..531e5fe516 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -126,6 +126,27 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) } +/// Whether `entry` reads its heap windows without a branch (`Lw::heap_flat`): with heap windows and +/// `HEAP_FLAT`, for compute programs (kernel and CS entries) only, the form that was timed. Mesh, GS, +/// vertex and pixel programs keep the guarded form. +fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +} + +#[cfg(test)] +#[test] +fn only_compute_programs_read_heap_windows_flat() { + use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; + assert!(reads_heap_flat(&Entry::Kernel, true, flat)); + assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + // the guarded heap form, and the switch over root UAVs + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); +} + /// The entry ABI. #[derive(Clone)] pub enum Entry { @@ -178,7 +199,7 @@ fn translate_entry( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -517,6 +538,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows), res, fmt_table: None, fmt_desc_cache: HashMap::new(), diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..10b08da5e6 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,6 +187,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + /// heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only, `kernel::reads_heap_flat`) + pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..3257449e03 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -401,12 +401,35 @@ impl Lw { out } + /// `with_mem_many_tys` of `n` dwords for a read (`f` only loads). With `heap_flat`, no branch: + /// `f` reads window `w`, or window 0 when `w` is outside the windows or the lane is not in + /// `guard`, and those lanes then take 0 (a raw buffer read out of the view's range gives 0, + /// so the read of window 0 is harmless). One path per access, as #1695 makes the HLSL heap + /// form: no handle phi, no block per read. pub(crate) fn with_mem_i32s( &mut self, guard: Option, n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + return vec![z; n]; + } + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..0ad34a19ae 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -85,6 +85,11 @@ pub const MEM_HEAP_BASE: u32 = 4; /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads the heap windows of compute stages without a branch +/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -1501,7 +1506,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { - normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..a64cf68256 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -80,9 +80,14 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) +} + +/// `n` windows as this run's programs take them (`mem_windows`; also the keys +/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up). +pub fn windows_for(n: u32) -> u32 { if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } @@ -118,6 +123,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap +/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +pub fn heap_flat() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..3656553c32 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4258,6 +4258,84 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { assert_eq!(*word(w1 + 0x3000), CANARY1, "out-of-UMA global_atomic_inc must not clobber w1"); } +/// Heap windows read without a branch (`HEAP_FLAT`, the direct translator): over 4 windows, the +/// same registers as the switch over root UAVs and as the guarded heap form, for scalar loads, +/// a V# load and per-lane global loads whose lanes pick different windows, some outside UMA +/// (read 0) and some not active (keep their old values). +#[test] +fn gpu_heap_flat_reads_match_the_switch_form() { + use crate::gpu::dxil::kernel::{translate, KernelOptions}; + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap(); + let w: Vec = (0..4).map(|k| arena.window(k).0 as u64).collect(); + let base_hi = (w[0] >> 32) as u32; + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &wk) in w.iter().enumerate() { + *word(wk + 0x40) = 0xA0 + k as u32; + // 65 words: lane 63's dwordx2 reads the 65th + for l in 0..65u64 { + *word(wk + 0x100 + 4 * l) = (k as u32 + 1) * 1000 + l as u32; + } + } + let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + (n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None) + }; + let list = vec![ + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)], None), // s[2:3] → window 2 + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None), // s[4:5] → outside UMA: 0 + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None), // V# s[8:11] in window 3 + // lanes 33.. active from here + ("V_CMPX_LT_U32", "ENC_VOPC", vec![("SRC0", 160), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), // V# s[12:15] in window 1 + glbl("GLOBAL_LOAD_DWORD", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), // v[4:5]: window lane % 4, or outside + glbl("GLOBAL_LOAD_DWORDX2", &[("VDST", 8), ("ADDR", 10), ("SADDR", 16), ("OFFSET", 0)]), // s[16:17] + v10: window 0 + ]; + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let p = prog(&refs); + let mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + 2]); + st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + 6]); + st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + 3) & 0xFFFF, 0x400, 0]); + st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + 1) & 0xFFFF | 4 << 16, 64, 0]); + st.sgpr[16..18].copy_from_slice(&[0x100, base_hi]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = l; + r[4] = 0x100 + 4 * l; + r[5] = if l % 8 == 7 { base_hi + 5 } else { base_hi + l % 4 }; + for k in 6..10 { + r[k] = 0x7777_7777; + } + r[10] = 4 * l; + } + let split = runner::split_wave64(); + let run = |windows: u32| { + let dxil = translate(&p, KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }).unwrap_or_else(|e| panic!("windows {windows:#x}: {e}")); + runner::run_in_arena(&dxil, &st, &arena).unwrap() + }; + let switch = run(4); + let flat = run(4 | super::HEAP_WINDOWS | super::HEAP_FLAT); + let guarded = run(4 | super::HEAP_WINDOWS); + assert_eq!((switch.sgpr[30], switch.sgpr[31]), (0xA2, 0), "s_load: window 2, outside UMA"); + assert_eq!(switch.sgpr[24..28], [4001, 4002, 4003, 4004], "s_buffer_load_dwordx4 from window 3"); + for l in 0..64u32 { + let v = &switch.vgpr[l as usize]; + let (old, active) = (0x7777_7777, l > 32); + assert_eq!(v[7], if active { 2000 + l } else { old }, "lane {l}: buffer_load from window 1"); + let global = if l % 8 == 7 { 0 } else { (l % 4 + 1) * 1000 + l }; + assert_eq!(v[6], if active { global } else { old }, "lane {l}: global_load from window {}", l % 4); + assert_eq!(v[8..10], if active { [1000 + l, 1001 + l] } else { [old, old] }, "lane {l}: global_load_dwordx2 from window 0"); + } + for (name, r) in [("heap flat", &flat), ("heap guarded", &guarded)] { + assert_eq!(r.sgpr[..32], switch.sgpr[..32], "{name}: SGPRs"); + for l in 0..64 { + assert_eq!(r.vgpr[l][..10], switch.vgpr[l][..10], "{name}: lane {l}"); + } + } +} + #[test] fn gpu_window_at_32bit_carry_edge_cases() { if !gpu_ready() { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 4c5a014974..7ef11a638e 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -914,12 +914,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; - // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + let runtime_windows = || runtime_windows(opts.windows); let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -994,6 +989,12 @@ pub fn run(path: &Path, args: &[String]) -> i32 { print(path, &what, agg, top, json, t0, compile) } +/// The runtime's memory windows (`pso::windows_for`, which `pso::mem_windows` takes too), as +/// `--precompile`, `--export-hlsl` and `--measure-pso` key and translate the programs. +fn runtime_windows(windows: u32) -> u32 { + recomp::pso::windows_for(windows) +} + #[cfg(test)] fn parse_record_hash(s: &str) -> Result { crate::cli::parse_hex_u64_str(s) @@ -1095,7 +1096,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { @@ -1685,7 +1686,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); @@ -2169,6 +2170,31 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// `--precompile` keys its programs with the runtime's windows: with `XCL_HEAP_WINDOWS=1 + /// XCL_HEAP_FLAT=1` they carry `HEAP_FLAT`, as `pso::mem_windows` does. The switches are + /// read once (`OnceLock`), so each setting runs in a new process. + #[test] + fn precompile_windows_are_the_runtimes() { + use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS}; + const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS"; + if let Ok(want) = std::env::var(RUN) { + assert_eq!(super::runtime_windows(4), pso::windows_for(4)); + assert_eq!(super::runtime_windows(4), want.parse::().unwrap()); + return; + } + for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) + .env(RUN, want.to_string()) + .env("XCL_HEAP_WINDOWS", "1") + .env("XCL_HEAP_FLAT", flat) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + } + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] From 60287fe493e7a37a130da18ea92ec88994c32796 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:28:21 -0500 Subject: [PATCH 2/2] Recompiler: NVIDIA compute programs take flat heap windows by default On NVIDIA, the compute programs the direct DXIL translator makes now read their memory windows through the shared descriptor heap in the flat form (HEAP_FLAT) by default, instead of through root UAVs. Other stages and other GPUs are unchanged. - pso::heap_windows: XCL_HEAP_WINDOWS=1 every stage (as before), =0 none, unset: on when the title's adapter is NVIDIA (set_adapter_vendor, from the device's DXGI adapter). XCL_HEAP_FLAT=0 turns the flat form off. - compute_mem_windows: the windows of a compute program, with the heap by default; mem_windows (graphics, mesh, GS) takes the heap only with XCL_HEAP_WINDOWS=1. The HLSL path keeps root UAVs unless XCL_HEAP_WINDOWS=1 (hlsl_windows): its heap form is not measured. - A pipeline the driver refuses with heap windows is still built with root UAVs (with_switch_fallback), but only when the stage it builds took heap windows (with_switch_fallback's `heap`): an E_OUTOFMEMORY of a graphics or mesh pipeline built with root UAVs is not retried. - xcl shaders --precompile / --export-hlsl / --measure-pso: the keys of the runtime, from the bench's adapter: compute programs take pso::compute_windows (compute_mem_windows), VS, PS and mesh programs pso::graphics_windows (mem_windows), so by default on NVIDIA only the compute programs are precompiled with heap windows (found by pvfreis). - The startup preparation (prepare_for_launch, #2555) keys its programs the same way: it runs before real::init notes the adapter, so it notes the vendor of the title's adapter itself (launch_windows) and takes runtime_windows' two counts. Without that the prepared compute programs miss on NVIDIA with XCL_HEAP_WINDOWS unset (found by pvfreis and upipibi; launch_windows_are_the_titles fails without it). - XCL_UMA_WINDOWS=8|16 still needs XCL_HEAP_WINDOWS=1. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/gpu/adapter.rs | 6 ++ crates/xcl/src/gpu/recomp/pso.rs | 125 +++++++++++++++++++++---- crates/xcl/src/gpu/uma.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 81 +++++++++++++--- crates/xcl/src/shaders.rs | 140 +++++++++++++++++++++------- crates/xcl/tests/gpu_compute_e2e.rs | 4 +- 6 files changed, 295 insertions(+), 63 deletions(-) diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61fd85..fdef426bed 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -149,6 +149,12 @@ pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1 hw.into_iter().enumerate().filter(|(i, _)| keep[*i]).map(|(_, a)| a).collect() } +/// PCI vendor id of the adapter a title would run on here (the first `sel` allows), if any. +pub fn vendor(sel: &Selector) -> Option { + let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?; + candidates(&factory, sel).first().map(|(_, d)| d.VendorId) +} + /// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips. pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String { let have: Vec = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect(); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index a64cf68256..ee6aa07429 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -78,21 +78,48 @@ pub fn fspx(blob: &[u8]) -> Option> { } /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when -/// shaders take them from the descriptor heap (`heap_windows`). +/// shaders of every stage take them from the descriptor heap (`XCL_HEAP_WINDOWS=1`). pub fn mem_windows() -> u32 { - windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) + graphics_windows(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) } -/// `n` windows as this run's programs take them (`mem_windows`; also the keys -/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up). -pub fn windows_for(n: u32) -> u32 { - if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { +/// `n` windows as a VS, PS, mesh or GS program of this run takes them (`mem_windows`; the keys +/// `xcl shaders --precompile` makes for them). +pub fn graphics_windows(n: u32) -> u32 { + with_heap(n, heap_windows_everywhere()) +} + +/// `mem_windows` for a compute program: also from the descriptor heap when heap windows are on +/// by default (`heap_windows`). Only the direct DXIL translator takes them then: the HLSL path +/// keeps the switch (`hlsl_windows`). +pub fn compute_mem_windows() -> u32 { + compute_windows(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) +} + +/// `n` windows as a compute program of this run takes them (`compute_mem_windows`; the keys +/// `xcl shaders --precompile` makes). +pub fn compute_windows(n: u32) -> u32 { + with_heap(n, heap_windows()) +} + +fn with_heap(n: u32, heap: bool) -> u32 { + if n > 1 && heap && !SWITCH_FORM.with(|s| s.get()) { n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } } +/// The windows the HLSL path translates a program with: from the heap only with +/// `XCL_HEAP_WINDOWS=1`; by default they are the direct translator's (`compute_mem_windows`). +pub fn hlsl_windows(windows: u32) -> u32 { + if heap_windows_everywhere() { + windows + } else { + windows & !(super::HEAP_WINDOWS | super::HEAP_FLAT) + } +} + thread_local! { /// this thread translates in the switch form (`in_switch_form`) static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -114,20 +141,50 @@ pub fn in_switch_form(f: impl FnOnce() -> R) -> R { /// Whether translated shaders reach the memory windows through the shared descriptor heap /// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) -/// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views -/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA -/// setups failed with it (the driver's compiler ending the process; a device removal when the -/// views are made on an 8 GB card) that other machines do not show. +/// instead of root UAVs, unless the views could not be made (no shared heap: then root UAVs, as +/// before). `XCL_HEAP_WINDOWS=1`: every stage; `=0`: none. By default on an NVIDIA adapter for the +/// compute programs the direct DXIL translator makes (`compute_mem_windows`), in `HEAP_FLAT` +/// form. Graphics stages keep root UAVs by default, as the other GPUs: the heap form is not +/// measured there. A pipeline the driver refuses with heap windows (E_OUTOFMEMORY, #156) is built +/// with root UAVs (`with_switch_fallback`). pub fn heap_windows() -> bool { - static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() + heap_windows_by(heap_windows_env(), ADAPTER_VENDOR.load(std::sync::atomic::Ordering::Relaxed)) && !crate::hle::d3d12x::console_heap::window_views_failed() +} + +/// `heap_windows` before the views: `XCL_HEAP_WINDOWS` when set, otherwise on for NVIDIA. +fn heap_windows_by(env: Option, vendor: u32) -> bool { + env.unwrap_or(vendor == NVIDIA) +} + +/// `XCL_HEAP_WINDOWS=1`: heap windows for every stage (`heap_windows`). +pub fn heap_windows_everywhere() -> bool { + heap_windows_env() == Some(true) && heap_windows() +} + +/// `XCL_HEAP_WINDOWS`: `1` on, `0` off, otherwise the adapter's default. +fn heap_windows_env() -> Option { + static ENV: OnceLock> = OnceLock::new(); + *ENV.get_or_init(|| match std::env::var("XCL_HEAP_WINDOWS").as_deref().map(str::trim) { + Ok("1") => Some(true), + Ok("0") => Some(false), + _ => None, + }) } -/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap -/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +const NVIDIA: u32 = 0x10DE; +/// PCI vendor id of the adapter the title's device (or `xcl shaders`' bench) runs on; 0 before. +static ADAPTER_VENDOR: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The adapter's PCI vendor id (`DXGI_ADAPTER_DESC1::VendorId`), for `heap_windows`' default. +pub fn set_adapter_vendor(vendor: u32) { + ADAPTER_VENDOR.store(vendor, std::sync::atomic::Ordering::Relaxed); +} + +/// With heap windows, the direct DXIL translator reads a compute stage's heap windows without +/// a branch per access (`HEAP_FLAT`); `XCL_HEAP_FLAT=0`: with the guarded branch. pub fn heap_flat() -> bool { static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) + *ENV.get_or_init(|| !std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "0")) } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. @@ -153,7 +210,8 @@ pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result Result { - console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows()) + let windows = if stage == Stage::Compute { compute_mem_windows() } else { mem_windows() }; + console_to_dxil_in(blob, stage, sampler_base, split_wave64, windows) } /// Global in-memory cache for translated shaders shared by `console_to_dxil_in` and `console_mesh`. @@ -624,7 +682,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } } - let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; + let (mut t, profile) = console_translation(blob, stage, sampler_base, hlsl_windows(windows), split_wave64)?; if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { if dxc::defer() { return Err("DXIL not compiled yet".into()); @@ -1396,6 +1454,39 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], } } +#[cfg(test)] +mod heap_window_default_tests { + use super::*; + + #[test] + fn heap_windows_by_default_on_nvidia_only() { + assert!(heap_windows_by(None, NVIDIA)); + for vendor in [0, 0x1002, 0x8086, 0x1414] { + assert!(!heap_windows_by(None, vendor), "{vendor:#x}"); + } + for vendor in [0, NVIDIA, 0x1002] { + assert!(heap_windows_by(Some(true), vendor)); + assert!(!heap_windows_by(Some(false), vendor)); + } + } + + /// By default (heap windows not for every stage) a compute program with heap windows takes + /// them flat; the HLSL path and the switch form take the switch. + #[test] + fn default_heap_windows_are_flat_and_for_the_direct_form_only() { + if heap_windows_env().is_some() || std::env::var_os("XCL_HEAP_FLAT").is_some() { + println!("XCL_HEAP_WINDOWS / XCL_HEAP_FLAT set – skipping"); + return; + } + let heap = super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; + assert_eq!(with_heap(4, true), 4 | heap); + assert_eq!(with_heap(1, true), 1); + assert_eq!(with_heap(4, heap_windows_everywhere()), 4, "graphics stages: the switch"); + assert_eq!(hlsl_windows(4 | heap), 4); + assert_eq!(in_switch_form(|| with_heap(4, true)), 4); + } +} + #[cfg(test)] mod slab_tests { use super::dispatch_slabs; diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..ad29f1073c 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -85,7 +85,7 @@ pub(crate) fn configured_runtime_windows() -> usize { crate::xlog_warn!("UMA: XCL_UMA_WINDOWS={val:?} must be 4, 8, or 16 – using {MAX_WINDOWS}"); return MAX_WINDOWS; } - if n > MAX_WINDOWS && !crate::gpu::recomp::pso::heap_windows() { + if n > MAX_WINDOWS && !crate::gpu::recomp::pso::heap_windows_everywhere() { crate::xlog_warn!("UMA: XCL_UMA_WINDOWS={n} requires XCL_HEAP_WINDOWS=1 – using {MAX_WINDOWS}"); return MAX_WINDOWS; } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9692cc4c59..6aeebf557b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -523,6 +523,7 @@ pub fn init() -> Result { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); + crate::gpu::recomp::pso::set_adapter_vendor(desc.VendorId); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } @@ -3778,6 +3779,8 @@ unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *co thread_local! { /// the driver ran out of memory on a pipeline with heap windows (`with_switch_fallback`) static HEAP_WINDOW_OOM: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// the pipeline this thread builds has heap windows (`with_switch_fallback`, first attempt) + static HEAP_WINDOW_BUILD: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// heap-window driver calls still to fail with E_OUTOFMEMORY (`inject_heap_window_oom`) @@ -3797,10 +3800,10 @@ pub fn switch_form_retries() -> u64 { SWITCH_FORM_RETRIES.load(Ordering::Relaxed) } -/// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is -/// noted for `with_switch_fallback`. +/// A driver pipeline call; E_OUTOFMEMORY on a pipeline whose stage was translated with heap +/// windows is noted for `with_switch_fallback`. unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + let heap = HEAP_WINDOW_BUILD.with(|h| h.get()); let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; if hr == E_OUTOFMEMORY && heap { @@ -3809,13 +3812,23 @@ unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *co hr } -/// Build a translated pipeline (`build`: a `translated_*` path); when the driver ran out of -/// memory on it with heap windows, translate it again in the switch form and build that. -/// NVIDIA 616.92 refuses some big programs whose heap index depends on the window with -/// E_OUTOFMEMORY in under a second, and builds the same programs in the switch form (#156). -fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { +/// Build a translated pipeline (`build`: a `translated_*` path) whose stage takes heap windows +/// when `heap` (`pso::compute_mem_windows` for compute, `pso::mem_windows` for graphics and +/// mesh); when the driver ran out of memory on it with heap windows, translate it again in the +/// switch form and build that. Other pipelines are built once: their E_OUTOFMEMORY is not a +/// heap-window refusal. NVIDIA 616.92 refuses some big programs whose heap index depends on the +/// window with E_OUTOFMEMORY in under a second, and builds the same programs in the switch form (#156). +fn with_switch_fallback(heap: bool, mut build: impl FnMut() -> R) -> R { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + HEAP_WINDOW_BUILD.with(|h| h.set(self.0)); + } + } + let _restore = Restore(HEAP_WINDOW_BUILD.with(|h| h.replace(heap))); HEAP_WINDOW_OOM.with(|o| o.set(false)); let r = build(); + HEAP_WINDOW_BUILD.with(|h| h.set(false)); if !HEAP_WINDOW_OOM.with(|o| o.replace(false)) { return r; } @@ -4120,6 +4133,49 @@ fn big_compile_commit_free(need: u64) -> bool { unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need } } +#[cfg(test)] +mod switch_fallback_tests { + use super::*; + + unsafe extern "system" fn out_of_memory(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + E_OUTOFMEMORY + } + + /// builds a pipeline whose driver call fails with E_OUTOFMEMORY: (the result, attempts) + fn refused_build(heap: bool) -> (HRESULT, u32) { + let mut attempts = 0; + let hr = with_switch_fallback(heap, || { + attempts += 1; + let mut out = std::ptr::null_mut(); + unsafe { driver_pso(out_of_memory, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut out) } + }); + (hr, attempts) + } + + #[test] + fn an_out_of_memory_without_heap_windows_is_not_retried() { + // a graphics pipeline in the switch form while compute takes heap windows (NVIDIA's default) + assert_eq!(refused_build(false), (E_OUTOFMEMORY, 1)); + assert!(!HEAP_WINDOW_OOM.with(|o| o.get())); + } + + #[test] + fn an_out_of_memory_with_heap_windows_is_built_again_once() { + assert_eq!(refused_build(true), (E_OUTOFMEMORY, 2)); + // the switch-form attempt is not a heap-window build, and nothing stays noted + assert!(!HEAP_WINDOW_BUILD.with(|h| h.get())); + assert!(!HEAP_WINDOW_OOM.with(|o| o.get())); + } + + #[test] + fn a_driver_call_outside_a_translated_build_is_not_a_heap_window_build() { + let mut out = std::ptr::null_mut(); + let hr = unsafe { driver_pso(out_of_memory, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut out) }; + assert_eq!(hr, E_OUTOFMEMORY); + assert!(!HEAP_WINDOW_OOM.with(|o| o.get())); + } +} + #[cfg(test)] mod big_compile_tests { use super::*; @@ -4310,7 +4366,8 @@ mod big_compile_tests { } unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { - with_switch_fallback(|| translated_compute_pso_once(this, f, desc, riid, ppv)) + let heap = crate::gpu::recomp::pso::compute_mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + with_switch_fallback(heap, || translated_compute_pso_once(this, f, desc, riid, ppv)) } unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { @@ -5204,7 +5261,8 @@ fn create_graphics_pso_cached( } unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) + let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + with_switch_fallback(heap, || translated_graphics_pso_once(this, f, desc, riid, ppv)) } unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { @@ -6196,7 +6254,8 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_mesh_stream_once(this, desc, riid, ppv)) + let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; + with_switch_fallback(heap, || translated_mesh_stream_once(this, desc, riid, ppv)) } unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 7ef11a638e..c0cf68ac9a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -914,7 +914,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; - let runtime_windows = || runtime_windows(opts.windows); + let runtime_windows = || { + note_adapter_vendor("auto"); + runtime_windows(opts.windows) + }; let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -957,7 +960,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { dir, opts.min_kb, opts.count, - runtime_windows(), + recomp::pso::hlsl_windows(runtime_windows().0), opts.split, opts.record_hash, ); @@ -967,16 +970,16 @@ pub fn run(path: &Path, args: &[String]) -> i32 { &input, hash, opts.repeat.max(1), - runtime_windows(), + recomp::pso::hlsl_windows(runtime_windows().0), opts.split, ); } if opts.precompile { // `--used-only`: only the compute programs whose pipelines an earlier run of a title used let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); - // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) - let windows = runtime_windows(); - return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { + // the runtime's key (`pso::compute_mem_windows`) + let (windows, graphics_windows) = runtime_windows(); + return match precompile(&input, opts.limit, windows, graphics_windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { Ok(()) => 0, Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; @@ -989,10 +992,24 @@ pub fn run(path: &Path, args: &[String]) -> i32 { print(path, &what, agg, top, json, t0, compile) } -/// The runtime's memory windows (`pso::windows_for`, which `pso::mem_windows` takes too), as -/// `--precompile`, `--export-hlsl` and `--measure-pso` key and translate the programs. -fn runtime_windows(windows: u32) -> u32 { - recomp::pso::windows_for(windows) +/// The vendor of the adapter `configured` selects as `real::init` picks it (the first match, or +/// the first of all when none matches), which sets the runtime's default windows +/// (`pso::heap_windows`). +fn note_adapter_vendor(configured: &str) { + use crate::gpu::adapter::{vendor, Selector}; + let sel = Selector::from_env_or(configured); + let v = if sel == Selector::Warp { None } else { vendor(&sel).or_else(|| vendor(&Selector::Auto)) }; + if let Some(v) = v { + recomp::pso::set_adapter_vendor(v); + } +} + +/// The memory windows of the runtime, as `--precompile`, `--export-hlsl` and `--measure-pso` key +/// and translate the programs: (compute programs, `pso::compute_windows` as +/// `pso::compute_mem_windows`; VS, PS and mesh programs, `pso::graphics_windows` as +/// `pso::mem_windows`). By default on NVIDIA only the first are from the descriptor heap. +fn runtime_windows(windows: u32) -> (u32, u32) { + (recomp::pso::compute_windows(windows), recomp::pso::graphics_windows(windows)) } #[cfg(test)] @@ -1644,16 +1661,23 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R if !files.is_empty() { inputs.push(Input::Files(files)); } } progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); - let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; - if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } + let (windows, graphics_windows) = launch_windows(&progress.adapter, crate::gpu::uma::configured_runtime_windows() as u32); for input in inputs { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - precompile(&input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; + precompile(&input, usize::MAX, windows, graphics_windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; } Ok(()) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { +/// The startup preparation's keys, as the title will make them (`runtime_windows`): the vendor of +/// the title's adapter sets the default windows (`pso::heap_windows`), and the preparation runs +/// before `real::init` notes it. +fn launch_windows(adapter: &str, windows: u32) -> (u32, u32) { + note_adapter_vendor(adapter); + runtime_windows(windows) +} + +fn precompile(input: &Input, limit: usize, windows: u32, graphics_windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; @@ -1763,10 +1787,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }; for p in &f.programs { let code = &f.data[p.offset..p.offset + p.len]; - // as `pso` translates: with the title's memory windows (`console_translation`, - // `translate_mesh`) + // as `pso` translates: with the title's memory windows for these stages + // (`mem_windows`: `console_translation`, `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: graphics_windows, ..Default::default() }; let t = match recomp::translate(code, &opt) { Ok(t) if t.complete() => t, Ok(_) => { @@ -2170,28 +2194,80 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { - /// `--precompile` keys its programs with the runtime's windows: with `XCL_HEAP_WINDOWS=1 - /// XCL_HEAP_FLAT=1` they carry `HEAP_FLAT`, as `pso::mem_windows` does. The switches are - /// read once (`OnceLock`), so each setting runs in a new process. + /// `--precompile` keys its programs with the runtime's windows, per stage: compute programs + /// as `pso::compute_mem_windows`, VS, PS and mesh programs as `pso::mem_windows`. With + /// `XCL_HEAP_WINDOWS=1 XCL_HEAP_FLAT=1` both carry `HEAP_FLAT`; by default on NVIDIA only the + /// compute programs take heap windows. The switches are read once (`OnceLock`), so each + /// setting runs in a new process. #[test] fn precompile_windows_are_the_runtimes() { use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS}; const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS"; - if let Ok(want) = std::env::var(RUN) { - assert_eq!(super::runtime_windows(4), pso::windows_for(4)); - assert_eq!(super::runtime_windows(4), want.parse::().unwrap()); + if let Ok(case) = std::env::var(RUN) { + let n: Vec = case.split(':').map(|v| v.parse().unwrap()).collect(); + pso::set_adapter_vendor(n[0]); + assert_eq!(super::runtime_windows(4), (n[1], n[2]), "(compute, VS / PS / mesh)"); + return; + } + let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; + // (XCL_HEAP_WINDOWS, XCL_HEAP_FLAT, adapter vendor, compute windows, VS / PS / mesh windows) + for (heap, flat_env, vendor, compute, graphics) in [ + (Some("1"), Some("1"), 0x10DE, flat, flat), + (Some("1"), Some("0"), 0x10DE, 4 | HEAP_WINDOWS, 4 | HEAP_WINDOWS), + (None, None, 0x10DE, flat, 4), + (None, None, 0x1002, 4, 4), + ] { + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) + .env(RUN, format!("{vendor}:{compute}:{graphics}")) + .env_remove("XCL_HEAP_WINDOWS") + .env_remove("XCL_HEAP_FLAT"); + if let Some(v) = heap { + cmd.env("XCL_HEAP_WINDOWS", v); + } + if let Some(v) = flat_env { + cmd.env("XCL_HEAP_FLAT", v); + } + let out = cmd.output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), + "XCL_HEAP_WINDOWS={heap:?} XCL_HEAP_FLAT={flat_env:?} vendor {vendor:#x}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + } + } + + /// The startup preparation (`prepare_for_launch`) keys its programs as the title will, with + /// the vendor of the title's adapter, which `real::init` has not noted yet when it runs: on + /// NVIDIA with `XCL_HEAP_WINDOWS` unset its compute programs carry the heap windows too, and + /// with `=1` every stage carries `HEAP_FLAT`. Each setting runs in a new process. + #[test] + fn launch_windows_are_the_titles() { + use crate::gpu::adapter::{vendor, Selector}; + use crate::gpu::recomp::pso; + const RUN: &str = "XCL_TEST_LAUNCH_WINDOWS"; + if std::env::var_os(RUN).is_some() { + let got = super::launch_windows("auto", 4); + let Some(v) = vendor(&Selector::from_env_or("auto")) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + // as the title keys them once `real::init` has noted its adapter + pso::set_adapter_vendor(v); + assert_eq!(got, super::runtime_windows(4), "(compute, VS / PS / mesh), vendor {v:#x}"); return; } - for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] { - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) - .env(RUN, want.to_string()) - .env("XCL_HEAP_WINDOWS", "1") - .env("XCL_HEAP_FLAT", flat) - .output() - .unwrap(); + for heap in [None, Some("1")] { + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", "shaders::tests::launch_windows_are_the_titles", "--nocapture"]) + .env(RUN, "1") + .env_remove("XCL_HEAP_WINDOWS") + .env_remove("XCL_HEAP_FLAT"); + if let Some(v) = heap { + cmd.env("XCL_HEAP_WINDOWS", v); + } + let out = cmd.output().unwrap(); let stdout = String::from_utf8_lossy(&out.stdout); - assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success() && stdout.contains("1 passed"), + "XCL_HEAP_WINDOWS={heap:?}: {stdout} +{}", String::from_utf8_lossy(&out.stderr)); } } diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5ffa519a96..08bfc1970a 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -430,8 +430,8 @@ fn heap_window_out_of_memory_falls_back_to_the_switch_form() { } let raw = real::device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); - if xcl::gpu::recomp::pso::mem_windows() & xcl::gpu::recomp::HEAP_WINDOWS == 0 { - println!("no heap windows (opt-in: XCL_HEAP_WINDOWS=1; or no shared heap) – skipping"); + if xcl::gpu::recomp::pso::compute_mem_windows() & xcl::gpu::recomp::HEAP_WINDOWS == 0 { + println!("no heap windows (default on NVIDIA, else XCL_HEAP_WINDOWS=1; or no shared heap) – skipping"); runner::skip_test("no heap windows"); return; }