diff --git a/Cargo.lock b/Cargo.lock index 324bc0bdf4..cb2a50ac1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -560,6 +560,7 @@ dependencies = [ "serde_json", "toml", "windows", + "windows-core", "windows-sys 0.61.2", ] diff --git a/README.md b/README.md index 321cc03a9e..973a027e86 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | | **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | -| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | +| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders, with misses for nodes outside mapped memory windows | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | Far-jump address calculations are resolved to fixed targets only when branches enter at the start of the calculation. @@ -229,9 +229,30 @@ xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driv xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` +Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. Add +`-Pipelines` to warm the GPU driver's compute-pipeline cache too (slower and GPU/driver-specific): + +```powershell +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' +.\scripts\precompile-shaders.ps1 -Package 'D:\data\shaders.rpf' -Pipelines +``` +
Switches, caches, logs and the files XCL writes +- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under + `shaders/`, XCL shows shader preparation in the game window before executing title code. + The same window then presents the game. The percentage counts + processed records. The timer counts seconds since one finished (or preparation started); + five seconds without progress counts as a stall, and the window shows when the last one ended. + XCL prepares supported shader stages and compute pipelines, including + split pieces and their whole fallback. Graphics pipelines are created during play the first + time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside + the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts + on the next launch, with their driver blobs kept, so the title makes them from those in + milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + Closing the window cancels the launch. A compiler or driver failure stops it and reports + the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - For compute shaders that XCL can split, the runtime first tries the saved driver blob for the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing or the driver rejects it, XCL builds the split pieces. @@ -267,7 +288,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the target gets its own piece, up to four times the target. Larger components and indirect - dispatches use the whole pipeline. + dispatches use the whole pipeline. A chained dispatch runs in slabs of groups that share one + scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording + share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet + reset hold together (past it a dispatch runs in smaller slabs). - Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so @@ -280,6 +304,13 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. +- A loop in a translated compute program run by a Dispatch (not ExecuteIndirect) is ended + after its dispatch's share of passes for each entry (between 1024 and 65 536 a thread, fewer the + more threads the dispatch has; the direct DXIL translator ends the thread's program there), so + one that runs away does not hold the GPU past the time Windows gives it. The direct + translator's compact form (programs of 20 000 instructions and more) and `XCL_PER_LANE` keep + only the thread's 65 536 passes in all. `XCL_DISPATCH_LOOP_BUDGET=0` leaves every loop the + thread's 65 536 passes, as before (to compare). - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated @@ -288,6 +319,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. +- The queue's page mappings (`CopyPageMappingsBatchX`: a title maps the pages its texture streaming + fills into its GPU views) are applied: a GPU-view page shows the physical page mapped into it. + `XCL_PAGE_MAPPINGS=0` turns them off (the call is ignored and a GPU-view page shows its CPU view at + the same offset, as before). - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), @@ -296,6 +331,17 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder (decoded 8-bit R+G+B > 30). The field is `null` until a frame is sampled; `non_dark_samples` is `null` if its format cannot be decoded. Intermediate render-target dumps do not update it. Sampling uses every fourth pixel in each direction (`XCL_FRAME_DUMP_FULL=1`: every pixel). + `XCL_DUMP_TARGETS=[,]` logs, for the first frames with that many draws and dispatches, + each render target and the depth buffer drawn into (draws ran / stand-in / PC / skipped) and dumps + the eight drawn into most (`target_.bmp`); `XCL_DUMP_AFTER_S=` waits `s` seconds first. + `XCL_CAPTURE_FRAME=[,]` writes the command stream of the first frame with that many draws + and dispatches (`s` seconds after the first present at the earliest) to `capture_/` next to + the log: `frame.jsonl` (every submit, barrier, copy, clear, draw and dispatch in the order the GPU got + them, with render targets and root arguments), `resources.jsonl`, `pipelines.jsonl`, the pipelines' + shaders translated again and `summary.txt`. Every frame is recorded until then, which costs time. + `XCL_GPU_TIMES=[,]` times every draw and dispatch of the next `frames` busy frames (from + `s` seconds after the first present) with GPU timestamps and logs the 60 programs that took the + most GPU time per frame (`D3D12.X: GPU times:` lines); the times are coarse, fine for ranking. A coarse sample can miss detail; a non-dark sample does not establish correct rendering or gameplay. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..238591b113 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -19,6 +19,7 @@ retour = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" +windows-core = "0.62" [dependencies.windows] version = "0.62" @@ -44,6 +45,7 @@ features = [ version = "0.61" features = [ "Win32_Foundation", + "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 22a7b89748..eda37ff09d 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -415,6 +415,24 @@ mod tests { } } + /// The Series S profile changes the title memory budget only: unified memory (`uma_mb`, the + /// window plan's size) is the memory mode's, the same as a Series X run's in that mode. + #[test] + fn the_series_s_budget_leaves_unified_memory_as_it_is() { + let manifest = crate::manifest::Manifest { + anaconda_memory: Some("Advanced".into()), + lockhart_memory: Some("Advanced".into()), + ..Default::default() + }; + let resolved = |device: &str| { + let mut c = Config { device_type: device.into(), ..Config::default() }; + c.resolve(Some(&manifest)); + (c.title_memory_mb, c.uma_mb) + }; + assert_eq!(resolved("anaconda"), (13_824, 4095)); + assert_eq!(resolved("lockhart"), (8_192, 4095)); + } + #[test] fn raytracing_tier_parsing() { assert_eq!(parse_raytracing_tier("auto"), None); diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..e02ae7528e 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -109,6 +109,23 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + // what happened lately at the title pages the registers point into + if !ctx.is_null() { + let c = &*ctx; + let mut seen: Vec = Vec::new(); + for (n, v) in [("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { + let p = v as usize; + if p < 0x1_0000 || seen.contains(&(p & !0xFFFF)) { + continue; + } + seen.push(p & !0xFFFF); + let d = crate::hle::kernelx::pagelog::describe(p); + if !d.is_empty() { + crate::xlog_error!("page of {n}={p:#x}: {d}"); + } + } + crate::xlog_error!("page events so far: {}", crate::hle::kernelx::pagelog::counts()); + } crate::report::write_final(Some(msg)); crate::log::flush(); } @@ -178,6 +195,116 @@ pub fn find_gs_check(code: &[u8]) -> Option { None } +/// The CPU has CLZERO (CPUID 8000_0008h, EBX bit 0): AMD's since Zen, no Intel CPU. +pub fn cpu_has_clzero() -> bool { + static HAS: std::sync::OnceLock = std::sync::OnceLock::new(); + *HAS.get_or_init(|| unsafe { + std::arch::x86_64::__cpuid(0x8000_0000).eax >= 0x8000_0008 && std::arch::x86_64::__cpuid(0x8000_0008).ebx & 1 != 0 + }) +} + +/// The code of a CLZERO loop's stand-in for a CPU without CLZERO, entered by a `call` in the +/// loop's place: `[rax & !63 .. )` zeroed in whole lines up to `end_reg`, at least one line, rax +/// and the flags left as the loop's last `add rax, 0x40; cmp rax, ` leaves them. No +/// other register changes. +fn clzero_loop_thunk(end_reg: u8) -> Vec { + let r = end_reg & 15; + let mut c: Vec = vec![0x57, 0x51, 0x50]; // push rdi; push rcx; push rax + c.extend_from_slice(&[0x48 | (r >> 3), 0x8B, 0xC8 | (r & 7)]); // mov rcx, + c.extend_from_slice(&[0x48, 0x89, 0xC7]); // mov rdi, rax + c.extend_from_slice(&[0x48, 0x83, 0xE7, 0xC0]); // and rdi, -64 + c.extend_from_slice(&[0x48, 0x29, 0xC1]); // sub rcx, rax + c.extend_from_slice(&[0x76, 0x0A]); // jbe one + c.extend_from_slice(&[0x48, 0x83, 0xC1, 0x3F]); // add rcx, 63 + c.extend_from_slice(&[0x48, 0xC1, 0xE9, 0x06]); // shr rcx, 6 + c.extend_from_slice(&[0xEB, 0x05]); // jmp go + c.extend_from_slice(&[0xB9, 0x01, 0x00, 0x00, 0x00]); // one: mov ecx, 1 + c.extend_from_slice(&[0x48, 0xC1, 0xE1, 0x06]); // go: shl rcx, 6 + c.extend_from_slice(&[0x48, 0x01, 0x0C, 0x24]); // add [rsp], rcx (the rax to leave) + c.extend_from_slice(&[0x31, 0xC0]); // xor eax, eax + c.extend_from_slice(&[0xF3, 0xAA]); // rep stosb + c.extend_from_slice(&[0x58, 0x59, 0x5F]); // pop rax; pop rcx; pop rdi + c.extend_from_slice(&[0x48 | ((r >> 3) << 2), 0x39, 0xC0 | ((r & 7) << 3)]); // cmp rax, + c.push(0xC3); // ret + c +} + +/// Executable memory a `call rel32` at `site` reaches (64 KiB, committed), made in the first free +/// place above it. None: none within 1 GiB. +unsafe fn code_near(site: usize) -> Option { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + let mut at = (site + 0x1_0000) & !0xFFFF; + while at - site < 0x4000_0000 { + let p = VirtualAlloc(at as *const std::ffi::c_void, 0x1_0000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + if p != 0 { + return Some(p); + } + at += 0x1_0000; + } + None +} + +/// Executable memory `[at, at + len)` of a title image on a CPU without CLZERO: each +/// `clzero; add rax, 0x40; cmp rax, ; jb` loop (`insn::ConsoleOnly::ClzeroLoop`, 12 bytes) +/// becomes a call of a stand-in that zeroes the same lines (`clzero_loop_thunk`). +/// `XCL_CLZERO_PATCH=0` leaves the loops as they are. The patched loops. +/// +/// Left alone, every run of such a loop is an illegal-instruction exception that +/// `emulate_console_only` answers: a retail title's memset is such a loop, and while its world +/// loaded one of its threads was in that exception at every look (thread dumps at 300, 360 and +/// 400 s of several runs on an Intel CPU), with the GPU measured at 0.2 to 0.5 s of work in world +/// frames of 17 to 43 s. +pub unsafe fn patch_clzero_loops(at: usize, len: usize, image: &str) -> usize { + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + if len < 12 || std::env::var("XCL_CLZERO_PATCH").is_ok_and(|v| v.trim() == "0") { + return 0; + } + let code = std::slice::from_raw_parts(at as *const u8, len); + let sites: Vec<(usize, u8)> = (0..len - 11) + .filter(|&i| code[i] == 0x0F && code[i + 1] == 0x01 && code[i + 2] == 0xFC && (i == 0 || code[i - 1] != 0x67)) + .filter_map(|i| match crate::insn::decode(&code[i..i + 12]) { + // (rsp is no end of a loop: the stand-in's pushes move it) + Some((crate::insn::ConsoleOnly::ClzeroLoop { end_reg }, 12)) if end_reg != 4 => Some((i, end_reg)), + _ => None, + }) + .collect(); + if sites.is_empty() { + return 0; + } + let Some(arena) = code_near(at + len) else { + crate::xlog_warn!("{image}: {} CLZERO loops stay emulated (no executable memory near the image)", sites.len()); + return 0; + }; + // one stand-in for each end register + let mut thunks = [0usize; 16]; + let mut next = arena; + let mut done = 0; + for &(i, reg) in &sites { + if thunks[reg as usize] == 0 { + let t = clzero_loop_thunk(reg); + std::ptr::copy_nonoverlapping(t.as_ptr(), next as *mut u8, t.len()); + thunks[reg as usize] = next; + next += (t.len() + 15) & !15; + } + let site = at + i; + let Ok(rel) = i32::try_from(thunks[reg as usize] as i64 - (site as i64 + 5)) else { continue }; + let mut patch = [0xE8u8, 0, 0, 0, 0, 0x0F, 0x1F, 0x80, 0, 0, 0, 0]; // call thunk; nop (7 bytes) + patch[1..5].copy_from_slice(&rel.to_le_bytes()); + let mut old = 0u32; + if VirtualProtect(site as *const std::ffi::c_void, 12, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + continue; + } + std::ptr::copy_nonoverlapping(patch.as_ptr(), site as *mut u8, 12); + VirtualProtect(site as *const std::ffi::c_void, 12, old, &mut old); + done += 1; + } + if done != 0 { + windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const std::ffi::c_void, len); + crate::xlog_info!("{image}: {done} CLZERO loops run as native code on this CPU, which has no CLZERO (XCL_CLZERO_PATCH=0: emulated, one exception a loop)"); + } + done +} + /// Executable memory `[at, at + len)` of a title image: its `__report_gsfailure` (the target of /// `__security_check_cookie`'s failure jump) is redirected to a report that names the /// function whose stack cookie did not match (the return address on the stack), then ends @@ -1046,6 +1173,41 @@ mod tests { assert_eq!(cmp_eflags(0x202, 0x8000_0000_0000_0000, 1), 0x202 | 0x004 | 0x010 | 0x800); } + /// A CLZERO loop patched for a CPU without CLZERO (`patch_clzero_loops`) zeroes the same + /// lines and leaves rax, the flags and every other register as the loop does. + #[test] + fn a_patched_clzero_loop_zeroes_whole_lines_and_keeps_registers() { + unsafe { + // clzero; add rax, 0x40; cmp rax, r10; jb -12; setb cl (the flags, seen); ret + let code = crate::stubs::alloc_code(64); + let bytes = [0x0Fu8, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4, 0x0F, 0x92, 0xC1, 0xC3]; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), code, bytes.len()); + assert_eq!(patch_clzero_loops(code as usize, bytes.len(), "test"), 1); + assert_eq!(*code, 0xE8, "a call in the loop's place"); + let run = |start: usize, end: usize| -> (usize, usize, usize, usize) { + let (rax, rcx, rdi, rdx): (usize, usize, usize, usize); + std::arch::asm!("call {f}", f = in(reg) code, inout("rax") start => rax, in("r10") end, inout("rcx") 0xAA00usize => rcx, inout("rdi") 0x1111usize => rdi, inout("rdx") 0x2222usize => rdx); + (rax, rcx, rdi, rdx) + }; + #[repr(align(64))] + struct Lines([u8; 64 * 6]); + let mut m = Lines([0xEE; 64 * 6]); + let base = m.0.as_mut_ptr() as usize; + // from the middle of line 1 to the middle of line 3: two passes (rax reaches the end + // after the second), the lines 1 and 2 whole + let (rax, rcx, rdi, rdx) = run(base + 64 + 8, base + 64 * 3 + 8); + assert_eq!(rax, base + 64 * 3 + 8); + assert_eq!(rcx, 0xAA00, "rcx is the caller's but for cl: rax is not below the end"); + assert_eq!((rdi, rdx), (0x1111, 0x2222), "no other register changes"); + assert!(m.0[..64].iter().all(|&b| b == 0xEE) && m.0[64..64 * 3].iter().all(|&b| b == 0) && m.0[64 * 3..].iter().all(|&b| b == 0xEE)); + // end at or before the start: one line, as the loop's first pass + m.0.fill(0xEE); + let (rax, _, _, _) = run(base + 64 * 2, base + 64); + assert_eq!(rax, base + 64 * 3); + assert!(m.0[..64 * 2].iter().all(|&b| b == 0xEE) && m.0[64 * 2..64 * 3].iter().all(|&b| b == 0) && m.0[64 * 3..].iter().all(|&b| b == 0xEE)); + } + } + #[test] fn clzero_loop_aligns_updates_flags_and_falls_back_when_end_le_start() { use std::sync::{atomic::AtomicBool, Arc}; diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index a1b0a36c3c..17393bac7e 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -22,8 +22,9 @@ //! 3×4 as in D3D12_RAYTRACING_INSTANCE_DESC; @112..127 zero. //! //! The console builder reports sizes for exactly these node sizes plus 4 bytes of parent -//! pointers per 64 bytes of nodes (`tests/console_dlls_e2e.rs`); where those pointers live is -//! unknown and no shader seen reads them, so they are not written. +//! pointers per 64 bytes of nodes (`tests/console_dlls_e2e.rs`). A title's traversal loop reads +//! the parent of node `n` (when its short stack runs out) at the dword +//! `base + 4·((n >> 3) − (header@52 >> 6 − header@56 >> 2))`; the builder here does not write them. //! //! Top-down build: median split of the leaf box centroids on the longest axis, twice per box //! node (4 children), one triangle / instance per leaf. @@ -120,6 +121,15 @@ pub fn build_top(instances: &[Instance]) -> Bvh { Builder { data: Vec::new(), bounds, leaf_bytes: INSTANCE_BYTES, leaf: &leaf }.finish() } +/// A structure no ray hits: its root a box32 node with no child (a top or bottom level alike). +pub fn empty() -> Bvh { + let mut data = vec![0; HEADER_BYTES + BOX_BYTES]; + let root = (HEADER_BYTES / 8) as u32 | BOX32; + put(&mut data, ROOT_AT, &[root]); + put(&mut data, HEADER_BYTES, &[INVALID; 4]); + Bvh { data, root } +} + fn put(out: &mut [u8], at: usize, words: &[u32]) { for (k, w) in words.iter().enumerate() { out[at + 4 * k..at + 4 * k + 4].copy_from_slice(&w.to_le_bytes()); @@ -419,6 +429,250 @@ impl Bvh { } } +/// The tiles a walk reports what it reached in (`Reach::tiles`): a GPU view's (64 KiB) +pub const WALK_TILE: u64 = 0x1_0000; +/// node offsets and parent pointers further than this from a structure's base are not followed +const WALK_SPAN: u64 = 2 << 30; +/// tiles a walk keeps read (64 MiB): more and they are read again +const WALK_CACHE: usize = 1024; +/// root ids followed into one bottom level (besides its header's) +const WALK_ROOTS: usize = 8; + +/// How far a walk of the title's structures goes: it reads memory the title may be writing. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// nodes of one structure + pub nodes: u64, + /// nodes of a top level and its bottom levels + pub scene_nodes: u64, + /// bytes read in a walk (whole tiles) + pub bytes: u64, + /// distinct bottom levels of a top level + pub bottoms: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { nodes: 4 << 20, scene_nodes: 32 << 20, bytes: 2 << 30, bottoms: 1 << 16 } + } +} + +/// What a traversal can read of one structure, found by walking it from its root(s). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Reach { + pub base: u64, + /// nodes reached (box, triangle, instance) + pub nodes: u64, + /// [first, end) byte of the header and the nodes reached (whole nodes) + pub span: (u64, u64), + /// [first, end) byte of the parent pointers of the nodes reached; None: header @52 and @56 + /// are 0, no parent array + pub parents: Option<(u64, u64)>, + /// the `WALK_TILE` tiles of all of it, as (address, bytes) runs + pub tiles: Vec<(u64, u64)>, + /// why the walk left something out + pub cut: Option<&'static str>, +} + +/// A top level and the bottom levels its instance nodes reach (`walk_scene`). +#[derive(Debug, Default)] +pub struct Scene { + pub top: Reach, + /// the bottom levels walked (those `walk_scene`'s `walk` asked for), by address + pub bottoms: Vec, + /// every distinct bottom-level address of an instance node reached, ascending + pub referenced: Vec, + /// the first thing any walk left out + pub cut: Option<&'static str>, +} + +/// The title's memory as a walk reads it: whole tiles, a few kept; a tile that cannot be read +/// whole is read for the bytes asked only. +struct Mem<'r> { + read: &'r mut dyn FnMut(u64, &mut [u8]) -> bool, + tiles: std::collections::HashMap>>, + bytes: u64, + nodes: u64, + lim: Limits, +} + +/// a read refused: `Err(true)` the byte cap, `Err(false)` memory that cannot be read +type Got = Result<(), bool>; + +impl Mem<'_> { + fn get(&mut self, at: u64, out: &mut [u8]) -> Got { + let end = at.checked_add(out.len() as u64).ok_or(false)?; + let mut p = at; + while p < end { + let t = p & !(WALK_TILE - 1); + let n = (end.min(t.saturating_add(WALK_TILE)) - p) as usize; + let dst = &mut out[(p - at) as usize..][..n]; + if !self.tiles.contains_key(&t) { + if self.bytes >= self.lim.bytes { + return Err(true); + } + if self.tiles.len() >= WALK_CACHE { + self.tiles.clear(); + } + self.bytes += WALK_TILE; + let mut b = vec![0u8; WALK_TILE as usize].into_boxed_slice(); + let whole = t.checked_add(WALK_TILE).is_some() && (self.read)(t, &mut b); + self.tiles.insert(t, whole.then_some(b)); + } + match &self.tiles[&t] { + Some(b) => dst.copy_from_slice(&b[(p - t) as usize..][..n]), + None => { + self.bytes += n as u64; + if !(self.read)(p, dst) { + return Err(false); + } + } + } + p += n as u64; + } + Ok(()) + } +} + +/// `[at, at + len)`'s tiles onto `tiles` (indices) +fn touch(tiles: &mut Vec, at: u64, len: u64) { + for t in at / WALK_TILE..=(at + len - 1) / WALK_TILE { + if tiles.last() != Some(&t) { + tiles.push(t); + } + } +} + +/// Every node the traversal can reach from the header's root and `roots`, once each (a visited +/// set: no loop, whatever the bytes say). `top`: box and instance nodes (whose (bottom-level +/// address, root) go to `found`); else box and triangle nodes. +fn walk(mem: &mut Mem, base: u64, roots: &[u32], top: bool, found: &mut Vec<(u64, u32)>) -> Reach { + let mut r = Reach { base, span: (base, base), ..Default::default() }; + let mut hdr = [0u8; HEADER_BYTES]; + if base.checked_add(WALK_SPAN).is_none() || mem.get(base, &mut hdr).is_err() { + r.cut = Some("header unreadable"); + return r; + } + let mut tiles = Vec::new(); + touch(&mut tiles, base, HEADER_BYTES as u64); + r.span.1 = base + HEADER_BYTES as u64; + // the parent of node n at base + 4·(n / 64 − shift) + let (h52, h56) = (word(&hdr, 52), word(&hdr, 56)); + let shift = (h52 != 0 || h56 != 0).then(|| (h52 >> 6) as i64 - (h56 >> 2) as i64); + let mut parents: Option<(u64, u64)> = None; + let mut seen: Vec = Vec::new(); + let mut stack = vec![word(&hdr, ROOT_AT)]; + stack.extend(roots.iter().rev()); + let mut node = [0u8; 128]; + while let Some(n) = stack.pop() { + if n == INVALID { + continue; + } + let ty = n & 7; + let (size, kind) = match ty { + BOX32 => (128, true), + 4 => (64, true), + INSTANCE => (128, top), + 0..=3 => (64, !top), + _ => (0, false), + }; + let off = node_at(n) as u64; + if !kind || off < HEADER_BYTES as u64 || off + size > WALK_SPAN { + r.cut = r.cut.or(Some("bad node id")); + continue; + } + let k = (off / 64) as usize; + if seen.len() <= k / 64 { + seen.resize(k / 64 + 1, 0); + } + if seen[k / 64] & 1 << (k % 64) != 0 { + continue; + } + if r.nodes >= mem.lim.nodes || mem.nodes >= mem.lim.scene_nodes { + r.cut = Some("node cap"); + break; + } + seen[k / 64] |= 1 << (k % 64); + let at = base + off; + let b = &mut node[..size as usize]; + match mem.get(at, b) { + Ok(()) => {} + Err(true) => { + r.cut = Some("byte cap"); + break; + } + Err(false) => { + r.cut = r.cut.or(Some("node unreadable")); + continue; + } + } + let b: &[u8] = b; + r.nodes += 1; + mem.nodes += 1; + r.span = (r.span.0.min(at), r.span.1.max(at + size)); + touch(&mut tiles, at, size); + if let Some(s) = shift { + let d = 4 * ((off / 64) as i64 - s); + match base.checked_add_signed(d).filter(|_| d.unsigned_abs() <= WALK_SPAN) { + Some(p) => { + parents = Some(parents.map_or((p, p + 4), |(lo, hi)| (lo.min(p), hi.max(p + 4)))); + touch(&mut tiles, p, 4); + } + None => r.cut = r.cut.or(Some("parent pointer out of range")), + } + } + match ty { + BOX32 | 4 => stack.extend((0..4).rev().map(|c| word(b, 4 * c)).filter(|&c| c != INVALID)), + INSTANCE => { + let (root, addr) = (word(b, 56) & 0x3FFF_FFFF, (word(b, 60) as u64) << 8); + if addr != 0 && root != 0x3FFF_FFFF { + found.push((addr, root)); + } + } + _ => {} + } + } + r.parents = parents; + tiles.sort_unstable(); + tiles.dedup(); + for t in tiles { + match r.tiles.last_mut() { + Some((a, n)) if *a + *n == t * WALK_TILE => *n += WALK_TILE, + _ => r.tiles.push((t * WALK_TILE, WALK_TILE)), + } + } + r +} + +/// What a ray traversal can read of the top level at `base` and of the bottom levels its +/// instance nodes reach, through `read` (copies `out.len()` bytes at an address; false when any +/// of them cannot be read). A bottom level is walked when `walk(address)` says so (one known +/// already need not be). Never more than `lim`; what was left out is in the `cut`s. +pub fn walk_scene(read: &mut dyn FnMut(u64, &mut [u8]) -> bool, base: u64, lim: &Limits, walk_bottom: &mut dyn FnMut(u64) -> bool) -> Scene { + let mut mem = Mem { read, tiles: Default::default(), bytes: 0, nodes: 0, lim: *lim }; + let mut found = Vec::new(); + let top = walk(&mut mem, base, &[], true, &mut found); + let mut s = Scene { cut: top.cut, top, ..Default::default() }; + found.sort_unstable(); + found.dedup(); + for g in found.chunk_by(|a, b| a.0 == b.0) { + if s.referenced.len() >= lim.bottoms { + s.cut = s.cut.or(Some("bottom-level cap")); + break; + } + let addr = g[0].0; + s.referenced.push(addr); + if !walk_bottom(addr) { + continue; + } + let roots: Vec = g.iter().take(WALK_ROOTS).map(|x| x.1).collect(); + let b = walk(&mut mem, addr, &roots, false, &mut Vec::new()); + s.cut = s.cut.or(b.cut); + s.bottoms.push(b); + } + s +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -594,6 +848,194 @@ pub(crate) mod tests { assert!(!is_compressed_header(&[])); } + /// The empty structure: a ray right through its (zero) bounds reaches no child, as a top or + /// a bottom level. + #[test] + fn the_empty_structure_has_nothing_to_hit() { + let e = empty(); + assert_eq!(word(&e.data, ROOT_AT), e.root); + let (o, d) = ([-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]); + assert_eq!(intersect_node(&e.data, e.root, 100.0, o, d, d.map(|x| 1.0 / x), true), [INVALID; 4]); + assert_eq!(e.trace(o, d, 100.0), None); + assert_eq!(e.trace_scene(&|_| None, o, d, 100.0), None); + let s = walk_scene(&mut space(&[(TOP_AT, e.data.clone())]), TOP_AT, &Limits::default(), &mut |_| true); + assert_eq!((s.top.nodes, s.referenced.len(), s.cut), (1, 0, None)); + } + + /// An address space of `regions` (address, bytes): a read inside one of them only. + fn space(regions: &[(u64, Vec)]) -> impl FnMut(u64, &mut [u8]) -> bool + '_ { + move |a, out| { + let r = regions.iter().find(|(at, d)| a >= *at && a + out.len() as u64 <= at + d.len() as u64); + r.map(|(at, d)| out.copy_from_slice(&d[(a - at) as usize..][..out.len()])).is_some() + } + } + + /// whole tiles over `[at, at + len)` + fn tiles_of(at: u64, len: u64) -> Vec<(u64, u64)> { + let lo = at & !(WALK_TILE - 1); + vec![(lo, (at + len).next_multiple_of(WALK_TILE) - lo)] + } + + /// `n` instances spread over bottom levels at `blas` + fn top_over(blas: &[(u64, Bvh)], n: usize) -> Bvh { + let mut r = rng(5); + let instances: Vec = (0..n) + .map(|i| { + let (addr, b) = &blas[i % blas.len()]; + let t = [r(-50.0, 50.0), r(-50.0, 50.0), r(-50.0, 50.0)]; + let m = [0, 1, 2].map(|row| [(row == 0) as u32 as f32, (row == 1) as u32 as f32, (row == 2) as u32 as f32, t[row]]); + Instance { transform: m, id: i as u32, mask: 0xFF, contribution: 0, flags: 0, blas_address: *addr, blas_root: b.root, blas_bounds: b.bounds() } + }) + .collect(); + build_top(&instances) + } + + const TOP_AT: u64 = 0x20_0000_0000; + + fn walk_all(regions: &[(u64, Vec)], lim: &Limits) -> Scene { + walk_scene(&mut space(regions), TOP_AT, lim, &mut |_| true) + } + + /// box + leaf nodes of a structure from the builder here (every node reachable) + fn node_count(b: &Bvh, leaf: usize, leaves: usize) -> u64 { + (leaves + (b.data.len() - HEADER_BYTES - leaf * leaves) / BOX_BYTES) as u64 + } + + /// A top level of 600 instances (over 64 KiB) over 3 bottom levels, one of them neither at + /// nor a whole number of tiles: the walk reaches exactly each structure's bytes and tiles. + #[test] + fn walk_reaches_exactly_the_top_level_and_each_bottom_level() { + let sizes = [30, 200, 1500]; + let addrs = [0x10_0000_0000u64, 0x10_0040_0000, 0x10_0081_2300]; + let blas: Vec<(u64, Bvh)> = (0..3).map(|k| (addrs[k], build(&random_tris(sizes[k], 40 + k as u64), 0))).collect(); + let top = top_over(&blas, 600); + assert!(top.data.len() > 0x1_0000, "{} bytes", top.data.len()); + let mut regions: Vec<(u64, Vec)> = blas.iter().map(|(a, b)| (*a, b.data.clone())).collect(); + regions[0].1.resize(0x1_0000, 0); // a whole tile: read whole + regions.push((TOP_AT, top.data.clone())); + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.cut, None); + let len = top.data.len() as u64; + assert_eq!(s.top.span, (TOP_AT, TOP_AT + len)); + assert_eq!(s.top.nodes, node_count(&top, INSTANCE_BYTES, 600)); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, len)); + assert_eq!(s.top.parents, None, "header @52 / @56 0: no parent array"); + assert_eq!(s.referenced, addrs); + for (k, b) in s.bottoms.iter().enumerate() { + let (a, built) = &blas[k]; + let len = built.data.len() as u64; + assert_eq!((b.base, b.span, b.cut), (*a, (*a, *a + len), None), "bottom level {k}"); + assert_eq!(b.nodes, node_count(built, TRI_BYTES, sizes[k]), "bottom level {k}"); + assert_eq!(b.tiles, tiles_of(*a, len), "bottom level {k}"); + } + // a bottom level known already is not walked again, still referenced + let s2 = walk_scene(&mut space(®ions), TOP_AT, &Limits::default(), &mut |a| a != addrs[1]); + assert_eq!((s2.referenced.len(), s2.bottoms.len()), (3, 2)); + } + + /// An instance's bottom level that cannot be read is left out and said so; the others are not. + #[test] + fn walk_leaves_out_an_unreadable_bottom_level() { + let good = build(&random_tris(50, 3), 0); + let blas = [(0x10_0000_0000u64, good), (0x30_0000_0000, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 8); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.referenced, [0x10_0000_0000, 0x30_0000_0000]); + assert_eq!(s.cut, Some("header unreadable")); + assert_eq!((s.bottoms[0].nodes, s.bottoms[0].cut), (node_count(&blas[0].1, TRI_BYTES, 50), None)); + assert_eq!((s.bottoms[1].nodes, s.bottoms[1].tiles.len(), s.bottoms[1].cut), (0, 0, Some("header unreadable"))); + assert_eq!(s.top.nodes, node_count(&top, INSTANCE_BYTES, 8)); + } + + /// A box pointing back at the root (or twice at one child) is walked once. + #[test] + fn walk_visits_a_node_once_in_a_cycle() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let mut top = top_over(&blas, 3); + assert_eq!(word(&top.data, HEADER_BYTES + 12), INVALID); + put(&mut top.data, HEADER_BYTES + 12, &[top.root]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.nodes, s.top.cut), (4, None)); + let first = word(&top.data, HEADER_BYTES); + put(&mut top.data, HEADER_BYTES + 12, &[first]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + assert_eq!(walk_all(®ions, &Limits::default()).top.nodes, 4); + } + + /// A root that is no node of a top level (a triangle, an unknown type, inside the header, + /// too far, not there) gives no node, and says why. + #[test] + fn walk_refuses_a_garbage_root() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 3); + let cases = [(0x7u32 | (HEADER_BYTES as u32 / 8), "bad node id"), (HEADER_BYTES as u32 / 8, "bad node id"), (0x10 | BOX32, "bad node id"), (0x4000_0000 | BOX32, "bad node id"), (0x10_0000 | BOX32, "node unreadable")]; + for (root, why) in cases { + let mut data = top.data.clone(); + put(&mut data, ROOT_AT, &[root]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, data)]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.nodes, s.top.cut, s.referenced.len()), (0, Some(why), 0), "root {root:#x}"); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, HEADER_BYTES as u64), "the header only"); + } + } + + /// Memory that ends inside the structure: the nodes before it, and said so. + #[test] + fn walk_stops_at_truncated_memory() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let top = top_over(&blas, 600); + let half = top.data.len() / 2 + 0x40; + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data[..half].to_vec())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!(s.top.cut, Some("node unreadable")); + assert!(s.top.nodes > 100 && s.top.nodes < node_count(&top, INSTANCE_BYTES, 600), "{} nodes", s.top.nodes); + assert!(s.top.span.1 <= TOP_AT + half as u64); + assert_eq!(s.referenced, [blas[0].0]); + } + + /// The node, scene and byte caps end a walk with what it found. + #[test] + fn walk_stops_at_its_caps() { + let blas = [(0x10_0000_0000u64, build(&random_tris(300, 4), 0))]; + let top = top_over(&blas, 600); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits { nodes: 10, ..Default::default() }); + assert_eq!((s.top.nodes, s.top.cut), (10, Some("node cap"))); + let all = node_count(&top, INSTANCE_BYTES, 600); + let s = walk_all(®ions, &Limits { scene_nodes: all + 7, ..Default::default() }); + assert_eq!((s.top.nodes, s.bottoms[0].nodes, s.cut), (all, 7, Some("node cap"))); + let s = walk_all(®ions, &Limits { bytes: WALK_TILE, ..Default::default() }); + assert_eq!(s.top.cut, Some("byte cap")); + assert!(s.top.span.1 <= TOP_AT + WALK_TILE); + let s = walk_all(®ions, &Limits { bottoms: 0, ..Default::default() }); + assert_eq!((s.referenced.len(), s.cut), (0, Some("bottom-level cap"))); + } + + /// The parent pointer of every node reached, at header@52 / @56's place: before the nodes + /// here (in the tile before the structure's); one too far is left out, without overflow. + #[test] + fn walk_reaches_the_parent_pointers() { + let blas = [(0x10_0000_0000u64, build(&random_tris(5, 4), 0))]; + let mut top = top_over(&blas, 600); + let last = (top.data.len() - INSTANCE_BYTES) as u64 / 64; + // shift = 0x40_0000 >> 6 − 0x40 >> 2 = 65520: the pointers from 4·(4 − 65520) on + put(&mut top.data, 52, &[0x40_0000, 0x40]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + let p = |k: u64| TOP_AT - 4 * (65520 - k); + assert_eq!(s.top.parents, Some((p(4), p(last) + 4))); + assert_eq!(s.top.cut, None); + let len = top.data.len() as u64; + assert_eq!(s.top.tiles, [tiles_of(p(4), p(last) + 4 - p(4)), tiles_of(TOP_AT, len)].concat()); + put(&mut top.data, 52, &[0, 0xFFFF_FFFC]); + let regions = vec![(blas[0].0, blas[0].1.data.clone()), (TOP_AT, top.data.clone())]; + let s = walk_all(®ions, &Limits::default()); + assert_eq!((s.top.parents, s.top.cut), (None, Some("parent pointer out of range"))); + assert_eq!(s.top.tiles, tiles_of(TOP_AT, len)); + } + #[test] fn grazing_axis_aligned_ray_and_nan_box() { let mut data = vec![0u8; 256]; diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index 31b3dcec2a..ffb98054fa 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -224,6 +224,39 @@ fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet BTreeMap> { + let n = cfg.blocks.len(); + let mut pos = vec![usize::MAX; n]; + for (i, &b) in cfg.rpo.iter().enumerate() { + pos[b] = i; + } + let body = |h: usize| { + let mut inside = vec![false; n]; + inside[h] = true; + let mut stack: Vec = cfg.blocks[h].preds.iter().copied().filter(|&p| pos[p] != usize::MAX && pos[p] >= pos[h]).collect(); + while let Some(x) = stack.pop() { + if !inside[x] { + inside[x] = true; + stack.extend(cfg.blocks[x].preds.iter().copied()); + } + } + inside + }; + let loops: Vec<(usize, Vec)> = cfg.headers.iter().map(|&h| (h, body(h))).collect(); + let size = |b: &[bool]| b.iter().filter(|&&x| x).count(); + loops + .iter() + .map(|&(h, _)| { + let around = loops.iter().filter(|(g, b)| *g != h && b[h]).min_by_key(|(g, b)| (size(b), pos[*g])).map(|&(g, _)| g); + (h, around) + }) + .collect() +} + fn succ_of(b: &CfgBlock) -> Vec { match b.term { Term::Jump(t) => vec![t], @@ -346,4 +379,70 @@ mod tests { assert_eq!(headers.len(), 1); assert_eq!(headers2.len(), 1); } + + /// A reducible `Cfg` of `blocks` (no instructions), as `Cfg::build` finishes one. + fn cfg_of(mut blocks: Vec) -> Cfg { + let (rpo, headers) = make_reducible(&mut blocks).unwrap(); + for &b in &rpo { + for t in succ_of(&blocks[b]) { + if !blocks[t].preds.contains(&b) { + blocks[t].preds.push(b); + } + } + } + Cfg { insts: Vec::new(), blocks, rpo, headers } + } + + fn parents(blocks: Vec) -> Vec<(usize, Option)> { + loop_parents(&cfg_of(blocks)).into_iter().collect() + } + + use Term::{Cond, End, Jump}; + + #[test] + fn loop_parents_of_one_loop_and_of_loops_one_after_the_other() { + // 0 → 1 → 2 → {1 | 3} + assert_eq!(parents(vec![blk(Jump(1)), blk(Jump(2)), blk(Cond(0, 1, 3)), blk(End)]), [(1, None)]); + // 0 → 1 ⟲, 1 → 2 → 3 ⟲, 3 → 4 + assert_eq!(parents(vec![blk(Jump(1)), blk(Cond(0, 1, 2)), blk(Jump(3)), blk(Cond(0, 3, 4)), blk(End)]), [(1, None), (3, None)]); + } + + #[test] + fn loop_parents_of_loops_inside_one_another() { + // 1 → 2 ⟲, 2 → 3 → {1 | 4} + assert_eq!(parents(vec![blk(Jump(1)), blk(Jump(2)), blk(Cond(0, 2, 3)), blk(Cond(0, 1, 4)), blk(End)]), [(1, None), (2, Some(1))]); + // three deep: 3 ⟲ inside 2 … 4 inside 1 … 5 + let deep = vec![blk(Jump(1)), blk(Jump(2)), blk(Jump(3)), blk(Cond(0, 3, 4)), blk(Cond(0, 2, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(deep), [(1, None), (2, Some(1)), (3, Some(2))]); + } + + /// Both back edges make the loop: each of 3 → 1 and 5 → 1 has an inner loop (2 ⟲, 4 ⟲) only + /// on its own path, so a body of either back edge alone leaves one of them outermost. + #[test] + fn loop_parents_of_a_loop_with_two_back_edges() { + let b = vec![blk(Jump(1)), blk(Cond(0, 2, 4)), blk(Cond(0, 2, 3)), blk(Jump(1)), blk(Cond(0, 4, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(b), [(1, None), (2, Some(1)), (4, Some(1))]); + } + + /// A loop entered in the middle, after `make_reducible` split it (0 → {3 | 1}, 1 → 2's copy, + /// cycle 2 → 3 → {2 | 4}): one loop, at 3. + #[test] + fn loop_parents_of_a_split_loop() { + let b = vec![blk(Cond(0, 3, 1)), blk(Jump(2)), blk(Jump(3)), blk(Cond(0, 2, 4)), blk(End)]; + assert_eq!(parents(b), [(3, None)]); + } + + /// The outer body enters the inner loop 4 from two blocks (2 and 3). + #[test] + fn loop_parents_of_a_loop_entered_from_two_blocks() { + let b = vec![blk(Jump(1)), blk(Cond(0, 2, 3)), blk(Jump(4)), blk(Jump(4)), blk(Cond(0, 4, 5)), blk(Cond(0, 1, 6)), blk(End)]; + assert_eq!(parents(b), [(1, None), (4, Some(1))]); + } + + /// The program's first block is the outer loop's header. + #[test] + fn loop_parents_of_a_loop_at_the_entry() { + let b = vec![blk(Jump(1)), blk(Cond(0, 1, 2)), blk(Cond(0, 0, 3)), blk(End)]; + assert_eq!(parents(b), [(0, None), (1, Some(0))]); + } } diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..4f0f700ffa 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -14,6 +14,153 @@ fn prog(list: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { v } +/// One console wave in two hardware halves (33 to 64 threads a group): the halves of a compute +/// or mesh group exchange through the bounded counters, as those of larger groups do, and meet +/// at no group barrier after the one at the program's start. A barrier at every exchange hung NVIDIA +/// GPUs when several such programs ran at once (#1727; the change is #1741's). +#[test] +fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { + use crate::gpu::recomp::CsInterface; + // v1 = lane 32's v0: the lower half needs the upper half's value + let code = prog(&[("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None)]); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let dis = |threads: u32, code: &[u8]| { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + super::validate::disassemble(&super::kernel::translate_compute(code, o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil) + }; + // (barrier mode 9: the thread group's sync with its memory fence, `ops::barrier::GROUP_SYNC`) + let syncs = |d: &str| d.matches("@dx.op.barrier(i32 80, i32 9)").count(); + let Ok(alone) = dis(32, &code) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + }; + assert_eq!(syncs(&alone), 1, "the start's barrier: +{alone}"); + assert!(alone.matches("atomicrmw").count() < 3, "a half without a partner does not wait for one: +{alone}"); + for threads in [33, 64, 128] { + let d = dis(threads, &code).unwrap(); + assert_eq!(syncs(&d), 1, "{threads} threads: a group barrier at the exchange: +{d}"); + assert!(d.matches("atomicrmw").count() >= 3, "{threads} threads: the exchange's counters: +{d}"); + } + // the text before the start's barrier, and after it + let at_start = |d: &str| d.split_at(d.find("@dx.op.barrier(i32 80, i32 9)").expect("the start's barrier")).0.to_string(); + // the value (`%N`) the first line of `pre` that `hit` accepts defines + fn def(pre: &str, hit: impl Fn(&str) -> bool) -> Option { + pre.lines().find(|l| hit(l)).and_then(|l| l.trim().split_once(" = ")).map(|(n, _)| n.to_string()) + } + // a zero stored through that address in `pre` + fn zeroed(pre: &str, at: Option) -> bool { + at.is_some_and(|p| pre.contains(&format!("store i32 0, i32 addrspace(3)* {p},"))) + } + // without LDS: slots and counters of their own (one console wave: 4 slot words, 2 counters), + // the counters zeroed before the start's barrier + let d = dis(64, &code).unwrap(); + assert!(d.contains("@xcl_xs = external addrspace(3) global [4 x i32]") && d.contains("@xcl_xc = external addrspace(3) global [2 x i32]"), "the spin storage: +{d}"); + let pre = at_start(&d); + assert!(zeroed(&pre, def(&pre, |l| l.contains("addrspace(3)* @xcl_xc, i32 0, i32 %"))), "the counters zeroed before the start's barrier: +{d}"); + // a mesh program's compute pass of one console wave (48 or 64 threads) exchanges the same way + for threads in [48, 64] { + let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64 }; + let d = super::validate::disassemble(&super::kernel::translate_mesh(&code, o, &ms).unwrap_or_else(|e| panic!("mesh, {threads} threads: {e}")).dxil).unwrap(); + assert_eq!(syncs(&d), 1, "mesh, {threads} threads: a group barrier at the exchange: +{d}"); + assert!(d.contains("@xcl_xc = external addrspace(3) global [2 x i32]") && d.matches("atomicrmw").count() >= 3, "mesh, {threads} threads: the exchange's counters: +{d}"); + let pre = at_start(&d); + assert!(zeroed(&pre, def(&pre, |l| l.contains("addrspace(3)* @xcl_xc, i32 0, i32 %"))), "mesh, {threads} threads: the counters zeroed before the start's barrier: +{d}"); + } + // with the program's LDS the counters live in its top words + let with_lds = prog(&[ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None), + ]); + let d = dis(64, &with_lds).unwrap(); + assert_eq!(syncs(&d), 1, "a group barrier at the exchange (LDS): +{d}"); + assert!(d.matches("atomicrmw").count() >= 3, "the exchange's counters (LDS): +{d}"); + // the HLSL layout: the thread counter in the top word (8191), the two counters below it + // (8189, 8190: zeroed before the start's barrier), the 4 slot words below them (from + // 8192 - 4 - 2 - 1 = 8185), and the program's LDS clamped below the slots (8184) + let pre = at_start(&d); + let rest = &d[pre.len()..]; + let index = def(&pre, |l| l.ends_with(", 8189")); + let counter = index.and_then(|i| def(&pre, |l| l.contains("@xcl_lds, i32 0, i32 ") && l.ends_with(&format!(" {i}")))); + assert!(pre.contains("@xcl_lds, i32 0, i32 8191") && zeroed(&pre, counter), "the top word and the counters zeroed before the start's barrier: +{d}"); + assert!(rest.contains(", 8185"), "the slots from word 8185: +{d}"); + assert_eq!(rest.matches(", 8189").count(), 2, "this half's and the partner's counter: +{d}"); + assert!(rest.contains("i32 8184)"), "the program's LDS below the exchange: +{d}"); +} + +/// The split form keeps the console wave's order of LDS accesses (`Lw::lds_in_order`): an LDS +/// read after a write, and a write after a read, meet the other half first (the kernel form's +/// group barrier, a compute group's counters); a read with no write since the last meet does +/// not, and a half without a partner and the native form never do. In a loop the meet is +/// conditional on the bits, and still validates. +#[test] +fn split_lds_reads_meet_after_writes() { + use crate::gpu::recomp::CsInterface; + type Inst<'a> = (&'a str, &'a str, &'a [(&'a str, u64)], Option); + let write: Inst = ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None); + let read: Inst = ("DS_READ_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 1)], None); + let syncs = |d: &str| d.matches("@dx.op.barrier(i32 80, i32 9)").count(); + let kernel = |list: &[Inst], split: bool| { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + super::validate::disassemble(&translate(&prog(list), o).unwrap_or_else(|e| panic!("{e}"))) + }; + let Ok(rw) = kernel(&[write, read], true) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + }; + let w = syncs(&kernel(&[write], true).unwrap()); + assert_eq!(syncs(&rw), w + 1, "the read meets after the write:\n{rw}"); + assert_eq!(syncs(&kernel(&[write, write], true).unwrap()), w, "a write after a write"); + assert_eq!(syncs(&kernel(&[read, write], true).unwrap()), w + 1, "the write meets after the read"); + assert_eq!(syncs(&kernel(&[write, read, read], true).unwrap()), w + 1, "the second read: the halves met since the write"); + assert_eq!(syncs(&kernel(&[write, read, write], true).unwrap()), w + 2, "a meet before the read and before the second write"); + let native = |list: &[Inst]| syncs(&kernel(list, false).unwrap()); + assert_eq!(native(&[write, read]), native(&[write]), "the native form"); + // a loop: read, write, three times – each waits for the other from the second pass on + let looped = |body: &[Inst]| { + let mut l: Vec = vec![("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 131)], None)]; + l.extend_from_slice(body); + // back to the loop's first instruction: the DS instructions are 2 words each + let back = 0x1_0000 - (2 * body.len() as u64 + 3); + l.extend_from_slice(&[ + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ]); + let mut code = prog(&l); + code.truncate(code.len() - 4); + code.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + syncs(&super::validate::disassemble(&translate(&code, o).unwrap_or_else(|e| panic!("{e}"))).unwrap()) + }; + assert!(looped(&[read, write]) >= looped(&[read]) + 2, "the loop's read and write meet when the bits are set"); + // compute groups: the counters' meet (two more atomics), none without a partner half + let atomics = |threads: u32, list: &[Inst]| { + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let d = super::validate::disassemble(&super::kernel::translate_compute(&prog(list), o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil).unwrap(); + d.matches("atomicrmw").count() + }; + for threads in [64, 128] { + assert_eq!(atomics(threads, &[write, read]), atomics(threads, &[write]) + 2, "{threads} threads"); + } + assert_eq!(atomics(32, &[write, read]), atomics(32, &[write]), "32 threads: no partner half"); +} + #[test] fn straight_line_and_loop_kernels_validate() { let code = prog(&[ @@ -329,7 +476,19 @@ fn geometry_mode_validates() { for (name, code, g) in cases { for split in [true, false] { let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; - super::kernel::translate_geometry(&code, o, &g).unwrap_or_else(|e| panic!("{name} split {split}: {}", &e[..e.len().min(3000)])); + match super::kernel::translate_geometry(&code, o, &g) { + Ok(_) => {} + // a split pass with an ES phase is left to the HLSL path (the safe barrier): + // complete there, and DXC compiles it + Err(e) if e.contains("split wave64 geometry: the ES phase exchanges at group barriers") => { + let t = crate::gpu::recomp::translate_geometry(&code, g.clone(), true, 1).unwrap_or_else(|e| panic!("{name} HLSL: {e}")); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + if crate::gpu::recomp::dxc::location().is_ok() { + crate::gpu::recomp::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{name} HLSL: {e}")); + } + } + Err(e) => panic!("{name} split {split}: {}", &e[..e.len().min(3000)]), + } } } } @@ -434,7 +593,7 @@ fn ps_get_lod_with_a_static_sampler() { let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); if crate::gpu::recomp::dxc::location().is_ok() { - super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true, &[]).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); } } @@ -613,6 +772,365 @@ fn window_at_lowers_to_32bit_carry_without_int64() { } } +/// A loop that only ends when its counter wraps to 0, then global_store_dword [v0 * 4], the +/// counter (the recompiler tests' `endless_loop_program`). +fn endless_loop() -> Vec { + prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 10)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +/// The same loop inside one of three passes (`endless_loop_entered_three_times`). +fn endless_loop_entered_three_times() -> Vec { + prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 10)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 11), ("SSRC1", 131)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF8)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +/// The blocks of the emitted `main`: (label, predecessors, text); the entry block is `%0`. +fn main_blocks(dis: &str) -> Vec<(String, Vec, String)> { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + let mut out = vec![("%0".to_string(), Vec::new(), String::new())]; + for line in body.lines() { + if let Some(rest) = line.strip_prefix(";