From 219a9756a3f19b49e78864216a417794a44b4531 Mon Sep 17 00:00:00 2001 From: Arths17 Date: Wed, 25 Nov 2026 16:12:59 -0600 Subject: [PATCH] Fix the f64 wave sum for hosts without fp64: use the integer add, with independent DXC probes, a bit-exact GPU test and negative controls --- CHANGELOG.md | 2 +- THIRD_PARTY_NOTICES.md | 2 + crates/victory-shader/UPSTREAM.md | 7 + .../src/emit/betterxen_tests.rs | 174 ++++++++++++++++++ crates/victory-shader/src/emit/bitcode.rs | 2 + crates/victory-shader/src/emit/lower.rs | 89 +++++---- docs/licenses.md | 1 + docs/research/shader-wave-semantics.md | 32 +++- workloads/d3d12-wave-probe/d3d12_run.c | 3 +- workloads/d3d12-wave-probe/hlsl/README.md | 17 +- 10 files changed, 279 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a815d31..ad8be16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added -- Investigated the two wave-operation failures of the vendored victory-shader tests under D3DMetal (`docs/research/shader-wave-semantics.md`). Measured device capabilities with a new original D3D12 host (`workloads/d3d12-wave-probe/d3d12_run.c caps`): shader model 6.6, wave operations supported, waves exactly 32 lanes, no double-precision shader operations. Established the cause of `a_sum_of_halves_where_lanes_have_left_...`: the test lowers for 64-lane hosts and runs on the 32-lane device, and the recompiler already refuses that program for 32 lanes; the test now checks the device's wave width (`Host::wave_lane_count_max`) and asserts that refusal. `whole_wave_f64_sum_and_cvt_f32_f64` remains failing: the PR's wave-width explanation does not apply (it is a Wave32 program); the one native-double site in the recompiler and the missing double support are consistent with the cause but unproven, because an independent compiler run was not authorized. HLSL probe sources are committed uncompiled. Local, not independently reproduced. +- Investigated and resolved the two wave-operation failures of the vendored victory-shader tests under D3DMetal (`docs/research/shader-wave-semantics.md`). Measured device capabilities with a new original D3D12 host (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 caused by unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` (a plain add, or a wave sum) ran without writing anything, while wave operations on floats 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, 3 ignored; was 224 passed and 2 failed); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both new tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer. - 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 run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) 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 (wave-wide reductions), 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 `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed. - Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 1a65ef2..1acea04 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -19,3 +19,5 @@ The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependenc llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied. `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 9c89345..37c6836 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 c1aa5e8..14357a6 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 eff0ac0..8638a41 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/lower.rs b/crates/victory-shader/src/emit/lower.rs index bd35832..32ca9b5 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/docs/licenses.md b/docs/licenses.md index 8383fb7..05988e1 100644 --- a/docs/licenses.md +++ b/docs/licenses.md @@ -15,6 +15,7 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa | llvm-mingw | 20261117 (sha256 `98d340bb…446aa`) | Apache-2.0 WITH LLVM-exception, plus component licences in its LICENSE.TXT (mingw-w64 runtime and headers have their own terms; not audited line by line) | External build tool for original Windows test programs, not linked, not distributed | | 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 index 1e5dfbc..6a3a767 100644 --- a/docs/research/shader-wave-semantics.md +++ b/docs/research/shader-wave-semantics.md @@ -1,6 +1,6 @@ # Shader wave-operation failures under D3DMetal: investigation -Branch `research/shader-wave-semantics`, based on PR #391. 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**. +Branch `research/shader-wave-semantics` (PR #392), based on the shader integration branch. 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`) @@ -27,22 +27,34 @@ Branch `research/shader-wave-semantics`, based on PR #391. Evidence class B (run **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` (hypothesis, not yet proven) +## 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 (`0x40a00000` as f32); it stores `0x00000000`. The program is Wave32 on a 32-lane device, so **the wave-width hypothesis from the PR does not apply to this test**. +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. -What is established from the source and the capability record: -- The recompiler emits native `double` DXIL in exactly one place: `active_f64_sum` (`makeDouble`, `waveActiveOp.f64` with opcode 119, `splitDouble`; sets the shader's "doubles" flag). Every other fp64 instruction uses upstream's integer emulation (`emit/f64.rs`), which upstream states exists because "the host (D3DMetal, Metal) has no fp64"; those tests pass here. -- The device reports `DoublePrecisionFloatShaderOps = 0`. -- D3DMetal nevertheless created the pipeline and ran it, returning zero rather than failing. +**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): -Hypothesis consistent with all of that: native double operations in DXIL are not honoured by D3DMetal on this hardware, and the one native-double site in the recompiler is therefore wrong for this backend; the recompiler should use its own integer f64 add for the cross-lane reduction as it does everywhere else. **Not yet established**, because every run so far went through the recompiler itself. Independent evidence needs a native-double shader from a different compiler (`hlsl/sum_f64_4.hlsl`, `hlsl/add_f64_4.hlsl`: a double sum across lanes and a plain double add, to separate "doubles" from "wave operations on doubles"), plus `hlsl/sum_f32_4.hlsl` and `hlsl/lanes4.hlsl` as controls. These need Microsoft's DXC (open source, GitHub release v1.9.2609, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc…a7e7f1`, matching the release digest) run under CrossOver to compile them. That step has not been done: the permission system blocked running the downloaded compiler and it was not retried. The sources are committed and marked not compiled or run. +| 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** | -No recompiler change is proposed for failure 1 until that evidence exists. +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 # expect: 1 failure (whole_wave_f64_sum_and_cvt_f32_f64) +scripts/hybrid/run-shader-gpu-tests.sh betterxen-test all # 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/workloads/d3d12-wave-probe/d3d12_run.c b/workloads/d3d12-wave-probe/d3d12_run.c index d1ec496..d6d46c2 100644 --- a/workloads/d3d12-wave-probe/d3d12_run.c +++ b/workloads/d3d12-wave-probe/d3d12_run.c @@ -10,8 +10,7 @@ // and prints every dword read back as `out 0x`. A dword that stays // 0xDEADBEEF was never written. // -// Status: `caps` has been compiled and run under CrossOver 26.3 on the M4. `run` has been -// compiled only; it has not been executed yet. +// 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 diff --git a/workloads/d3d12-wave-probe/hlsl/README.md b/workloads/d3d12-wave-probe/hlsl/README.md index f19074b..aecc639 100644 --- a/workloads/d3d12-wave-probe/hlsl/README.md +++ b/workloads/d3d12-wave-probe/hlsl/README.md @@ -1,7 +1,12 @@ -# Wave-semantics HLSL probes (NOT YET COMPILED OR RUN) +# Wave-semantics HLSL probes -Original BetterXen sources, GPL-3.0-or-later. They are meant to be compiled with Microsoft's -open-source DXC (`dxc -T cs_6_6 -E main`) and dispatched with `d3d12_run.exe run`. Neither step has -been done: running the downloaded DXC under CrossOver was not authorized in the session that wrote -them, and `d3d12_run.exe run` has only been compiled, not executed (`caps` has been run). -Expected values are worked out by hand from the HLSL specification and listed in each file. +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 +```