Skip to content

recomp: memory window from the full address, carry in 32 bits (#123 again) - #138

Open
gefydev wants to merge 1 commit into
ivall:mainfrom
gefydev:recomp-window-carry-32
Open

gefydev wants to merge 1 commit into
ivall:mainfrom
gefydev:recomp-window-carry-32

Conversation

@gefydev

@gefydev gefydev commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

#123 was reverted in 70f8dc4: AMD's shader compiler crashed on XDefiant's CS 8e4af296b9d7fd9c. This PR is a second try, in the form suggested there: a 32-bit carry compare instead of uint64_t.

The problem it fixes is the same. With several memory windows, smem, MUBUF and FLAT / global picked the window from the base's high dword before adding the offsets. So an offset that carried out of the low dword went to the base's window at the wrapped address.

What changed from #123:

  • window_at adds the low dword and the offsets in 32 bits and counts the carries with one compare per term: xcl_ws += t; xcl_wc += (uint)(xcl_ws < t);.
  • A negative constant offset (SMEM / global) subtracts a borrow instead.
  • Zero terms are skipped.
  • No 64-bit integers anywhere on that path. The V# stride * index product is now 32-bit, so it no longer catches a product above 4 GiB.

For example, a global load with SADDR emits:

{ uint xcl_ws = s16, xcl_wc = 0u, xcl_wt; xcl_wt = v1; xcl_ws += xcl_wt; xcl_wc += (uint)(xcl_ws < xcl_wt); xcl_w = ((s17) + xcl_wc) & 3u; }

As in #123, with one window it emits nothing, so the single-window HLSL and its DXIL cache are unchanged; gpu_memory_windows_above_4_gib checks that.

Test gpu_memory_window_carry (from #123): the base sits at 0xFFFF_F000 of window 0, and s_load, s_buffer_load, buffer load / store, global load with SADDR and a global atomic each reach window 1. It now also checks that the xcl_w = lines contain no 64-bit arithmetic. Without the emit change it fails; with it, it passes on a GTX 1650 under Wine, and so do the other lib tests that run there.

I can't run XDefiant or an AMD GPU here, so whether this shape avoids the amdxc64.dll crash needs your RX 9070 check. If it still crashes, the next step would be your other suggestion: emit the carry only where an offset can actually cross the dword.

ivall#123 again (reverted in 70f8dc4): with several memory windows, smem, MUBUF
and FLAT / global picked the window from the base's high dword before the
offsets were added, so an offset that carried out of the low dword went to
the base's window at the wrapped address.

ivall#123 summed the address in uint64_t at every access, and the AMD shader
compiler crashed on that in XDefiant (CS 8e4af296b9d7fd9c). window_at now
adds the terms in 32 bits and counts the carries with a compare per term
(a borrow for a negative constant offset); no 64-bit integers. With one
window it emits nothing, so the single-window HLSL is unchanged.

Test gpu_memory_window_carry, now also checking that the window lines have
no 64-bit arithmetic.
@tronLives111

Copy link
Copy Markdown

One remaining carry case in b7177b1: buffer_window passes stride * index to window_at as a single HLSL uint. The multiplication can already have discarded its high word before window_at counts the carries from addition. AMD’s RDNA 2 ISA guide §8.1.1 adds Stride * Vindex to the full linear buffer address.

For a synthetic, in-range structured buffer, take base 0:0x4000, stride 16, index 0x10000001, and NumRecords = 0x10000002, with both byte offsets zero. The product is 1:0x10, so the full address is 1:0x4010. The emitted arithmetic keeps the same low word but selects 0:0x4010. This is separate from the offset-addition carries already covered by gpu_memory_window_carry.

The emitter already has mul_hi_u32. Adding its result to the window’s high word alongside the existing addition carry would keep this path 32-bit. I checked that arithmetic against a full-width integer oracle for 100,000 stride/index/base-low combinations. This was a CPU arithmetic check and source review, with no DXC or GPU run. AI-assisted review.

AMD RDNA 2 ISA guide, §8.1

@WarmMilkCodes

Copy link
Copy Markdown
Contributor

Tested #138 b7177b1 merged onto main 956a476 on AMD Radeon RX 6600 XT (RDNA2), driver 32.0.21045.29003, Windows 11 23H2 (22631.6199): pass

cargo test --workspace --no-fail-fast -- --test-threads=4, no XCL_SAMPLE_* data:

main this
passed 568 569
failed 1 1
GPU tests skipped 0 0

No new failures vs main. The PR's new test passes on RDNA2. The one failure on both, gpu_wave64_ps_whole_wave_reductions, is the 32-lane PS case on this card (#155).

@RemingtonWilcox

Copy link
Copy Markdown
Contributor

Read: gpu/recomp/emit.rs (window_at, flat_window, flat) at b7177b1, and emit.rs / tests.rs on main.
global_load_dword_addtid / global_store_dword_addtid reach flat_window(global, saddr, f("ADDR"), off) at emit.rs:3681, and with a real SADDR flat_window adds self.vreg(addr) as a carry term (emit.rs:1551). Those forms have no ADDR operand: the address is SADDR + 4 * lane_id + OFFSET, and main's global_dword_addtid_address_is_saddr_plus_4_per_lane asserts the ADDR bits are never read as a VGPR.
So with more than one memory window the carry comes from an unrelated register and can select the wrong window. That register also lands in vgprs. Passing 4u * lane_id as the term for the addtid forms would fix it.

AI-assisted review (Gemini + Claude); code read only, not run.

@ivall

ivall commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Not merged in this round on purpose: it changes the HLSL of every multi-window program, so the next run of a title recompiles all of its shaders, and I wanted the other merges checked on a warm cache first. It is next. Could you rebase on main (6da33fa)?

@Kalmarv

Kalmarv commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The carry fix holds where lanes disagree: one load whose even lanes stay in window 0 and odd lanes carry into window 1 (4 GiB apart) reads 17 / 31 with this PR in all 64 lanes, and 17 / 23 on main (the carry lost). Same on the merge with main 6da33fa.

Tested

A single translated GLOBAL_LOAD_DWORD selected different windows for adjacent lanes on Blackwell. I used two 1 MiB windows 4 GiB apart, SADDR low word 0x1004, and signed instruction offset −4. Even lanes supplied VGPR offset 0 and loaded 17 from window 0 at 0x1000. Odd lanes supplied 0xfffffffc and should load 31 from window 1 at 0xffc. Window 0 held 23 at that same offset to distinguish a lost carry from a wrong low address.

Probe Main 6da33fa + tests #138 b7177b1 Merged onto main e263903
PR carry test, first scalar pair (0, 0) (0xc0ffee, 0x1234) Same
Alternating lanes, expected 17 / 31 17 / 23 17 / 31 across all 64 lanes Same

RTX 5070 Ti, 610.74, Windows x64, native D3D12. Built with cargo test -p xcl --lib --no-run -j 2 and ran gpu::recomp:: --test-threads=1. Direct head passed 165 module tests, plus the mixed-lane probe separately. The merge passed 173 including that probe, with 18 ignored. The shared main control passed 171 and failed both #138 tests and three carried #202 tests. The original 956a476 control also returned 17 / 23.

Not tested

Retail shaders, AMD, native wave64, ADDTID, or stride-product overflow. The mixed-lane case used the split wave64 implementation on 32-lane hardware.

AI use — Codex, GPT-6.2 Astra.

@srcamarda

Copy link
Copy Markdown

RDNA3 run plus the two open review points (@tronLives111's stride * index, @RemingtonWilcox's *_addtid), on RX 7800 XT, driver 32.0.32029.2010, Windows 11 26300, native 64-lane waves, debug build.

Rebase: b7177b1 onto main 0f34407 has one conflict in tests.rs, where gpu_uma_import_check_at_init and gpu_memory_window_carry were added at the same spot. Keeping both resolves it.

The two points, fixed in 32 bits

  • buffer_window: the window's high dword gets + mul_hi_u32(stride, index) next to the carries, so a structured buffer past 4 GiB of records moves to the next window. The low word stays the wrapping 32-bit product. Nothing changes without IDXEN (index is 0u).
  • flat_window: addr is now Option<u64>, and the *_addtid call passes None. The terms are then SADDR + 4u * lane_id, or 0u : 4u * lane_id with a null SADDR. The ADDR field's VGPR is no longer read (or registered).

Patch below (on the rebased commit). The HLSL changes only for multi-window programs with an indexed MUBUF access or an addtid access.

New GPU test: gpu_memory_window_stride_product_and_addtid

Two 1 MiB windows 4 GiB apart. Each wrong window holds a sentinel.

  • buffer_load_dword with IDXEN: base 0:0x4000, stride 16, index 0x1000_0001, num_records 0x1000_0002 → 1:0x4010 (tronLives111's example). All 64 lanes read window 1's value.
  • global_load_dword_addtid, SADDR 0xFFFF_FF80, v0 = 0: lanes 32..63 carry into window 1. EXEC is set to lanes 32..63 for this load. Lanes 0..31 would read the top of window 0, which the arena doesn't map, and that removed the device here (0x887A0006) and took the next tests down with it.
  • The HLSL checks (mul_hi_u32( and 4u * lane_id in the xcl_w = lines, no 64-bit integers) come first.

Checked by sabotage. Without the emit.rs change, the HLSL check fails. With the HLSL checks disabled, the GPU check reads 0xBAD0 (the stride sentinel in window 0). With only the addtid call reverted, lane 32 reads 0xBAD1 (the addtid sentinel).

Results (rebased + patch)

  • cargo test -p xcl --lib -- --test-threads=4: 613 passed, 0 failed, 20 ignored
  • XCL_SPLIT_WAVE64=1: 613 passed, 0 failed
  • gpu_memory_window_carry, gpu_memory_windows_above_4_gib, gpu_mesh_mode_reads_memory_windows, gpu_bvh64_intersect_ray_across_memory_windows_and_grazing, and the addtid tests: pass

Not tested: XDefiant (the amdxc64 crash from #123), retail packs, NVIDIA, RDNA2.

Patch on b7177b1 rebased onto 0f34407 (git apply)
diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs
index 4b85902..9be7454 100644
--- a/crates/xcl/src/gpu/recomp/emit.rs
+++ b/crates/xcl/src/gpu/recomp/emit.rs
@@ -1563,22 +1563,28 @@ impl Em {
     }
 
     /// `window_at` for a FLAT / global address: the SADDR pair plus the VGPR offset (global
-    /// with SADDR) or the 64-bit VGPR address, plus the signed instruction offset.
-    fn flat_window(&mut self, global: bool, saddr: u64, addr: u64, off: u32) {
+    /// with SADDR) or the 64-bit VGPR address, plus the signed instruction offset. The
+    /// `*_addtid` forms have no ADDR operand: SADDR (0 when off) plus 4 · lane.
+    fn flat_window(&mut self, global: bool, saddr: u64, addr: Option<u64>, off: u32) {
         if self.opt.mem_windows > 1 {
-            let (hi, terms) = if global && saddr != 0x7D && saddr != 0x7F {
-                (self.sreg(saddr + 1), vec![self.sreg(saddr), self.vreg(addr)])
-            } else {
-                (self.vreg(addr + 1), vec![self.vreg(addr)])
+            let with_saddr = global && saddr != 0x7D && saddr != 0x7F;
+            let (hi, terms) = match (addr, with_saddr) {
+                (Some(addr), true) => (self.sreg(saddr + 1), vec![self.sreg(saddr), self.vreg(addr)]),
+                (Some(addr), false) => (self.vreg(addr + 1), vec![self.vreg(addr)]),
+                (None, true) => (self.sreg(saddr + 1), vec![self.sreg(saddr), "4u * lane_id".to_string()]),
+                (None, false) => ("0u".to_string(), vec!["4u * lane_id".to_string()]),
             };
             self.window_at(&hi, &terms, Some(off));
         }
     }
 
     /// `window_at` for a MUBUF address: V# base + SOFFSET + `{t}_off` + `{t}_stride` · index.
+    /// The product's high word moves the address too (a structured buffer past 4 GiB of
+    /// records): it goes into the high dword next to the carries (`mul_hi_u32`, 32-bit only).
     fn buffer_window(&mut self, d0: &str, d1: &str, soff: &str, t: &str, index: &str) {
         let terms = [d0.to_string(), soff.to_string(), format!("{t}_off"), format!("{t}_stride * ({index})")];
-        self.window_at(d1, &terms, None);
+        let hi = if index == "0u" { d1.to_string() } else { format!("{d1} + mul_hi_u32({t}_stride, {index})") };
+        self.window_at(&hi, &terms, None);
     }
 
     /// The sampler of the MIMG instruction at `pc`: a static sampler when its S# is constant
@@ -3687,7 +3693,7 @@ impl Em {
             let base = if global && saddr != 0x7D && saddr != 0x7F { format!("{} + {addr}", self.sreg(saddr)) } else { addr };
             let raw = f("OFFSET") as u32;
             let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw };
-            self.flat_window(global, saddr, f("ADDR"), off);
+            self.flat_window(global, saddr, Some(f("ADDR")), off);
             let t = self.t();
             self.line(&format!("uint {t}_a = {base} + {};", hex(off)));
             let act = self.act();
@@ -3733,7 +3739,7 @@ impl Em {
         };
         let raw = f("OFFSET") as u32;
         let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw };
-        self.flat_window(global, saddr, f("ADDR"), off);
+        self.flat_window(global, saddr, Some(f("ADDR")).filter(|_| !op.ends_with("_addtid")), off);
         let t = self.t();
         self.line(&format!("uint {t}_a = {base} + {};", hex(off)));
         let act = self.act();
@@ -3805,7 +3811,7 @@ impl Em {
         let base = if global && saddr != 0x7D && saddr != 0x7F { format!("{} + {addr}", self.sreg(saddr)) } else { addr };
         let raw = f("OFFSET") as u32;
         let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw };
-        self.flat_window(global, saddr, f("ADDR"), off);
+        self.flat_window(global, saddr, Some(f("ADDR")), off);
         let t = self.t();
         let x2 = op.ends_with("_x2");
         let op = op.trim_end_matches("_x2");
diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs
index 5f74fe8..4ce4292 100644
--- a/crates/xcl/src/gpu/recomp/tests.rs
+++ b/crates/xcl/src/gpu/recomp/tests.rs
@@ -3208,6 +3208,57 @@ fn gpu_memory_window_carry() {
     assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add carried into window 1");
 }
 
+/// The two window terms `gpu_memory_window_carry` does not cover. A structured buffer whose
+/// `stride · index` passes 4 GiB (base 0:0x4000, stride 16, index 0x1000_0001 → 1:0x4010): the
+/// product's high word moves the address to the next window. `global_load_dword_addtid` (EA =
+/// SADDR + 4 · lane + OFFSET, no ADDR operand): lanes 32..63 of SADDR 0xFFFF_FF80 carry into
+/// window 1, whatever the VGPR the ADDR field names holds. Each wrong window holds a sentinel.
+#[test]
+fn gpu_memory_window_stride_product_and_addtid() {
+    if !gpu_ready() {
+        return;
+    }
+    let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
+    let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
+    assert_eq!((w1 - w0, w0 as u32), (1 << 32, 0));
+    let word = |a: u64| unsafe { &mut *(a as *mut u32) };
+    *word(w1 + 0x4010) = 0x5157;
+    *word(w0 + 0x4010) = 0xBAD0; // the product's carry lost
+    for l in 0..32u64 {
+        *word(w1 + 4 * l) = 7000 + l as u32;
+        *word(w0 + 4 * l) = 0xBAD1; // addtid's carry lost
+    }
+    let list: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = vec![
+        ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 4), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None),
+        // lanes 0..31 would read the top of window 0, which this arena does not map
+        ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None),
+        ("GLOBAL_LOAD_DWORD_ADDTID", "ENC_FLAT_GLBL", &[("VDST", 11), ("SADDR", 16), ("OFFSET", 0)], None),
+    ];
+    let t = translate(&prog(&list), &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap();
+    assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl);
+    let carries: Vec<&str> = t.hlsl.lines().filter(|l| l.contains("xcl_w =")).collect();
+    assert!(carries.iter().all(|l| !l.contains("64")), "{carries:#?}");
+    assert!(carries.iter().any(|l| l.contains("mul_hi_u32(")), "the product's high word\n{carries:#?}");
+    assert!(carries.iter().any(|l| l.contains("4u * lane_id")), "addtid's lane term\n{carries:#?}");
+    let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
+    let hi0 = (w0 >> 32) as u32;
+    let mut st = KernelState::default();
+    st.sgpr[8..12].copy_from_slice(&[0x4000, (hi0 & 0xFFFF) | (16 << 16), 0x1000_0002, 0]);
+    st.sgpr[16..18].copy_from_slice(&[0xFFFF_FF80, hi0]);
+    st.sgpr[30..32].copy_from_slice(&[0, u32::MAX]);
+    for r in st.vgpr.iter_mut() {
+        r[0] = 0; // what the old addtid window read as its offset
+        r[4] = 0x1000_0001;
+    }
+    let r = runner::run_in_arena(&dxil, &st, &arena).unwrap();
+    for l in 0..64usize {
+        assert_eq!(r.vgpr[l][10], 0x5157, "lane {l}: structured buffer_load past 4 GiB of records");
+        if l >= 32 {
+            assert_eq!(r.vgpr[l][11], 7000 + (l as u32 - 32), "lane {l}: global_load_dword_addtid carried into window 1");
+        }
+    }
+}
+
 /// End-to-end GPU test of the sparse-window VRAM runtime layout:
 /// - Window 0..2 = sparse VRAM (tiled reserved buffers on DEFAULT heaps)
 /// - Window 3 = committed coherent RAM (`OpenExistingHeapFromAddress`)

@Kalmarv

Kalmarv commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Driver cost of this PR's 32-bit carry when combined with #187's heap windows, on an access-dense compute program: with #187, #138 makes first creation in the driver about 50–65 % slower. That is still about 25× faster than the switch form without #138.

The shape is split wave64 compute with a load and a store of title memory every round and an exec-masked block every 4 rounds. Each cell is 2 programs the driver had never seen, and the driver times are min / max:

4 windows, heap form (#187) DXIL DXC per program driver, first creation
1000 rounds 274 KB 3.4–4.2 s 3.43 / 3.72 s
1000 rounds + #138 302 KB 3.7–4.3 s 5.71 / 6.24 s
2000 rounds 580 KB 16.4–19.1 s 14.21 / 17.00 s
2000 rounds + #138 643 KB 11.1–11.3 s 22.43 / 24.85 s

Tested

Not tested

🤖 Claude Fable 5.2, Claude Opus 5.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants