Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/xcl/src/gpu/dxil/geometry_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ fn geometry_forms_validate() {
}

/// The split form's ES phase meets its other half at a group barrier at every exchange (#1727's
/// pattern; the HLSL path spins): with the safe barrier wanted the direct translator leaves such
/// pattern; the HLSL path spins): unless `XCL_SAFE_BARRIER=0` the direct translator leaves such
/// a pass to the HLSL path. The GS alone (no partner) and the native wave64 form stay direct.
#[test]
fn split_geometry_with_an_es_phase_is_left_to_the_hlsl_path() {
if !crate::gpu::recomp::emit::safe_barrier_wanted() {
if crate::gpu::recomp::emit::safe_barrier_set_off() {
return;
}
let (code, g) = branchy_program();
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res
// and lane read meets at a group barrier, the pattern that hung NVIDIA GPUs (#1727). The
// HLSL path's exchange spins by default: such a pass is left to it (`XCL_SAFE_BARRIER=0`:
// as before). The GS alone runs in the lower half without a partner.
if o.split && g.gs_start != Some(0) && crate::gpu::recomp::emit::safe_barrier_wanted() {
if o.split && g.gs_start != Some(0) && !crate::gpu::recomp::emit::safe_barrier_set_off() {
return Err("split wave64 geometry: the ES phase exchanges at group barriers".into());
}
translate_geometry_unrefused(code, o, g)
Expand Down
4 changes: 2 additions & 2 deletions crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2842,7 +2842,7 @@ mod stage_guard_tests {

#[test]
fn geometry_export_rejected() {
let safe_barrier = crate::gpu::recomp::emit::safe_barrier_wanted();
let refused = !crate::gpu::recomp::emit::safe_barrier_set_off();
for en in [0xFu64, 0] {
let code = prog(&[("EXP", "ENC_EXP", &[("TGT", 0), ("EN", en), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)])]);
for gs_start in [Some(0), None] {
Expand All @@ -2851,7 +2851,7 @@ mod stage_guard_tests {
let err = kernel::translate_geometry(&code, opts(true, split), &gs)
.err()
.unwrap_or_else(|| panic!("geometry EXP en={en:#x} gs_start={gs_start:?} split={split} unexpectedly succeeded"));
let want = if split && gs_start != Some(0) && safe_barrier {
let want = if split && gs_start != Some(0) && refused {
"split wave64 geometry: the ES phase exchanges at group barriers"
} else {
"export target"
Expand Down
21 changes: 18 additions & 3 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6702,10 +6702,25 @@ uint2 xcl_x_ballot_local(bool b) {
uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); }
"#;

/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier
/// (`XCL_SAFE_BARRIER=0`: the plain group barrier, in both translators).
/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier, in both
/// translators: `XCL_SAFE_BARRIER=0` / `1` decides; by default yes, except on a Mac
/// (`util::mac_host`: D3DMetal). There the waves spinning in it starve the waves they wait for
/// (a 1024-thread group: a waiting wave's loop ran about 0.1 ms per iteration) until the spin
/// gives up and the barrier lets them read LDS too early (#258), while Metal's group barrier does
/// not wait for simdgroups that have exited (`gpu_safe_s_barrier_multi_warp_and_early_endpgm`
/// passes with it).
pub(crate) fn safe_barrier_wanted() -> bool {
std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0")
match std::env::var("XCL_SAFE_BARRIER") {
Ok(v) => v.trim() != "0",
Err(_) => !crate::util::mac_host(),
}
}

/// Whether `XCL_SAFE_BARRIER=0` is set. Only then does `dxil::kernel::translate_geometry` take the
/// split form's ES phase directly, on a Mac too: the Mac default of `safe_barrier_wanted` changes
/// the barrier, not that refusal.
pub(crate) fn safe_barrier_set_off() -> bool {
std::env::var("XCL_SAFE_BARRIER").is_ok_and(|v| v.trim() == "0")
}

/// Early-exit-safe, bounded workgroup barrier for multi-warp Compute / Mesh `s_barrier`.
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub(crate) fn compute_policy_key() -> ComputePolicyKey {
structured: std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none(),
precise_x64_masks: std::env::var_os("XCL_X64_ALL_MASKS").is_none(),
wave64_spin: std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0"),
safe_barrier: std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"),
safe_barrier: super::emit::safe_barrier_wanted(),
// The HLSL path can route enormous compute programs through the direct translator too.
direct_compact: crate::gpu::dxil::kernel::compact_mode(),
direct_compact_nest: crate::gpu::dxil::kernel::compact_nest_tag(),
Expand Down
55 changes: 53 additions & 2 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4489,7 +4489,7 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() {
// heap (the direct translator leaves this s_barrier of two console waves to the HLSL path)
let split = translate(&code, &Options { mode: Mode::Mesh(ms.clone()), wave64: true, split_wave64: true, mem_windows: super::HEAP_WINDOWS | 16, ..Default::default() }).unwrap();
assert!(split.complete(), "split, 16 heap windows: {:?}", split.unsupported_why);
if std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") {
if super::emit::safe_barrier_wanted() {
assert!(split.hlsl.contains("xcl_s_barrier();"), "split, 16 heap windows: expected xcl_s_barrier()");
}
if dxc::location().is_ok() {
Expand Down Expand Up @@ -11504,7 +11504,7 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() {
for wave64 in [true, false] {
let t = translate(&p_all, &on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() })).unwrap();
assert!(t.complete(), "wave64={wave64}: {:?}", t.unsupported_why);
if std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") {
if super::emit::safe_barrier_wanted() {
assert!(t.hlsl.contains("xcl_s_barrier();"), "wave64={wave64}: expected xcl_s_barrier()");
}
let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl));
Expand Down Expand Up @@ -11823,6 +11823,57 @@ fn gpu_qsad_and_mqsad() {
}
}

/// `s_barrier` in a 1024-thread group (32 hardware waves in the split form) waits for waves
/// still working: every wave runs 1000 `v_readfirstlane`s (exchanges between its halves),
/// writes its LDS word, and after the barrier reads the word of the farthest wave
/// (`tid ^ 1023`). On D3DMetal (#258) the waves spinning in `xcl_s_barrier` starved the ones
/// still in the loop until the spin gave up, and the barrier let them read too early.
#[test]
fn gpu_s_barrier_1024_threads_waits_for_working_waves() {
if !gpu_ready() {
return;
}
let p = prog(&[
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), // v1 = tid * 4
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 0)], Some(0x100)), // v6 = tid + 0x100
("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], Some(1023)), // v2 = tid ^ 1023
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), // v2 *= 4
("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], Some(1000)), // s10 = 1000
("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), // s12 = 0
("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V)], None), // v11 = tid
("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None), // loop: s10 == 0?
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 5)], None), // -> ds_write
("S_SUB_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 129), ("VSRC1", 11)], None),
("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 11)], None), // s11 = v11 of lane 0
("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 11)], None), // s12 += s11
("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None), // -> loop
("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None),
("S_BARRIER", "ENC_SOPP", &[], None),
("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None),
("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 4)], None), // v4 = partner's + 1
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 1)], None), // v7 = s0 + tid * 4
("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", 12)], None),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 7)], Some(4096)),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 15), ("SADDR", 0x7D)], None), // s12 after it
]);
let cs = super::CsInterface { threads: [1024, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 };
let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap();
assert!(t.complete(), "{:?}", t.unsupported_why);
let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl));
let base = 0x1000usize;
let out = runner::dispatch(&dxil, [1, 1, 1], &[base as u32, 0], &vec![0u32; (base + 2048 * 4) / 4]).unwrap();
let wrong: Vec<usize> = (0..1024).filter(|&tid| out[base / 4 + tid] != ((tid ^ 1023) + 0x101) as u32).collect();
assert!(wrong.is_empty(), "{} threads read their partner's LDS word before it was written (first: {:?})", wrong.len(), &wrong[..wrong.len().min(8)]);
for tid in 0..1024usize {
let cw = (tid / 64) as u32;
assert_eq!(out[base / 4 + 1024 + tid], 1000 * cw * 64 + 1000 * 1001 / 2, "tid={tid}: v_readfirstlane sum");
}
}

