From 328cf2963183235085efa4fab0bd0ced779a9293 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:55:23 -0300 Subject: [PATCH] DXC: compute programs are linked with their memory accessors With several memory windows every access is a switch between them. DXC inlines the accessors before it optimises, so a program gets one switch per access and its time grows much faster than their number. Compute programs with 100 accesses or more are now compiled with the accessors only declared and linked with them afterwards (IDxcLinker inlines them): 1600 accesses 36 s -> 4.4 s, the same DXIL size and GPU time. The generated HLSL is unchanged. XCL_LINK_MEM=0 turns it off; a program that cannot be linked is compiled whole. --- crates/xcl/src/gpu/recomp/dxc.rs | 134 ++++++++++++++++--- crates/xcl/src/gpu/recomp/emit.rs | 62 +++++++-- crates/xcl/src/gpu/recomp/tests.rs | 199 +++++++++++++++++++++++++++++ 3 files changed, 368 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 0840dceb7..e402986dc 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -13,7 +13,9 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; -use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8}; +use windows::Win32::Graphics::Direct3D::Dxc::{ + CLSID_DxcCompiler, CLSID_DxcLinker, CLSID_DxcUtils, DxcBuffer, IDxcBlob, IDxcBlobEncoding, IDxcCompiler3, IDxcLinker, IDxcResult, IDxcUtils, DXC_CP, DXC_CP_UTF8, +}; type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; @@ -210,6 +212,92 @@ pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result< } fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + // compute (also what MS and GS programs run as): DXC's time for its memory accesses is + // linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before. + if profile.starts_with("cs_") && linking() { + if let Some((program, library)) = super::emit::linked_form(src, LINK_MIN_ACCESSES) { + match compile_linked(&program, &library, entry, profile, extra) { + Ok(dxil) => return Ok(dxil), + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole: {e}")); + } + } + } + } + compile_whole(src, entry, profile, extra) +} + +/// Accesses a program needs to be linked with its accessors: with 100 both ways take DXC 0.3 s. +const LINK_MIN_ACCESSES: usize = 100; + +/// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with +/// another `XCL_DXIL_CACHE`). +fn linking() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LINK_MEM").map_or(true, |v| v != "0")) +} + +/// Compile `program` and `library` (its memory accessors, kept once compiled) as libraries and +/// link them to `profile`. +fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + let model = profile.split_once('_').map_or("6_6", |(_, m)| m); + let lib = format!("lib_{model}"); + let accessors = { + static KEPT: Mutex>>>> = Mutex::new(None); + let key = format!("{lib} {extra:?}\n{library}"); + let kept = KEPT.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned(); + match kept { + Some(a) => a, + None => { + let a = Arc::new(compile_whole(library, "", &lib, extra)?); + KEPT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, a.clone()); + a + } + } + }; + let program = compile_whole(program, "", &lib, extra)?; + let instance = |clsid: &GUID, iid: &GUID| -> Result<*mut c_void, String> { + let mut p = std::ptr::null_mut(); + let hr = unsafe { create_fn()?(clsid, iid, &mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("DxcCreateInstance: {hr:?}")); + } + Ok(p) + }; + unsafe { + let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?); + let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?); + let names = [crate::util::wide("program"), crate::util::wide("accessors")]; + for (name, dxil) in names.iter().zip([&program, &*accessors]) { + let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; + linker.RegisterLibrary(PCWSTR(name.as_ptr()), &blob).map_err(|e| format!("RegisterLibrary: {e}"))?; + } + let (entry, profile) = (crate::util::wide(entry), crate::util::wide(profile)); + let r = linker + .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), None) + .map_err(|e| format!("Link: {e}"))?; + output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) + } +} + +/// The bytes of a finished DXC operation, or its messages. +unsafe fn output(status: windows::core::Result, errors: windows::core::Result, result: windows::core::Result) -> Result, String> { + if status.map_err(|e| format!("{e}"))?.is_err() { + let msg = errors + .ok() + .map(|b| { + let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()); + String::from_utf8_lossy(s).trim_end_matches('\0').to_string() + }) + .unwrap_or_default(); + return Err(format!("dxc: {msg}")); + } + let blob = result.map_err(|e| format!("{e}"))?; + Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()) +} + +fn compile_whole(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let c = compiler()?; let mut args: Vec> = ["-E", entry, "-T", profile, "-HV", "2021"].iter().map(|a| crate::util::wide(a)).collect(); // DXC's optimiser was superlinear on translated programs full of short-circuit `?:` / @@ -231,20 +319,7 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result let buf = DxcBuffer { Ptr: src.as_ptr() as *const c_void, Size: src.len(), Encoding: DXC_CP_UTF8.0 }; unsafe { let r: IDxcResult = c.Compile(&buf, Some(&ptrs), None).map_err(|e| format!("Compile: {e}"))?; - let status = r.GetStatus().map_err(|e| format!("{e}"))?; - if status.is_err() { - let msg = r - .GetErrorBuffer() - .ok() - .map(|b| { - let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()); - String::from_utf8_lossy(s).trim_end_matches('\0').to_string() - }) - .unwrap_or_default(); - return Err(format!("dxc: {msg}")); - } - let blob: IDxcBlob = r.GetResult().map_err(|e| format!("{e}"))?; - Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()) + output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) } } @@ -981,3 +1056,32 @@ mod cache_tests { }); } } + +/// `src` compiled whole and linked with its memory accessors, whatever their number, with the +/// seconds each took. +#[cfg(test)] +pub(super) fn both_forms(src: &str, profile: &str) -> Result<[(Vec, f64); 2], String> { + std::thread::scope(|s| { + let t = std::thread::Builder::new().stack_size(DXC_STACK).spawn_scoped(s, || { + let (program, library) = super::emit::linked_form(src, 0).ok_or("no linked form")?; + let t0 = std::time::Instant::now(); + let linked = compile_linked(&program, &library, "main", profile, &[])?; + let linked = (linked, t0.elapsed().as_secs_f64()); + let t0 = std::time::Instant::now(); + let whole = compile_whole(src, "main", profile, &[])?; + Ok([(whole, t0.elapsed().as_secs_f64()), linked]) + }); + t.map_err(|e| e.to_string())?.join().map_err(|_| "DXC: panic".to_string())? + }) +} + +/// The disassembly of a DXIL container. +#[cfg(test)] +pub(super) fn disassemble(dxil: &[u8]) -> Result { + let c = compiler()?; + let buf = DxcBuffer { Ptr: dxil.as_ptr() as *const c_void, Size: dxil.len(), Encoding: 0 }; + unsafe { + let r: IDxcResult = c.Disassemble(&buf).map_err(|e| format!("Disassemble: {e}"))?; + output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()).map(|b| String::from_utf8_lossy(&b).into_owned()) + } +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 605126f4e..b367821ca 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4828,8 +4828,8 @@ fn windowed(h: &str, windows: u32) -> String { out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1) } -/// The accessor functions: one per `mem` method (and overload) the translator emits. -fn mem_accessors(windows: u32) -> String { +/// The `mem` methods (and overloads) the translator emits: result, name, parameters, arguments. +fn mem_methods() -> Vec<(&'static str, String, &'static str, &'static str)> { let mut sigs: Vec<(&str, String, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a"), ("uint2", "Load2".into(), "uint a", "a"), @@ -4853,23 +4853,61 @@ fn mem_accessors(windows: u32) -> String { sigs.push(("void", format!("Interlocked{op}64"), "uint a, int64_t v, out int64_t o", "a, v, o")); } } - let mut s = String::new(); - let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); + sigs +} + +/// The body of an accessor: the switch on the window `w` (`xcl_loadx4`, a `mem` method). +fn loadx4_switch(windows: u32, w: &str) -> String { + let mut s = format!("[branch] switch ({w}) {{ "); for k in 1..windows { let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); } - let _ = writeln!(s, "default: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }} }}"); - for (ret, name, params, args) in sigs { - let r = if ret == "void" { "" } else { "return " }; - let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ "); - for k in 1..windows { - let _ = write!(s, "case {k}u: {r}mem{k}.{name}({args}); break; "); - } - let _ = writeln!(s, "default: {r}mem.{name}({args}); break; }} }}"); + s.push_str("default: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }"); + s +} + +fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str) -> String { + let r = if ret == "void" { "" } else { "return " }; + let mut s = format!("[branch] switch ({w}) {{ "); + for k in 1..windows { + let _ = write!(s, "case {k}u: {r}mem{k}.{name}({args}); break; "); + } + let _ = write!(s, "default: {r}mem.{name}({args}); break; }}"); + s +} + +/// The accessor functions: one per `mem` method. +fn mem_accessors(windows: u32) -> String { + let mut s = format!("uint4 xcl_loadx4(uint4 a) {{ {} }}\n", loadx4_switch(windows, "xcl_w")); + for (ret, name, params, args) in mem_methods() { + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ {} }}", method_switch(windows, "xcl_w", ret, &name, args)); } s } +/// A translated program with several memory windows as two libraries for DXC's linker: the +/// program, whose accessors are only declared, and the accessors. DXC inlines a function when +/// it compiles the program, before it optimises: a switch per access, and its time grows with +/// the square of them. The linker inlines the declared ones afterwards. None: no windows, or +/// fewer than `min_accesses` places that use them (DXC is fast enough then). +pub(super) fn linked_form(hlsl: &str, min_accesses: usize) -> Option<(String, String)> { + let (windows, inline) = (2..=4).map(|w| (w, mem_accessors(w))).find(|(_, a)| hlsl.contains(a.as_str()))?; + let (head, rest) = hlsl.split_once(inline.as_str())?; + if rest.matches("xcl_m").count() + rest.matches("xcl_loadx4(").count() < min_accesses || rest.matches("[numthreads(").count() != 1 { + return None; + } + let mut declared = String::from("uint4 xcl_l_loadx4(uint w, uint4 a);\nuint4 xcl_loadx4(uint4 a) { return xcl_l_loadx4(xcl_w, a); }\n"); + let mut library: String = head.lines().filter(|l| l.contains("RWByteAddressBuffer mem")).map(|l| format!("{l}\n")).collect(); + let _ = writeln!(library, "export uint4 xcl_l_loadx4(uint w, uint4 a) {{ {} }}", loadx4_switch(windows, "w")); + for (ret, name, params, args) in mem_methods() { + let r = if ret == "void" { "" } else { "return " }; + let _ = writeln!(declared, "{ret} xcl_l_{name}(uint w, {params});\n{ret} xcl_m{name}({params}) {{ {r}xcl_l_{name}(xcl_w, {args}); }}"); + let _ = writeln!(library, "export {ret} xcl_l_{name}(uint w, {params}) {{ {} }}", method_switch(windows, "w", ret, &name, args)); + } + let program = format!("{head}{declared}{}", rest.replacen("[numthreads(", "[shader(\"compute\")]\n[numthreads(", 1)); + Some((program, library)) +} + /// Sub-dword d16 forms: (bytes, sign-extend, store, half: 0 low / 1 high) by the name after /// the `buffer_` / `flat_` / `global_` prefix. fn d16_small(op: &str) -> Option<(u32, bool, bool, u32)> { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 01cff4362..13a2ac7a0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6652,3 +6652,202 @@ fn fspx_containers_translate_and_compile() { println!("FSPX: {ok} / {n} translated and compiled"); assert_eq!(ok, n); } + +/// A program linked with its memory accessors (`emit::linked_form`) does what it does compiled +/// whole: loads and stores of 1..4 dwords, scalar loads, 32- and 64-bit atomics, in two windows, +/// the lanes of a wave in different ones. +#[test] +fn gpu_linked_memory_accessors() { + if !gpu_ready() { + return; + } + type Ins = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let smem = |n: &'static str, data: u64, base: u64, off: u64| -> Ins { (n, "ENC_SMEM", vec![("SDATA", data), ("SBASE", base), ("OFFSET", off), ("SOFFSET", 125)], None) }; + let mubuf = |n: &'static str, data: u64, srsrc: u64, off: u64| -> Ins { (n, "ENC_MUBUF", vec![("VDATA", data), ("VADDR", 0), ("SRSRC", srsrc), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", off)], None) }; + let glbl = |n: &'static str, f: Vec<(&'static str, u64)>| -> Ins { (n, "ENC_FLAT_GLBL", f, None) }; + let atomic = |n: &'static str, dst: u64, data: u64, off: u64| -> Ins { (n, "ENC_FLAT_GLBL", vec![("VDST", dst), ("ADDR", 26), ("DATA", data), ("SADDR", 0x7D), ("OFFSET", off), ("GLC", 1)], None) }; + // s[8:11] / s[12:15]: V#s in windows 1 and 0, stride 16; s[2:3]: an address in window 1; + // v[4:5] / v[6:7] / v[26:27]: addresses per lane, odd lanes in window 1 + let list = vec![ + smem("S_LOAD_DWORD", 20, 1, 4), + smem("S_LOAD_DWORDX2", 22, 1, 8), + smem("S_LOAD_DWORDX8", 24, 1, 16), + smem("S_BUFFER_LOAD_DWORD", 32, 8, 4), + smem("S_BUFFER_LOAD_DWORDX8", 36, 8, 16), + mubuf("BUFFER_LOAD_DWORD", 10, 2, 0), + mubuf("BUFFER_LOAD_DWORDX2", 11, 2, 4), + mubuf("BUFFER_LOAD_DWORDX3", 13, 2, 0), + mubuf("BUFFER_LOAD_DWORDX4", 16, 2, 0), + mubuf("BUFFER_STORE_DWORD", 10, 3, 0), + mubuf("BUFFER_STORE_DWORDX2", 11, 3, 4), + mubuf("BUFFER_STORE_DWORDX3", 13, 3, 1024), + mubuf("BUFFER_STORE_DWORDX4", 16, 3, 2048), + glbl("GLOBAL_LOAD_DWORD", vec![("VDST", 20), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), + glbl("GLOBAL_STORE_DWORD", vec![("ADDR", 6), ("DATA", 20), ("SADDR", 0x7D), ("OFFSET", 0)]), + atomic("GLOBAL_ATOMIC_ADD", 21, 0, 0), + atomic("GLOBAL_ATOMIC_SMIN", 22, 2, 4), + atomic("GLOBAL_ATOMIC_CMPSWAP", 23, 2, 8), + atomic("GLOBAL_ATOMIC_ADD_X2", 24, 2, 16), + ]; + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let t = translate(&prog(&refs), &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let [(whole, _), (linked, _)] = super::dxc::both_forms(&t.hlsl, "cs_6_6").unwrap_or_else(|e| panic!("{e}")); + assert!(whole != linked); + let run = |dxil: &[u8]| { + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + for (w, seed) in [(w0, 1u32), (w1, 2)] { + for k in 0..0x4000u64 { + unsafe { *((w + 4 * k) as *mut u32) = (k as u32).wrapping_mul(0x9E37_79B1).wrapping_add(seed) }; + } + } + let hi = |a: u64| (a >> 32) as u32; + let mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]); + st.sgpr[8..12].copy_from_slice(&[(w1 + 0x2000) as u32, hi(w1) & 0xFFFF | 16 << 16, 64, 0]); + st.sgpr[12..16].copy_from_slice(&[(w0 + 0x4000) as u32, hi(w0) & 0xFFFF | 16 << 16, 4096, 0]); + st.sgpr[16..20].copy_from_slice(&[(w1 + 0x3000) as u32, hi(w1) & 0xFFFF, 256, 0]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let w = if l % 2 == 1 { w1 } else { w0 }; + let l = l as u64; + r[0] = l as u32; + r[2] = 7 * l as u32; + r[3] = 3 + l as u32; + for (v, at) in [(4, 0x9000 + 4 * l), (6, 0xA000 + 4 * l), (26, 0xB000 + 32 * l)] { + r[v] = (w + at) as u32; + r[v + 1] = hi(w); + } + } + let r = runner::run_in_arena(dxil, &st, &arena).unwrap(); + let mem: Vec = [w0, w1].iter().flat_map(|&w| (0..0x4000u64).map(move |k| unsafe { *((w + 4 * k) as *const u32) })).collect(); + // what ran: results against the memory's own contents + let word = |seed: u32, at: u64| ((at / 4) as u32).wrapping_mul(0x9E37_79B1).wrapping_add(seed); + assert_eq!(r.sgpr[20], word(2, 0x1004), "s_load from window 1"); + assert_eq!(r.sgpr[24..32], (0..8).map(|k| word(2, 0x1010 + 4 * k)).collect::>(), "s_load_dwordx8"); + assert_eq!(r.sgpr[36..44], (0..8).map(|k| word(2, 0x3010 + 4 * k)).collect::>(), "s_buffer_load_dwordx8"); + for l in 0..64usize { + let at = 0x2000 + 16 * l as u64; + assert_eq!(r.vgpr[l][16..20], (0..4).map(|k| word(2, at + 4 * k)).collect::>(), "lane {l}: buffer_load_dwordx4"); + assert_eq!(r.vgpr[l][20], word(1 + (l % 2) as u32, 0x9000 + 4 * l as u64), "lane {l}: global_load from its own window"); + } + let regs: Vec = r.vgpr.iter().flat_map(|v| v[..32].to_vec()).chain(r.sgpr[20..48].iter().copied()).collect(); + (regs, mem) + }; + let (a, b) = (run(&linked), run(&whole)); + // v4..v7, v26 and v27 hold addresses of each run's own arena + let own = |i: usize| i < 64 * 32 && matches!(i % 32, 4..=7 | 26..=27); + let differ: Vec = (0..a.0.len()).filter(|&i| !own(i) && a.0[i] != b.0[i]).collect(); + assert!(differ.is_empty(), "registers differ: {differ:?}"); + assert!(a.1 == b.1, "memory differs at dword {:?}", (0..a.1.len()).find(|&i| a.1[i] != b.1[i])); +} + +/// The cost of the memory windows: DXC, the driver's pipeline and a dispatch for programs of +/// 100 / 400 / 1 600 memory accesses with one window, and with four compiled whole and linked. +/// Ignored: minutes. +#[test] +#[ignore] +fn bench_memory_window_accessors() { + use super::CsInterface; + if !gpu_ready() { + return; + } + println!("GPU: {}", runner::adapter().unwrap()); + // a different program every time: the driver must not answer from its cache + let mut nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u32 | 1; + let program = |n: u64, nonce: u32| { + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![]; + for i in 0..n { + let (a, b) = (1 + i % 24, 1 + (i + 1) % 24); + match i % 4 { + 0 => list.push(("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24 + 4 * (i % 8)), ("SBASE", 8), ("OFFSET", 16 * i), ("SOFFSET", 125)], None)), + 1 => list.push(("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", a), ("VADDR", b), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 4 * (i % 512))], None)), + _ => list.push(("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", b), ("VADDR", a), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 4 * (i % 512))], None)), + } + list.push(("V_XOR_B32", "ENC_VOP2", vec![("VDST", b), ("SRC0", 24 + 4 * (i % 8)), ("VSRC1", b)], None)); + } + list.push(("V_XOR_B32", "ENC_VOP2", vec![("VDST", 1), ("SRC0", 255), ("VSRC1", 1)], Some(nonce))); + list.push(("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", 1), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + prog(&refs) + }; + // loads stay in range: V#s over the memory, small values in it + let mem: Vec = (0..1u32 << 18).map(|k| k & 0xFF).collect(); + let mut sgprs = vec![0u32; 24]; + for (at, base) in [(8usize, 0u32), (12, 0x8_0000), (16, 0)] { + sgprs[at..at + 4].copy_from_slice(&[base, 4 << 16, 0x1_0000, 0]); + } + for n in [100u64, 400, 1600] { + for round in 0..3 { + for windows in [1, 4] { + nonce = nonce.wrapping_mul(0x9E37_79B1) | 1; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let t = translate(&program(n, nonce), &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, mem_windows: windows, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let forms = if windows == 1 { + let t0 = std::time::Instant::now(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + vec![("1 window", dxil, t0.elapsed().as_secs_f64())] + } else { + let [(whole, w), (linked, l)] = super::dxc::both_forms(&t.hlsl, "cs_6_6").unwrap_or_else(|e| panic!("{e}")); + vec![("4, whole", whole, w), ("4, linked", linked, l)] + }; + for (name, dxil, dxc) in forms { + let t0 = std::time::Instant::now(); + runner::dispatch_timed(&dxil, [1, 1, 1], &sgprs, &mem, 1).unwrap(); + let pipeline = t0.elapsed().as_secs_f64(); + let mut times = runner::dispatch_timed(&dxil, [2048, 1, 1], &sgprs, &mem, 9).unwrap(); + times.sort_by(|a, b| a.total_cmp(b)); + println!( + "{n:5} accesses, round {round}, {name:9}: DXC {dxc:6.2} s, DXIL {:4} KB, pipeline {pipeline:5.2} s, 2048 groups: median {:.3} min {:.3}", + dxil.len() >> 10, + times[times.len() / 2], + times[0] + ); + } + } + } + } +} + +/// What a linked program declares stays: its wave size, thread count, the windows' registers, +/// and no accessor is left a function (a driver may not inline those: 5x slower on NVIDIA). +#[test] +fn linked_programs_keep_their_declarations() { + if super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let buf = |n: &'static str, srsrc: u64| (n, "ENC_MUBUF", vec![("VDATA", 1u64), ("VADDR", 0), ("SRSRC", srsrc), ("SOFFSET", 128), ("IDXEN", 1)], None); + let list = [buf("BUFFER_LOAD_DWORD", 2), buf("BUFFER_STORE_DWORD", 3)]; + 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); + for wave64 in [false, true] { + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64, mem_windows: 4, ..Default::default() }).unwrap(); + let size = if wave64 { 64 } else { 32 }; + assert!(t.hlsl.contains(&format!("[WaveSize({size})]")), "{}", t.hlsl); + let [whole, linked] = super::dxc::both_forms(&t.hlsl, "cs_6_6").unwrap_or_else(|e| panic!("{e}")).map(|(d, _)| super::dxc::disassemble(&d).unwrap()); + let declared = |text: &str| -> Vec { + let lines = text.lines().filter(|l| l.contains("WaveSize") || l.contains("NumThreads") || l.contains("byte") && l.contains("UAV")); + let mut v: Vec = lines.map(|l| l.split_whitespace().collect::>().join(" ")).collect(); + v.sort(); + v + }; + // how each buffer is accessed (globallycoherent is one of these bits) + let properties = |text: &str| -> std::collections::BTreeSet { + text.split("ResourceProperties { ").skip(1).filter_map(|r| r.split_once(" }")).map(|(r, _)| r.to_string()).collect() + }; + assert!(t.hlsl.contains("globallycoherent RWByteAddressBuffer mem1")); + assert_eq!(properties(&whole), properties(&linked)); + // the resources' ids may be numbered in another order + let registers = |text: &str| (2..6).map(|k| declared(text).iter().any(|l| l.contains(&format!(" u{k} ")))).collect::>(); + assert_eq!(registers(&whole), [true; 4], "{whole}"); + assert_eq!(registers(&linked), [true; 4], "{linked}"); + for text in [&whole, &linked] { + assert!(text.contains("NumThreads=(8,4,2)"), "{text}"); + assert!(text.contains(&format!("WaveSize={size}")) || text.contains(&format!("{{i32 {size}}}")), "{text}"); + } + assert_eq!(whole.matches("define ").count(), linked.matches("define ").count(), "{linked}"); + } +}