From 2ef9796f0cc166abad578e656f7a8daf18bcbe72 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:43:19 -0600 Subject: [PATCH 1/2] leonida-shader: double-buffer shared wave64 exchange banks to halve loop barriers (D3D12-SHADER-DOUBLE-BUFFERED-EXCHANGE) Addresses the d3d12/docs/findings.md item ("exchanges inside loops (two barriers each: about 110 of the 134 barriers of the 8 x 8 material program 1f1fbd86759b3da2 are in loops)" / "What would make it cheap: one barrier per exchange (two dwords used by turns)"). When exchange_sites() > 0 and LDS has room for a second shared bank (2 * waves extra dwords), allocate two alternating shared exchange banks and thread a per-thread 1-bit bank parity SSA value (i32 in {0, 1}) across IR blocks. Every shared-bank exchange (including inside loops) alternates banks with one group_sync after its stores and flips bank ^= 1, eliminating the second post-load barrier while keeping bank reads and next-iteration stores strictly separated by the preceding barrier. Falls back cleanly to the 2-barrier single-bank path when LEONIDA_EXCHANGE_SITES=0 or when LDS is too full for the second bank. AI-assisted: Antigravity (Gemini 4 Neon) --- d3d12/crates/leonida-shader/src/emit/lower.rs | 75 +++++++++++++++- .../leonida-shader/src/emit/wave64_tests.rs | 85 +++++++++++++++++++ 2 files changed, 159 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index faeb2137cf..1be3cebba1 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -516,6 +516,12 @@ struct Lower<'a> { /// group, and per IR block whether a thread can run it more than once ([`in_cycle`]). fresh_pairs: (u32, u32, u32), cyclic: Vec, + /// With `exchange`: stride in dwords (`2 * waves`) to a second shared exchange bank so + /// shared-bank exchanges (including inside loops) alternate banks with one group barrier + /// instead of two, plus per-IR-block entry/current bank parity (`i32` in `{0, 1}`). + double_bank: Option, + bank_in: Vec>, + bank_cur: Vec>, /// A console wave64 program in host waves of 32: the LDS dword counting the console threads /// handed to host waves (`wave_base`), and the base made in the entry block. halves: Option, @@ -2403,6 +2409,7 @@ impl<'a> Lower<'a> { // a console wave64 program in two host waves of 32 (`exchange`) let mut exchange: Option<(u32, bool, Vec)> = None; let mut fresh_pairs = (0u32, 0u32, 0u32); + let mut double_bank: Option = None; // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter let mut halves: Option = None; // console lanes in a group of several host waves: the LDS dword of `wave_base`'s counter @@ -2506,6 +2513,12 @@ impl<'a> Lower<'a> { if !LOCAL_WAVES.get() || s.lds_dwords + 2 * waves + 1 <= 8192 { s.lds_dwords += 2 * waves; } + if group > 32 && !LOCAL_WAVES.get() && exchange_sites() > 0 && s.lds_dwords + 2 * waves + 2 <= 8192 { + // A second shared bank (`2 * waves` dwords) lets cyclic/shared + // exchanges alternate banks with one barrier instead of two. + double_bank = Some(2 * waves); + s.lds_dwords += 2 * waves; + } if group > 32 { // pairs of their own, as far as D3D12's 32 KiB of group // memory and the dword a ticket may still take allow @@ -2843,6 +2856,9 @@ impl<'a> Lower<'a> { pair: None, fresh_pairs, cyclic: if fresh_pairs.0 > 0 { in_cycle(p) } else { Vec::new() }, + double_bank, + bank_in: vec![None; p.blocks.len()], + bank_cur: vec![None; p.blocks.len()], halves, ticket, partial_active: None, @@ -3638,6 +3654,17 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } + if self.double_bank.is_some() { + for (idx, &b) in order.iter().enumerate() { + let v = if idx == 0 { + self.s.m.i32(0) + } else { + self.s.m.phi(self.block[b].expect("reachable"), self.s.t.i32) + }; + self.bank_in[b] = Some(v); + self.bank_cur[b] = Some(v); + } + } // Loop headers count iterations (`LOOP_LIMIT`). for &b in &order { let header = p.blocks[b] @@ -5938,6 +5965,35 @@ impl<'a> Lower<'a> { }) .collect(); } + let ir = if at == self.cur { + Some(self.cur_ir) + } else { + self.tail.iter().position(|t| *t == Some(at)) + }; + if let (Some(stride), Some(ir)) = (self.double_bank, ir) + && let Some(mut bank) = self.bank_cur[ir] + { + let pair = self.exchange_pair(slot); + let stride_v = self.s.m.i32(stride); + let mut out = Vec::with_capacity(mine.len()); + for &m in mine { + let bank_off = self.s.m.bin(at, Bin::Mul, bank, stride_v); + let bank_pair = self.s.m.bin(at, Bin::Add, pair, bank_off); + let index = self.s.m.bin(at, Bin::Add, bank_pair, half); + let ptr = self.s.m.element(at, lds, index); + self.s.m.store(at, ptr, m); + self.group_sync(at); + let k1 = self.s.m.bin(at, Bin::Add, bank_pair, one); + let p0 = self.s.m.element(at, lds, bank_pair); + let p1 = self.s.m.element(at, lds, k1); + let lo = self.s.m.load(at, p0); + let hi = self.s.m.load(at, p1); + bank = self.s.m.bin(at, Bin::Xor, bank, one); + out.push((lo, hi)); + } + self.bank_cur[ir] = Some(bank); + return out; + } mine.iter() .map(|&m| { // the pair of dwords of this thread's console wave: its half's, then both @@ -5973,11 +6029,12 @@ impl<'a> Lower<'a> { } let slot = self.exchange.as_ref()?.0; let pair = self.exchange_pair(slot); + let shared_banks = if self.double_bank.is_some() { 2 } else { 1 }; self.fresh_pairs.1 += n; Some( (0..n) .map(|k| { - let off = self.s.m.i32(2 * waves * (taken + k + 1)); + let off = self.s.m.i32(2 * waves * (taken + k + shared_banks)); self.s.m.bin(at, Bin::Add, pair, off) }) .collect(), @@ -15482,6 +15539,22 @@ impl<'a> Lower<'a> { for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { self.s.m.set_phi(phi, incoming); } + if self.double_bank.is_some() { + for (b, phi) in self.bank_in.iter().enumerate() { + let Some(phi) = *phi else { continue }; + if !matches!(phi, V::Inst(_)) { + continue; + } + let mut incoming = Vec::new(); + for &q in &p.blocks[b].preds { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let v = self.bank_cur[q].unwrap_or_else(|| self.s.m.i32(0)); + incoming.push((v, qb)); + } + self.s.m.set_phi(phi, incoming); + } + } Ok(()) } } diff --git a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs index bf9cb76ec7..b5c9579c5f 100644 --- a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs @@ -1923,3 +1923,88 @@ fn a_loop_the_lanes_leave_one_by_one_is_left_by_each_host_wave_together_when_ask Err(_) => eprintln!("no dxil.dll: neither form validated"), } } + +/// A cross-half wave OR inside a scalar 8-iteration loop: with double-buffered +/// shared exchange banks (`LEONIDA_EXCHANGE_SITES > 0`), each exchange in the +/// loop emits one group barrier instead of two and produces bit-identical results +/// on the GPU across all iterations. +#[test] +fn exchanges_in_a_loop_meet_once_with_double_buffered_banks() { + // s20 = 0 (loop counter), s21 = 0 (accumulator) + // loop: + // v7 = v0 + s20 + // WAVE_OR_V7_TO_S7 (cross-half exchange inside cyclic block) + // s21 = s21 + s7 + // s20 = s20 + 1 + // s_cmp_lt_u32 s20, 8 + // s_cbranch_scc1 loop + // buffer_store_dword s21 -> uav[0] + let mut words = vec![ + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_0380, // s_mov_b32 s21, 0 + ]; + let loop_start = words.len(); + words.push(0x4A0E_0014); // v_add_nc_u32 v7, s20, v0 + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x8015_0715, // s_add_u32 s21, s21, s7 + 0x8014_8114, // s_add_u32 s20, s20, 1 + 0xBF04_8814, // s_cmp_lt_u32 s20, 8 + ]); + let rel = (loop_start as isize - (words.len() as isize + 1)) as i16 as u16; + words.push(0xBF85_0000 | u32::from(rel)); // s_cbranch_scc1 loop_start + words.extend_from_slice(&[ + 0x7E00_0215, // v_mov_b32 v0, s21 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let lower_with = |sites: u32| { + let was_wave = lower::TEST_HOST_WAVE.replace(Some(32)); + let was_sites = lower::TEST_EXCHANGE_SITES.replace(Some(sites)); + lower::TEST_GROUP_SYNCS.set(0); + let shader = lowered(&native, &p, &HashSet::new()); + let syncs = lower::TEST_GROUP_SYNCS.get(); + lower::TEST_EXCHANGE_SITES.set(was_sites); + lower::TEST_HOST_WAVE.set(was_wave); + (syncs, shader.expect("lower")) + }; + let (off_syncs, off) = lower_with(0); + let (on_syncs, on) = lower_with(24); + assert!( + on_syncs < off_syncs, + "double-buffered loop exchange should emit fewer barriers: {on_syncs} vs {off_syncs}" + ); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + for s in [&off, &on] { + let mut copy = s.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + return; + }; + let want: u32 = (0u32..8).map(|i| (0u32..64).fold(0u32, |acc, l| acc | (l + i))).sum(); + for (label, s) in [("off", &off), ("on", &on)] { + let Ok((root, pso)) = host.compute_pipeline(s) else { + continue; + }; + let ud = vec![0u32; s.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch"); + assert_eq!(out[0][0], want, "{label}: 8-iteration wave OR sum mismatch"); + } +} From 7efcddb210e85ea3ebe5530d6d7435d176868de9 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:24:36 -0600 Subject: [PATCH 2/2] leonida-shader: fence single-bank fallback under double-buffered exchange --- d3d12/crates/leonida-shader/src/emit/lower.rs | 6 ++ .../leonida-shader/src/emit/wave64_tests.rs | 57 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index b8a7442831..3be2c3ccca 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -6183,6 +6183,12 @@ impl<'a> Lower<'a> { self.bank_cur[ir] = Some(bank); return out; } + if self.double_bank.is_some() && !mine.is_empty() { + // A preceding double-bank exchange omits its trailing barrier; + // fence before reusing bank 0 in the single-bank fallback so the + // other half finishes reading bank 0 before we overwrite it. + self.group_sync(at); + } mine.iter() .map(|&m| { // the pair of dwords of this thread's console wave: its half's, then both diff --git a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs index 425cc5c521..e19dc382a6 100644 --- a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs @@ -2009,6 +2009,63 @@ fn exchanges_in_a_loop_meet_once_with_double_buffered_banks() { } } +/// When `double_bank` is active and a late entry-block ballot (`def_block == None`, +/// `at == self.s.entry`) runs after block 0 already emitted a double-bank exchange +/// on bank 0 and split `self.s.entry`, `exchange_many` falls back to the +/// single-bank path targeting bank 0 and must emit a leading barrier so bank 0 +/// is not overwritten before the other half finishes reading it. +#[test] +fn double_bank_single_bank_fallback_fences_before_reusing_bank_zero() { + let words = vec![ + 0x7E0A_0280, // v_mov_b32 v5, 0 (LDS address) + // Exchange 1 (uses fresh pair 0 with sites=1; leaves EXEC untouched): + 0x7D88_00A8, // v_cmp_gt_u32 vcc, 40, v0 + 0x8012_816A, // s_add_u32 s18, vcc_lo, 1 + // Exchange 2 (uses double_bank bank 0; leaves EXEC untouched): + 0x7D88_0094, // v_cmp_gt_u32 vcc, 20, v0 + 0x8013_126A, // s_add_u32 s19, vcc_lo, s18 + // ds_max_f32 v5, v0: CAS loop splits `self.s.entry` without rewriting `EXEC`. + 0x36 << 26 | 0x13 << 18, + 0 << 8 | 5, + // Reads unmodified entry EXEC (`def_block == None` -> `at == self.s.entry`, + // while `self.cur != self.s.entry` and `self.tail[0] == None`, so `ir == None`). + 0x8015_137E, // s_add_u32 s21, exec_lo, s19 + 0x7E00_0215, // v_mov_b32 v0, s21 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let lower_with = |sites: u32| { + let was_wave = lower::TEST_HOST_WAVE.replace(Some(32)); + let was_sites = lower::TEST_EXCHANGE_SITES.replace(Some(sites)); + lower::TEST_GROUP_SYNCS.set(0); + let shader = lowered(&native, &p, &HashSet::new()); + let syncs = lower::TEST_GROUP_SYNCS.get(); + lower::TEST_EXCHANGE_SITES.set(was_sites); + lower::TEST_HOST_WAVE.set(was_wave); + (syncs, shader.expect("lower")) + }; + // sites=0: 3 single-bank exchanges (2 syncs each = 6). + // sites=1: exchange 1 uses fresh pair (1), exchange 2 uses double_bank bank 0 (1), + // late entry ballot falls back to single-bank bank 0 and adds 1 leading fence + 2 syncs (3) => 5. + // Without the leading fence on the fallback, on_syncs drops to 4 (racing bank 0). + let (off_syncs, off) = lower_with(0); + let (on_syncs, on) = lower_with(1); + assert_eq!( + off_syncs - on_syncs, + 1, + "fallback after double-bank must emit a leading fence (off={off_syncs}, on={on_syncs})" + ); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + for s in [&off, &on] { + let mut copy = s.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + } +} + /// A 1-D wave64 group (`[128, 1, 1]`) on a 32-lane host needs no entry ticket /// barrier or LDS atomic: each host wave already has a consecutive run of flat /// thread IDs, and every console thread 0..127 writes its own slot.