/// `XCL_SAMPLE_FSPX=<folder>`: every `*.bin` there that is an FSPX (driver) compute container –
/// e.g. the FSR4 pipelines XCL dumps to `<data>\shaders` – translates and compiles.
#[test]
Expand Down
44 changes: 44 additions & 0 deletions crates/xcl/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,36 @@ pub fn under_wine() -> bool {
})
}

/// The process runs under Wine on a Mac (ntdll's `wine_get_host_version` says Darwin): CrossOver
/// or the Game Porting Toolkit, where D3D12 is Apple's D3DMetal and, on Apple Silicon, the
/// title's code runs through Rosetta 2. Known from the start of the run, before there is a
/// device. `XCL_MAC_HOST=1` / `0` overrides the detection.
pub fn mac_host() -> bool {
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
static MAC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*MAC.get_or_init(|| {
let forced = std::env::var("XCL_MAC_HOST").ok();
// SAFETY: ntdll is always loaded; Wine's export fills two pointers to static strings.
let sysname = unsafe {
GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_host_version".as_ptr() as *const u8).and_then(|f| {
let f: unsafe extern "C" fn(*mut *const u8, *mut *const u8) = std::mem::transmute(f);
let (mut sysname, mut release) = (std::ptr::null(), std::ptr::null());
f(&mut sysname, &mut release);
from_cstr_ptr(sysname)
})
};
mac_host_from(forced.as_deref(), sysname.as_deref())
})
}

/// `mac_host`'s answer from `XCL_MAC_HOST` (`forced`) and the host's system name, if Wine gave one.
fn mac_host_from(forced: Option<&str>, sysname: Option<&str>) -> bool {
match forced {
Some(v) => v.trim() != "0",
None => sysname.is_some_and(|s| s.eq_ignore_ascii_case("Darwin")),
}
}

/// Normalised DLL key: lower-case file name, ".dll" appended when no extension.
pub fn dll_key(name: &str) -> String {
let base = name.rsplit(['\\', '/']).next().unwrap_or(name);
Expand Down Expand Up @@ -321,6 +351,20 @@ unsafe impl Sync for SendPtr {}
mod tests {
use super::*;

/// Darwin from Wine's host version is a Mac (in any case); Linux, Windows and no answer are
/// not; `XCL_MAC_HOST` decides when it is set, "0" for no and anything else for yes.
#[test]
fn a_mac_host_is_darwin_under_wine_unless_forced() {
assert!(mac_host_from(None, Some("Darwin")));
assert!(mac_host_from(None, Some("darwin")));
assert!(!mac_host_from(None, Some("Linux")));
assert!(!mac_host_from(None, None));
assert!(!mac_host_from(Some("0"), Some("Darwin")));
assert!(!mac_host_from(Some(" 0 "), Some("Darwin")));
assert!(mac_host_from(Some("1"), None));
assert!(mac_host_from(Some("1"), Some("Linux")));
}

#[test]
fn dll_keys() {
assert_eq!(dll_key("KERNELX"), "kernelx.dll");
Expand Down
Loading