diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 3bea26174..dc0c9fda6 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -3881,11 +3881,30 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { /// A program whose only cross-half operations are first-lane reads goes to /// halves for them (#522). Where halves cannot pass the read between them, -/// here in a loop counted to the host wave's first lane, it is translated as -/// before #522, each host wave reading its own first lane, rather than -/// refused (its draws dropped). +/// here in a loop counted to the console wave's first lane, it is refused, +/// with or without console lanes asked for as well: each 32-lane host wave +/// reading its own first lane would count the upper half's loop to thread +/// 32 and store 32 there, where the console stores 0 +/// ([`a_first_lane_read_in_a_loop_matches_the_console_on_every_gpu`]). #[test] -fn first_lane_reads_halves_refuse_fall_back_to_the_host_waves() { +fn first_lane_reads_halves_cannot_pass_are_refused() { + let words = first_lane_in_a_counted_loop(); + let with_mbcnt = in_a_loop(&[0x7E18_0500], 12, Count::FirstLane); + for threads in [64, 128, 256] { + for program in [&words, &with_mbcnt] { + let why = refusal(program, threads, 0); + assert!( + why.contains("a first-lane read of a value that may differ between 32-lane halves"), + "{threads} threads: {why}" + ); + } + } +} + +/// [`in_a_loop`] of `v_readfirstlane_b32 s12, v0` counted to the first +/// lane, without its `v_mbcnt`: a program whose only cross-half operations +/// are first-lane reads, one of them in a loop. +fn first_lane_in_a_counted_loop() -> Vec { let mbcnt = [0xD765_0001, 0x0001_00C1]; // v_mbcnt_lo_u32_b32 v1, -1, 0 let first = [0x7E18_0500]; // v_readfirstlane_b32 s12, v0 let with_mbcnt = in_a_loop(&first, 12, Count::FirstLane); @@ -3893,15 +3912,176 @@ fn first_lane_reads_halves_refuse_fall_back_to_the_host_waves() { .windows(2) .position(|w| w == mbcnt) .expect("in_a_loop's v_mbcnt"); - let words = [&with_mbcnt[..at], &with_mbcnt[at + 2..]].concat(); - for threads in [64, 128, 256] { - assert_eq!(refusal(&words, threads, 0), "translated", "{threads} threads"); - // With console lanes asked for as well, the program stays in halves, - // and the read is still refused there. - let why = refusal(&with_mbcnt, threads, 0); + [&with_mbcnt[..at], &with_mbcnt[at + 2..]].concat() +} + +/// A first-lane read the halves cannot pass between them is refused, never +/// made by each 32-lane host wave from its own first lane: on the console +/// every lane of a wave64 reads the wave's first lane, thread `l & !63`, +/// where the upper host wave's own first lane is thread `l & !31`. +#[cfg(windows)] +#[test] +fn a_first_lane_read_in_a_loop_matches_the_console_on_every_gpu() { + let words = first_lane_in_a_counted_loop(); + let mut failed = Vec::new(); + for threads in [64, 128] { + match lowered(&native(&words, true, threads, 0), true) { + Err(e) => { + let why = e.to_string(); + let across = "a first-lane read of a value that may differ between 32-lane halves"; + assert!(why.contains(across), "{threads} threads: {why}"); + } + Ok(_) => { + let want: Vec = (0..threads).map(|l| l & !63).collect(); + failed.extend(differences(&words, threads, 1, &want)); + } + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// `v_readfirstlane_b32 s12, v4` inside an `s_and_saveexec_b64` region +/// whose EXEC is `mask_words`'s, of `v4 = f32(s14) + 1.0` made there, with +/// `s14` the first dword of the SRV buffer at table dword 8 (a scalar load, +/// as in GTA VI's reciprocals of constant-buffer divisors): the same in +/// every lane EXEC has. `inside`: `v2 = s12` under the region's EXEC (only +/// lanes that ran the read see it), else after EXEC is restored (every +/// lane). +fn readfirstlane_of_a_scalar_in_branch( + mask_words: &[u32], + with_mbcnt: bool, + inside: bool, +) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0xF408_0B02, + 0xFA00_0020, // s_load_dwordx4 s[44:47], s[4:5], 0x20 + S_WAITCNT_LGKM, + 0xF420_0396, + 0xFA00_0000, // s_buffer_load_dword s14, s[44:47], 0x0 + S_WAITCNT_LGKM, + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E04_0280, // v_mov_b32 v2, 0 + ]); + if with_mbcnt { + w.extend([ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + ]); + } + w.extend(mask_words); + w.push(0xBE80_246A); // s_and_saveexec_b64 s[0:1], vcc + let region = [ + 0x7E08_0C0E, // v_cvt_f32_u32 v4, s14 + 0x0608_08F2, // v_add_f32 v4, 1.0, v4 + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + ]; + let skip = region.len() as u32 + u32::from(inside); + w.push(0xBF88_0000 | skip); // s_cbranch_execz (past the region) + w.extend(region); + if inside { + w.push(0x7E04_020C); // v_mov_b32 v2, s12 + } + w.push(0xBEFE_0400); // s_mov_b64 exec, s[0:1] + if !inside { + w.push(0x7E04_020C); // v_mov_b32 v2, s12 + } + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_scalar_readfirstlane_programs_are_what_their_comments_say() { + for inside in [false, true] { + let words = readfirstlane_of_a_scalar_in_branch(&MASK_LANES_40_41, true, inside); + 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 [ + "s_load_dwordx4 s[44:47], s[4:5], 0x000020", + "s_buffer_load_dword s14, s[44:47]", + "v_cmp_eq_u32 vcc, 20, v3", + "s_and_saveexec_b64 s[0:1], vcc", + "s_cbranch_execz", + "v_cvt_f32_u32 v4, s14", + "v_add_f32 v4, 1.0, v4", + "v_readfirstlane_b32 s12, v4", + "v_mov_b32 v2, s12", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } + } +} + +/// A first-lane read of a value every lane EXEC has computed alike, whose +/// result only those lanes see, is made by each host half by itself: its +/// own first active lane, with no value passed between the halves (none of +/// an exchange's group barriers), so it translates also where the halves +/// cannot meet (#522 refused it there). Seen by lanes outside the read's +/// EXEC, it still passes the halves' first lanes and ballots between them. +#[test] +fn a_first_lane_read_only_active_lanes_see_is_made_in_each_half() { + for mask in [&MASK_LANES_8_9, &MASK_LANES_40_41, &MASK_LANES_12_44] { + let inside = readfirstlane_of_a_scalar_in_branch(mask, true, true); + let alone = lowered(&native(&inside, true, 64, 0), true).expect("read alone in halves"); + assert_eq!(alone.wave_size, Some(32)); + let outside = readfirstlane_of_a_scalar_in_branch(mask, true, false); + let across = lowered(&native(&outside, true, 64, 0), true).expect("read across in halves"); + // At least two exchanges (the value, the ballot) of two barriers. assert!( - why.contains("a first-lane read of a value that may differ between 32-lane halves"), - "{threads} threads: {why}" + across.barriers >= alone.barriers + 4, + "{} {}", + across.barriers, + alone.barriers ); } } + +/// [`readfirstlane_of_a_scalar_in_branch`] read inside its region gives the +/// console's lanes on every hardware adapter: `f32(41) + 1.0` in the lanes +/// EXEC has, 0 elsewhere, with the active lanes in the lower half only, in +/// the upper half only (the lower host wave has none), in both, or none (the +/// region is skipped); with console lanes needed elsewhere (halves) and not. +#[test] +#[cfg(windows)] +fn a_first_lane_read_only_active_lanes_see_matches_the_console_on_every_gpu() { + let value = (41.0f32 + 1.0).to_bits(); + let lower: fn(u32) -> bool = |l| l >> 1 == 4; + let upper: fn(u32) -> bool = |l| l >> 1 == 20; + let both: fn(u32) -> bool = |l| l & 31 == 12; + let none: fn(u32) -> bool = |_| false; + let mut failed = Vec::new(); + for (label, mask, active) in [ + ("lower_8_9", &MASK_LANES_8_9, lower), + ("upper_40_41", &MASK_LANES_40_41, upper), + ("both_12_44", &MASK_LANES_12_44, both), + ("empty", &MASK_EMPTY, none), + ] { + for with_mbcnt in [false, true] { + let words = readfirstlane_of_a_scalar_in_branch(mask, with_mbcnt, true); + let want: Vec = (0..64).map(|l| if active(l) { value } else { 0 }).collect(); + let found = differences_with_buffer( + true, + &words, + 64, + 1, + &want, + 0, + false, + false, + &[41, 0, 0, 0], + ); + failed.extend( + found + .into_iter() + .map(|msg| format!("{label}(mbcnt={with_mbcnt}): {msg}")), + ); + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3795d686d..e21a1a503 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -24,6 +24,7 @@ mod atomics; mod barriers; mod bvh; mod f64; +mod first_lane; /// Format loads that move 16-bit halves without the d16 form, a child /// module so it shares the emitter's state. #[path = "half_views.rs"] @@ -428,6 +429,9 @@ struct Lower<'a> { /// In halves: VGPR values the same in every lane of the console wave /// ([`halves::lane_uniform`]), whose first lane either half reads. alike: HashSet, + /// The results of first-lane reads each host half makes by itself + /// ([`first_lane::read_alone`]). + first_alone: HashSet, /// Pixel: an ordered section (POPS), whose UAVs the host makes /// rasterizer-ordered views. pops: bool, @@ -672,7 +676,6 @@ impl<'a> Lower<'a> { bad: &'a HashMap, keep: Option<&KeptOutputs>, per_vertex_center: bool, - first_lane_halves: bool, meet_plan: &'a Set, meet_found: &'a std::cell::RefCell>, ) -> Self { @@ -704,6 +707,13 @@ impl<'a> Lower<'a> { let mut console_lanes = false; let (mut halves, mut halves_refused) = (false, None); let mut alike_cache: Option> = None; + // First-lane reads each 32-lane host half of a console wave makes + // by itself (`first_lane`). + let first_alone = if x.host_wave32 { + first_lane::read_alone(x) + } else { + HashSet::new() + }; let mut split_barriers = Set::default(); let mut pred = predicate::PredicatePlan::empty(Vec::new()); if let StageIo::Cs(cs) = x.native.io { @@ -746,7 +756,7 @@ impl<'a> Lower<'a> { .iter() .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_))) }) - } || (first_lane_halves && halves::needs_first_lane(x, &mut alike_cache)); + } || halves::needs_first_lane(x, &mut alike_cache, &first_alone); let wave = if x.native.wave64 { 64 } else { 32 }; let group = cs.threads.iter().product::(); let one_wave = group <= wave; @@ -941,6 +951,7 @@ impl<'a> Lower<'a> { } else { HashSet::new() }, + first_alone, pops: matches!(x.native.io, StageIo::Ps { db_shader_control, .. } if db_shader_control & 1 << 16 != 0), depth_before_shader: matches!(x.native.io, StageIo::Ps { db_shader_control, .. } @@ -7611,7 +7622,10 @@ impl<'a> Lower<'a> { let is_vec = matches!(v.src.first(), Some(&Operand::Vector { .. })); let is_alike = matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) if inst.read(Reg::V(reg)).is_some_and(|x| self.alike.contains(&x))); - if self.halves && !self.one_host_wave() && is_vec && !is_alike { + // Each half's own first active lane is the console's + // (`first_lane`): read it, with no exchange. + let alone = inst.writes.first().is_some_and(|w| self.first_alone.contains(&w.1)); + if self.halves && !self.one_host_wave() && is_vec && !is_alike && !alone { if !self.across_here() { return Err(halves::FIRST_ACROSS); } diff --git a/crates/victory-shader/src/emit/lower/first_lane.rs b/crates/victory-shader/src/emit/lower/first_lane.rs new file mode 100644 index 000000000..11d48a0a8 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/first_lane.rs @@ -0,0 +1,427 @@ +//! `v_readfirstlane_b32` reads a console wave64's 32-lane host halves can +//! make each by itself, with no value passed between them. +//! +//! The console reads the first lane EXEC has across the wave's 64 lanes; a +//! host half, the first it has of its own 32. The two agree, and nothing +//! needs to cross the halves, where: +//! +//! 1. **The value is the same in every lane EXEC has at the read.** Every +//! instruction that made it ran under the read's own EXEC value (the same +//! SSA value: no EXEC write between them) and computed it from constants +//! and scalar registers alone, by plain VALU operations, so every active +//! lane holds the same function of the same scalars. The scalars are +//! root parameters and what scalar loads and scalar ALU operations make +//! of them: what each host half computes for itself in every halves +//! translation, none of them made from a lane mask or a lane's value. +//! 2. **Only lanes EXEC has at the read see the result.** A half with no +//! active lane reads a lane of its own that does not hold the value; that +//! is harmless only if no lane outside the read's EXEC ever sees what it +//! read. So every instruction that reads the result, or a scalar made from +//! it, is a scalar ALU operation (whose results are held to the same) or +//! a vector instruction that writes no scalar register and runs under an +//! EXEC no wider than the read's: one made from it by compares into EXEC, +//! ANDs and copies of such masks (`s_and_saveexec`, `s_and_b64`, +//! `s_andn2_b64` of one, `s_mov_b64` of one, phis of them). No branch, +//! scalar memory access, EXEC, VCC or M0 write takes it. +//! +//! With both, a half with an active lane reads the console's value and a +//! half without one reads something no lane of the result's readers can +//! see. Where EXEC is empty in the whole console wave, no reader runs at +//! all. The read must be in no cycle, so its EXEC value is one mask. +//! +//! Before #522 such reads were made each by its own host half without these +//! checks; #522 refused every read of a value that may differ between the +//! lanes of the console wave in code the halves cannot meet in, which left +//! out GTA VI's `8bb272e763f76148` (a division by a constant-buffer value +//! whose reciprocal the console compiler reads from the first lane). + +use std::collections::{HashMap, HashSet}; + +use super::Parts; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{EXEC, Inst, Reg, VCC, Value}; + +/// The results (the SGPR value written) of the `v_readfirstlane_b32` reads +/// of a wave64 program each host half can make by itself (module notes). +pub(super) fn read_alone(x: &Parts) -> HashSet { + let p = x.p; + if !x.native.wave64 { + return HashSet::new(); + } + let mut def: HashMap = HashMap::new(); + let mut phi_def: HashMap = HashMap::new(); + let mut uses: HashMap> = HashMap::new(); + let mut phi_uses: HashMap> = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (k, phi) in block.phis.iter().enumerate() { + phi_def.insert(phi.value, (b, k)); + for &a in &phi.args { + phi_uses.entry(a).or_default().push((b, k)); + } + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + def.insert(v, (b, i)); + } + for &(_, v) in &inst.reads { + uses.entry(v).or_default().push((b, i)); + } + } + } + let a = Analysis { + x, + def, + phi_def, + uses, + phi_uses, + params: x.res.params.iter().map(|&(v, _, _)| v).collect(), + }; + let mut out = HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + for inst in &block.insts { + if inst.name() != "v_readfirstlane_b32" { + continue; + } + let Some(&(_, result)) = inst.writes.first() else { + continue; + }; + if a.alone(b, inst) { + out.insert(result); + } + } + } + out +} + +/// Values decided (`Some`), and being decided (`None`). +type Memo = HashMap>; + +struct Analysis<'a, 'p> { + x: &'a Parts<'p>, + /// Where each value is written: (block, instruction). + def: HashMap, + /// Where each phi value is: (block, phi). + phi_def: HashMap, + /// The instructions reading each value. + uses: HashMap>, + /// The phis taking each value. + phi_uses: HashMap>, + params: HashSet, +} + +/// Lane masks and other registers a value of the first condition may not be +/// made from or go to: VCC, M0, EXEC (and what lies past them). +fn special(code: u8) -> bool { + code >= VCC +} + +impl Analysis<'_, '_> { + fn inst(&self, at: (usize, usize)) -> &Inst { + &self.x.p.blocks[at.0].insts[at.1] + } + + fn alone(&self, b: usize, read: &Inst) -> bool { + let Fields::Valu(v) = &read.fields else { + return false; + }; + let Some(&Operand::Vector { reg, .. }) = v.src.first() else { + return false; + }; + let (Some(src), Some(exec)) = (read.read(Reg::V(reg)), self.exec(read)) else { + return false; + }; + let Some(&(_, result)) = read.writes.first() else { + return false; + }; + !self.on_cycle(b) + && self.active_alike(src, exec, &mut HashMap::new()) + && self.seen_only_inside(result, exec) + } + + /// The EXEC value (both dwords) a vector instruction runs under. + fn exec(&self, inst: &Inst) -> Option<(Value, Value)> { + Some((inst.read(Reg::S(EXEC))?, inst.read(Reg::S(EXEC + 1))?)) + } + + fn on_cycle(&self, b: usize) -> bool { + let blocks = &self.x.p.blocks; + let mut seen = vec![false; blocks.len()]; + let mut stack = blocks[b].exit.successors(); + while let Some(q) = stack.pop() { + if q == b { + return true; + } + if !std::mem::replace(&mut seen[q], true) { + stack.extend(blocks[q].exit.successors()); + } + } + false + } + + /// Condition 1: `v` is the same in every lane active under `exec`. + /// `memo`: values decided, and those being decided (`None`: a value + /// that needs itself is not proven). + fn active_alike(&self, v: Value, exec: (Value, Value), memo: &mut Memo) -> bool { + match memo.get(&v) { + Some(&r) => return r.unwrap_or(false), + None => memo.insert(v, None), + }; + let r = self.active_alike_of(v, exec, memo); + memo.insert(v, Some(r)); + r + } + + fn active_alike_of(&self, v: Value, exec: (Value, Value), memo: &mut Memo) -> bool { + let Some(&at) = self.def.get(&v) else { + return false; + }; + let inst = self.inst(at); + let Fields::Valu(f) = &inst.fields else { + return false; + }; + let name = inst.name(); + let plain = f.dpp.is_none() + && f.sdwa.is_none() + && f.carry.is_none() + && f.opsel == 0 + && ![ + "lane", "cndmask", "mbcnt", "_co_", "interp", "mac", "dot", "cmp", "16", "mix", + "perm", "sad", "msad", "qsad", + ] + .iter() + .any(|n| name.contains(n)); + if !plain || self.exec(inst) != Some(exec) || !matches!(f.dst, Some(Operand::Vector { .. })) + { + return false; + } + f.src.iter().all(|op| match *op { + Operand::Const(c) => c < 251, + Operand::Literal(_) => true, + Operand::Scalar { code, dwords } => { + !special(code) + && (0..dwords).all(|k| { + inst.read(Reg::S(code + k)) + .is_some_and(|s| self.scalar_ok(s, &mut HashMap::new())) + }) + } + Operand::Vector { reg, dwords } => (0..dwords).all(|k| { + inst.read(Reg::V(reg + k)) + .is_some_and(|s| self.active_alike(s, exec, memo)) + }), + Operand::Attr { .. } => false, + }) + } + + /// A scalar value each host half computes alike: a root parameter, or + /// what scalar loads and scalar ALU operations make of them. + fn scalar_ok(&self, v: Value, memo: &mut Memo) -> bool { + if self.params.contains(&v) { + return true; + } + match memo.get(&v) { + Some(&r) => return r.unwrap_or(false), + None => memo.insert(v, None), + }; + let r = self.scalar_ok_of(v, memo); + memo.insert(v, Some(r)); + r + } + + fn scalar_ok_of(&self, v: Value, memo: &mut Memo) -> bool { + if let Some(&(b, k)) = self.phi_def.get(&v) { + // Only a phi of one value (and itself, around a loop). + let phi = &self.x.p.blocks[b].phis[k]; + let mut others = phi.args.iter().filter(|&&a| a != v); + let Some(&first) = others.next() else { + return false; + }; + return others.all(|&a| a == first) && self.scalar_ok(first, memo); + } + let Some(&at) = self.def.get(&v) else { + return false; + }; + let inst = self.inst(at); + let name = inst.name(); + let reads_ok = |memo: &mut Memo| { + inst.reads.iter().all(|&(r, rv)| match r { + Reg::S(code) => !special(code) && self.scalar_ok(rv, memo), + Reg::Scc | Reg::V(_) => false, + }) + }; + match &inst.fields { + Fields::Sop { .. } => { + let banned = [ + "exec", + "pc", + "getreg", + "setreg", + "bcnt", + "ff0", + "ff1", + "flbit", + "wqm", + "quadmask", + "movrel", + "cbranch", + "sendmsg", + "memtime", + "memrealtime", + "ttrace", + ]; + !banned.iter().any(|n| name.contains(n)) && reads_ok(memo) + } + Fields::Smem { .. } => { + (name.starts_with("s_load_") || name.starts_with("s_buffer_load_")) + && reads_ok(memo) + } + _ => false, + } + } + + /// Condition 2: only instructions running under an EXEC no wider than + /// `exec` see `result`, or scalars made from it. + fn seen_only_inside(&self, result: Value, exec: (Value, Value)) -> bool { + let inside = self.masks_inside(exec); + let mut tainted = vec![result]; + let mut done: HashSet = HashSet::new(); + while let Some(t) = tainted.pop() { + if !done.insert(t) { + continue; + } + for &(b, k) in self.phi_uses.get(&t).into_iter().flatten() { + let phi = &self.x.p.blocks[b].phis[k]; + if !matches!(phi.reg, Reg::S(c) if !special(c)) { + return false; + } + tainted.push(phi.value); + } + for &at in self.uses.get(&t).into_iter().flatten() { + let inst = self.inst(at); + if let Some((lo, hi)) = self.exec(inst) { + // A vector instruction: only under a mask inside the + // read's, and writing no scalar (nor a lane by index). + let writes_scalar = inst.writes.iter().any(|w| !matches!(w.0, Reg::V(_))); + if !inside.contains(&lo) + || !inside.contains(&hi) + || writes_scalar + || inst.name().contains("lane") + { + return false; + } + continue; + } + let Fields::Sop { .. } = &inst.fields else { + return false; + }; + let name = inst.name(); + let to_special = inst + .writes + .iter() + .any(|w| matches!(w.0, Reg::S(c) if special(c))); + if to_special + || ["exec", "pc", "cbranch", "setreg", "sendmsg", "movrel"] + .iter() + .any(|n| name.contains(n)) + { + return false; + } + tainted.extend(inst.writes.iter().map(|w| w.1)); + } + } + true + } + + /// The EXEC-like mask dwords no wider than `exec`'s: `exec` itself, and + /// what compares into EXEC, `s_and_saveexec`, ANDs, `s_andn2` and copies + /// make of them, and phis of them (the greatest such set: around a loop a + /// phi of masks no wider stays so). + fn masks_inside(&self, exec: (Value, Value)) -> HashSet { + let p = self.x.p; + // Every SGPR dword value an operation of those kinds writes, by the + // rule that keeps it inside. + let mut rules: HashMap> = HashMap::new(); + let mut any: HashMap> = HashMap::new(); + for block in &p.blocks { + for phi in &block.phis { + if matches!(phi.reg, Reg::S(_)) { + rules.insert(phi.value, phi.args.clone()); + } + } + for inst in &block.insts { + let name = inst.name(); + let read = |code: u8| inst.read(Reg::S(code)); + let src = |k: usize| match &inst.fields { + Fields::Sop { src, .. } => src.get(k).copied(), + _ => None, + }; + let dword = |op: Option, d: u8| match op { + Some(Operand::Scalar { code, .. }) => read(code + d), + _ => None, + }; + for &(r, w) in &inst.writes { + let Reg::S(code) = r else { continue }; + let d = code & 1; + let exec_in = read(EXEC + d); + if (code == EXEC || code == EXEC + 1) + && (name.starts_with("v_cmpx_") || name == "s_and_saveexec_b64") + { + if let Some(e) = exec_in { + rules.insert(w, vec![e]); + } + continue; + } + match name { + "s_and_saveexec_b64" => { + // The saved copy of the old EXEC. + if let Some(e) = exec_in { + rules.insert(w, vec![e]); + } + } + "s_mov_b64" => { + if let Some(s) = dword(src(0), d) { + rules.insert(w, vec![s]); + } + } + "s_andn2_b64" => { + if let Some(s) = dword(src(0), d) { + rules.insert(w, vec![s]); + } + } + "s_and_b64" => { + let both: Vec = [dword(src(0), d), dword(src(1), d)] + .into_iter() + .flatten() + .collect(); + any.insert(w, both); + } + _ => {} + } + } + } + } + let mut inside: HashSet = rules.keys().chain(any.keys()).copied().collect(); + inside.insert(exec.0); + inside.insert(exec.1); + loop { + let before = inside.len(); + let keep: Vec = inside + .iter() + .copied() + .filter(|v| { + *v == exec.0 + || *v == exec.1 + || rules.get(v).is_some_and(|args| { + !args.is_empty() && args.iter().all(|a| inside.contains(a)) + }) + || any + .get(v) + .is_some_and(|args| args.iter().any(|a| inside.contains(a))) + }) + .collect(); + inside = keep.into_iter().collect(); + if inside.len() == before { + return inside; + } + } + } +} diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 992b5948c..79e33360c 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -647,15 +647,22 @@ pub(super) const FIRST_ACROSS: Why = "a first-lane read of a value that may diff /// Whether `x` (a wave64 compute program) has a non-waterfall /// `v_readfirstlane_b32` whose vector source may differ between lanes of the /// console wave: such a read needs console-wave lane order (and halves on a -/// 32-lane host) so both halves see the same first active lane. -pub(super) fn needs_first_lane(x: &Parts, alike: &mut Option>) -> bool { +/// 32-lane host) so both halves see the same first active lane. Not one each +/// host half can make by itself (`alone`, [`super::first_lane::read_alone`]). +pub(super) fn needs_first_lane( + x: &Parts, + alike: &mut Option>, + alone: &HashSet, +) -> bool { if !x.native.wave64 { return false; } let wf = &x.res.waterfall.reads; let is_vec_first = |i: &Inst| -> Option { if i.name() != "v_readfirstlane_b32" - || i.writes.first().is_some_and(|w| wf.contains(&w.1)) + || i.writes + .first() + .is_some_and(|w| wf.contains(&w.1) || alone.contains(&w.1)) { return None; } diff --git a/crates/victory-shader/src/emit/lower/retry.rs b/crates/victory-shader/src/emit/lower/retry.rs index be606cdff..4b3338af8 100644 --- a/crates/victory-shader/src/emit/lower/retry.rs +++ b/crates/victory-shader/src/emit/lower/retry.rs @@ -28,36 +28,9 @@ pub(crate) fn lower_limited( per_vertex_center: bool, literal_halves: bool, limits: bool, -) -> Result { - let lowered = lower_with_literal_retry(parts, keep, per_vertex_center, literal_halves, limits); - // A program whose only cross-half operation is a first lane read goes to - // halves for it (#522). Where halves cannot read that first lane, the - // per-lane form reads each host wave's own first lane, as before: closer - // to the console than dropping the program's draws. - if matches!( - &lowered, - Err(ShaderError::Unsupported { - what: halves::FIRST_ACROSS, - .. - }) - ) && let Ok(l) = lower_with_structure(parts, keep, per_vertex_center, limits, false) - { - return Ok(l); - } - lowered -} - -/// The per-lane form, and a 64-thread wave64 program it refuses at a -/// cross-half gate again in literal halves ([`lower_literal`]). -fn lower_with_literal_retry( - parts: &Parts, - keep: Option<&KeptOutputs>, - per_vertex_center: bool, - literal_halves: bool, - limits: bool, ) -> Result { // Retry refusals from the legacy cross-half gates with whole-wave control flow. - let original = lower_with_structure(parts, keep, per_vertex_center, limits, true); + let original = lower_with_structure(parts, keep, per_vertex_center, limits); if !literal_halves || !parts.host_wave32 || !parts.native.wave64 @@ -116,7 +89,6 @@ pub(crate) fn lower_literal( // A group in literal halves takes one path: its lanes never leave // past a count of threads (`Lower::can_leave_past_a_count`). false, - true, ) } @@ -125,7 +97,6 @@ fn lower_with_structure( keep: Option<&KeptOutputs>, per_vertex_center: bool, limits: bool, - first_lane_halves: bool, ) -> Result { let mut bad = HashMap::new(); // Divergent sites where the halves meet (`lower::meet`): a pass that @@ -133,8 +104,7 @@ fn lower_with_structure( let mut plan: Set = Set::default(); loop { let found = std::cell::RefCell::new(Set::default()); - let r = Lower::new(parts, &bad, keep, per_vertex_center, first_lane_halves, &plan, &found) - .run(limits); + let r = Lower::new(parts, &bad, keep, per_vertex_center, &plan, &found).run(limits); let found = found.into_inner(); if !found.is_empty() { plan.extend(found);