Compare commits

..
18 changed files with 553 additions and 33 deletions

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- 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.
+2
View File
@@ -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.
+7
View File
@@ -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).
@@ -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<u32> = 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<u8> = 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<f64> = (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");
}
}
@@ -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)
}
+18
View File
@@ -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<u32> {
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::<D3D12_FEATURE_DATA_D3D12_OPTIONS1>() 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<Self, String> {
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
+58 -31
View File
@@ -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 })
}
@@ -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();
+1
View File
@@ -70,6 +70,7 @@ checkpoints retain their original evidence scope.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Upstream integration audit](research/upstream-integration-audit.md) — Source-level review of external macOS compatibility projects, licence and provenance decisions, and what was implemented in `crates/hybrid`.
- [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 fail under D3DMetal: device capabilities, what is established and what is not.
- [CrossOver baseline](research/crossover-baseline-2026-11-25.md) — First executions of original workloads under CrossOver 26.3 on the M4, backend comparison and its limits.
- [Windows cross-toolchain](research/hybrid-toolchain.md) — Pinned llvm-mingw release, how original Windows workloads are built, and what was and was not executed.
- [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.
+1
View File
@@ -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
+61
View File
@@ -0,0 +1,61 @@
# Shader wave-operation failures under D3DMetal: investigation
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`)
| 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 <llvm-mingw-dir> 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 <file>.dxil 1 <dwords>
# 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 <bottle> ./d3d12_run.exe caps
```
+20 -2
View File
@@ -21,8 +21,26 @@ rustup run 1.100.0 cargo build -q -p betterxen-hybrid
export PATH="$TC/bin:$PATH"
export CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER="$TC/bin/x86_64-w64-mingw32-clang"
export CARGO_TARGET_DIR="$ROOT/artifacts/victory-win"
rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run
EXE=$(ls -t "$CARGO_TARGET_DIR"/x86_64-pc-windows-gnullvm/debug/build/victory-shader/*/out/victory_shader-*.exe | head -1)
# Build the Windows test executable and take its path from cargo's own build message. It normally
# lands in <target>/x86_64-pc-windows-gnullvm/debug/deps/, but cargo's layout can differ with the
# build configuration, so the path is not guessed; `deps/` is only the fallback.
EXE=$(rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run \
--message-format=json | python3 -I -c '
import json, sys
exe = None
for line in sys.stdin:
try:
m = json.loads(line)
except ValueError:
continue
if m.get("reason") == "compiler-artifact" and m.get("profile", {}).get("test") \
and m.get("target", {}).get("name") in ("victory_shader", "victory-shader") and m.get("executable"):
exe = m["executable"]
print(exe or "")')
if [ -z "$EXE" ]; then
EXE=$(ls -t "$CARGO_TARGET_DIR"/x86_64-pc-windows-gnullvm/debug/deps/victory_shader-*.exe 2>/dev/null | head -1)
fi
[ -n "$EXE" ] && [ -f "$EXE" ] || { echo "could not find the victory-shader test executable" >&2; exit 1; }
file "$EXE" | grep -q "PE32+ executable.*x86-64" || { echo "not an x86-64 PE: $EXE" >&2; exit 1; }
B="$ROOT/target/debug/betterxen-hybrid"
if [ "$WHICH" = all ]; then
+143
View File
@@ -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 <shader.dxil> <groups_x> <out_dwords>
// Creates a root signature with one root UAV (u0), a compute PSO from the DXIL file,
// fills a UAV buffer of <out_dwords> dwords with 0xDEADBEEF, dispatches <groups_x> groups
// and prints every dword read back as `out <index> 0x<hex>`. 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 <d3d12.h>
#include <dxgi1_4.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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 <shader.dxil> <groups_x> <out_dwords>\n");
return 1;
}
+12
View File
@@ -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 <shader.dxil> 1 <dwords>`
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 <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 <bottle> ./d3d12_run.exe run sum_f64_4.dxil 1 8
```
@@ -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));
}
@@ -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()); }
@@ -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))); }
@@ -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));
}