From 126a40f947f91c184040050daf3606f956fd1004 Mon Sep 17 00:00:00 2001 From: ottco Date: Fri, 27 Nov 2026 07:08:44 +0100 Subject: [PATCH 1/3] refactor(shader): move the round-mode analysis and packed halves out of lower.rs The halves rendezvous puts lower.rs 2.3 KB over the asset policy's 512 KiB limit. round16/round16_after and packed_half are free functions with no state of their own, so they move to lower/round_mode.rs and lower/packed.rs unchanged, as #375 did with the atomic-lock lowering. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 100 +----------------- .../victory-shader/src/emit/lower/packed.rs | 41 +++++++ .../src/emit/lower/round_mode.rs | 64 +++++++++++ 3 files changed, 109 insertions(+), 96 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/packed.rs create mode 100644 crates/victory-shader/src/emit/lower/round_mode.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 61b45dcbf..705cc7558 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -28,6 +28,8 @@ mod bvh; #[path = "half_views.rs"] mod half_views; mod halves; +mod packed; +mod round_mode; mod mesh; mod predicate; #[cfg(test)] @@ -35,6 +37,8 @@ use barriers::split_wave_barriers; use barriers::{in_step, split_wave_barriers_with_step, step_and_cap}; pub(crate) use mesh::KeptOutputs; use mesh::prune_signature; +use packed::packed_half; +use round_mode::{round16, round16_after}; type Why = &'static str; @@ -543,65 +547,6 @@ struct Lower<'a> { mode16: Option, } -/// The 16/64-bit round mode (MODE bits 3:2: 0 nearest even, 3 toward zero) -/// after `inst`, from `mode` before it (`None`: not known). -fn round16_after(inst: &Inst, mode: Option) -> Option { - match (inst.name(), &inst.fields) { - ("s_round_mode", Fields::Sopp { imm }) => Some((imm >> 2 & 3) as u8), - ( - "s_setreg_imm32_b32" | "s_setreg_b32", - Fields::Sop { - src, imm: Some(h), .. - }, - ) => { - let (id, off, size) = (h & 0x3F, h >> 6 & 0x1F, (h >> 11 & 0x1F) + 1); - if id != 1 || off >= 4 || off + size <= 2 { - return mode; - } - match src.first() { - Some(&Operand::Literal(x)) if off <= 2 && off + size >= 4 => { - Some((x >> (2 - off) & 3) as u8) - } - _ => None, - } - } - _ => mode, - } -} - -/// The 16/64-bit round mode each block starts with: nearest even at the -/// program's start, then as the MODE writes on the way set it; `None` where -/// paths that set it differently join (or a write is not a constant). -fn round16(p: &crate::ir::Program) -> Vec> { - // None: not reached yet; Some(m): the mode (m None: not known). - let mut entry: Vec>> = vec![None; p.blocks.len()]; - entry[0] = Some(Some(0)); - let order = crate::ir::reverse_postorder(&p.blocks); - loop { - let mut changed = false; - for &b in &order { - let Some(mut m) = entry[b] else { continue }; - for inst in &p.blocks[b].insts { - m = round16_after(inst, m); - } - for s in p.blocks[b].exit.successors() { - let new = match entry[s] { - None => Some(m), - Some(old) if old == m => continue, - Some(_) => Some(None), - }; - if entry[s] != new { - entry[s] = new; - changed = true; - } - } - } - if !changed { - return entry.into_iter().map(Option::flatten).collect(); - } - } -} - /// Iterations after which a loop is left (per entry into it), unless /// [`super::loop_limit`] says otherwise. The console runs a loop as long as /// its data says; data the host has not mirrored yet (a null view reads @@ -687,43 +632,6 @@ fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { }) } -/// Where half `h` (dword h / 2, the high half when odd) of the parameter -/// whose first element is in row `a` comes from, when the console packs -/// 16-bit values two per dword: a row and channel of `elements`, none for -/// padding. The console fills its parameters with the 16-bit elements taken -/// by first channel, then row: each takes whole dwords of the first -/// parameter with room for it (four dwords each), its channels in order. -fn packed_half(elements: &[SigElement], a: u8, h: u8) -> Option<(u8, u8)> { - let mut halves: Vec<&SigElement> = elements - .iter() - .filter(|e| e.half && e.kind == 0 && e.row.is_some()) - .collect(); - halves.sort_by_key(|e| (e.col, e.row)); - // (first element's row, (row, channel) per half) - type Param = (Option, Vec>); - let mut params: Vec = Vec::new(); - for e in halves { - let need = usize::from(e.cols.div_ceil(2) * 2); - let i = match params.iter().position(|p| p.1.len() + need <= 8) { - Some(i) => i, - None => { - params.push((e.row, Vec::new())); - params.len() - 1 - } - }; - let row = u8::try_from(e.row?).ok()?; - let slots = &mut params[i].1; - slots.extend((0..e.cols).map(|c| Some((row, e.col + c)))); - slots.resize(slots.len().next_multiple_of(2), None); - } - // Two parameters starting in one row would leave the half ambiguous. - let mut found = params.iter().filter(|p| p.0 == Some(u32::from(a))); - match (found.next(), found.next()) { - (Some(p), None) => p.1.get(usize::from(h)).copied().flatten(), - _ => None, - } -} - /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]), /// by row: whether two per dword. fn half_outputs(io: &StageIo) -> HashMap { diff --git a/crates/victory-shader/src/emit/lower/packed.rs b/crates/victory-shader/src/emit/lower/packed.rs new file mode 100644 index 000000000..2ed4cc583 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/packed.rs @@ -0,0 +1,41 @@ +//! Where the console's packed 16-bit parameters come from, moved out of +//! `lower.rs` to keep it under the size limit. + +use super::SigElement; + +/// Where half `h` (dword h / 2, the high half when odd) of the parameter +/// whose first element is in row `a` comes from, when the console packs +/// 16-bit values two per dword: a row and channel of `elements`, none for +/// padding. The console fills its parameters with the 16-bit elements taken +/// by first channel, then row: each takes whole dwords of the first +/// parameter with room for it (four dwords each), its channels in order. +pub(super) fn packed_half(elements: &[SigElement], a: u8, h: u8) -> Option<(u8, u8)> { + let mut halves: Vec<&SigElement> = elements + .iter() + .filter(|e| e.half && e.kind == 0 && e.row.is_some()) + .collect(); + halves.sort_by_key(|e| (e.col, e.row)); + // (first element's row, (row, channel) per half) + type Param = (Option, Vec>); + let mut params: Vec = Vec::new(); + for e in halves { + let need = usize::from(e.cols.div_ceil(2) * 2); + let i = match params.iter().position(|p| p.1.len() + need <= 8) { + Some(i) => i, + None => { + params.push((e.row, Vec::new())); + params.len() - 1 + } + }; + let row = u8::try_from(e.row?).ok()?; + let slots = &mut params[i].1; + slots.extend((0..e.cols).map(|c| Some((row, e.col + c)))); + slots.resize(slots.len().next_multiple_of(2), None); + } + // Two parameters starting in one row would leave the half ambiguous. + let mut found = params.iter().filter(|p| p.0 == Some(u32::from(a))); + match (found.next(), found.next()) { + (Some(p), None) => p.1.get(usize::from(h)).copied().flatten(), + _ => None, + } +} diff --git a/crates/victory-shader/src/emit/lower/round_mode.rs b/crates/victory-shader/src/emit/lower/round_mode.rs new file mode 100644 index 000000000..7bae0c4ce --- /dev/null +++ b/crates/victory-shader/src/emit/lower/round_mode.rs @@ -0,0 +1,64 @@ +//! The 16/64-bit round mode (MODE bits 3:2) each block starts with, moved +//! out of `lower.rs` to keep it under the size limit. + +use crate::gfx10::{Fields, Operand}; +use crate::ir::Inst; + +/// The 16/64-bit round mode (MODE bits 3:2: 0 nearest even, 3 toward zero) +/// after `inst`, from `mode` before it (`None`: not known). +pub(super) fn round16_after(inst: &Inst, mode: Option) -> Option { + match (inst.name(), &inst.fields) { + ("s_round_mode", Fields::Sopp { imm }) => Some((imm >> 2 & 3) as u8), + ( + "s_setreg_imm32_b32" | "s_setreg_b32", + Fields::Sop { + src, imm: Some(h), .. + }, + ) => { + let (id, off, size) = (h & 0x3F, h >> 6 & 0x1F, (h >> 11 & 0x1F) + 1); + if id != 1 || off >= 4 || off + size <= 2 { + return mode; + } + match src.first() { + Some(&Operand::Literal(x)) if off <= 2 && off + size >= 4 => { + Some((x >> (2 - off) & 3) as u8) + } + _ => None, + } + } + _ => mode, + } +} + +/// The 16/64-bit round mode each block starts with: nearest even at the +/// program's start, then as the MODE writes on the way set it; `None` where +/// paths that set it differently join (or a write is not a constant). +pub(super) fn round16(p: &crate::ir::Program) -> Vec> { + // None: not reached yet; Some(m): the mode (m None: not known). + let mut entry: Vec>> = vec![None; p.blocks.len()]; + entry[0] = Some(Some(0)); + let order = crate::ir::reverse_postorder(&p.blocks); + loop { + let mut changed = false; + for &b in &order { + let Some(mut m) = entry[b] else { continue }; + for inst in &p.blocks[b].insts { + m = round16_after(inst, m); + } + for s in p.blocks[b].exit.successors() { + let new = match entry[s] { + None => Some(m), + Some(old) if old == m => continue, + Some(_) => Some(None), + }; + if entry[s] != new { + entry[s] = new; + changed = true; + } + } + } + if !changed { + return entry.into_iter().map(Option::flatten).collect(); + } + } +} From 42a3e186496737d163218bc40a6ee46ebc8802df Mon Sep 17 00:00:00 2001 From: lakshan Date: Thu, 26 Nov 2026 21:02:35 +0100 Subject: [PATCH 2/3] shader: keep lanes leaving early on to the end in a split wave A cross-lane exchange or synced LDS between the two host waves of a console wave needs both at each group barrier. The common early exit, s_cbranch_execz straight to s_endpgm (if (id < n) { whole shader }), makes the lanes that leave skip them, so such programs were refused. Refused for a halves reason, a compute program is lowered again with those branches dropped (ir::keep_lanes_to_end): the lanes run on with EXEC off. Programs with scalar memory writes are left as they were. Ported from LakshanSivakumar/Native-Victory-macOS 0a8bee7 (GPL-3.0) onto emit_pruned, keyed on this tree's halves refusal texts. On an M5 Pro the pack warm-up's compute pipelines that do not translate fell from 247 to 219; victory-shader's suite passes under Wine. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/mod.rs | 30 ++++++++++++++++ crates/victory-shader/src/ir.rs | 52 +++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b1aa0063f..b2e5ebfe4 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -962,6 +962,13 @@ pub fn emit_with( ) } +/// Whether `what` refuses a program because its console wave64 runs as two +/// 32-lane host waves that cannot meet where it needs them to. +fn halves_refusal(what: &str) -> bool { + what.contains("(wave64 on a 32-lane host)") + || what.starts_with("LDS one console wave64 shares without barriers") +} + fn emit_pruned( input: &EmitInput<'_>, options: Options, @@ -1059,6 +1066,29 @@ fn emit_pruned( options.per_vertex_center, !options.disable_literal_halves, ) { + // A console wave the host splits into 32-lane halves needs both at + // each group barrier, and lanes that left early for the end never + // arrive; kept on to the end with EXEC off (`ir::keep_lanes_to_end`), + // they do. A program with no such early exit stays refused. + Err(e @ ShaderError::Unsupported { what, .. }) + if options.host_wave32 && native.stage == HwStage::Cs && halves_refusal(what) => + { + let Some(q) = crate::ir::keep_lanes_to_end(p) else { + return Err(e); + }; + let st = structure::structure(&q)?; + let res = resource::track(&q, &native.layout, native.stage, Some(&st))?; + return emit_pruned( + &EmitInput { + p: &q, + st: &st, + res: &res, + ..*input + }, + options, + keep, + ); + } // Discarded lanes kept on as helpers can read what no surviving // lane does (a register only killed lanes skipped writing); such a // program kills them as the console does (`structure::killing`). diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 444bab20d..123a00b3f 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -121,6 +121,58 @@ impl Inst { } } +/// `p` with each `s_cbranch_execz` that leaves for a bare `s_endpgm` block +/// dropped: the lanes the branch would end run on to the program's end with +/// EXEC off, as the console's do while their wave has a lane left. Only a +/// wave whose every lane is off now runs that code too, which changes +/// nothing but scalar memory writes (none allowed here). `None`: no such +/// branch, or a scalar memory write. +/// +/// For a console wave the host splits into 32-lane halves: the common early +/// exit (`if (id < n) { whole shader }`) made the lanes that leave skip the +/// group barriers the halves meet at, so such programs were refused. +/// Ported from LakshanSivakumar/Native-Victory-macOS 0a8bee7 (GPL-3.0). +pub(crate) fn keep_lanes_to_end(p: &Program) -> Option { + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + if insts().any(|i| { + let n = i.name(); + n.starts_with("s_store") + || n.starts_with("s_buffer_store") + || n.starts_with("s_") && n.contains("atomic") + }) { + return None; + } + let bare_end = |b: &Block| { + b.exit == Exit::End + && b.phis.is_empty() + && b + .insts + .iter() + .all(|i| matches!(i.name(), "s_endpgm" | "s_inst_prefetch" | "s_nop")) + }; + let mut q = p.clone(); + let mut changed = false; + for b in 0..q.blocks.len() { + let Exit::Branch { taken, not_taken } = q.blocks[b].exit else { + continue; + }; + let end = &q.blocks[taken]; + if taken == not_taken + || q.blocks[b].insts.last().map(Inst::name) != Some("s_cbranch_execz") + || !bare_end(end) + || end.preds.len() < 2 + { + continue; + } + let k = end.preds.iter().position(|&x| x == b)?; + q.blocks[taken].preds.remove(k); + q.blocks[b].insts.pop(); + q.blocks[b].exit = Exit::Jump(not_taken); + changed = true; + } + changed.then_some(q) +} + /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). From 4ed7a481ce7fff0da6a002b70e53af4c9ad45068 Mon Sep 17 00:00:00 2001 From: ottco Date: Thu, 26 Nov 2026 21:26:10 +0100 Subject: [PATCH 3/3] feat(shader): halves meet for lane-mask ballots in divergent code A console wave64 program in 32-lane halves passed ballots between the halves only between group barriers, in blocks every lane of the group runs together; a lane mask read as data in divergent code was refused ("a lane mask read as data (wave64 on a 32-lane host)"). The two host waves of one console wave now wait for each other there on group-shared memory (lower::meet): each half publishes its ballot and an epoch-tagged arrival, and its lanes count every site they will not reach on the edges they take, so a half waits until the other arrived or all of its lanes are done with the site. Only in acyclic regions entered from an in-step branch block and left to one join (a group barrier there when the branch block loops); the deadlock-freedom argument is in the module notes. Sites are found in a first pass and laid out in a second (lower_pruned). Options::halves_rendezvous switches it (victory-gpu: on, VICTORY_HALVES_RENDEZVOUS=0 off, keyed in the shader cache). Tests: divergent ballots on the GPU (if, only the lower half entering, if/else, 128 threads diverging per console wave, 96 threads, the branch in a loop), validation, and a loop inside the branch staying refused. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shader_cache.rs | 23 +- crates/victory-shader/src/emit/bvh_tests.rs | 1 + .../src/emit/crosslane_tests.rs | 1 + crates/victory-shader/src/emit/deltas.rs | 1 + .../victory-shader/src/emit/halves_tests.rs | 350 +++++++++ crates/victory-shader/src/emit/host.rs | 1 + .../src/emit/image_store_tests.rs | 1 + crates/victory-shader/src/emit/lower.rs | 65 +- crates/victory-shader/src/emit/lower/meet.rs | 694 ++++++++++++++++++ crates/victory-shader/src/emit/lower/tests.rs | 8 + crates/victory-shader/src/emit/mark_tests.rs | 1 + .../victory-shader/src/emit/memory_tests.rs | 9 + crates/victory-shader/src/emit/mod.rs | 7 + .../src/emit/semantics_tests.rs | 1 + .../victory-shader/src/emit/stride_tests.rs | 1 + .../src/emit/synthetic_tests.rs | 2 + .../src/emit/typed_buffer_tests.rs | 1 + crates/victory-shader/src/emit/valu_tests.rs | 5 + .../src/emit/waterfall_tests.rs | 1 + 19 files changed, 1167 insertions(+), 6 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/meet.rs diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 0f3075b95..72a1b7f5d 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -168,6 +168,16 @@ pub fn narrow_waves() -> bool { }) } +/// Whether the two 32-lane halves of a console wave64 pass each other +/// values in divergent code by waiting for each other on group-shared +/// memory (`victory_shader::emit::Options::halves_rendezvous`): on, wherever +/// programs run in halves. `VICTORY_HALVES_RENDEZVOUS=0` goes back to +/// refusing such programs. +fn halves_rendezvous() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_HALVES_RENDEZVOUS").as_deref() != Ok("0")) +} + /// Whether 64-thread wave64 shaders keep only the per-lane translation. fn literal_halves_disabled() -> bool { static OFF: OnceLock = OnceLock::new(); @@ -263,17 +273,20 @@ pub(crate) fn translation_build(options: victory_shader::emit::Options) -> &'sta let umax = rounds && options.atomic_umax; let uav_level0 = options.uav_size_level0; let no_literal = options.host_wave32 && options.disable_literal_halves; - if !locks && !bias && !narrow && !no_literal && !uav_level0 { + // Only where programs run in halves does the rendezvous change them. + let apart = options.host_wave32 && !options.halves_rendezvous; + if !locks && !bias && !narrow && !no_literal && !uav_level0 && !apart { return build(); } - static BUILDS: [OnceLock<[u8; 32]>; 128] = [const { OnceLock::new() }; 128]; + static BUILDS: [OnceLock<[u8; 32]>; 256] = [const { OnceLock::new() }; 256]; let n = usize::from(locks) | usize::from(bias) << 1 | usize::from(narrow) << 2 | usize::from(rounds) << 3 | usize::from(umax) << 4 | usize::from(no_literal) << 5 - | usize::from(uav_level0) << 6; + | usize::from(uav_level0) << 6 + | usize::from(apart) << 7; BUILDS[n].get_or_init(|| { let mut h = blake3::Hasher::new(); h.update(build()); @@ -298,6 +311,9 @@ pub(crate) fn translation_build(options: victory_shader::emit::Options) -> &'sta if no_literal { h.update(b"literal halves disabled"); } + if apart { + h.update(b"no halves rendezvous"); + } *h.finalize().as_bytes() }) } @@ -319,6 +335,7 @@ pub(crate) fn runtime_options() -> victory_shader::emit::Options { disable_literal_halves: literal_halves_disabled(), per_vertex_center: false, uav_size_level0: uav_size_level0(), + halves_rendezvous: halves_rendezvous(), } } diff --git a/crates/victory-shader/src/emit/bvh_tests.rs b/crates/victory-shader/src/emit/bvh_tests.rs index 4fd2a1a7e..da2f30435 100644 --- a/crates/victory-shader/src/emit/bvh_tests.rs +++ b/crates/victory-shader/src/emit/bvh_tests.rs @@ -583,6 +583,7 @@ fn build(wide: bool, memory: bool) -> HostShader { ); let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/crosslane_tests.rs b/crates/victory-shader/src/emit/crosslane_tests.rs index d2e591998..c7860cb11 100644 --- a/crates/victory-shader/src/emit/crosslane_tests.rs +++ b/crates/victory-shader/src/emit/crosslane_tests.rs @@ -401,6 +401,7 @@ fn build_wave32_cs(pattern: MaskPattern, div: Divergence, op_words: &[u32]) -> H resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/deltas.rs b/crates/victory-shader/src/emit/deltas.rs index 73f850313..14679b270 100644 --- a/crates/victory-shader/src/emit/deltas.rs +++ b/crates/victory-shader/src/emit/deltas.rs @@ -280,6 +280,7 @@ mod tests { bias_as_gradients: false, narrow_waves: false, uav_size_level0: false, + halves_rendezvous: false, host_wave32: false, view_marks: false, }, diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 34638b28d..a1d8dcf84 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -172,6 +172,7 @@ fn lower_halves( bias_as_gradients: false, narrow_waves, uav_size_level0: false, + halves_rendezvous: true, host_wave32, }; if literal && matches!(&native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64) { @@ -2854,6 +2855,7 @@ fn thread_ticket_relabels_2d_and_partial_tail_groups_bijectively() { let io = io::raise(&p, prog).expect("io"); super::with_thread_ticket(ticket, || { lower::lower(&lower::Parts { + halves_rendezvous: false, native: prog, p: &p, st: &st, @@ -2941,3 +2943,351 @@ fn thread_ticket_relabels_2d_and_partial_tail_groups_bijectively() { let got_40 = run(lowered_40, 40); assert_eq!(got_40, vec![1u32; 40], "all 40 threads (32 full + 8 partial) must run once"); } + +// ---- the halves meet in divergent code (`lower::meet`) ---- + +/// Which lanes take a divergent branch: the even ones +/// (`v_and_b32 v3, 1, v0; v_cmp_eq_u32 vcc, 0, v3`), or those below a +/// thread id (`v_cmp_gt_u32 vcc, n, v0`). +#[derive(Clone, Copy)] +enum Side { + Even, + Below(u32), +} + +impl Side { + fn words(self) -> Vec { + match self { + Side::Even => vec![0x3606_0081, 0x7D84_0680], + Side::Below(n) => vec![0x7D88_00FF, n], + } + } + + fn takes(self, l: u32) -> bool { + match self { + Side::Even => l.is_multiple_of(2), + Side::Below(n) => l < n, + } + } +} + +/// `v_cmp_gt_u32 vcc, limit, v0`, the console wave's count of those lanes +/// (`s_bcnt1_i32_b64 s12, vcc`) into `v1` and their high dword (`vcc_hi`) +/// into `v2`: a lane mask read as data where it is written. +fn ballot_below(limit: u32) -> [u32; 5] { + [ + 0x7D88_00FF, + limit, // v_cmp_gt_u32 vcc, limit, v0 + 0xBE8C_106A, // s_bcnt1_i32_b64 s12, vcc + 0x7E02_020C, // v_mov_b32 v1, s12 + 0x7E04_026B, // v_mov_b32 v2, vcc_hi + ] +} + +const S_AND_SAVEEXEC_S20_VCC: u32 = 0xBE94_246A; // s_and_saveexec_b64 s[20:21], vcc +const S_MOV_EXEC_S20: u32 = 0xBEFE_0414; // s_mov_b64 exec, s[20:21] +const S_ANDN2_EXEC_S20_EXEC: u32 = 0x8AFE_7E14; // s_andn2_b64 exec, s[20:21], exec +const fn s_cbranch_execz(skip: usize) -> u32 { + 0xBF88_0000 | skip as u32 +} + +/// `v1`, `v2` start at -1; in the lanes `side` takes, [`ballot_below`]` +/// (limit)` behind `s_cbranch_execz`; both stored. Per lane two dwords. +fn ballot_in_an_if(side: Side, limit: u32) -> Vec { + let body = ballot_below(limit); + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_02C1, // v_mov_b32 v1, -1 + 0x7E04_02C1, // v_mov_b32 v2, -1 + ]); + w.extend(side.words()); + w.extend([S_AND_SAVEEXEC_S20_VCC, s_cbranch_execz(body.len())]); + w.extend(body); + w.push(S_MOV_EXEC_S20); + w.extend(store(1, 0)); + w.extend(store(2, 4)); + w.push(S_ENDPGM); + w +} + +/// [`ballot_in_an_if`] with an else: the lanes `side` does not take run +/// [`ballot_below`]`(other)`, behind a branch of their own. +fn ballots_in_an_if_and_else(side: Side, limit: u32, other: u32) -> Vec { + let (then, otherwise) = (ballot_below(limit), ballot_below(other)); + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_02C1, // v_mov_b32 v1, -1 + 0x7E04_02C1, // v_mov_b32 v2, -1 + ]); + w.extend(side.words()); + w.extend([S_AND_SAVEEXEC_S20_VCC, s_cbranch_execz(then.len())]); + w.extend(then); + w.extend([S_ANDN2_EXEC_S20_EXEC, s_cbranch_execz(otherwise.len())]); + w.extend(otherwise); + w.push(S_MOV_EXEC_S20); + w.extend(store(1, 0)); + w.extend(store(2, 4)); + w.push(S_ENDPGM); + w +} + +/// [`ballot_in_an_if`] in a scalar loop that runs twice (the branch block +/// runs twice, in step), each pass adding the count to `v1` (from 0): +/// `v1` is twice the count where the lane takes the branch. +fn ballot_in_an_if_in_a_loop(side: Side, limit: u32) -> Vec { + let body = [ + 0x7D88_00FF, + limit, // v_cmp_gt_u32 vcc, limit, v0 + 0xBE8C_106A, // s_bcnt1_i32_b64 s12, vcc + 0x4A02_020C, // v_add_nc_u32 v1, s12, v1 + ]; + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBE96_0380, // s_mov_b32 s22, 0 + ]); + let top = w.len(); + w.extend(side.words()); + w.extend([S_AND_SAVEEXEC_S20_VCC, s_cbranch_execz(body.len())]); + w.extend(body); + w.extend([ + S_MOV_EXEC_S20, + 0x8016_8116, // s_add_u32 s22, s22, 1 + 0xBF0A_8216, // s_cmp_lt_u32 s22, 2 + ]); + let back = top as i32 - (w.len() as i32 + 1); + w.push(0xBF85_0000 | (back as u32 & 0xFFFF)); // s_cbranch_scc1 (back to the top) + w.extend(store(1, 0)); + w.push(S_ENDPGM); + w +} + +/// A scalar loop of two passes inside the branch: the region is a cycle, +/// where the halves cannot meet. +fn ballot_in_a_loop_in_an_if(side: Side, limit: u32) -> Vec { + let mut body = vec![0xBE96_0380]; // s_mov_b32 s22, 0 + let top = body.len(); + body.extend([ + 0x7D88_00FF, + limit, // v_cmp_gt_u32 vcc, limit, v0 + 0xBE8C_106A, // s_bcnt1_i32_b64 s12, vcc + 0x4A02_020C, // v_add_nc_u32 v1, s12, v1 + 0x8016_8116, // s_add_u32 s22, s22, 1 + 0xBF0A_8216, // s_cmp_lt_u32 s22, 2 + ]); + let back = top as i32 - (body.len() as i32 + 1); + body.push(0xBF85_0000 | (back as u32 & 0xFFFF)); // s_cbranch_scc1 + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + ]); + w.extend(side.words()); + w.extend([S_AND_SAVEEXEC_S20_VCC, s_cbranch_execz(body.len())]); + w.extend(body); + w.push(S_MOV_EXEC_S20); + w.extend(store(1, 0)); + w.push(S_ENDPGM); + w +} + +/// The console's [`ballot_below`]`(limit)` in lane `l` of a group of +/// `threads` where the lanes `active` runs it: the count of its console +/// wave's active lanes below `limit`, and their high dword. +fn console_ballot(threads: u32, l: u32, active: impl Fn(u32) -> bool, limit: u32) -> [u32; 2] { + let wave = l & !63; + let on = |t: u32| t < threads && active(t) && t < limit; + let count = (wave..wave + 64).filter(|&t| on(t)).count() as u32; + let high = (0..32) + .filter(|&k| on(wave + 32 + k)) + .fold(0u32, |m, k| m | 1 << k); + [count, high] +} + +/// The divergent test programs are what their comments say. +#[test] +fn the_divergent_ballot_programs_are_what_their_comments_say() { + let programs: Vec<(Vec, &[&str])> = vec![ + ( + ballot_in_an_if(Side::Even, 50), + &[ + "v_and_b32 v3, 1, v0", + "v_cmp_eq_u32 vcc, 0, v3", + "s_and_saveexec_b64 s[20:21], vcc", + "s_cbranch_execz", + "s_bcnt1_i32_b64 s12, vcc", + "s_mov_b64 exec, s[20:21]", + ], + ), + ( + ballots_in_an_if_and_else(Side::Even, 50, 40), + &["s_andn2_b64 exec, s[20:21], exec", "v_mov_b32 v2, vcc_hi"], + ), + ( + ballot_in_an_if_in_a_loop(Side::Even, 50), + &[ + "s_mov_b32 s22, 0", + "v_add_nc_u32 v1, s12, v1", + "s_add_u32 s22, s22, 1", + "s_cmp_lt_u32 s22, 2", + "s_cbranch_scc1", + ], + ), + ]; + for (words, wants) in programs { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + for want in wants { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } + } +} + +/// A lane mask read as data in divergent code: the halves meet there +/// (`lower::meet`) in groups of more than one host wave, and the program +/// validates; a loop inside the branch keeps it refused. +#[test] +fn lane_masks_in_divergent_code_meet_between_halves() { + let programs = [ + ballot_in_an_if(Side::Even, 50), + ballot_in_an_if(Side::Below(20), 64), + ballots_in_an_if_and_else(Side::Even, 50, 40), + ballot_in_an_if_in_a_loop(Side::Below(40), 64), + ]; + for words in &programs { + for threads in [32, 64, 96, 128] { + assert_eq!(refusal(words, threads, 0), "translated", "{threads} threads"); + } + let halves = lowered(&native(words, true, 128, 0), true).expect("halves"); + assert_eq!(halves.wave_size, Some(32)); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut halves.dxil.clone()) + .expect("DXIL validation failed"); + } + } + let looped = ballot_in_a_loop_in_an_if(Side::Even, 50); + // Refused before main's scalar mask numbers (`Lower::mask_number`), + // which now give such a mask as the console does: either is right. + let why = refusal(&looped, 64, 0); + assert!( + why == "translated" || why.contains("a lane mask read as data (wave64 on a 32-lane host)"), + "{why}" + ); + assert_eq!(refusal(&looped, 32, 0), "translated"); + // Without the rendezvous, refused as before. + let n = native(&programs[0], true, 64, 0); + let p = ir::build(&n.code, n.wave64, n.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &n.layout, n.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &n).expect("io::raise"); + let off = lower::lower(&lower::Parts { + uav_size_level0: false, + native: &n, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: false, + atomic_locks: false, + atomic_lock_rounds: false, + atomic_umax: false, + bias_as_gradients: false, + narrow_waves: false, + halves_rendezvous: false, + host_wave32: true, + }); + let why = off.err().map(|e| e.to_string()).unwrap_or_else(|| "translated".into()); + assert!( + why == "translated" || why.contains("a lane mask read as data (wave64 on a 32-lane host)"), + "{why}" + ); +} + +/// The divergent ballots on every hardware adapter give the console's +/// masks: some lanes of each half in the branch, only the lower half's +/// (the upper half meets no one and must not wait), both sides of an if +/// and else, two console waves diverging differently (128 threads), a +/// console wave with no upper half (96), and the branch in a loop run +/// twice (the epochs). +#[test] +fn lane_masks_in_divergent_code_match_the_console_on_every_gpu() { + let mut failed = Vec::new(); + let cases = [ + (Side::Even, 50, 64), + (Side::Below(20), 64, 64), + (Side::Below(20), 64, 128), + (Side::Below(80), 100, 128), + (Side::Even, 90, 128), + (Side::Even, 90, 96), + (Side::Below(40), 70, 96), + ]; + for (side, limit, threads) in cases { + let want: Vec = (0..threads) + .flat_map(|l| { + if side.takes(l) { + console_ballot(threads, l, |t| side.takes(t), limit) + } else { + [u32::MAX; 2] + } + }) + .collect(); + failed.extend(differences(&ballot_in_an_if(side, limit), threads, 2, &want)); + } + for (side, limit, other, threads) in [ + (Side::Even, 50, 40, 64), + (Side::Below(20), 64, 40, 64), + (Side::Below(80), 100, 110, 128), + (Side::Even, 90, 70, 96), + ] { + let want: Vec = (0..threads) + .flat_map(|l| { + if side.takes(l) { + console_ballot(threads, l, |t| side.takes(t), limit) + } else { + console_ballot(threads, l, |t| !side.takes(t), other) + } + }) + .collect(); + failed.extend(differences( + &ballots_in_an_if_and_else(side, limit, other), + threads, + 2, + &want, + )); + } + for (side, limit, threads) in [ + (Side::Below(40), 64, 64), + (Side::Even, 90, 128), + (Side::Below(20), 64, 96), + ] { + let want: Vec = (0..threads) + .map(|l| { + if side.takes(l) { + 2 * console_ballot(threads, l, |t| side.takes(t), limit)[0] + } else { + 0 + } + }) + .collect(); + failed.extend(differences( + &ballot_in_an_if_in_a_loop(side, limit), + threads, + 1, + &want, + )); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 301378bf4..79f24ed52 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -947,6 +947,7 @@ fn fmad_probe() -> Result { host_wave32: false, narrow_waves: false, uav_size_level0: false, + halves_rendezvous: false, view_marks: false, })?; Ok(HostShader { diff --git a/crates/victory-shader/src/emit/image_store_tests.rs b/crates/victory-shader/src/emit/image_store_tests.rs index fac5c343a..9190e5b30 100644 --- a/crates/victory-shader/src/emit/image_store_tests.rs +++ b/crates/victory-shader/src/emit/image_store_tests.rs @@ -138,6 +138,7 @@ fn lower(native: &NativeProgram) -> Result { resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(&p, native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 705cc7558..fa3bafc36 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -28,6 +28,7 @@ mod bvh; #[path = "half_views.rs"] mod half_views; mod halves; +mod meet; mod packed; mod round_mode; mod mesh; @@ -37,6 +38,8 @@ use barriers::split_wave_barriers; use barriers::{in_step, split_wave_barriers_with_step, step_and_cap}; pub(crate) use mesh::KeptOutputs; use mesh::prune_signature; +pub(crate) use meet::MeetSite; +use super::bitcode::Rmw; use packed::packed_half; use round_mode::{round16, round16_after}; @@ -196,6 +199,9 @@ pub(crate) struct Parts<'a> { pub bias_as_gradients: bool, /// The host's waves have at most 32 lanes (`emit::Options::host_wave32`). pub host_wave32: bool, + /// In halves, the two halves of a console wave meet in divergent code + /// ([`Options::halves_rendezvous`](super::Options), `lower::meet`). + pub halves_rendezvous: bool, /// See [`Options::narrow_waves`](super::Options). pub narrow_waves: bool, /// A size query on a writable image asks for level 0, not an undefined @@ -285,8 +291,18 @@ fn lower_with_structure( per_vertex_center: bool, ) -> Result { let mut bad = HashMap::new(); + // Divergent sites where the halves meet (`lower::meet`): a pass that + // finds new ones goes again with them laid out. + let mut plan: Set = Set::default(); loop { - match Lower::new(parts, &bad, keep, per_vertex_center).run() { + let found = std::cell::RefCell::new(Set::default()); + let r = Lower::new(parts, &bad, keep, per_vertex_center, &plan, &found).run(); + let found = found.into_inner(); + if !found.is_empty() { + plan.extend(found); + continue; + } + match r { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -487,6 +503,18 @@ struct Lower<'a> { /// In halves: the group-shared dwords values pass between the halves /// through, once made ([`Lower::exchange_halves`]). half_words: Option, + /// In halves, a group of more than one host wave: the divergent + /// regions where the halves can meet (`lower::meet`). + meet: Option, + /// The sites earlier passes found, laid out in this one. + meet_plan: &'a Set, + /// Sites this pass found that are not laid out yet. + meet_found: &'a std::cell::RefCell>, + meet_layout: meet::MeetLayout, + /// The rendezvous words, once made ([`Lower::meet_prologue`]). + meet_words: Option, + /// Each region's epoch, from its branch block's end on. + meet_epoch: Map, /// The DXIL block the instruction being lowered starts in: every lane /// running its IR block runs it (no guard of the instruction's own). level: usize, @@ -734,6 +762,8 @@ impl<'a> Lower<'a> { bad: &'a HashMap, keep: Option<&KeptOutputs>, per_vertex_center: bool, + meet_plan: &'a Set, + meet_found: &'a std::cell::RefCell>, ) -> Self { let p = x.p; let mut phi_at = Map::default(); @@ -915,7 +945,10 @@ impl<'a> Lower<'a> { } } let (step, cap_escaped, group_scalars) = step_and_cap(p, x.st, halves); - Lower { + let one_host_wave = s.threads.is_some_and(|t| t.iter().product::() <= 32); + let meet = (halves && !one_host_wave && x.halves_rendezvous) + .then(|| meet::meet_regions(p, x.st, &step)); + let mut l = Lower { s, x, bad, @@ -984,6 +1017,12 @@ impl<'a> Lower<'a> { group_scalars, cap_escaped, half_words: None, + meet, + meet_plan, + meet_found, + meet_layout: meet::MeetLayout::default(), + meet_words: None, + meet_epoch: Map::default(), level: 0, alike: if halves { halves::lane_uniform(x) @@ -1027,7 +1066,9 @@ impl<'a> Lower<'a> { abort: None, round16: round16(p), mode16: Some(0), - } + }; + l.lay_out_meet(); + l } /// The dword of the program's code at byte `byte` (a constant table @@ -1623,6 +1664,7 @@ impl<'a> Lower<'a> { } self.find_sections(); self.inputs()?; + self.meet_prologue(); if let Some(mesh) = self.s.mesh { self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; self.block[order[0]] = Some(self.cur); @@ -1667,6 +1709,7 @@ impl<'a> Lower<'a> { self.vals.insert(phi.value, val); } } + self.meet_enter(b); let mut i = 0; self.mode16 = self.round16[b]; while i < p.blocks[b].insts.len() { @@ -1684,6 +1727,7 @@ impl<'a> Lower<'a> { if self.split_barriers.contains(&(b, i)) { self.group_barrier(); } + self.meet_masks(b, Some(i)); self.level = self.cur; self.inst(b, i)?; self.mode16 = round16_after(&p.blocks[b].insts[i], self.mode16); @@ -1700,6 +1744,12 @@ impl<'a> Lower<'a> { if self.split_barriers.contains(&(b, p.blocks[b].insts.len())) { self.group_barrier(); } + self.meet_masks(b, None); + let offset = p.blocks[b] + .insts + .last() + .map_or(p.blocks[b].offset, |i| i.machine.offset); + self.meet_exit(b).map_err(|w| unsupported(offset, w))?; self.mask_ok = self.mask_data == MaskData::Console; self.tail[b] = Some(self.cur); self.level = self.cur; @@ -2307,6 +2357,15 @@ impl<'a> Lower<'a> { if across { match self.across_at(def) { Some(a) => at = a, + // In divergent code the halves meet there (laid + // out by the next pass: a stand-in until then). + None if def + .is_some_and(|d| self.meet_later(MeetSite::Mask(lo), d)) => + { + let zero = self.s.m.i32(0); + self.ballots.insert(lo, (zero, zero)); + return Ok(zero); + } None => { if let Ok(xy) = self.mask_number(lo) { self.ballots.insert(lo, xy); diff --git a/crates/victory-shader/src/emit/lower/meet.rs b/crates/victory-shader/src/emit/lower/meet.rs new file mode 100644 index 000000000..7a42e4acb --- /dev/null +++ b/crates/victory-shader/src/emit/lower/meet.rs @@ -0,0 +1,694 @@ +//! Rendezvous of the two 32-lane halves of a console wave64 in divergent +//! code (`lower::halves`), where no group barrier can go. +//! +//! In halves a console wave runs as host waves `2w` and `2w + 1`. Values +//! cross between them through group-shared memory; between group barriers +//! ([`Lower::exchange_halves`]) only in a block every lane of the group runs +//! together ([`in_step`]). Here the two host waves of one console wave wait +//! for each other by spinning on group-shared memory instead, which needs +//! no other wave of the group. Measured on an M5 Pro (D3DMetal 4.0b3): two +//! host waves of one group spinning on each other's group-shared words +//! (exchange to publish, a group-shared fence, `or` 0 to poll) never timed +//! out, from 64 to 65,536 groups, with the other half busy for ~100k spins. +//! A lane spinning on another lane of its own host wave never finishes on +//! Apple GPUs; nothing here does that: a host wave only ever waits for the +//! other one. +//! +//! # Where +//! +//! A site is an exchange (a lane mask's ballot, [`MeetSite::Mask`]) in a +//! block that is not [`in_step`]. Its region `R` is that of the outermost +//! divergent branch around it whose branch block `B` is in step +//! ([`meet_regions`]): the blocks only the lanes taking one side of `B`'s +//! branch may run. `R` must be acyclic, entered only from `B`, and left +//! only to one block `J` (`B`'s immediate post-dominator) or the program's +//! end. Elsewhere the exchange stays refused. +//! +//! # Epochs +//! +//! Both halves run `B` equally often (it is in step), so each counts its +//! runs of `B` alike: the epoch `e` (1 when `B` is in no cycle). Every word a +//! half publishes is tagged with it, so a word from an earlier run of `R` +//! never passes for this one. Where `B` is in a cycle, `J` must be in step +//! too and gets a group barrier: no half starts its next run of `R` (and +//! overwrites its words) before the other is done reading this one's. The +//! words are zeroed in the entry block, before one group barrier: group- +//! shared memory starts undefined. +//! +//! # Words (per host wave, per region) +//! +//! * `epoch`: the half's count of runs of `B` (only where `B` is in a cycle); +//! * `count`: `e << 8 | n`, `n` the half's lanes at `B`'s end, published +//! there (after the `resolved` words are reset to `e << 8`); +//! * per site: `arrived` (`e` once the half ran the site, after `value`), +//! `value` (the half's own: its ballot), and `resolved` (`e << 8` plus +//! one per lane of the half that is done with the site this epoch). +//! +//! A lane is done with a site once it ran it (counted after its own wait), +//! or once it took an edge after which the site's block cannot be reached +//! (counted on that edge, at the end of the block it leaves: [`Lower:: +//! meet_leave`]), or when it ends. Along a lane's path through the acyclic +//! `R` what it can still reach only shrinks, so it counts each site once. +//! +//! # A site +//! +//! The half stores its value, fences, publishes `arrived = e`, then spins +//! (at most [`MEET_SPINS`] times) until the other half's `arrived` is `e` +//! (its value is read) or its `resolved` equals its `count` with the tag +//! `e` (all its lanes are done with the site without running it: ballot 0). +//! `resolved` is read before `arrived`, with a fence between: a half +//! publishes `arrived` before its lanes count the site resolved, so a full +//! count read first means `arrived` is seen if it was set. A console wave +//! with no upper half (a group not a multiple of 64) waits for nothing. +//! +//! # Why it cannot deadlock +//! +//! Assume, as the lowering of a ballot in divergent code does anyway, that a +//! host wave runs each block of `R` at most once per epoch with all its lanes +//! that reach it, and that it runs the blocks of `R` in one topological order +//! of `R`, the same for both halves (the order of the compiled code, which +//! both run). Let half `A` wait at site `k` for half `H`. `H` is either +//! (a) before `B` of this epoch: it is not blocked by `A` there (a group +//! barrier `A` passed has seen `H` too, and an earlier epoch's sites `A` has +//! all resolved or run), so it comes; (b) in `R`, waiting at a site `q`: if +//! `q` is `k`, both have arrived. If `q` comes before `k` in the common +//! order, `A` has run past `q`: every lane of `A` either ran `q` or is at a +//! block after `q` in topological order, from which `q` cannot be reached, +//! so it counted `q` on the way; so `A`'s `q` is arrived or fully resolved, +//! and `H` goes on. If `q` comes after `k`, the same holds with the roles +//! swapped: every lane of `H` has run `k` or counted it, so `A` goes on; +//! (c) past `R`: all of its lanes have resolved or run every site. A +//! console wave's two halves thus never wait for each other in a cycle. +//! The spin bound is a fuse, not part of the argument: a half that runs +//! out reads the other's lanes as absent. +//! +//! What is assumed is what the single-wave lowering of a ballot in +//! divergent code already relies on (the host runs a block once with the +//! lanes reaching it); a host that ran the halves' divergent paths in +//! different orders could make both wait out [`MEET_SPINS`]. + +use super::*; + +/// How many times a half polls the other's words at a site before it +/// reads the other's lanes as absent. +pub(super) const MEET_SPINS: u32 = 1 << 20; + +/// An exchange between the halves of a console wave at a divergent site. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(crate) enum MeetSite { + /// The ballot of the lane mask with this low dword, taken right after + /// the instruction writing it. + Mask(Value), +} + +/// A divergent region whose branch block is in step ([`meet_regions`]). +pub(super) struct MeetRegion { + /// `B`: the branch block, in step. + pub branch: usize, + /// `J`: where every lane leaving the region goes (none: all end). + pub join: Option, + /// The region's blocks. + pub blocks: Vec, + /// `B` is in a cycle: it runs more than once. + pub looped: bool, + /// Per block of the region and `B`: the region's blocks reachable from + /// it by one edge or more. + pub reach: Map>, +} + +/// The regions where the halves can meet in a program, and which region +/// each block is in. +#[derive(Default)] +pub(super) struct Meet { + pub regions: Vec, + pub region_of: Vec>, +} + +/// Each divergent branch whose block is in step (`step`, [`in_step`]) and +/// whose region (`halves::branch_regions`) the halves can meet in: acyclic, +/// entered only from the branch, left only to one block or the end, and, +/// where the branch block is in a cycle, left to a block in step (where a +/// group barrier goes). A block in two such regions is in none. +pub(super) fn meet_regions(p: &Program, st: &Structured, step: &[bool]) -> Meet { + let n = st.exits.len(); + let mut meet = Meet { + regions: Vec::new(), + region_of: vec![None; n], + }; + let Some(regions) = halves::branch_regions(p, st) else { + return meet; + }; + let succ = |b: usize| -> Vec { + match st.exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { + taken, not_taken, .. + } => vec![taken, not_taken], + _ => Vec::new(), + } + }; + let mut preds: Vec> = vec![Vec::new(); n]; + for b in 0..n { + for t in succ(b) { + preds[t].push(b); + } + } + let mut conflict = vec![false; n]; + for (d, region) in regions { + if !step.get(d).copied().unwrap_or(false) || region[d] { + continue; + } + let blocks: Vec = (0..n).filter(|&b| region[b]).collect(); + // A uniform branch: its sides are in step. + if blocks.is_empty() || blocks.iter().all(|&b| step[b]) { + continue; + } + let entered_from_branch = blocks + .iter() + .all(|&b| preds[b].iter().all(|&q| q == d || region[q])); + let mut outside: Vec = blocks + .iter() + .chain([&d]) + .flat_map(|&b| succ(b)) + .filter(|&t| !region[t]) + .collect(); + outside.sort_unstable(); + outside.dedup(); + let ends = blocks.iter().any(|&b| st.exits[b] == LaneExit::End); + if !entered_from_branch + || outside.len() > 1 + || blocks + .iter() + .any(|&b| matches!(st.exits[b], LaneExit::Indirect)) + { + continue; + } + let join = outside.first().copied(); + // Acyclic: every block of the region in a topological order. + let mut ins: Vec = (0..n) + .map(|b| preds[b].iter().filter(|&&q| region[q]).count()) + .collect(); + let mut ready: Vec = blocks.iter().copied().filter(|&b| ins[b] == 0).collect(); + let mut sorted = 0; + while let Some(b) = ready.pop() { + sorted += 1; + for t in succ(b) { + if region[t] { + ins[t] -= 1; + if ins[t] == 0 { + ready.push(t); + } + } + } + } + if sorted != blocks.len() { + continue; + } + // The branch block in a cycle: reached again from its successors. + let mut seen = vec![false; n]; + let mut stack = succ(d); + while let Some(b) = stack.pop() { + if !std::mem::replace(&mut seen[b], true) { + stack.extend(succ(b)); + } + } + let looped = seen[d]; + if looped && (ends || !join.is_some_and(|j| step[j])) { + continue; + } + let mut reach = Map::default(); + for &u in blocks.iter().chain([&d]) { + let mut r = vec![false; n]; + let mut stack: Vec = succ(u).into_iter().filter(|&t| region[t]).collect(); + while let Some(b) = stack.pop() { + if !std::mem::replace(&mut r[b], true) { + stack.extend(succ(b).into_iter().filter(|&t| region[t])); + } + } + reach.insert(u, r); + } + let k = meet.regions.len(); + for &b in &blocks { + if meet.region_of[b].is_some() { + conflict[b] = true; + } + meet.region_of[b] = Some(k); + } + meet.regions.push(MeetRegion { + branch: d, + join, + blocks: region, + looped, + reach, + }); + } + // A block in two regions: neither region's sites there can meet. + for (b, c) in conflict.iter().enumerate() { + if *c { + meet.region_of[b] = None; + } + } + meet +} + +/// Where a site's exchange sits in the group-shared words. +#[derive(Clone, Copy)] +pub(super) struct MeetSlot { + pub region: usize, + /// The site's three words: `arrived`, `value`, `resolved`. + pub word: u32, + pub block: usize, +} + +/// The layout of the rendezvous words: per region, its first word (the +/// epoch, then the count) and its sites; the words per host wave. +#[derive(Default)] +pub(super) struct MeetLayout { + pub slots: Map, + pub region_base: Vec, + pub region_sites: Vec>, + /// Mask sites per IR block: (instruction before which, site), in order. + pub masks: Map>, + /// Words per host wave, a multiple of 32. + pub stride: u32, +} + +impl Lower<'_> { + /// Whether an exchange at `site`, in IR block `block`, can wait for the + /// other half there; if so (and it is not laid out yet) it is noted for + /// the next pass (`lower_pruned`), and this pass goes on with a stand-in. + pub(super) fn meet_later(&mut self, site: MeetSite, block: usize) -> bool { + let Some(meet) = &self.meet else { + return false; + }; + if meet.region_of.get(block).copied().flatten().is_none() || self.meet_plan.contains(&site) + { + return false; + } + self.meet_found.borrow_mut().insert(site); + true + } + + /// Lays out the words of the sites `plan` names (found by an earlier + /// pass), if group-shared memory has room for them. + pub(super) fn lay_out_meet(&mut self) { + let Some(meet) = &self.meet else { + return; + }; + let p = self.x.p; + let mut sites: Vec<(usize, usize, MeetSite)> = Vec::new(); + for &site in self.meet_plan { + let MeetSite::Mask(lo) = site; + let Some(&b) = self.def_block.get(&lo) else { + continue; + }; + let Some(_) = meet.region_of[b] else { + continue; + }; + // Right after the instruction writing it (a phi: at the start). + let at = p.blocks[b] + .insts + .iter() + .position(|i| i.writes.iter().any(|w| w.1 == lo)) + .map_or(0, |i| i + 1); + sites.push((b, at, site)); + } + sites.sort_unstable(); + let mut layout = MeetLayout { + region_base: vec![0; meet.regions.len()], + region_sites: vec![Vec::new(); meet.regions.len()], + ..MeetLayout::default() + }; + for &(b, _, site) in &sites { + let r = meet.region_of[b].expect("in a region"); + layout.region_sites[r].push(site); + } + let mut word = 0; + for r in 0..meet.regions.len() { + if layout.region_sites[r].is_empty() { + continue; + } + layout.region_base[r] = word; + word += 2; + for &site in &layout.region_sites[r] { + let &(b, _, _) = sites.iter().find(|s| s.2 == site).expect("listed"); + layout.slots.insert( + site, + MeetSlot { + region: r, + word, + block: b, + }, + ); + word += 3; + } + } + if word == 0 { + return; + } + for &(b, at, site) in &sites { + layout.masks.entry(b).or_default().push((at, site)); + } + layout.stride = word.next_multiple_of(32); + let group: u32 = self.s.threads.map_or(0, |t| t.iter().product()); + let waves = group.div_ceil(64) * 2; + // Room for these and for the barrier exchanges' words too. + if self.s.lds_dwords + waves * layout.stride + waves > GROUP_SHARED_DWORDS { + return; + } + self.meet_layout = layout; + } + + /// The rendezvous words, zeroed by every lane in the entry block before + /// a group barrier; none without sites. + pub(super) fn meet_prologue(&mut self) { + if self.meet_layout.stride == 0 { + return; + } + let group: u32 = self.s.threads.map_or(0, |t| t.iter().product()); + let waves = group.div_ceil(64) * 2; + let stride = self.meet_layout.stride; + let i32t = self.s.t.i32; + let arr = self.s.m.array(waves * stride, i32t); + let g = self.s.m.global("half_meet", arr, 3); + self.meet_words = Some(g); + let c = self.cur; + let f = self.relabelled_flat(); + let (k5, k31) = (self.s.m.i32(5), self.s.m.i32(31)); + let slot = self.s.m.bin(c, Bin::LShr, f, k5); + let k = self.s.m.i32(stride); + let base = self.s.m.bin(c, Bin::Mul, slot, k); + let lane = self.s.m.bin(c, Bin::And, f, k31); + let first = self.s.m.bin(c, Bin::Add, base, lane); + let zero = self.s.m.i32(0); + for j in (0..stride).step_by(32) { + let off = self.s.m.i32(j); + let at = self.s.m.bin(c, Bin::Add, first, off); + let ptr = self.s.m.element(c, g, at); + self.s.m.store(c, ptr, zero); + } + self.group_barrier(); + } + + /// Element `word` of this host wave's (`other`: the other half's) + /// rendezvous words, in block `at`. + fn meet_word(&mut self, at: usize, word: u32, other: bool) -> V { + let g = self.meet_words.expect("laid out"); + let f = self.relabelled_flat(); + let k5 = self.s.m.i32(5); + let mut slot = self.s.m.bin(at, Bin::LShr, f, k5); + if other { + let one = self.s.m.i32(1); + slot = self.s.m.bin(at, Bin::Xor, slot, one); + } + let k = self.s.m.i32(self.meet_layout.stride); + let base = self.s.m.bin(at, Bin::Mul, slot, k); + let w = self.s.m.i32(word); + let i = self.s.m.bin(at, Bin::Add, base, w); + self.s.m.element(at, g, i) + } + + /// A group-shared memory fence, with no sync: allowed where the lanes + /// of the group are not all together. + fn meet_fence(&mut self, at: usize) { + let mode = self.s.m.i32(8); + let void = self.s.t.void; + self.s + .op(at, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// The region IR block `b` is the branch block of, with sites. + fn meet_branch_of(&self, b: usize) -> Option { + let meet = self.meet.as_ref()?; + (0..meet.regions.len()) + .find(|&r| meet.regions[r].branch == b && !self.meet_layout.region_sites[r].is_empty()) + } + + /// At the start of IR block `b`: a group barrier if it is the join of a + /// region with sites whose branch block runs more than once (no half + /// starts the region again before the other is done with it). + pub(super) fn meet_enter(&mut self, b: usize) { + if self.meet_layout.stride == 0 { + return; + } + let meet = self.meet.as_ref().expect("laid out"); + let barrier = (0..meet.regions.len()).any(|r| { + let g = &meet.regions[r]; + g.looped && g.join == Some(b) && !self.meet_layout.region_sites[r].is_empty() + }); + if barrier { + self.group_barrier(); + } + } + + /// The mask sites of IR block `b` before instruction `i` (`None`: all + /// left, at its end): each mask's ballot, met between the halves. + pub(super) fn meet_masks(&mut self, b: usize, i: Option) { + let Some(list) = self.meet_layout.masks.get_mut(&b) else { + return; + }; + let n = list + .iter() + .take_while(|(at, _)| i.is_none_or(|i| *at <= i)) + .count(); + let due: Vec = list.drain(..n).map(|(_, s)| s).collect(); + for site in due { + let MeetSite::Mask(lo) = site; + if self.ballots.contains_key(&lo) { + continue; + } + let Some(&m) = self.x.st.masks.get(&lo) else { + continue; + }; + let Ok(bit) = self.boolean(m, self.cur) else { + continue; + }; + let c = self.cur; + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self + .s + .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); + self.s.flags |= flags::WAVE_OPS; + let own = self.s.m.extract(c, r, 0); + let zero = self.s.m.i32(0); + if let Ok(xy) = self.meet_halves(site, own, zero) { + self.ballots.insert(lo, xy); + } + } + } + + /// At the end of IR block `b`, before its exit: as a region's branch + /// block, the half's epoch, its `resolved` words reset and its lane + /// count published; as the branch block or a block of a region with + /// sites, the sites its lanes are done with on leaving + /// ([`Lower::meet_leave`]). + pub(super) fn meet_exit(&mut self, b: usize) -> Result<(), Why> { + if self.meet_layout.stride == 0 { + return Ok(()); + } + if let Some(r) = self.meet_branch_of(b) { + self.meet_start(r); + self.meet_leave(r, b)?; + } + let r = self.meet.as_ref().expect("laid out").region_of[b]; + if let Some(r) = r + && !self.meet_layout.region_sites[r].is_empty() + { + self.meet_leave(r, b)?; + } + Ok(()) + } + + /// The epoch of region `r` at its branch block's end, the half's + /// `resolved` words reset to it, then its count of lanes published. + fn meet_start(&mut self, r: usize) { + let c = self.cur; + let base = self.meet_layout.region_base[r]; + let looped = self.meet.as_ref().expect("laid out").regions[r].looped; + let e = if looped { + let p = self.meet_word(c, base, false); + let old = self.s.m.load(c, p); + let one = self.s.m.i32(1); + let e = self.s.m.bin(c, Bin::Add, old, one); + self.s.m.store(c, p, e); + e + } else { + self.s.m.i32(1) + }; + let k8 = self.s.m.i32(8); + let tag = self.s.m.bin(c, Bin::Shl, e, k8); + for site in self.meet_layout.region_sites[r].clone() { + let w = self.meet_layout.slots[&site].word; + let p = self.meet_word(c, w + 2, false); + self.s.m.store(c, p, tag); + } + self.meet_fence(c); + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let yes = self.s.m.bool(true); + let ballot = self + .s + .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]); + self.s.flags |= flags::WAVE_OPS; + let lanes = self.s.m.extract(c, ballot, 0); + let n = self.unary_bits(c, 31, lanes); + let count = self.s.m.bin(c, Bin::Or, tag, n); + let p = self.meet_word(c, base + 1, false); + self.s.m.atomic(c, Rmw::Xchg, p, count); + self.meet_epoch.insert(r, e); + } + + /// The sites of region `r` the lanes leaving IR block `b` (in the + /// region, or its branch block) are done with: those still ahead of + /// `b` that the block a lane goes to cannot reach. Each such lane adds + /// one to the half's `resolved` word of each. + fn meet_leave(&mut self, r: usize, b: usize) -> Result<(), Why> { + let meet = self.meet.as_ref().expect("laid out"); + let g = &meet.regions[r]; + let ahead = |u: usize, s: usize| g.reach.get(&u).is_some_and(|x| x[s]); + // Sites still ahead after going to `v`: in `v` or reachable from it. + let kept = |v: usize, s: usize| g.blocks[v] && (s == v || ahead(v, s)); + let exit = self.x.st.exits[b]; + let (to, other) = match exit { + LaneExit::Jump(v) => (Some(v), None), + LaneExit::Branch { + taken, not_taken, .. + } => (Some(taken), Some(not_taken)), + _ => (None, None), + }; + // Per site ahead of `b`: its word, and whether it stays ahead on + // the (taken) and the not-taken way. + let sites: Vec<(u32, bool, bool)> = self.meet_layout.region_sites[r] + .iter() + .map(|s| self.meet_layout.slots[s]) + .filter(|slot| ahead(b, slot.block)) + .map(|slot| { + let on = |v: Option| v.is_some_and(|v| kept(v, slot.block)); + (slot.word, on(to), on(other)) + }) + .collect(); + if sites.is_empty() { + return Ok(()); + } + let c = self.cur; + let (zero, one) = (self.s.m.i32(0), self.s.m.i32(1)); + let adds: Vec<(u32, V)> = match exit { + LaneExit::Branch { when, .. } => { + let cond = self.boolean(when, c)?; + let on_taken = self.s.m.select(c, cond, one, zero); + let on_not = self.s.m.select(c, cond, zero, one); + sites + .iter() + .filter_map(|&(w, t, f)| match (t, f) { + (false, false) => Some((w, one)), + (false, true) => Some((w, on_taken)), + (true, false) => Some((w, on_not)), + (true, true) => None, + }) + .collect() + } + _ => sites + .iter() + .filter(|&&(_, t, _)| !t) + .map(|&(w, _, _)| (w, one)) + .collect(), + }; + for (w, by) in adds { + let p = self.meet_word(c, w + 2, false); + self.s.m.atomic(c, Rmw::Add, p, by); + } + Ok(()) + } + + /// What each half of this lane's console wave gives as `own` at the + /// divergent site `site` (a dword the same in every lane of the host + /// wave): (lower half's, upper half's), the other's `missing` where it + /// has no lane there (see the module notes). Lowered at [`Lower::cur`], + /// which moves past the wait. + pub(super) fn meet_halves( + &mut self, + site: MeetSite, + own: V, + missing: V, + ) -> Result<(V, V), Why> { + const UNLAID: Why = + "a rendezvous between 32-lane halves with no words (wave64 on a 32-lane host)"; + let slot = *self.meet_layout.slots.get(&site).ok_or(UNLAID)?; + let e = *self.meet_epoch.get(&slot.region).ok_or(UNLAID)?; + let count = self.meet_layout.region_base[slot.region] + 1; + let w = slot.word; + let i32t = self.s.t.i32; + let c = self.cur; + let value = self.meet_word(c, w + 1, false); + self.s.m.store(c, value, own); + self.meet_fence(c); + let arrived = self.meet_word(c, w, false); + self.s.m.atomic(c, Rmw::Xchg, arrived, e); + // A console wave with no upper half waits for nothing. + let group: u32 = self.s.threads.map_or(0, |t| t.iter().product()); + let gone = if group.is_multiple_of(2 * HALF_LANES) { + None + } else { + let f = self.relabelled_flat(); + let (k5, one) = (self.s.m.i32(5), self.s.m.i32(1)); + let slot = self.s.m.bin(c, Bin::LShr, f, k5); + let other = self.s.m.bin(c, Bin::Xor, slot, one); + let first = self.s.m.bin(c, Bin::Shl, other, k5); + let n = self.s.m.i32(group); + Some(self.s.m.cmp(c, pred::IUGE, first, n)) + }; + let head = self.s.m.new_block(); + let after = self.s.m.new_block(); + self.s.m.terminate(c, Term::Br(head)); + let spins = self.s.m.phi(head, i32t); + let zero = self.s.m.i32(0); + let p = self.meet_word(head, count, true); + let counted = self.s.m.atomic(head, Rmw::Or, p, zero); + let p = self.meet_word(head, w + 2, true); + let resolved = self.s.m.atomic(head, Rmw::Or, p, zero); + self.meet_fence(head); + let p = self.meet_word(head, w, true); + let there = self.s.m.atomic(head, Rmw::Or, p, zero); + let got = self.s.m.cmp(head, pred::EQ, there, e); + let k8 = self.s.m.i32(8); + let tag = self.s.m.bin(head, Bin::LShr, counted, k8); + let tagged = self.s.m.cmp(head, pred::EQ, tag, e); + let full = self.s.m.cmp(head, pred::EQ, resolved, counted); + let none = self.s.m.bin(head, Bin::And, tagged, full); + let one = self.s.m.i32(1); + let next = self.s.m.bin(head, Bin::Add, spins, one); + let bound = self.s.m.i32(MEET_SPINS); + let spent = self.s.m.cmp(head, pred::IUGE, next, bound); + let mut stop = self.s.m.bin(head, Bin::Or, got, none); + stop = self.s.m.bin(head, Bin::Or, stop, spent); + if let Some(gone) = gone { + stop = self.s.m.bin(head, Bin::Or, stop, gone); + } + self.s.m.terminate(head, Term::CondBr(stop, after, head)); + self.s.m.set_phi(spins, vec![(zero, c), (next, head)]); + self.meet_fence(after); + let p = self.meet_word(after, w + 1, true); + let theirs = self.s.m.load(after, p); + let theirs = self.s.m.select(after, got, theirs, missing); + // This half's lanes here are done with the site. + let p = self.meet_word(after, w + 2, false); + self.s.m.atomic(after, Rmw::Add, p, one); + self.cur = after; + let f = self.relabelled_flat(); + let k5 = self.s.m.i32(5); + let slot = self.s.m.bin(after, Bin::LShr, f, k5); + let h = self.s.m.bin(after, Bin::And, slot, one); + let upper = self.s.m.cmp(after, pred::NE, h, zero); + let lo = self.s.m.select(after, upper, theirs, own); + let hi = self.s.m.select(after, upper, own, theirs); + Ok((lo, hi)) + } +} + +/// Console lanes per host wave in halves. +const HALF_LANES: u32 = 32; + +/// The group-shared dwords a D3D12 compute program may declare, at most +/// (32 KiB). +const GROUP_SHARED_DWORDS: u32 = 8192; diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs index 61a901de4..2a0a8322b 100644 --- a/crates/victory-shader/src/emit/lower/tests.rs +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -67,6 +67,7 @@ fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = io::raise(&p, &native).unwrap(); lower(&Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -125,6 +126,7 @@ fn lower_wave( let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; let io = io::raise(&p, &native).unwrap(); lower(&Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -434,6 +436,7 @@ fn perm_features(selector: u32) -> u64 { let io = io::raise(&p, &native).unwrap(); let emitted = lower(&Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -1412,6 +1415,7 @@ fn lowered_result( let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = io::raise(&p, &native).unwrap(); lower(&Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -1643,6 +1647,7 @@ fn lowered_halves(words: &[u32], lanes: u32) -> Result Result { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -293,6 +294,7 @@ fn program() -> HostShader { assert_eq!(memory, 11, "every access through the pointer is title memory"); let io = io::raise(&p, &native).expect("io::raise"); let l = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -506,6 +508,7 @@ fn runs_from_just_before_a_copy_read_its_first_dwords() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let l = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -695,6 +698,7 @@ fn root_views_read_their_copy_and_zeros_past_it() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, native).expect("io::raise"); lower::lower(&lower::Parts { + halves_rendezvous: false, native, p: &p, st: &st, @@ -855,6 +859,7 @@ fn writes_through_views_mark_their_pages() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let l = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -1099,6 +1104,7 @@ fn heap_direct_texture_reads_mark_their_heap_index() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -1232,6 +1238,7 @@ fn straddling_writes_across_256mib_and_4gib_boundaries_mark_exact_pages() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let l = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, @@ -1414,6 +1421,7 @@ fn early_depth_stencil_skips_occluded_read_mark_pixel_shaders() { let vres = resource::track(&vp, &vs_native.layout, vs_native.stage, Some(&vst)).expect("vs res"); let vio = io::raise(&vp, &vs_native).expect("vs io"); let vs_lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &vs_native, p: &vp, st: &vst, @@ -1514,6 +1522,7 @@ fn early_depth_stencil_skips_occluded_read_mark_pixel_shaders() { let pres = resource::track(&pp, &ps_native.layout, ps_native.stage, Some(&pst)).expect("ps res"); let pio = io::raise(&pp, &ps_native).expect("ps io"); let ps_lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &ps_native, p: &pp, st: &pst, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b2e5ebfe4..c5abfcfeb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -529,6 +529,12 @@ pub struct Options { /// `VICTORY_P10`/`VICTORY_P20` inputs from a geometry shader. Used as a /// mesh+pixel fallback where no geometry stage exists. pub per_vertex_center: bool, + /// With [`Options::host_wave32`]: the two 32-lane halves of a console + /// wave pass each other values in divergent code too, waiting for each + /// other on group-shared memory (`lower::meet`), where without it such + /// a read across the halves is refused. The translation differs, so + /// the shader cache keys on it. + pub halves_rendezvous: bool, } /// Metal's limit on a mesh shader's outputs per thread group, in bytes @@ -1059,6 +1065,7 @@ fn emit_pruned( host_wave32: options.host_wave32, narrow_waves: options.narrow_waves, uav_size_level0: options.uav_size_level0, + halves_rendezvous: options.halves_rendezvous, }; let l = match lower::lower_pruned( &parts(st, res), diff --git a/crates/victory-shader/src/emit/semantics_tests.rs b/crates/victory-shader/src/emit/semantics_tests.rs index e2047617a..12c13d2ee 100644 --- a/crates/victory-shader/src/emit/semantics_tests.rs +++ b/crates/victory-shader/src/emit/semantics_tests.rs @@ -283,6 +283,7 @@ fn lower_program(words: &[u32]) -> Result { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).map_err(e)?; let io = io::raise(&p, &native).map_err(e)?; let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/stride_tests.rs b/crates/victory-shader/src/emit/stride_tests.rs index ceb87b4bb..28ae0594a 100644 --- a/crates/victory-shader/src/emit/stride_tests.rs +++ b/crates/victory-shader/src/emit/stride_tests.rs @@ -234,6 +234,7 @@ fn build( let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/synthetic_tests.rs b/crates/victory-shader/src/emit/synthetic_tests.rs index 3944cead9..b7953f94f 100644 --- a/crates/victory-shader/src/emit/synthetic_tests.rs +++ b/crates/victory-shader/src/emit/synthetic_tests.rs @@ -134,6 +134,7 @@ fn lowered(native: &NativeProgram) -> Result let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, native).expect("io::raise"); lower::lower(&lower::Parts { + halves_rendezvous: false, native, p: &p, st: &st, @@ -925,6 +926,7 @@ fn pops_wait_loop_exits_immediately_for_inactive_lanes() { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource"); let io = io::raise(&p, native).expect("io"); let l = lower::lower(&lower::Parts { + halves_rendezvous: false, native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/typed_buffer_tests.rs b/crates/victory-shader/src/emit/typed_buffer_tests.rs index a604f6f49..de0833537 100644 --- a/crates/victory-shader/src/emit/typed_buffer_tests.rs +++ b/crates/victory-shader/src/emit/typed_buffer_tests.rs @@ -101,6 +101,7 @@ fn lowered() -> lower::Lowered { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st, diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index d0cd3fae6..dbccf761b 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -141,6 +141,7 @@ fn lower_valu_cs(native: &NativeProgram) -> Result HostShader { let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, &native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { + halves_rendezvous: false, native: &native, p: &p, st: &st,