Repository navigation
Recompiler: emit per-instruction globallycoherent on compute flat memory (stacked on #1850) - #2067
certified-retart wants to merge 2 commits into
Conversation
Ready-to-pick-up fixPackaged the verified per-lane repair and its regression as one commit: d8e7cfd, based directly on this PR's Full-workspace follow-up for the per-lane candidateCompleted the broader build/regression check for the small fix below. Both snapshots are Native Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74, Rust/Cargo 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug,
The candidate removes only the new coherence-routing failure. Both retain Both runs have the same 27 explicit All 322 source hashes in each snapshot matched before and after the Windows run and against the local patch; XCL recompiled for each. This supersedes the earlier “no full suite” limitation for this local candidate only. No AMD/native-wave64 execution, retail smoke, concurrent stale-read reproduction, or candidate performance claim. Earlier performance results farther below belong to the unchanged regular compiler, not this fix. The patch and failing-first test are ready for the author's consideration; the required clean-head/main retail gate remains outstanding. AI use: Codex (GPT-6) prepared the patch/test and performed and reported the native Windows validation. Follow-up: single-window per-lane shortcuts bypass the new coherence policyVerified a narrow integration gap on unchanged Small candidate below: a default no-op instruction-policy hook in Tested — native Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74, Rust/Cargo 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug:
Both runs emit the same 17 SKIPPED notices: 14 native-wave64 subcases unavailable on this adapter, and three existing refused wave32 per-lane subcases (f16 arithmetic, f16 packed, f32 conversions). The new regression does not skip. It lowers an actual synthetic compute program through This proves incorrect emitted handle routing and its repair; it does not reproduce a stale cross-thread read or a gameplay failure. Both 322-file source snapshots matched before/after on Windows and locally; XCL rebuilt for each. An earlier attempt failed to compile because my test read a private handle field; neither variant executed then. The final fixture uses existing module-inspection APIs and needs no visibility changes. Not tested — full workspace suite, retail smoke, AMD/native-wave64 hardware, concurrency stress, imported-memory alias visibility, or performance of this candidate. Earlier timing results below remain for unchanged AI use — Codex (GPT-6) identified the missed path, wrote the candidate/regression, ran and verified the native comparison and prepared this update. Candidate and regression against a03bc75diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs
index ca82cf4..7eae6d8 100644
--- a/crates/xcl/src/gpu/recomp/lower.rs
+++ b/crates/xcl/src/gpu/recomp/lower.rs
@@ -102,6 +102,8 @@ pub trait Ir: Sink {
/// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of
/// range reads 0 and writes nothing, as D3D12 raw buffers do
fn mem_load(&mut self, addr: Self::V) -> Self::V;
+ /// Memory policy for the single-window shortcuts of the instruction about to be lowered.
+ fn mem_instruction(&mut self, _d: &Decoded) {}
fn mem_store(&mut self, addr: Self::V, value: Self::V);
/// the 4 GiB memory windows the program addresses: with more than one, `mem_load` /
/// `mem_store` (window 0 only) are not used, and memory instructions go to `foreign`
@@ -1753,6 +1755,7 @@ impl<I: Ir> Lower<'_, I> {
/// Lowers one non-terminator instruction in block `b`, falling back to `bridge`.
fn lower_inst(&mut self, b: usize, d: &Decoded) -> R<()> {
+ self.ir.mem_instruction(d);
let name = d.inst.name;
let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") {
self.smem(b, d)
diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs
index 978dd74..8482c2c 100644
--- a/crates/xcl/src/gpu/recomp/lower_dxil.rs
+++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs
@@ -305,12 +305,16 @@ impl Ir for DxilIr {
let res = self.res.expect("res is bound in kernel mode");
self.lw.s.raw_store(res, a, &[value]);
}
+ fn mem_instruction(&mut self, d: &Decoded) {
+ self.lw.inst_coherent_load = self.lw.coherence == super::CoherenceMode::AllCoherent
+ || super::inst_has_mem_coherence_bits(d) || super::inst_is_flat_atomic(d);
+ }
fn mem_load(&mut self, addr: Value) -> Value {
- let mem = self.mem;
+ let mem = if self.lw.inst_coherent_load { self.lw.mems_coh.first().copied().unwrap_or(self.mem) } else { self.mem };
self.lw.s.raw_load(mem, addr, 1)[0]
}
fn mem_store(&mut self, addr: Value, value: Value) {
- let mem = self.mem;
+ let mem = self.lw.mems_coh.first().copied().unwrap_or(self.mem);
self.lw.s.raw_store(mem, addr, &[value]);
}
// through `Lw`, which records the edges for its own variables (the split form's exchange
@@ -428,6 +432,68 @@ mod tests {
use super::super::lower::tests::*;
use super::super::{dxc, runner, translate, Mode, Options};
+ /// The single-window shortcuts must preserve the same coherence policy as bridged ops.
+ #[test]
+ fn per_lane_memory_shortcuts_preserve_coherence() {
+ use crate::gpu::dxil::module::{Block, InstInfo};
+ let lines: &[I] = &[
+ ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]),
+ ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 5), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125), ("GLC", 1)]),
+ ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 6), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125), ("DLC", 1)]),
+ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]),
+ ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 0)]),
+ ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("SADDR", 0), ("GLC", 1)]),
+ ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 4), ("VSRC1", 2)]),
+ ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 5), ("VSRC1", 4)]),
+ ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 6), ("VSRC1", 4)]),
+ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 4), ("SADDR", 2)]),
+ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 3), ("SADDR", 2), ("OFFSET", 128)]),
+ ENDPGM,
+ ];
+ let insts = decode(lines);
+ let cs = crate::gpu::recomp::CsInterface { threads: [32, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 };
+ let initial = super::DxilIr::new(&insts, false, &super::Entry::Compute(cs.clone()));
+ let ir = super::lower::lower_compute(&insts, &cs, false, initial).unwrap();
+ let m = &ir.lw.s.m;
+ // Follow each emitted memory call through annotateHandle to its root-UAV register.
+ let binding = |handle| {
+ let super::Value::Inst(i) = handle else { panic!("handle is not an instruction") };
+ let InstInfo::Call(name, args) = m.inst_info(i) else { panic!("handle is not annotated") };
+ assert_eq!(name, "dx.op.annotateHandle");
+ let super::Value::Inst(i) = args[1] else { panic!("binding is not an instruction") };
+ let InstInfo::Call(name, args) = m.inst_info(i) else { panic!("missing binding") };
+ assert_eq!(name, "dx.op.createHandleFromBinding");
+ m.const_u64(args[2]).unwrap()
+ };
+ let mut counts = [0usize; 4]; // plain/coherent loads, plain/coherent stores
+ for b in 0..m.block_count() {
+ for &i in m.block_insts(Block(b as u32)) {
+ if let InstInfo::Call(name, args) = m.inst_info(i) {
+ let slot = if name.starts_with("dx.op.rawBufferLoad.") { 0 } else if name.starts_with("dx.op.rawBufferStore.") { 2 } else { continue };
+ if binding(args[1]) == 2 { counts[slot] += 1; }
+ if binding(args[1]) == 6 { counts[slot + 1] += 1; }
+ }
+ }
+ }
+ println!("PER_LANE_COHERENCE handles={counts:?}");
+ let dxil = ir.finish(cs.threads, 32).unwrap().dxil;
+ crate::gpu::dxil::validate::validate(&dxil).unwrap();
+ if gpu() {
+ println!("PER_LANE_COHERENCE_GPU={}", runner::adapter().unwrap());
+ let mut io = vec![0u32; super::super::KERNEL_SGPRS];
+ io[0] = 0x100; io[2] = 0x200;
+ let mut mem = vec![0u32; 0x400 / 4];
+ for lane in 0..32 { mem[0x100 / 4 + lane] = 100 + lane as u32; }
+ let out = runner::dispatch(&dxil, [1, 1, 1], &io, &mem).unwrap();
+ for lane in 0..32 {
+ assert_eq!(out[0x200 / 4 + lane], 403 + lane as u32);
+ assert_eq!(out[0x280 / 4 + lane], 100 + lane as u32);
+ }
+ println!("PER_LANE_COHERENCE_OUTPUT=64/64");
+ }
+ assert_eq!(counts, [2, 3, 0, 2], "GLC/DLC loads and all mixed-policy stores must use the coherent alias");
+ }
+
fn gpu() -> bool {
if !gpu_waves() {
runner::skip_test("no GPU with 32-lane waves");Independent RTX 3090 / Ampere results on exact Tested — Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74 (
The cost fixture uses actual console-ISA translation, a 1 MiB pointer chain in a 2 MiB
Timestamps exclude resource/PSO creation, uploads, readback, CPU waits and the barriers between dispatches. One process per policy, control then head, no clock control or randomized order. These are workload-specific measurements, not a predicted world-loading or frame-rate gain. Root and heap configurations select window 0; every window descriptor/alias points to the same imported allocation. Warm translation API cost was also recorded: one warm translation then three timed translations per path, byte-identical within each path/policy; explicit final validation is outside these timings. These debug samples do not establish a compilation-speed improvement:
All three source snapshots matched their 322-file SHA256 manifests before/after on Windows and locally; XCL recompiled for each. The host-memory runner override is Not tested — full workspace suite, retail smoke/world loading, AMD/native wave64, same-lane alias visibility specifically on imported host memory, cross-workgroup communication, distinct-window addresses, invalidation opcodes, cold driver compilation, or peak process memory. No merge-readiness claim. The tests below are offered as complementary regression/benchmark coverage for this PR. AI use — Codex (GPT-6) reviewed the code, wrote the synthetic fixtures/test seam, ran and verified the native comparisons and prepared this report. The coherence implementation is the PR author's. Same-lane alias regression (test only)diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 5ab82cd..cc537df 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -9278,3 +9278,58 @@ fn gpu_compute_coherent_and_cached_loads() {
}
}
}
+
+/// A lane must see its own stores and atomics through the ordinary-load alias.
+#[test]
+fn gpu_per_instruction_alias_reads_observe_own_writes() {
+ if !gpu_ready() { return; }
+ println!("ALIAS_GPU={}", runner::adapter().unwrap());
+ let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 10, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+ let mut p = Vec::new();
+ let mut add = |n: &str, e: &str, f: &[(&str, u64)]| p.extend(encode(n, e, f, None).unwrap());
+ add("S_LSHL_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 10), ("SSRC1", 133)]);
+ add("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 11), ("VSRC1", 0)]);
+ add("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 9)]);
+ add("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("SADDR", 0)]);
+ add("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 135), ("VSRC1", 3)]);
+ add("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 4), ("SADDR", 0)]);
+ add("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 1), ("SADDR", 0)]);
+ add("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]);
+ add("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 6), ("ADDR", 1), ("DATA", 8), ("SADDR", 0), ("GLC", 1)]);
+ add("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 7), ("ADDR", 1), ("SADDR", 0)]);
+ for (reg, base) in [(3, 2), (5, 4), (6, 6), (7, 8)] {
+ add("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", reg), ("SADDR", base)]);
+ }
+ add("S_ENDPGM", "ENC_SOPP", &[]);
+ let mut io = vec![0u32; super::KERNEL_SGPRS];
+ for (s, addr) in [(0, 0x400), (2, 0x1000), (4, 0x1400), (6, 0x1800), (8, 0x1c00)] { io[s] = addr; }
+ let mut input = vec![0xDEAD_BEEFu32; 0x2000 / 4];
+ for lane in 0..128 { input[0x400 / 4 + lane] = 1000 + lane as u32; }
+ let mut failures = Vec::new();
+ for heap in [false, true] {
+ for direct in [false, true] {
+ let start = std::time::Instant::now();
+ let dxil = if direct {
+ let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 2 | if heap { super::HEAP_WINDOWS } else { 0 }, sampler_base: 0 };
+ crate::gpu::dxil::kernel::translate_compute(&p, o, &cs).unwrap().dxil
+ } else {
+ let t = translate(&p, &Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: 2, heap_windows: heap, ..Default::default() }).unwrap();
+ assert!(t.complete(), "{:?}", t.unsupported_why);
+ super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()
+ };
+ let compile_ms = start.elapsed().as_secs_f64() * 1000.0;
+ crate::gpu::dxil::validate::validate(&dxil).unwrap();
+ let out = runner::dispatch(&dxil, [4, 1, 1], &io, &input).unwrap();
+ let mut wrong = [0usize; 5];
+ for (stage, (addr, delta)) in [(0x400 / 4, 8), (0x1000 / 4, 0), (0x1400 / 4, 7), (0x1800 / 4, 7), (0x1c00 / 4, 8)].into_iter().enumerate() {
+ for lane in 0..128 {
+ let expected = 1000 + lane as u32 + delta;
+ if out[addr + lane] != expected { wrong[stage] += 1; }
+ }
+ }
+ println!("ALIAS direct={direct} heap={heap} words=640 wrong={wrong:?} first={:?} dxil_bytes={} compile_ms={compile_ms:.3}", [out[0x400/4], out[0x1000/4], out[0x1400/4], out[0x1800/4], out[0x1c00/4]], dxil.len());
+ if wrong != [0; 5] { failures.push((direct, heap, wrong)); }
+ }
+ }
+ assert!(failures.is_empty(), "same-lane alias visibility: {failures:?}");
+}Translated host-memory cost fixture and test-only runner seamdiff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs
index da5e99b..6f99d47 100644
--- a/crates/xcl/src/gpu/recomp/runner.rs
+++ b/crates/xcl/src/gpu/recomp/runner.rs
@@ -1675,6 +1675,22 @@ fn dispatch_with(
std::ptr::copy_nonoverlapping(m.as_ptr(), (p as *mut u32).add(io.len()), m.len());
upload.Unmap(0, None);
let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?;
+ #[cfg(test)]
+ let mem_buf = if let Some(base) = HOST_PROBE.with(|p| p.get()) {
+ let dev3: ID3D12Device3 = dev.cast().map_err(e)?;
+ let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(e)?;
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: mem_bytes, Height: 1,
+ DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+ Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
+ ..Default::default()
+ };
+ let mut r: Option<ID3D12Resource> = None;
+ dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).map_err(e)?;
+ r.ok_or("host probe resource")?
+ } else { buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)? };
+ #[cfg(not(test))]
let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?;
let res_buf = buffer(dev, 256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?;
let readback = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?;
@@ -1763,3 +1779,27 @@ fn dispatch_with(
Ok((out, ms))
}
}
+
+#[cfg(test)]
+thread_local! { static HOST_PROBE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) }; }
+
+#[cfg(test)]
+pub fn dispatch_host_probe(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], reps: usize, arena: &crate::gpu::uma::Uma) -> Result<(Vec<u32>, Vec<f64>), String> {
+ assert!(mem.len() * 4 <= arena.window(0).1);
+ assert!(HOST_PROBE.with(|p| p.replace(Some(arena.window(0).0 as usize))).is_none());
+ struct Reset;
+ impl Drop for Reset { fn drop(&mut self) { HOST_PROBE.with(|p| p.set(None)); } }
+ let _reset = Reset;
+ let mut g = GPU.lock().unwrap();
+ let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?;
+ let pso: ID3D12PipelineState = unsafe {
+ gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+ pRootSignature: transmute_copy(&gpu.rs),
+ CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() },
+ ..Default::default()
+ })
+ }
+ .map_err(|x| format!("CreateComputePipelineState: {x}"))?;
+ dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true)
+}
+
diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 5ab82cd..caf0fcb 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -9278,3 +9278,67 @@ fn gpu_compute_coherent_and_cached_loads() {
}
}
}
+
+/// Translated dependent loads plus an atomic on real imported host memory.
+#[test]
+fn gpu_per_instruction_host_memory_cost() {
+ if !gpu_ready() { return; }
+ println!("HOST_GPU={}", runner::adapter().unwrap());
+ let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 8, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+ let p = prog(&[
+ ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 9), ("SSRC0", 8), ("SSRC1", 133)], None),
+ ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 9), ("VSRC1", 0)], None),
+ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)], None),
+ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 259)], None),
+ ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 1), ("SADDR", 0)], None),
+ ("S_SUB_U32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 6), ("SSRC1", 129)], None),
+ ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 6), ("SSRC1", 128)], None),
+ ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFB)], None),
+ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 2)], None),
+ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None),
+ ("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 3), ("DATA", 4), ("SADDR", 4), ("GLC", 1)], None),
+ ]);
+ let arena = crate::gpu::uma::Uma::with_windows(1, 2 << 20).unwrap();
+ let base = arena.window(0).0 as u64;
+ let mut io = vec![0u32; super::KERNEL_SGPRS];
+ for (s, offset) in [(0, 0u64), (2, 0x10_0000), (4, 0x11_0000)] {
+ let addr = base + offset;
+ io[s] = addr as u32;
+ io[s + 1] = (addr >> 32) as u32;
+ }
+ io[super::IO_UMA_BASE_HI] = (base >> 32) as u32;
+ io[6] = 512;
+ let mut mem = vec![0u32; (2 << 20) / 4];
+ for idx in 0..262144 { mem[idx] = (((idx + 65537) & 262143) * 4) as u32; }
+ for heap in [false, true] {
+ for direct in [false, true] {
+ let compile = || {
+ if direct {
+ let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 2 | if heap { super::HEAP_WINDOWS } else { 0 }, sampler_base: 0 };
+ crate::gpu::dxil::kernel::translate_compute(&p, o, &cs).unwrap().dxil
+ } else {
+ let t = translate(&p, &Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: 2, heap_windows: heap, ..Default::default() }).unwrap();
+ assert!(t.complete(), "{:?}", t.unsupported_why);
+ super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()
+ }
+ };
+ let dxil = compile();
+ crate::gpu::dxil::validate::validate(&dxil).unwrap();
+ let mut compile_ms = Vec::new();
+ for _ in 0..3 {
+ let t = std::time::Instant::now();
+ let again = compile();
+ compile_ms.push(t.elapsed().as_secs_f64() * 1000.0);
+ assert_eq!(again, dxil);
+ }
+ let (out, times) = runner::dispatch_host_probe(&dxil, [64, 1, 1], &io, &mem, 11, &arena).unwrap();
+ assert_eq!(&out[..262144], &mem[..262144], "input chain changed");
+ for lane in 0..2048 {
+ let want = (((lane + 512 * 65537) & 262143) * 4) as u32;
+ assert_eq!(out[0x10_0000 / 4 + lane], want, "heap={heap} direct={direct} lane={lane}");
+ assert_eq!(out[0x11_0000 / 4 + lane], 11, "atomic count lane={lane}");
+ }
+ println!("HOST direct={direct} heap={heap} output_words=4096 chain_words=262144 dxil_bytes={} compile_ms={compile_ms:?} gpu_ms={times:?}", dxil.len());
+ }
+ }
+}For the control only, replace |
|
Tested
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -Command "& 'L:/XclTooling/Invoke-ArcTest.ps1' -Test { & 'L:\XclTooling\pr1778-2e2ee55-20261125-020159\target\debug\build\xcl\97fdf2b9ff8e1482\out\xcl-97fdf2b9ff8e1482.exe' --exact gpu::recomp::tests::gpu_compute_coherent_and_cached_loads --nocapture --test-threads=1 }"
Not tested
AI use
|
|
A run with vkd3d-proton as the host D3D12. The DXIL goes through dxil-spirv and then the NVIDIA Vulkan driver, a different compiler from a native-Windows run: this PR's 3 new tests pass. Tested
Not tested
AI use
|
|
AMD RDNA4 run, which this PR lists as not tested (only an RTX 5070 so far; the other reports here are Intel / NVIDIA). Tested: pass, head
Not tested: RDNA2/3; dispatch timing. AI use: Claude Code (Claude Opus 5.5) ran the tests on this machine and wrote this report. |
What is in it
Follow-up stacked on #1850 (
ecc9723): instead of marking every memory access in an atomic- orGLC-containing compute shadergloballycoherent, split flat-memory accesses per instruction so ordinary loads (!GLC && !DLC && !SLC) stay L1-cached while coherent loads, stores, and atomics usegloballycoherentviews.Why this matters: #1850 removes
globallycoherentfrom compute shaders with no atomics/GLC/cache-inv (~77% of compute shaders), but the remaining ~23% that contain even a single atomic orGLCop still pay full L1 bypass on every ordinary SMEM/MUBUF/FLAT/GLOBAL/BVH load — which is especially costly onOpenExistingHeapFromAddresshost-memory windows. Measured on RTX 5070 against 1 MiBOpenExistingHeapFromAddresshost memory (64 groups × 32 threads, 512 dependent loads + 1InterlockedAdd):ResourceDescriptorHeaploads +globallycoherentatomic):13.51 ms → 0.23 ms(59.2× faster)u2loads +globallycoherent u6atomic on the same GPU VA):13.88 ms → 0.38 ms(36.6× faster)globallycoherentstores (512 stores/thread):0.157 msvs0.157 ms(0.0% overhead)plain Load → coherent Store → plain Load → coherent InterlockedAdd → plain Load):0/128stale readsChanges:
CoherenceMode(crates/xcl/src/gpu/recomp/mod.rs): replacesneeds_coherent_memwith a three-tier classification for compute shaders:None: no flat-memory atomics,GLC/DLC/SLC, or cache invalidations → plain (L1-cached) views only (same as Recompiler: emit globallycoherent on compute memory windows only when needed #1850).PerInstruction: flat-memory atomics and/orGLC/DLC/SLCops, no data-cache invalidation → ordinary loads (!GLC && !DLC && !SLC, including SMEM, MUBUF/MTBUF, FLAT/GLOBAL, and BVH traversal) use plain views;GLC/DLC/SLCloads, all stores (0% overhead, preserves write-through cross-workgroup visibility matching RDNA2 GL0), and all atomics (including CAS loads) usegloballycoherentviews.AllCoherent: program containsS_DCACHE_INV,S_GL1_INV,BUFFER_GL0_INV, orBUFFER_GL1_INV→ every memory access staysgloballycoherent(D3D12 has no L1-invalidate intrinsic for non-coherent UAVs).crates/xcl/src/gpu/recomp/emit.rs): inPerInstruction, declares plainmem..(u2..u5) + coherentmemc..(u6..u9) for root UAVs, or plainXCL_MW+ coherentXCL_MWCindexingResourceDescriptorHeap[MEM_HEAP_BASE + xcl_w]forXCL_HEAP_WINDOWS=1, with matchingxcl_loadx4/xcl_loadx4_c,ld_raw/ld_raw_c, andxcl_m*/xcl_mc*accessors.crates/xcl/src/gpu/dxil/kernel.rs,lower.rs,lower_mem.rs,recomp/lower_dxil.rs): allocates plainu2..and coherentu6..RawUavhandles for root-UAVPerInstruction, routes loads viainst_coherent_loadand stores/atomics viacoherence != None, and passes per-accesscoherenttoheap_raw_buffer_uav(i, coherent)forXCL_HEAP_WINDOWS=1.crates/xcl/src/gpu/recomp/pso.rs,runner.rs,hle/d3d12x/bind.rs,console_list.rs): extends the ABI root signature from 6 to 10 root UAVs (u0io,u1res,u2..u5plain windows,u6..u9coherent aliases; 20 DWORDs vs the 64-DWORD limit) and binds computeu6..u9to the same 4 memory-window GPU VAs asu2..u5.crates/xcl/src/gpu/recomp/tests.rs): updatescompute_globallycoherent_only_when_neededfor all three tiers, addscompute_per_instruction_globallycoherent(single-window, multi-window root UAV, multi-window heap, DXC SM 6.6 compile, and Direct DXILannotateHandle4107/20491validation), and extends real-GPUgpu_compute_coherent_and_cached_loadsto exercise mixed plain SMEM/GLOBAL loads + atomic + coherent store +GLC=1load across both HLSL and Direct DXIL.Tested
cargo test --workspace -- --test-threads=4:1,157 passed, 0 failed(on NVIDIA RTX 5070, Agility SDK v614, DXC/dxil1.9.2602.17).cargo test -p xcl --test console_dlls_e2e -- xbox_bvh_builder_builds --nocapture --test-threads=1withXCL_CONSOLE_LISTS=1,XCL_PROBE_BVH_GPU=1,XCL_PROBE_BVH_TLAS=1):XCL_HEAP_WINDOWS=1: TLAS 800/800 & BLAS 500/500 + 500/500 rays match brute force.Regression run
Matched 60 s
scripts/smoke.ps1runs on RTX 5070 (baseline binary built fromorigin/maincbc296a, PR binary built froma03bc75):Baseline (
origin/maincbc296a):PR (
a03bc75, default root UAVs):PR (
a03bc75, withXCL_HEAP_WINDOWS=1):Not tested
OpenExistingHeapFromAddressmicrobenchmark; cross-vendor world-load validation welcome.AI use
Written and verified with AI assistance. All code changes, unit/GPU tests, console BVH E2E runs, and matched 60 s smoke runs were executed and reviewed locally.