diff --git a/CHANGELOG.md b/CHANGELOG.md index a05b431e..6aa4ebdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer. - Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's four fixture tests or the whole upstream suite. It takes the test executable's path from cargo's own build message instead of guessing the target layout (the first version looked in `debug/build/.../out/`; the usual location is `debug/deps/`, which is the fallback). It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; the `debug/deps` fallback is untested on this machine, whose cargo layout puts the executable elsewhere. Not independently reviewed. - Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`. - Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c9d1c6ba..b61c96cd 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -17,3 +17,5 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses. `crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`. + +Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed. diff --git a/crates/victory-shader/UPSTREAM.md b/crates/victory-shader/UPSTREAM.md index 9c893455..37c6836a 100644 --- a/crates/victory-shader/UPSTREAM.md +++ b/crates/victory-shader/UPSTREAM.md @@ -21,6 +21,13 @@ Changes to upstream files (19 lines, nothing functional) and files BetterXen add - `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream. - `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`). +### Functional edits to upstream files (research/shader-wave-semantics, PR #392) + +- `src/emit/lower.rs` (`active_f64_sum`, about 90 lines): the whole-wave f64 sum no longer emits a native `double` wave operation (`makeDouble`, `waveActiveOp.f64`, `splitDouble`); it builds the console's balanced tree over the lanes with the crate's own integer `add_f64`, reading partner runs through `waveReadLaneAt` and a ballot for lanes that are not present, and no longer sets the doubles feature flag. Why: D3DMetal reports no double-precision shader operations and a shader that uses a `double` ran without writing anything (docs/research/shader-wave-semantics.md). +- `src/emit/bitcode.rs`: two `#[allow(dead_code)]` for the double type, now never constructed. +- `src/emit/host.rs`: `Host::wave_lane_count_max()` (test host only). +- `src/emit/wave64_tests.rs`: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` checks the device's wave width and, on a device narrower than 64 lanes, asserts the recompiler's refusal instead of running a 64-lane lowering. + ## Not carried The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. The shader inputs the upstream project was built for are not included; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record). diff --git a/crates/victory-shader/src/emit/betterxen_tests.rs b/crates/victory-shader/src/emit/betterxen_tests.rs index c1aa5e82..14357a68 100644 --- a/crates/victory-shader/src/emit/betterxen_tests.rs +++ b/crates/victory-shader/src/emit/betterxen_tests.rs @@ -220,3 +220,177 @@ mod on_the_gpu { } } } + +// ---- f64 whole-wave sum (research/shader-wave-semantics) -------------------------------------- +// +// The console's whole-wave f64 sum, as `valu_tests::whole_wave_f64_sum_and_cvt_f32_f64` builds it, +// but storing both words of the f64 result instead of converting to f32, so all 64 bits are +// compared. Upstream lowered it to a native `double` wave operation, which D3DMetal does not run +// (docs/research/shader-wave-semantics.md); it is now done with the integer fp64 add. +// Expected results come from a CPU model of the balanced tree over the lanes in their order +// (lanes 2k and 2k+1, then pairs, ...) with the CPU's own f64 additions, `+0.0` for lanes that +// are not launched; nothing is taken from the recompiler. + +const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) +} + +const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + ] +} + +const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] { + [ + 0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF), + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8, + ] +} + +/// A one-group compute program over `threads` threads: each lane's f64 is root constants +/// `(s0, s1)`; the program sums the wave and stores the sum's low then high word to the UAV. +fn f64_wave_sum_program(threads: u32) -> NativeProgram { + let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_row_mirror = |vdst: u8, vsrc: u8| { + [ + vop1(0x001, vdst, 0xFA), + vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28), + ] + }; + let mut w: Vec = Vec::new(); + w.push(0xBE80_0000 | 5 << 16 | 0x03 << 8 | 0x80); // s_mov_b32 s5, 0 (table address high) + w.extend_from_slice(&[0x3D << 26 | 0x02 << 18 | 8 << 6 | (4 >> 1), 125 << 25]); // s_load_dwordx4 s[8:11], s[4:5], 0 + w.push(vop1(0x001, 6, 0)); // v_mov_b32 v6, s0 + w.push(vop1(0x001, 7, 1)); // v_mov_b32 v7, s1 + w.push(0xBE80_0000 | 12 << 16 | 0x3D << 8 | 0xC1); // s_or_saveexec_b32 s12, -1 + w.extend_from_slice(&vop3(0x101, 2, 0x80, 256 + 6, 12)); + w.extend_from_slice(&vop3(0x101, 3, 0x80, 256 + 7, 12)); + for sel in [14570689u32, 9658386, 2340] { + w.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + w.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); // v_add_f64 + } + w.extend_from_slice(&v_mov_row_mirror(4, 2)); + w.extend_from_slice(&v_mov_row_mirror(5, 3)); + w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); + w.extend_from_slice(&vop3(0x378, 4, 256 + 2, 0x80, 0x80)); // v_permlanex16_b32 + w.extend_from_slice(&vop3(0x378, 5, 256 + 3, 0x80, 0x80)); + w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); + w.extend_from_slice(&vop3(0x360, 14, 256 + 2, 0x80, 0)); // v_readlane_b32 s14, v2, 0 + w.extend_from_slice(&vop3(0x360, 15, 256 + 3, 0x80, 0)); // v_readlane_b32 s15, v3, 0 + w.push(0xBE80_0000 | 16 << 16 | 0x03 << 8 | 14); // s_mov_b32 s16, s14 + w.push(0xBE80_0000 | 17 << 16 | 0x03 << 8 | 15); // s_mov_b32 s17, s15 + w.push(0xBE80_0000 | 126 << 16 | 0x03 << 8 | 12); // s_mov_b32 exec_lo, s12 + w.push(vop1(0x001, 0, 16)); // v_mov_b32 v0, s16 (low word) + w.extend_from_slice(&buffer_store_dword(0, 8, 0)); + w.push(vop1(0x001, 0, 17)); // v_mov_b32 v0, s17 (high word) + w.extend_from_slice(&buffer_store_dword(0, 8, 4)); + w.push(0xBF81_0000); // s_endpgm + let code: Vec = w.iter().flat_map(|x| x.to_le_bytes()).collect(); + let param = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 12, + layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [threads, 1, 1] }), + code, + } +} + +/// The CPU model: the balanced tree over 32 lanes, the first `launched` holding `x`, the rest `+0.0`. +fn tree_sum(x: f64, launched: usize) -> f64 { + let mut v: Vec = (0..32).map(|l| if l < launched { x } else { 0.0 }).collect(); + while v.len() > 1 { + v = v.chunks(2).map(|p| p[0] + p[1]).collect(); + } + v[0] +} + +#[test] +fn the_f64_wave_sum_is_lowered_without_native_doubles() { + let shader = translate_native(&f64_wave_sum_program(4)).expect("translate"); + let c = crate::dxbc::Container::parse(&shader.dxil).expect("container"); + let sfi0 = c.part(crate::dxbc::FourCC::SFI0).expect("SFI0 part").data; + let features = u64::from_le_bytes(sfi0[..8].try_into().unwrap()); + assert_ne!(features & 0x4000, 0, "the sum uses wave operations (sanity check of this parse)"); + assert_eq!(features & 0x1, 0, "no native double may be declared: D3DMetal does not run them"); +} + +#[test] +fn the_cpu_model_is_the_balanced_tree() { + // 4 lanes of 1.25: (1.25 + 1.25) twice, then 2.5 + 2.5, then the rest +0 + assert_eq!(tree_sum(1.25, 4), 5.0); + assert_eq!(tree_sum(1.25, 32), 40.0); + // the order matters for values that round: this is not the sequential sum + let x = 0.1; + let sequential: f64 = (0..32).fold(0.0, |a, _| a + x); + assert_ne!(tree_sum(x, 32).to_bits(), sequential.to_bits()); +} + +#[cfg(windows)] +mod f64_on_the_gpu { + use super::*; + use crate::emit::host::{Dispatch, Host, Root, View}; + + /// Whole-wave f64 sums on the default D3D12 device, all 64 bits compared with the CPU model, + /// for full and partial waves and for values that round. Fails when there is no device. + #[test] + fn f64_wave_sums_match_the_cpu_tree_bit_for_bit() { + let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified"); + let mut ran = 0; + for threads in [1u32, 4, 20, 32] { + let shader = translate_native(&f64_wave_sum_program(threads)).expect("translate"); + let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline"); + for x in [1.25f64, 0.1, -3.75e10, 1.0e-300, 123456.789, f64::from_bits(0x3FF0_0000_0000_0001)] { + let b = x.to_bits(); + let inputs = [b as u32, (b >> 32) as u32, 0, 0]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(2)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let got = u64::from(out[0][0]) | u64::from(out[0][1]) << 32; + let want = tree_sum(x, threads as usize).to_bits(); + assert_eq!(got, want, "{threads} threads of {x:e}: got {got:#018x}, want {want:#018x}"); + ran += 1; + } + } + eprintln!("betterxen: {ran} f64 wave sums ran on the GPU and matched the CPU tree bit for bit"); + } +} diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index eff0ac08..8638a410 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -30,6 +30,7 @@ enum TypeDef { Void, Int(u32), Float, + #[allow(dead_code)] // BetterXen: no native double is emitted any more (see lower.rs active_f64_sum) Double, /// Pointee and address space. Ptr(Ty, u32), @@ -248,6 +249,7 @@ impl Module { pub fn float(&mut self) -> Ty { self.ty(TypeDef::Float) } + #[allow(dead_code)] // BetterXen: see TypeDef::Double pub fn double(&mut self) -> Ty { self.ty(TypeDef::Double) } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index a51d0ac1..be3b5028 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -82,6 +82,24 @@ fn err(e: windows::core::Error) -> String { } impl Host { + /// The widest wave the device reports (`D3D12_OPTIONS1.WaveLaneCountMax`), or `None` when the + /// device does not report wave operations. BetterXen addition: tests that lower for a given + /// host wave width must not run on a narrower device (see wave64_tests.rs). + pub fn wave_lane_count_max(&self) -> Option { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: `o` is a correctly sized, writable feature-data struct for this feature. + unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&mut o as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS1).cast(), + std::mem::size_of::() as u32, + ) + .ok()?; + } + (o.WaveOps.as_bool() && o.WaveLaneCountMax > 0).then_some(o.WaveLaneCountMax) + } + /// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`). pub fn new(warp: bool) -> Result { let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index bd358322..32ca9b51 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2052,6 +2052,19 @@ impl<'a> Lower<'a> { /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), /// returning the low (`!high`) or high (`high`) 32-bit word. + /// + /// BetterXen change (research/shader-wave-semantics): upstream emitted a native `double` + /// wave operation here (`makeDouble`, `waveActiveOp.f64`, `splitDouble`). The host this is + /// run on (D3DMetal over Metal) has no fp64: it reports no double-precision shader operations + /// and, observed with shaders from Microsoft's DXC, a shader that uses a `double` runs without + /// writing anything. Every other fp64 instruction here is done with 64-bit integer + /// operations ([`super::f64::add_f64`], checked against the CPU's doubles); this does the + /// same. The console's sum is the balanced tree over the lanes in their order (lanes 2k and + /// 2k+1, then pairs, ...; [`super::wave::buddies`]), which is how it is built here: each + /// lane adds its partner run's partial sum, read from the first lane of that run that is + /// present, and `+0.0` where none is (a lane outside EXEC adds `+0` on the console, and a + /// lane the host never launched is the same). The addition is commutative, so every lane + /// holds the same sum. fn active_f64_sum( &mut self, lo: Value, @@ -2075,25 +2088,48 @@ impl<'a> Lower<'a> { let z = self.s.m.i32(0); let lo = self.s.m.select(c, on, lo, z); let hi = self.s.m.select(c, on, hi, z); - self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; - let f64t = self.s.m.double(); + self.s.flags |= flags::WAVE_OPS; let i32t = self.s.t.i32; - let split_ty = self - .s - .m - .named_struct("dx.types.splitdouble", vec![i32t, i32t]); - let arg = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); - let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); - let sum = self - .s - .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); - let mut r_lo = self.s.m.extract(c, split, 0); - let mut r_hi = self.s.m.extract(c, split, 1); + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // Steps within one host wave: the console wave's lanes, or 32 of them when two host + // waves of 32 exchange their halves for the last addition. + let steps = if self.exchange.is_some() || !self.x.native.wave64 { 5 } else { 6 }; + let mut sum = self.join64(lo, hi); + for step in 0..steps { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + // The lanes of the partner run that are here, from bit 0. + let upper = self.s.m.cmp(c, pred::IUGE, base, k32); + let word = self.s.m.select(c, upper, bhi, blo); + let at = self.s.m.bin(c, Bin::And, base, k31); + let shifted = self.s.m.bin(c, Bin::LShr, word, at); + let bits = if size >= 32 { + shifted + } else { + let mk = self.s.m.i32((1u32 << size) - 1); + self.s.m.bin(c, Bin::And, shifted, mk) + }; + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let (slo, shi) = self.split64(sum); + let tlo = self.read_lane(slo, from); + let thi = self.read_lane(shi, from); + let tlo = self.s.m.select(c, any, tlo, zero); + let thi = self.s.m.select(c, any, thi, zero); + let theirs = self.join64(tlo, thi); + sum = super::f64::add_f64(&mut Gen { l: self }, sum, theirs); + } + let (mut r_lo, mut r_hi) = self.split64(sum); if self.exchange.is_some() { if !self.all_lanes(self.cur_ir) { need(self.cur_ir); @@ -2101,19 +2137,10 @@ impl<'a> Lower<'a> { } let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); - let c = self.cur; - let d0 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); - let d1 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); - let total = self.s.m.bin(c, Bin::Add, d0, d1); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); - r_lo = self.s.m.extract(c, split, 0); - r_hi = self.s.m.extract(c, split, 1); + let d0 = self.join64(lo0, hi0); + let d1 = self.join64(lo1, hi1); + let total = super::f64::add_f64(&mut Gen { l: self }, d0, d1); + (r_lo, r_hi) = self.split64(total); } Ok(if high { r_hi } else { r_lo }) } diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 55cc55de..05d7f704 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -235,6 +235,23 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { words[1] = 0xBF88_0000 | (words.len() as u32 - 2); let native = native(&words); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + // BetterXen correction (research/shader-wave-semantics): this program is lowered for a host + // of 64-lane waves. A device whose waves are narrower cannot run that lowering: its lanes 32 + // and up do not exist, and the observed result was 0 instead of the tree. Such a device + // must be offered the lowering for its own width instead, which the recompiler refuses for + // this program ("a wave sum of 16-bit floats where not every lane runs"): the test then + // asserts that refusal, which is the correct behaviour, rather than reporting a failure + // or silently skipping. + if let Some(w) = Host::new(false).ok().and_then(|h| h.wave_lane_count_max()).filter(|&w| w < 64) { + let refused = lowered_on(&native, &p, &HashSet::new(), w); + assert!( + matches!(&refused, Err(ShaderError::Unsupported { what, .. }) if what.contains("16-bit floats where not every lane runs")), + "a {w}-lane device must be refused this program, got {:?}", + refused.as_ref().map(|_| "a shader") + ); + eprintln!("device waves are {w} lanes; refused for that width as expected; not run on the device"); + return; + } let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower"); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); diff --git a/docs/README.md b/docs/README.md index b899f991..cac8c102 100644 --- a/docs/README.md +++ b/docs/README.md @@ -69,6 +69,7 @@ checkpoints retain their original evidence scope. - [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior. - [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks. - [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified. +- [Shader wave-semantics investigation](research/shader-wave-semantics.md) — Why two upstream wave tests failed under D3DMetal: device capabilities, independent probes, the fix and its limits. - [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups. - [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only. - [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites. diff --git a/docs/licenses.md b/docs/licenses.md index cfee2557..ecb1b3d1 100644 --- a/docs/licenses.md +++ b/docs/licenses.md @@ -14,6 +14,7 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa | LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked | | victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md | | thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited | +| DirectX Shader Compiler | v1.9.2609, `dxc_2026_09_29.zip` (sha256 `ad31b1fc…a7e7f1`) | University of Illinois/NCSA plus MIT components (per its licence files) | External tool for compiling HLSL probes under CrossOver; not vendored, not distributed | | Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed | ## Runtime redistribution review diff --git a/docs/research/shader-wave-semantics.md b/docs/research/shader-wave-semantics.md new file mode 100644 index 00000000..caa7824a --- /dev/null +++ b/docs/research/shader-wave-semantics.md @@ -0,0 +1,61 @@ +# Shader wave-operation failures under D3DMetal: investigation + +Part of the shader integration PR (#394). It began as the separate investigation PR #392, whose content is carried here. Evidence class B (runs on one machine: Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, default backend), not independently reproduced. The two failures are the ones recorded in `victory-shader-integration.md`. This note separates what is **established** from what is **a hypothesis**. + +## Device capabilities (measured with BetterXen's own host, `workloads/d3d12-wave-probe/d3d12_run.c caps`) + +| Field | Value | +| --- | --- | +| Adapter reported | "AMD Compatibility Mode", vendor 0x1002, 18,186 MB (D3DMetal's reported identity; the hardware is the M4) | +| Device created at feature level | 12_1 | +| Highest shader model | 6.6 | +| `WaveOps` | supported | +| `WaveLaneCountMin` / `Max` | 32 / 32 (waves are exactly 32 lanes; `TotalLaneCount` 1024) | +| `DoublePrecisionFloatShaderOps` | **0** (no double-precision shader operations) | +| `Int64ShaderOps` | supported | +| Min-precision support | 0x2 (16-bit) | + +## Failure 2: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (established) + +**Cause: a wrong test precondition (a subgroup-size assumption), not a translation error.** + +1. The test lowers the program with `lowered_on(.., 64)`, "for a host of 64-lane waves (AMD)" per its own comment, then dispatches it on the default device without asking that device's wave width. +2. The device's waves are exactly 32 lanes (table above). A program written for 64-lane waves reads lanes 32 to 63, which do not exist; the observed result was `0x0` against the expected tree `0x5914`. +3. It is the only test in that file that lowers for 64 lanes (line 238); the sibling `a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit` lowers for 32 (line 160) and passes on the same device. +4. Lowering this same program for a 32-lane host does not produce a wrong shader: the recompiler refuses it with `Unsupported: a wave sum of 16-bit floats where not every lane runs`. So the recompiler already behaves correctly; it states a limit instead of emitting something wrong. +5. The expected value `0x5914` is derived on the host by integer 16-bit float arithmetic in the test itself, independent of the recompiler. + +**Correction made (test, not recompiler):** `Host::wave_lane_count_max()` (new, from `D3D12_OPTIONS1`), and the test now checks the device first. On a device narrower than 64 lanes it asserts the refusal above and returns, printing why; on a 64-lane device it runs the original hardware comparison unchanged. After the change the test passes on this device, and what it verifies there is "the recompiler refuses a 64-lane-only program for a 32-lane host", not "the sum is correct on the GPU". The correct-sum claim stays **unverified on 32-lane hardware** and has not been run on a 64-lane device. + +## Failure 1: `whole_wave_f64_sum_and_cvt_f32_f64` (established: unsupported double-precision operations in D3DMetal; fixed in the recompiler) + +Observed: a Wave32 program with 4 launched threads, each contributing 1.25, should store 5.0; it stored `0x00000000`. It is a Wave32 program on a 32-lane device, so wave width was never the cause. + +**Independent evidence** (Microsoft's DXC compiled original HLSL, BetterXen's own host dispatched it; expected values derived by hand before running; DXC v1.9.2609 digest-verified and run under CrossOver 26.3): + +| Probe (`workloads/d3d12-wave-probe/hlsl/`) | Expected | Observed | +| --- | --- | --- | +| `lanes4`: wave size and lane index, 4 threads | `0x2000`..`0x2003` (wave of 32) | exactly that | +| `sum_f32_4`: `WaveActiveSum(1.25f)`, 4 threads | `0x40a00000` in every lane | exactly that | +| `add_f64_4`: a plain `double` add (no wave operation) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** | +| `sum_f64_4`: `WaveActiveSum` over a `double` | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** | + +So wave operations, wave width and partial waves are fine on this device. Any shader that uses a `double` runs without effect: pipeline creation succeeds, the dispatch completes, and nothing is stored. That matches the capability record (`DoublePrecisionFloatShaderOps = 0`; Metal has no fp64). Upstream's test harness zero-fills its output buffer, which is why it saw `0` instead of the sentinel. **Conclusion:** the failure comes from unsupported double-precision operations in the backend, combined with the recompiler emitting a native `double` in one place (`active_f64_sum`) while using integer emulation everywhere else. It is not a mistranslation of the wave operation and not a wave-semantics problem. + +**Fix (recompiler, `active_f64_sum`):** the existing integer fp64 add (`add_f64`, checked upstream against the CPU's doubles) is reused to build the console's sum, which is the balanced tree over the lanes in their order. Each lane adds its partner run's partial sum, read through `waveReadLaneAt` from the first lane of that run that is present (found with a ballot, as `half_sum_present` already does for 16-bit sums), `+0.0` where none is, which is what a lane outside EXEC adds on the console. No `double` type is emitted and the doubles feature flag is no longer set. The same code covers the console wave64 on two host waves of 32 (an integer add for the last step). + +**Validation** (M4, CrossOver 26.3, default backend; one machine, not independently reproduced): +- Whole suite under CrossOver: **229 passed, 0 failed, 3 ignored** (was 224 passed, 2 failed). macOS: 179 + new tests pass (`cargo test -p victory-shader`). +- New test `f64_wave_sums_match_the_cpu_tree_bit_for_bit`: 24 cases (1, 4, 20 and 32 launched threads; six values including ones that round: 0.1, 123456.789, a value one ulp above 1.0, -3.75e10, 1e-300), comparing all 64 bits with a CPU model of the balanced tree using the CPU's own f64 additions and `+0.0` for lanes that are not launched. All 24 match. The model is independent of the recompiler. +- Negative controls: against the **original** lowering this GPU test fails (`got 0x0000000000000000, want 0x3ff4000000000000`) and the new `the_f64_wave_sum_is_lowered_without_native_doubles` test (the container's feature word must declare wave operations but not doubles) fails too; both pass with the fix. + +**Limits:** (1) the tree order is what the recompiler's recognizer claims the console program computes (`wave::buddies`); this was not independently simulated from the DPP instructions, so bit-for-bit fidelity to the console for rounding values is only as good as that recognition. (2) The cost of the integer version was not measured and no performance claim is made. (3) Other fp64 wave operations (products, min/max) were not examined; only this one site emitted native doubles. (4) On a device with real fp64 the old native operation would work and is no longer used. (5) DXC is an external tool (University of Illinois/NCSA licence plus MIT components per its licence files), used only to compile probes; nothing from it is in the repository. + +## Reproduce +```sh +scripts/hybrid/run-shader-gpu-tests.sh betterxen-test all # the runner script is in PR #395; or run the cross-built test executable with wine directly # expect: 0 failures with the fix in this branch (the vendored original has 2) +# probes: compile hlsl/*.hlsl with DXC under CrossOver, then d3d12_run.exe run .dxil 1 +# capabilities (needs the d3d12_run.exe built from workloads/d3d12-wave-probe/d3d12_run.c with llvm-mingw): +# x86_64-w64-mingw32-clang -O2 -o d3d12_run.exe d3d12_run.c -ld3d12 -ldxgi -ldxguid +# CrossOver bin/wine --bottle ./d3d12_run.exe caps +``` diff --git a/docs/research/victory-shader-integration.md b/docs/research/victory-shader-integration.md index cce4c233..480dac7f 100644 --- a/docs/research/victory-shader-integration.md +++ b/docs/research/victory-shader-integration.md @@ -24,23 +24,24 @@ Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game | BetterXen fixtures run on the GPU: D3D12 under CrossOver 26.3 (D3DMetal) | **6 of 6 output words match the manifest** | via `betterxen-hybrid run`, 2.3 to 2.6 s including bottle start; the GPU is a D3D12 device with shader model 6.6 as upstream's host layer requires | | Negative control | a flipped expected word is rejected; the output is not the zeroed buffer | `a_wrong_expectation_is_detected` | | Same GPU tests on DXMT, DXVK and wined3d (no D3D12) | fail with "no SM 6.6 D3D12 hardware device: not verified" | confirms they cannot pass by skipping; upstream's own tests print "skipped" instead | -| Whole suite under CrossOver (default backend), 229 tests including BetterXen's 4 | 224 passed, **2 failed**, 3 ignored | see below | +| Whole upstream suite, vendored unchanged, under CrossOver (default backend), 229 tests | 224 passed, **2 failed**, 3 ignored | the two failures are explained in `shader-wave-semantics.md` | +| Whole suite with the fixes in this PR, under CrossOver | **232 tests: 229 passed, 0 failed, 3 ignored** | the 3 additional tests are BetterXen's f64 tests; see below | | Upstream suite on a backend without D3D12 (DXMT) | 201 passed, 25 failed, 3 ignored | see the classification below | The two failures are `whole_wave_f64_sum_and_cvt_f32_f64` (a wave-wide fp64 sum returned 0, expected `0x40a00000`) and `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (64 lanes: got 0, expected `0x5914`). Both are cross-lane wave reductions of the console's 64-lane waves. Hypothesis, **not verified**: the host's waves are 32 lanes wide (Apple GPU) and D3DMetal does not honour the required wave size or wave operation semantics. The cause, and whether upstream passes them on a Windows GPU, were not investigated. ## Which tests actually executed on the GPU -The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each of the 229 tests was therefore run on both the default backend (D3D12 via D3DMetal) and DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. +The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each test was therefore run on the default backend (D3D12 via D3DMetal) and on DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. Final content of this PR (232 tests: 225 upstream, 7 BetterXen): | Group | Tests | | --- | --- | -| Executed on the D3D12 hardware device and passed | 30 (25 of them fail without D3D12; 5 pass only by skipping without it) | -| Executed on the D3D12 hardware device and failed | 2 (they "pass" without D3D12 by skipping, which hides the failure) | -| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 197, including 3 ignored | -| Total | 229 (225 upstream + 4 BetterXen; BetterXen's 2 GPU tests are among the 32 GPU-dependent) | +| Executed on the D3D12 hardware device and passed | **31** (26 of them fail without D3D12; 5 pass only by skipping there) | +| Executed on the D3D12 hardware device and failed | **0** | +| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 201, including 3 ignored | +| Total | 232 | -Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such. +For the vendored upstream code before the fixes in this PR the same method gave 229 tests: 32 GPU-dependent, 30 passed on the device and 2 failed (they "passed" without D3D12 by skipping, which hid the failures), see `shader-wave-semantics.md`. Three of the 31 are BetterXen's GPU tests (fixtures, negative control, bit-exact f64 sums). Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such. ## Limits diff --git a/workloads/d3d12-wave-probe/d3d12_run.c b/workloads/d3d12-wave-probe/d3d12_run.c new file mode 100644 index 00000000..d6d46c28 --- /dev/null +++ b/workloads/d3d12-wave-probe/d3d12_run.c @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original BetterXen workload (shader wave-semantics investigation): a minimal Direct3D 12 +// compute host that is independent of the vendored recompiler. +// +// d3d12_run.exe caps +// Prints the default adapter and the device capabilities relevant to wave operations. +// d3d12_run.exe run +// Creates a root signature with one root UAV (u0), a compute PSO from the DXIL file, +// fills a UAV buffer of dwords with 0xDEADBEEF, dispatches groups +// and prints every dword read back as `out 0x`. A dword that stays +// 0xDEADBEEF was never written. +// +// Status: `caps` and `run` have both been compiled and run under CrossOver 26.3 on the M4. +// Exit codes: 0 ran, 2 no device, 3 pipeline creation failed, 4 other D3D12 failure. +#define COBJMACROS +#include +#include +#include +#include +#include + +#define CK(x, what) do { HRESULT h_ = (x); if (FAILED(h_)) { \ + printf("FAIL %s hr=0x%08lx\n", what, (unsigned long)h_); return 4; } } while (0) + +static ID3D12Device *make_device(void) { + ID3D12Device *dev = NULL; + static const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0}; + for (unsigned i = 0; i < sizeof levels / sizeof *levels; i++) { + if (SUCCEEDED(D3D12CreateDevice(NULL, levels[i], &IID_ID3D12Device, (void **)&dev))) { + printf("device_created_at_feature_level=0x%x\n", (unsigned)levels[i]); + return dev; + } + } + return NULL; +} + +static int caps(void) { + ID3D12Device *dev = make_device(); + if (!dev) { printf("NO DEVICE\n"); return 2; } + LUID luid; dev->lpVtbl->GetAdapterLuid(dev, &luid); // (the C macro cannot return a struct) + IDXGIFactory4 *f = NULL; + if (SUCCEEDED(CreateDXGIFactory1(&IID_IDXGIFactory4, (void **)&f))) { + IDXGIAdapter1 *ad = NULL; + if (SUCCEEDED(IDXGIFactory4_EnumAdapterByLuid(f, luid, &IID_IDXGIAdapter1, (void **)&ad))) { + DXGI_ADAPTER_DESC1 d; IDXGIAdapter1_GetDesc1(ad, &d); + char n[128]; size_t i = 0; for (; d.Description[i] && i < 127; i++) n[i] = (char)d.Description[i]; n[i] = 0; + printf("adapter=%s vendor=0x%x device=0x%x vram_mb=%u shared_mb=%u\n", n, d.VendorId, d.DeviceId, + (unsigned)(d.DedicatedVideoMemory >> 20), (unsigned)(d.SharedSystemMemory >> 20)); + } + } + D3D12_FEATURE_DATA_SHADER_MODEL sm = {D3D_SHADER_MODEL_6_7}; + HRESULT h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm); + if (FAILED(h)) { sm.HighestShaderModel = D3D_SHADER_MODEL_6_6; h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm); } + printf("highest_shader_model=0x%x (query hr=0x%08lx)\n", (unsigned)sm.HighestShaderModel, (unsigned long)h); + D3D12_FEATURE_DATA_D3D12_OPTIONS o = {0}; + h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof o); + printf("options: hr=0x%08lx double_ops=%d min_precision=0x%x resource_binding_tier=%d\n", (unsigned long)h, o.DoublePrecisionFloatShaderOps, (unsigned)o.MinPrecisionSupport, (int)o.ResourceBindingTier); + D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1 = {0}; + h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof o1); + printf("options1: hr=0x%08lx wave_ops=%d wave_lane_count_min=%u wave_lane_count_max=%u total_lane_count=%u expanded_compute_resource_states=%d int64_shader_ops=%d\n", + (unsigned long)h, o1.WaveOps, o1.WaveLaneCountMin, o1.WaveLaneCountMax, o1.TotalLaneCount, o1.ExpandedComputeResourceStates, o1.Int64ShaderOps); + return 0; +} + +static int run(const char *path, unsigned groups, unsigned dwords) { + FILE *fp = fopen(path, "rb"); + if (!fp) { printf("FAIL open %s\n", path); return 4; } + fseek(fp, 0, SEEK_END); long n = ftell(fp); fseek(fp, 0, SEEK_SET); + void *code = malloc((size_t)n); + if (fread(code, 1, (size_t)n, fp) != (size_t)n) { printf("FAIL read\n"); return 4; } + fclose(fp); + ID3D12Device *dev = make_device(); + if (!dev) { printf("NO DEVICE\n"); return 2; } + + D3D12_ROOT_PARAMETER rp = {0}; + rp.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + rp.Descriptor.ShaderRegister = 0; + rp.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_ROOT_SIGNATURE_DESC rsd = {0}; + rsd.NumParameters = 1; rsd.pParameters = &rp; + ID3DBlob *blob = NULL, *err = NULL; + CK(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err), "serialize root signature"); + ID3D12RootSignature *rs = NULL; + CK(ID3D12Device_CreateRootSignature(dev, 0, ID3D10Blob_GetBufferPointer(blob), ID3D10Blob_GetBufferSize(blob), &IID_ID3D12RootSignature, (void **)&rs), "create root signature"); + + D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {0}; + pd.pRootSignature = rs; + pd.CS.pShaderBytecode = code; pd.CS.BytecodeLength = (SIZE_T)n; + ID3D12PipelineState *pso = NULL; + HRESULT h = ID3D12Device_CreateComputePipelineState(dev, &pd, &IID_ID3D12PipelineState, (void **)&pso); + if (FAILED(h)) { printf("PSO_FAILED hr=0x%08lx\n", (unsigned long)h); return 3; } + + UINT64 bytes = (UINT64)dwords * 4; + D3D12_HEAP_PROPERTIES hp_def = {0}, hp_up = {0}, hp_rb = {0}; + hp_def.Type = D3D12_HEAP_TYPE_DEFAULT; hp_up.Type = D3D12_HEAP_TYPE_UPLOAD; hp_rb.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC rd = {0}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; rd.Width = bytes; rd.Height = 1; rd.DepthOrArraySize = 1; rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_UNKNOWN; rd.SampleDesc.Count = 1; rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource *def, *up, *rb; + D3D12_RESOURCE_DESC rdu = rd; rdu.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + CK(ID3D12Device_CreateCommittedResource(dev, &hp_def, D3D12_HEAP_FLAG_NONE, &rdu, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&def), "create default"); + CK(ID3D12Device_CreateCommittedResource(dev, &hp_up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &IID_ID3D12Resource, (void **)&up), "create upload"); + CK(ID3D12Device_CreateCommittedResource(dev, &hp_rb, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&rb), "create readback"); + unsigned *p; CK(ID3D12Resource_Map(up, 0, NULL, (void **)&p), "map upload"); + for (unsigned i = 0; i < dwords; i++) p[i] = 0xDEADBEEFu; + ID3D12Resource_Unmap(up, 0, NULL); + + D3D12_COMMAND_QUEUE_DESC qd = {0}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + ID3D12CommandQueue *q; CK(ID3D12Device_CreateCommandQueue(dev, &qd, &IID_ID3D12CommandQueue, (void **)&q), "queue"); + ID3D12CommandAllocator *al; CK(ID3D12Device_CreateCommandAllocator(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator, (void **)&al), "allocator"); + ID3D12GraphicsCommandList *cl; CK(ID3D12Device_CreateCommandList(dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, al, pso, &IID_ID3D12GraphicsCommandList, (void **)&cl), "list"); + ID3D12GraphicsCommandList_CopyBufferRegion(cl, def, 0, up, 0, bytes); + D3D12_RESOURCE_BARRIER b = {0}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = def; b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b); + ID3D12GraphicsCommandList_SetComputeRootSignature(cl, rs); + ID3D12GraphicsCommandList_SetComputeRootUnorderedAccessView(cl, 0, ID3D12Resource_GetGPUVirtualAddress(def)); + ID3D12GraphicsCommandList_Dispatch(cl, groups, 1, 1); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b); + ID3D12GraphicsCommandList_CopyBufferRegion(cl, rb, 0, def, 0, bytes); + CK(ID3D12GraphicsCommandList_Close(cl), "close"); + ID3D12CommandList *lists[1] = {(ID3D12CommandList *)cl}; + ID3D12CommandQueue_ExecuteCommandLists(q, 1, lists); + ID3D12Fence *fence; CK(ID3D12Device_CreateFence(dev, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, (void **)&fence), "fence"); + HANDLE ev = CreateEventA(NULL, FALSE, FALSE, NULL); + CK(ID3D12CommandQueue_Signal(q, fence, 1), "signal"); + ID3D12Fence_SetEventOnCompletion(fence, 1, ev); + if (WaitForSingleObject(ev, 30000) != WAIT_OBJECT_0) { printf("FAIL timeout waiting for the GPU\n"); return 4; } + CK(ID3D12Resource_Map(rb, 0, NULL, (void **)&p), "map readback"); + for (unsigned i = 0; i < dwords; i++) printf("out %u 0x%08x\n", i, p[i]); + return 0; +} + +int main(int argc, char **argv) { + if (argc == 2 && !strcmp(argv[1], "caps")) return caps(); + if (argc == 5 && !strcmp(argv[1], "run")) return run(argv[2], (unsigned)atoi(argv[3]), (unsigned)atoi(argv[4])); + printf("usage: d3d12_run caps | run \n"); + return 1; +} diff --git a/workloads/d3d12-wave-probe/hlsl/README.md b/workloads/d3d12-wave-probe/hlsl/README.md new file mode 100644 index 00000000..aecc639a --- /dev/null +++ b/workloads/d3d12-wave-probe/hlsl/README.md @@ -0,0 +1,12 @@ +# Wave-semantics HLSL probes + +Original BetterXen sources, GPL-3.0-or-later. They are compiled with Microsoft's open-source DXC +(`dxc -T cs_6_6 -E main`; release v1.9.2609, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc...a7e7f1`, equal to +the release digest; an external tool, not vendored) and dispatched with `d3d12_run.exe run 1 ` +under CrossOver. Expected values were worked out by hand before running. Results and what they show: +`docs/research/shader-wave-semantics.md`. + +```sh +wine --bottle ./dxc.exe -T cs_6_6 -E main -Fo sum_f64_4.dxil sum_f64_4.hlsl # dxcompiler.dll and dxil.dll beside it +wine --bottle ./d3d12_run.exe run sum_f64_4.dxil 1 8 +``` diff --git a/workloads/d3d12-wave-probe/hlsl/add_f64_4.hlsl b/workloads/d3d12-wave-probe/hlsl/add_f64_4.hlsl new file mode 100644 index 00000000..75ffab7e --- /dev/null +++ b/workloads/d3d12-wave-probe/hlsl/add_f64_4.hlsl @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// No wave operation: a plain double addition 1.25 + 0.75 = 2.0 (0x4000000000000000), to separate +// "doubles unsupported" from "wave operations on doubles unsupported". +// Expected (by hand): low word 0x00000000, high word 0x40000000. +RWByteAddressBuffer o : register(u0); +[numthreads(4, 1, 1)] +void main(uint t : SV_GroupIndex) { + double a = 1.25, b = 0.75 + (double)(t - t); + double s = a + b; + uint lo, hi; + asuint(s, lo, hi); + o.Store2(t * 8, uint2(lo, hi)); +} diff --git a/workloads/d3d12-wave-probe/hlsl/lanes4.hlsl b/workloads/d3d12-wave-probe/hlsl/lanes4.hlsl new file mode 100644 index 00000000..7139f1bf --- /dev/null +++ b/workloads/d3d12-wave-probe/hlsl/lanes4.hlsl @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Expected (by hand): each launched thread t stores (laneCount << 8) | t, where laneCount is the +// device's wave width (32 per the capability record), so 0x2000, 0x2001, 0x2002, 0x2003. +RWByteAddressBuffer o : register(u0); +[numthreads(4, 1, 1)] +void main(uint t : SV_GroupIndex) { o.Store(t * 4, (WaveGetLaneCount() << 8) | WaveGetLaneIndex()); } diff --git a/workloads/d3d12-wave-probe/hlsl/sum_f32_4.hlsl b/workloads/d3d12-wave-probe/hlsl/sum_f32_4.hlsl new file mode 100644 index 00000000..ec9a792e --- /dev/null +++ b/workloads/d3d12-wave-probe/hlsl/sum_f32_4.hlsl @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Expected (by hand): 4 threads each add 1.25f, every launched lane reads 5.0 = 0x40a00000. +RWByteAddressBuffer o : register(u0); +[numthreads(4, 1, 1)] +void main(uint t : SV_GroupIndex) { o.Store(t * 4, asuint(WaveActiveSum(1.25f))); } diff --git a/workloads/d3d12-wave-probe/hlsl/sum_f64_4.hlsl b/workloads/d3d12-wave-probe/hlsl/sum_f64_4.hlsl new file mode 100644 index 00000000..bf49e307 --- /dev/null +++ b/workloads/d3d12-wave-probe/hlsl/sum_f64_4.hlsl @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Expected (by hand): 4 threads each add the double 1.25; the sum is 5.0, whose bit pattern is +// 0x4014000000000000, so each lane stores low word 0x00000000 and high word 0x40140000. +// The device reports DoublePrecisionFloatShaderOps = 0; this probe shows what actually happens. +RWByteAddressBuffer o : register(u0); +[numthreads(4, 1, 1)] +void main(uint t : SV_GroupIndex) { + double s = WaveActiveSum(1.25); + uint lo, hi; + asuint(s, lo, hi); + o.Store2(t * 8, uint2(lo, hi)); +}