diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 216240bd2c..8b5a1f03c2 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -43,6 +43,12 @@ pub(super) struct Em { /// split wave64: pc โ†’ SGPRs whose whole value may be read after that instruction /// (`x64_masks`); a mask written to none of them stays in its half (no exchange) pub x64_whole_live: BTreeMap, + /// instruction PCs where `EXEC` is guaranteed equal to entry `ballot(true)` (`exec_active`); + /// VGPR writes and ballots skip per-instruction EXEC masking there + pub exec_all_active: BTreeSet, + /// whether the emitted body reads or updates the cached per-lane active flag `ea` + uses_ea: bool, + wrote_exec: bool, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -481,6 +487,9 @@ impl Em { uses_scratch: false, x64_words: 1, x64_whole_live: BTreeMap::new(), + exec_all_active: BTreeSet::new(), + uses_ea: false, + wrote_exec: false, upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -605,7 +614,11 @@ impl Em { } } - fn act(&self) -> &'static str { + fn all_active(&self) -> bool { + self.exec_all_active.contains(&self.cur_pc) + } + + fn act_expr(&self) -> &'static str { // no short-circuit `?:` (HLSL 2021 makes it a branch โ€“ one per instruction at -O0) if self.opt.wave64 { "lanebit(exec_lo, exec_hi)" @@ -614,6 +627,21 @@ impl Em { } } + fn act(&mut self) -> &'static str { + if self.all_active() { + "true" + } else { + self.uses_ea = true; + "ea" + } + } + + fn sync_ea(&mut self) { + self.wrote_exec = true; + let expr = self.act_expr(); + self.line(&format!("ea = {expr};")); + } + fn unsupported(&mut self, d: &Decoded, why: &str) { let m = rdna2::mnemonic(d); *self.unsupported_why.entry(format!("{m}: {why}")).or_default() += 1; @@ -792,12 +820,19 @@ impl Em { // driver's compiler could take on a 15 000-instruction console shader) Dst::V(n) => { let v = self.vreg(*n); - let a = self.act(); - self.line(&format!("{v} = select({a}, {val}, {v});")); + if self.all_active() { + self.line(&format!("{v} = {val};")); + } else { + let a = self.act(); + self.line(&format!("{v} = select({a}, {val}, {v});")); + } } Dst::S(n) => { let s = self.sreg(*n); self.line(&format!("{s} = {val};")); + if *n == 126 || *n == 127 { + self.sync_ea(); + } } Dst::Null => {} } @@ -807,12 +842,19 @@ impl Em { match dst { Dst::V(n) => { let (a, b) = (self.vreg(*n), self.vreg(*n + 1)); - let act = self.act(); - self.line(&format!("{a} = select({act}, {lo}, {a}); {b} = select({act}, {hi}, {b});")); + if self.all_active() { + self.line(&format!("{a} = {lo}; {b} = {hi};")); + } else { + let act = self.act(); + self.line(&format!("{a} = select({act}, {lo}, {a}); {b} = select({act}, {hi}, {b});")); + } } Dst::S(n) => { let (a, b) = (self.sreg(*n), self.sreg(*n + 1)); self.line(&format!("{a} = {lo}; {b} = {hi};")); + if *n == 126 { + self.sync_ea(); + } } Dst::Null => {} } @@ -820,7 +862,6 @@ impl Em { /// Lane mask from a per-lane condition (inactive lanes give 0) into a register pair. fn write_mask(&mut self, dst: &Dst, cond: &str) { - let a = self.act(); let m = self.t(); let mut ballot = self.ballot_fn(); // no exchange for a mask that is only ever read lane by lane (the half's own word is @@ -833,7 +874,12 @@ impl Em { if self.x64() && (local || cond == "false") { ballot = "xcl_x_ballot_local"; } - self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")); + if self.all_active() { + self.line(&format!("uint2 {m} = {ballot}({cond});")); + } else { + let a = self.act(); + self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")); + } if self.opt.wave64 { self.write64(dst, &format!("{m}.x"), &format!("{m}.y")); } else { @@ -1149,6 +1195,7 @@ impl Em { self.line(&format!("uint {o0} = {el};")); self.line(&format!("uint {t0} = {nl};")); self.line(&format!("{el} = {t0};")); + self.sync_ea(); self.line(&format!("scc = (uint)({t0} != 0u);")); let v = if name.contains("wrexec") { t0 } else { o0 }; self.write32(&dst, &v); @@ -1160,6 +1207,7 @@ impl Em { self.line(&format!("uint {o0} = {el}; uint {o1} = {eh};")); self.line(&format!("uint {t0} = {nl}; uint {t1} = {nh};")); self.line(&format!("{el} = {t0}; {eh} = {t1};")); + self.sync_ea(); self.line(&format!("scc = (uint)(({t0} | {t1}) != 0u);")); let (a, b) = if name.contains("wrexec") { (t0, t1) } else { (o0, o1) }; self.write64(&dst, &a, &b); @@ -2684,8 +2732,12 @@ impl Em { match (self.dpp_enable.take(), dst) { (Some(en), Dst::V(n)) => { let v = self.vreg(*n); - let a = self.act(); - self.line(&format!("{v} = select(and({a}, {en}), {val}, {v});")); + if self.all_active() { + self.line(&format!("{v} = select({en}, {val}, {v});")); + } else { + let a = self.act(); + self.line(&format!("{v} = select(and({a}, {en}), {val}, {v});")); + } } _ => self.write32(dst, &val), } @@ -4311,6 +4363,9 @@ impl Em { } load_sgprs(&mut h); let _ = writeln!(h, " uint scc = io.Load({}u);", KERNEL_SCC_SLOT * 4); + if self.uses_ea || self.wrote_exec { + let _ = writeln!(h, " bool ea = {};", self.act_expr()); + } for &v in &self.vgprs { let _ = writeln!(h, " uint v{v} = io.Load(({}u + xcl_hw_lane * {}u + {v}u) * 4u);", KERNEL_SGPRS, KERNEL_VGPRS); } @@ -4351,6 +4406,9 @@ impl Em { } load_sgprs(&mut h); h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + if self.uses_ea || self.wrote_exec { + h.push_str(" bool ea = true;\n"); + } for &v in &self.vgprs { // SV_VertexID / SV_InstanceID listed in ISG1 come through the fetch shader like an // attribute (retail VInstanced* read the instance id in v8 = r1) @@ -4435,6 +4493,9 @@ impl Em { let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + if self.uses_ea || self.wrote_exec { + h.push_str(" bool ea = true;\n"); + } for &v in &self.vgprs { let init = match v { 0 => "gtid.x", @@ -4480,6 +4541,9 @@ impl Em { h.push_str(" s3 = (s3 & 0xF0FFFFFFu) | (xcl_wave << 24);\n"); } let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + if self.uses_ea || self.wrote_exec { + h.push_str(" bool ea = true;\n"); + } for &v in &self.vgprs { let init = if v == 5 { format!("gid.x * {t}u + xcl_slot") } else { "0u".into() }; let _ = writeln!(h, " uint v{v} = {init};"); @@ -4515,6 +4579,9 @@ impl Em { h.push_str(" s3 = xcl_nv | (xcl_np << 8); // merged wave info: ES vertices, GS primitives, wave 0\n"); } h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + if self.uses_ea || self.wrote_exec { + let _ = writeln!(h, " bool ea = {};", self.act_expr()); + } for &v in &self.vgprs { let init = match v { 0 => format!("(lane_id < xcl_np) ? ((lane_id * 3u * {item}u) | ((lane_id * 3u + 1u) * {item}u << 16)) : 0u"), @@ -4584,6 +4651,9 @@ impl Em { h.push_str(" s3 = xcl_nv | (xcl_np << 8); // merged wave info: ES vertices, GS primitives, wave 0\n"); } h.push_str(" uint scc = 0u;\n { uint2 e0 = xcl_x_ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + if self.uses_ea || self.wrote_exec { + let _ = writeln!(h, " bool ea = {};", self.act_expr()); + } for &v in &self.vgprs { let init = match v { // LDS dword offsets of the triangle's vertices (ES vertex i at i ยท item) @@ -4676,6 +4746,9 @@ impl Em { } load_sgprs(&mut h); h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); + if self.uses_ea || self.wrote_exec { + h.push_str(" bool ea = true;\n"); + } let sys = |bit: u32| ps_input_vgpr(ps.input_ena, bit); for &v in &self.vgprs { let init = if Some(v) == sys(8) { diff --git a/crates/xcl/src/gpu/recomp/exec_active.rs b/crates/xcl/src/gpu/recomp/exec_active.rs new file mode 100644 index 0000000000..6cd1314f51 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/exec_active.rs @@ -0,0 +1,359 @@ +//! Forward dataflow analysis proving where `EXEC` equals its entry value (all executing lanes +//! active). +//! +//! At entry of every non-kernel shader (`Vertex`, `Pixel`, `Compute`, `Mesh`, `Geometry`), the +//! emitter sets `exec = ballot(true)`, so every hardware lane executing the shader has its EXEC +//! bit set. In straight-line code and outside divergent `s_and_saveexec` / `v_cmpx` regions, +//! `EXEC` stays equal to that entry mask โ€“ or is restored to it by `s_mov_b64 exec, s_saved` / +//! `s_or_b64 exec, exec, s_saved` from a register that saved the entry mask. +//! +//! Where `all_active_pcs` includes `pc`, every executing lane is guaranteed active: +//! - VGPR writes emit `v = val;` instead of `v = select(lanebit(exec_lo, exec_hi), val, v);`, +//! removing both the per-instruction `select`/`lanebit` IR and the false read dependency on +//! the old VGPR value (which otherwise extends live ranges across DXC and the GPU driver). +//! - Lane-mask writes emit `ballot(cond)` instead of `ballot(and(lanebit(...), cond))`. +//! +//! Conservative where it cannot prove: `Mode::Kernel` starts with an arbitrary `EXEC` from `io` +//! (never all-active at entry), any non-fetch indirect jump makes the whole program conservative, +//! and every `LOOP_GUARD` exit out of a loop is treated as an incoming edge at the loop's exit. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::emit::ext_encoding; +use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +type Regs = u128; + +const VCC: Regs = 3 << 106; +const M0: Regs = 1 << 124; +const EXEC: Regs = 3 << 126; +const ALL: Regs = !0; + +fn range(first: u64, n: u64) -> Regs { + (first..(first + n).min(128)).fold(0, |m, r| m | 1u128 << r) +} + +fn scalar_code(v: u64, n: u64) -> Regs { + match v { + 125 => 0, + v if v <= 127 => range(v, n), + _ => 0, + } +} + +/// Superset of SGPRs (0..=127) that `d` may write. Over-approximating is always sound for a +/// must-analysis: at worst it drops a saved-EXEC register or marks EXEC unknown. +fn written_sgprs(d: &Decoded) -> Regs { + let name = d.inst.name; + if name.starts_with("S_MOVREL") { + return ALL & !EXEC; + } + let mut written: Regs = 0; + if d.variant == Variant::Sdwa { + let Some(e) = ext_encoding(d) else { return ALL }; + if d.enc.name == "ENC_VOPC" && !name.starts_with("V_CMPX") { + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + written |= if fv("SD") == 1 { scalar_code(fv("SDST"), 2) } else { VCC }; + } + } + if name.starts_with("V_CMPX") || name.contains("SAVEEXEC") || name.contains("WREXEC") { + written |= EXEC; + } + for o in d.ienc.operands { + if !o.output { + continue; + } + let n = (o.size as u64).div_ceil(32).max(1); + let regs = match (o.field, o.ty) { + (_, "OPR_VCC") => VCC, + (_, "OPR_EXEC" | "OPR_SDST_EXEC") => EXEC, + (_, "OPR_SDST_M0") => M0, + (None, _) | (Some("LITERAL"), _) => continue, + (Some(f), ty) => { + if !["SREG", "SSRC", "SDST", "OPR_SRC"].iter().any(|k| ty.contains(k)) { + continue; + } + scalar_code(rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f), n) + } + }; + written |= regs; + } + written +} + +/// Clear any saved-entry bit whose register (or high half in wave64) overlaps `written`. +fn kill_saved(saved: Regs, written: Regs, wave64: bool) -> Regs { + let mask = if wave64 { written | (written >> 1) } else { written }; + saved & !mask +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct State { + /// `exec` is guaranteed to equal `entry_exec` (every executing lane active). + exec_entry: bool, + /// Bit `r` (0..=105, 108..=123) is 1 iff `s[r]` (wave32) or `s[r..r+2]` (wave64) is + /// guaranteed to hold `entry_exec`. + saved: Regs, +} + +impl State { + fn meet(self, other: Self) -> Self { + Self { exec_entry: self.exec_entry && other.exec_entry, saved: self.saved & other.saved } + } + + fn is_entry_src(self, code: u64) -> bool { + if code == 126 { + self.exec_entry + } else if code <= 105 || (108..=123).contains(&code) { + (self.saved & (1u128 << code)) != 0 + } else { + false + } + } +} + +fn is_normal_sgpr(code: u64, wave64: bool) -> bool { + if wave64 { + code <= 104 || (108..=122).contains(&code) + } else { + code <= 105 || (108..=123).contains(&code) + } +} + +fn step(st: State, d: &Decoded, wave64: bool) -> State { + let name = d.inst.name; + let written = written_sgprs(d); + let mut saved = kill_saved(st.saved, written, wave64); + let mut exec_entry = if written & EXEC != 0 { false } else { st.exec_entry }; + + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + let save_bit = |r: u64| if is_normal_sgpr(r, wave64) { 1u128 << r } else { 0 }; + + if wave64 { + match name { + n if n.ends_with("_SAVEEXEC_B64") => { + if st.exec_entry { + saved |= save_bit(fv("SDST")); + } + exec_entry = false; + } + "S_MOV_B64" => { + let (dst, src) = (fv("SDST"), fv("SSRC0")); + if dst == 126 { + exec_entry = st.is_entry_src(src); + } else if st.is_entry_src(src) { + saved |= save_bit(dst); + } + } + "S_OR_B64" if fv("SDST") == 126 => { + exec_entry = st.is_entry_src(fv("SSRC0")) || st.is_entry_src(fv("SSRC1")); + } + "S_WQM_B64" if fv("SDST") == 126 && fv("SSRC0") == 126 => { + exec_entry = st.exec_entry; + } + _ => {} + } + } else { + match name { + n if n.ends_with("_SAVEEXEC_B32") => { + if st.exec_entry { + saved |= save_bit(fv("SDST")); + } + exec_entry = false; + } + "S_MOV_B32" => { + let (dst, src) = (fv("SDST"), fv("SSRC0")); + if dst == 126 { + exec_entry = st.is_entry_src(src); + } else if st.is_entry_src(src) { + saved |= save_bit(dst); + } + } + "S_OR_B32" if fv("SDST") == 126 => { + exec_entry = st.is_entry_src(fv("SSRC0")) || st.is_entry_src(fv("SSRC1")); + } + "S_WQM_B32" if fv("SDST") == 126 && fv("SSRC0") == 126 => { + exec_entry = st.exec_entry; + } + _ => {} + } + } + + State { exec_entry, saved } +} + +/// Set of instruction PCs where `EXEC` is guaranteed equal to `entry_exec` (all executing lanes +/// active). Empty when `insts` is empty or contains an unhandled indirect branch. +pub fn all_active_pcs(insts: &[Decoded], wave64: bool) -> BTreeSet { + if insts.is_empty() { + return BTreeSet::new(); + } + let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut succ: Vec> = vec![Vec::new(); insts.len()]; + for (i, d) in insts.iter().enumerate() { + let f = d.inst.flags; + if f & F_INDIRECT != 0 { + // `s_swappc_b64 s[n:n+1], s[n:n+1]` is the ignored fetch-shader call (falls through) + let is_fetch_call = d.inst.name == "S_SWAPPC_B64" + && rdna2::field_value(d.enc, &d.words, "SDST") == rdna2::field_value(d.enc, &d.words, "SSRC0"); + if !is_fetch_call { + return BTreeSet::new(); + } + if i + 1 < insts.len() { + succ[i].push(i + 1); + } + continue; + } + if let Some(t) = rdna2::branch_target(d) { + if let Some(&j) = pcs.get(&t) { + succ[i].push(j); + } + if f & F_CONDITIONAL != 0 && i + 1 < insts.len() { + succ[i].push(i + 1); + } + } else if f & F_TERMINATOR == 0 && i + 1 < insts.len() { + succ[i].push(i + 1); + } + } + // `LOOP_GUARD` runs at the top of each loop `[a, b)` (before the instruction at `a`) and + // breaks directly to `b`, so `in_state[head]` flows into `in_state[exit]`. + let mut loop_guard_edges: Vec<(usize, usize)> = Vec::new(); + for (a, b) in super::loop_ranges(insts) { + if let (Some(&head_i), Some((_, &exit_j))) = (pcs.get(&a), pcs.range(b..).next()) { + loop_guard_edges.push((head_i, exit_j)); + } + } + + let mut in_state: Vec> = vec![None; insts.len()]; + in_state[0] = Some(State { exec_entry: true, saved: 0 }); + + loop { + let mut changed = false; + for i in 0..insts.len() { + let Some(st) = in_state[i] else { continue }; + let out = step(st, &insts[i], wave64); + for &j in &succ[i] { + let next = match in_state[j] { + None => out, + Some(prev) => prev.meet(out), + }; + if in_state[j] != Some(next) { + in_state[j] = Some(next); + changed = true; + } + } + } + for &(head_i, exit_j) in &loop_guard_edges { + let Some(st) = in_state[head_i] else { continue }; + let next = match in_state[exit_j] { + None => st, + Some(prev) => prev.meet(st), + }; + if in_state[exit_j] != Some(next) { + in_state[exit_j] = Some(next); + changed = true; + } + } + if !changed { + break; + } + } + + insts + .iter() + .enumerate() + .filter_map(|(i, d)| in_state[i].filter(|s| s.exec_entry).map(|_| d.pc)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + out + } + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + + fn asm(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + program(&bytes) + } + + #[test] + fn straight_line_without_exec_writes_is_all_active() { + let p = asm(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 0), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)]), + ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]), + ]); + let active = all_active_pcs(&p, true); + assert_eq!(active.len(), p.len()); + } + + #[test] + fn saveexec_narrows_and_or_exec_restores_all_active() { + let p = asm(&[ + // 0: all active + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 0), ("SRC0", V + 1), ("VSRC1", 2)]), + // 1: s_and_saveexec_b64 s[4:5], vcc -> saves entry exec in s[4:5], narrows exec + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + // 2: NOT all active (inside divergent region) + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)]), + // 3: s_or_b64 exec, exec, s[4:5] -> restores entry exec + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + // 4: all active again! + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 1)]), + ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]), + ]); + let active = all_active_pcs(&p, true); + assert!(active.contains(&p[0].pc)); + assert!(active.contains(&p[1].pc)); + assert!(!active.contains(&p[2].pc), "inside saveexec region must NOT be all-active"); + assert!(!active.contains(&p[3].pc), "restore instruction itself still sees narrowed exec"); + assert!(active.contains(&p[4].pc), "after s_or_b64 exec, s_saved must be all-active again"); + } + + #[test] + fn clobbering_high_half_of_saved_pair_prevents_false_restore() { + let p = asm(&[ + // 0: save entry exec into s[4:5] + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + // 1: clobber s5 (high half of s[4:5])! + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 128)]), + // 2: s_mov_b64 exec, s[4:5] -> s[4:5] is NO LONGER entry_exec + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]), + // 3: must NOT be considered all-active + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 0), ("SRC0", V + 1), ("VSRC1", 2)]), + ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]), + ]); + let active = all_active_pcs(&p, true); + assert!(active.contains(&p[0].pc)); + assert!(!active.contains(&p[3].pc), "clobbered high half must invalidate saved pair"); + } + + #[test] + fn wave32_saveexec_and_mov_restore() { + let p = asm(&[ + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V), ("VSRC1", 2)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]), + ]); + let active = all_active_pcs(&p, false); + assert!(active.contains(&p[0].pc)); + assert!(!active.contains(&p[1].pc)); + assert!(!active.contains(&p[2].pc)); + assert!(active.contains(&p[3].pc)); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 0f4a9049d2..eba944f930 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -53,6 +53,7 @@ pub mod dxc; pub(crate) mod emit; +pub mod exec_active; pub mod mesh_dispatch; pub mod mesh_wave; pub mod x64_masks; @@ -1402,6 +1403,12 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { em.x64_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); } + // non-kernel stages start with `exec = ballot(true)` (every executing lane active): where + // forward dataflow proves `exec` still equals that entry mask, VGPR writes and ballots skip + // per-instruction EXEC emulation (`XCL_NO_EXEC_ELIDE=1` to disable). + if matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_) | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_NO_EXEC_ELIDE").is_none() { + em.exec_all_active = exec_active::all_active_pcs(&insts, opt.wave64); + } // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a // program with a read to change gets the form diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 5a8d735396..de730070a1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -299,7 +299,7 @@ fn v_swaprel_b32_uses_the_m0_relative_switch() { assert!(t.hlsl.contains("uint t1 = v5;"), "{}", t.hlsl); assert!(t.hlsl.contains("uint t2 = 0u; switch (m0) { case 0u: t2 = v10; break; default: break; }"), "{}", t.hlsl); // EXEC-gated exchange of the two captured values - assert!(t.hlsl.contains("if (lanebit(exec_lo, exec_hi)) { v5 = t2; switch (m0) { case 0u: v10 = t1; break; default: break; } }"), "{}", t.hlsl); + assert!(t.hlsl.contains("if (ea) { v5 = t2; switch (m0) { case 0u: v10 = t1; break; default: break; } }"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); } @@ -3717,7 +3717,9 @@ fn gpu_geometry_mode_es_gs_strip() { for (k, want) in xy.iter().enumerate() { let v = MESH_HEADER + (4 * lane + k) * vd; let pos = [f32::from_bits(r[v]), f32::from_bits(r[v + 1]), f32::from_bits(r[v + 2]), f32::from_bits(r[v + 3])]; - assert_eq!(pos, [want[0], want[1], 0.5, 1.0], "group {grp} lane {lane} vertex {k}"); + // Without -Gis, DXC can reassociate (b + c) - a by 1 ULP when select(ea, ...) shares `ea`. + assert!((pos[0] - want[0]).abs() < 1e-6 && (pos[1] - want[1]).abs() < 1e-6 && pos[2] == 0.5 && pos[3] == 1.0, + "group {grp} lane {lane} vertex {k}: got {pos:?}, want [{}, {}, 0.5, 1.0]", want[0], want[1]); assert_eq!((r[v + 4], r[v + 5]), (p as u32, k as u32), "group {grp} lane {lane} vertex {k}: TEXCOORD0"); } let pk = |i: usize, j: usize, l: usize| (i | j << 10 | l << 20) as u32; @@ -6870,7 +6872,7 @@ fn gpu_mad_nf_f16_rounds_intermediate_in_binary16() { if (lane_id == 0u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x7BFFu), f16tof32(0x3C01u), f16tof32(0xFBFFu), 0u), 0u);\n\ if (lane_id == 1u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x7BFFu), f16tof32(0x3C01u), f16tof32(0xFBFFu), 3u), 3u);\n\ if (lane_id == 2u) v0 = f32_to_f16_rm(mad_nf_f16(f16tof32(0x3C01u), f16tof32(0x3C01u), f16tof32(0xBC02u), 0u), 0u);\n"; - let marker = " v0 = select((((exec_lo >> lane_id) & 1u) != 0u), (v0), v0);\n"; + let marker = " v0 = select(ea, (v0), v0);\n"; assert!(hlsl.contains(marker), "unexpected kernel body:\n{hlsl}"); hlsl = hlsl.replace(marker, probe); @@ -7589,3 +7591,47 @@ fn jumps_to_outer_loop_heads_are_structured() { println!("{structured} of 120 programs structured ({entered} jumps into a loop), {ran} run both ways"); assert!(structured >= 100 && entered > 20, "{structured} structured, {entered} jumps into loops"); } + +/// EXEC elision in compute mode: writes before divergence and after `s_or_b64 exec` restore +/// emit direct VGPR assignments, while divergent writes use the cached `ea` lane-active bit. +#[test] +fn gpu_exec_elide_divergent_and_restored_compute() { + use super::{dxc, CsInterface}; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 1, tgid: [false, false, false], tg_size: false, tid_components: 1 }; + let p = prog(&[ + // Pre-divergence (all active): v1 = v0 + 10 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 138), ("VSRC1", 0)], None), + // Diverge: lanes with 32 > v0 (i.e. v0 < 32) + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)], None), + // Divergent (NOT all active): v1 = v1 + 100 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 1)], Some(100)), + // Restore EXEC + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)], None), + // Post-merge (all active again): v2 = v1 + 1 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)], None), + // Store v2 at s0 + v0 * 4 + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 0), ("VSRC1", 3)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 2), ("SADDR", 0x7D)], None), + ]); + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(t.hlsl.contains("v1 = (10u + v0);"), "pre-divergence write should elide select:\n{}", t.hlsl); + assert!(t.hlsl.contains("v1 = select(ea,"), "divergent write should mask with cached ea:\n{}", t.hlsl); + assert!(t.hlsl.contains("v2 = (1u + v1);"), "post-restore write should elide select:\n{}", t.hlsl); + assert!(!t.hlsl.contains("select(lanebit("), "should use cached ea, not inline lanebit:\n{}", t.hlsl); + if !gpu_ready() { + return; + } + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let base = 0x100usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + let out = runner::dispatch(&dxil, [1, 1, 1], &io, &vec![0u32; (base + 64 * 4) / 4]).unwrap(); + for lane in 0..64u32 { + let want = if lane < 32 { lane + 10 + 100 + 1 } else { lane + 10 + 1 }; + assert_eq!(out[base / 4 + lane as usize], want, "lane {lane}"); + } +}