From e56f9ee48cba1e85153801493f54600891a70a84 Mon Sep 17 00:00:00 2001 From: Nick Stallman Date: Fri, 27 Nov 2026 05:35:39 +1100 Subject: [PATCH] xshader: a guarded mesh half result does not read the launch bits no reader takes 99 ProjectScarlett mesh programs were refused with "unsupported mesh launch register v7" (59) or "v6" (40). Each first writes the register with a VOP1 v_cvt_f16_f32, and some write v8 the same way. On RDNA2 that writes bits 15:0 and keeps 31:16, so `live_in`, which takes registers read before they are written in program order, counts the write as a read of the launch value. Every later reader is a v_cvt_f32_f16 or a v_pack_b32_f16 without op_sel, which reads bits 15:0 only. In some programs a v_cvt_f32_f16 then replaces the whole register before the vertex exports read it. `kept_half_unread` proves that for each such register, over the whole program including the export sequence, in `live_in`'s program order. The 16-bit write must sit in the block the vertex-count guard opens: s_mov_b64 s[n:n+1], exec; v_cmpx_gt_u32 count, lane; s_cbranch_execz to s_mov_b64 exec, s[n:n+1]. `count` and `lane` are the registers the export sequence tests, and neither changes after the guard. The guard is the last EXEC change before the write. Up to the export sequence EXEC only narrows or returns to a value saved since the block opened, and inside the block to one saved after the guard. No branch crosses the guard or the write except the guard's own, taken when no lane is active. So every lane that reads the register has executed the write. After the block nothing touches the register before the vertex exports, which test the same count against the same lane; the export recognizer now records where they begin. Each later reader takes the low half, until a full write that no path leaves early or comes back into, and no register range may hold the register without naming it. Any other shape is still refused. The translation starts the kept bits at zero, as before. When one register holds both counts, as the recognizer now also accepts, the vertex exports still test that register against the lane, so a guard on it keeps the same lanes. The check never reads the primitive count. A read in the primitive part is still refused, though its lanes are then the guard's. Over the recorded ProjectScarlett requests (24,848, and 24,866 for the byte comparison, as a game run was adding to them), against 68e79b7: the 99 translate, compile with Linux DXC 1.8.2505.1 and pass DXV. All 22,970 requests main translates give byte-identical output, and every other refusal is unchanged. No GPU run. Co-Authored-By: Claude Opus 5.5 --- tools/shader-compiler/src/hlsl/mesh.rs | 231 +++++++++++++++ .../shader-compiler/src/hlsl/mesh_exports.rs | 4 + tools/shader-compiler/src/tests/hlsl/mesh.rs | 277 +++++++++++++++++- 3 files changed, 498 insertions(+), 14 deletions(-) diff --git a/tools/shader-compiler/src/hlsl/mesh.rs b/tools/shader-compiler/src/hlsl/mesh.rs index 6d5a2dae..643e4135 100644 --- a/tools/shader-compiler/src/hlsl/mesh.rs +++ b/tools/shader-compiler/src/hlsl/mesh.rs @@ -78,6 +78,8 @@ pub(super) fn translate( if has_primitive_attributes != has_attribute_exports { return Err("mesh primitive attribute exports do not match PSG1".into()); } + // The export sequence also reads registers. + let program = body.clone(); body.truncate(exports.start); if body.iter().any(|op| op.mnemonic == "v_writelane_b32") { super::lower_lane_spills(&mut body, false, false)?; @@ -151,6 +153,10 @@ pub(super) fn translate( if unset || matches!(reg.as_str(), "s0" | "s3" | "v5") { return false; } + // A 16-bit result can keep launch bits that no reader takes. + if reg.strip_prefix('v').and_then(|n| n.parse::().ok()).is_some_and(|n| kept_half_unread(&program, n, &exports)) { + return false; + } match &bindings { Some(mesh) => { let sgpr = reg.strip_prefix('s').and_then(|n| n.parse::().ok()); @@ -427,6 +433,231 @@ fn validate_launch(body: &[Insn], group_shift: i64, lane_index: Opnd) -> Result< Err("unrecognized mesh launch group or wave/lane register calculation".into()) } +/// Whether launch register `v{reg}` is live only through the upper half that a +/// VOP1 `v_cvt_f16_f32` keeps. RDNA2 16-bit results write bits 15:0 and leave +/// 31:16, so `live_in` counts the write as a read of the launch value. The +/// translation starts those bits at zero, which is faithful when no result takes +/// them. In the recorded programs the register is v6, v7 or v8. +/// +/// The proof covers the whole program, export sequence included. It follows +/// `live_in`'s program order: EXEC saves and restores pair up in that order, and +/// each branch is checked against it. +/// - The 16-bit write sits in the block the vertex-count guard opens: +/// `s_mov_b64 s[n:n+1], exec`, then `v_cmpx_gt_u32 count, lane` with the +/// `count` and `lane` registers the export sequence tests, then +/// `s_cbranch_execz` to `s_mov_b64 exec, s[n:n+1]`. The guard is the last EXEC +/// change before the write, and neither register changes after it. Up to the +/// export sequence EXEC only narrows or returns to a value saved since the +/// block opened, and inside the block to one saved after the guard. No branch +/// crosses the guard or the write except the guard's own, taken when no lane is +/// active. So every lane that reads the register in the block has executed the +/// write. After the block nothing touches the register before the vertex +/// exports, which test the same count against the same lane. +/// - Every later reader takes bits 15:0 only, until a full 32-bit write that no +/// path leaves early or enters from later code. No register range (loads, +/// stores, 64-bit and DPP operands) may hold the register without naming it. +fn kept_half_unread(insns: &[Insn], reg: u8, exports: &mesh_exports::MeshExports) -> bool { + let this = Opnd::Vgpr(reg); + let half_write = |op: &Insn| { + op.mnemonic == "v_cvt_f16_f32" && op.enc == Enc::Vop1 && op.aux.sdwa.is_none() && !op.src.contains(&this) + }; + // VOP3 OPSEL bits 11 and 12 pick the high half of source 0 and 1. + let low_half_read = |op: &Insn| { + let high = |i: usize| op.enc == Enc::Vop3 && op.raw[0] >> (11 + i) & 1 != 0; + op.aux.sdwa.is_none() + && matches!(op.enc, Enc::Vop1 | Enc::Vop3) + && op.src.iter().enumerate().all(|(i, src)| { + *src != this + || match op.mnemonic.as_str() { + "v_cvt_f32_f16" => i == 0 && !high(i), + "v_pack_b32_f16" => op.enc == Enc::Vop3 && i < 2 && !high(i), + _ => false, + } + }) + }; + // A full write of a 32-bit result: no partial, accumulating, lane or 64-bit forms. + let full_write = |op: &Insn| { + let m = op.mnemonic.as_str(); + matches!(op.enc, Enc::Vop1 | Enc::Vop2 | Enc::Vop3) + && op.aux.sdwa.is_none() + && (m == "v_cvt_f32_f16" || m == "v_pack_b32_f16" || !["16", "64", "mac", "lane", "movrel"].iter().any(|s| m.contains(s))) + }; + // A register range that may include `reg` without naming it, or an operand + // the decoder leaves raw (such as a DPP source). + let covers = |op: &Insn| { + let m = op.mnemonic.as_str(); + if op.src.iter().any(|o| matches!(o, Opnd::Raw(_))) { + return true; + } + if matches!(op.enc, Enc::Mubuf | Enc::Mtbuf) && (m.starts_with("buffer_load_") || m.starts_with("tbuffer_load_")) { + // VDATA holds the loaded dwords (one more with TFE, bit 55); VADDR is one + // register, or an index and an offset with IDXEN and OFFEN (bits 13 and 12). + let words = Emitter::mubuf_dwords(m).or_else(|| m.split('_').next_back().map(|s| s.len() as u32)); + let words = words.unwrap_or(16) + (op.raw.get(1).is_some_and(|w| w >> 23 & 1 != 0) as u32); + let addresses = 1 + (op.raw[0] >> 12 & 3 == 3) as u8; + let inside = |base: u8, count: u32| reg > base && u32::from(reg - base) < count; + return op.dst.iter().any(|o| matches!(o, Opnd::Vgpr(b) if inside(*b, words))) + || matches!(op.src.first(), Some(Opnd::Vgpr(a)) if inside(*a, u32::from(addresses))); + } + let wide = !matches!(op.enc, Enc::Vop1 | Enc::Vop2 | Enc::Vop3 | Enc::Vopc | Enc::Exp) + || ["64", "movrel"].iter().any(|s| m.contains(s)); + wide && op.src.iter().chain(&op.dst).any(|o| matches!(o, Opnd::Vgpr(b) if *b < reg && reg - b < 16)) + }; + // Whether `op` may write `target`, by name or within a wider destination. The + // decoder gives V_NOP an operand it does not write, and names the register an + // S_CMPK compare reads as its destination. + let writes = |op: &Insn, target: Opnd| { + let m = op.mnemonic.as_str(); + let lane_read = m == "v_readlane_b32"; + m != "v_nop" && !m.starts_with("s_cmpk_") && op.dst.iter().any(|dst| { + // V_READLANE_B32 names its scalar destination as a vector register. + let dst = match *dst { + Opnd::Vgpr(n) if lane_read => Opnd::Sgpr(n), + dst => dst, + }; + let width: u16 = match (op.enc, dst) { + // The dwords an SMEM load writes, as `live_in` counts them. + (Enc::Smem, _) => 1 << (op.op & 7), + (Enc::Sop1 | Enc::Sop2 | Enc::Sopk, _) | (Enc::Vop1 | Enc::Vop2 | Enc::Vop3, Opnd::Vgpr(_)) => { + 1 + u16::from(m.contains("64")) + } + _ if lane_read || m == "v_readfirstlane_b32" => 1, + // A wave64 lane mask. + (Enc::Vopc | Enc::Vop3, _) => 2, + // A destination this check does not size. + _ => 16, + }; + match (dst, target) { + (Opnd::Sgpr(b), Opnd::Sgpr(n)) | (Opnd::Vgpr(b), Opnd::Vgpr(n)) => n >= b && u16::from(n - b) < width, + _ => false, + } + }) + }; + let target = |op: &Insn| { + (op.enc == Enc::Sopp && op.mnemonic.contains("branch")) + .then(|| (op.offset + 4).checked_add_signed(op.aux.imm as isize * 4)) + }; + let exec = |op: &Insn| { + op.dst.iter().any(|d| matches!(d, Opnd::ExecLo | Opnd::ExecHi)) + || ["v_cmpx", "saveexec", "wrexec"].iter().any(|s| op.mnemonic.contains(s)) + }; + // V_READLANE_B32 names its scalar destination as a vector register. + let write = |op: &Insn| op.dst.first() == Some(&this) && op.mnemonic != "v_readlane_b32"; + let touches = |op: &Insn| op.src.contains(&this) || write(op); + if insns.iter().any(|op| matches!(op.mnemonic.as_str(), "s_setpc_b64" | "s_swappc_b64")) { + return false; + } + let Some(first) = insns.iter().position(|op| op.mnemonic != "v_nop" && touches(op)) else { + return false; + }; + if !half_write(&insns[first]) || insns[..first].iter().any(covers) { + return false; + } + let Some(guard) = insns[..first].iter().rposition(exec) else { + return false; + }; + let (count, lane) = (exports.vertices, exports.lane_index); + let test = &insns[guard]; + // The pair of SGPRs a `s_mov_b64 s[n:n+1], exec` before `at` saved and nothing + // rewrote since, with the index of the save. + let saved = |at: usize, pair: Opnd| { + let Opnd::Sgpr(n) = pair else { return None }; + let high = Opnd::Sgpr(n.checked_add(1)?); + let save = insns[..at].iter().rposition(|op| writes(op, pair) || writes(op, high))?; + let op = &insns[save]; + (op.mnemonic == "s_mov_b64" && op.dst[..] == [pair] && op.src[..] == [Opnd::ExecLo]).then_some(save) + }; + let restore = |op: &Insn| match (op.mnemonic.as_str(), &op.dst[..], &op.src[..]) { + ("s_mov_b64", [Opnd::ExecLo], &[pair]) => Some(pair), + _ => None, + }; + // The guard's branch skips to the restore that closes its block. The save that + // opens the block is the only EXEC change before the guard that matters: the + // guard narrows what it saved. + let Some(Some(end)) = insns.get(guard + 1).filter(|op| op.mnemonic == "s_cbranch_execz").and_then(target) else { + return false; + }; + let Some(close) = insns.iter().position(|op| op.offset == end) else { + return false; + }; + let Some(open) = restore(&insns[close]).and_then(|pair| saved(close, pair)) else { + return false; + }; + if !(test.mnemonic == "v_cmpx_gt_u32" && test.enc == Enc::Vopc && test.aux.sdwa.is_none() && test.src[..] == [count, lane]) + || open >= guard + || first >= close + || close >= exports.start + || insns[open + 1..guard].iter().any(exec) + || insns[guard + 1..].iter().any(|op| writes(op, count) || writes(op, lane)) + || insns[close..exports.vertex_start].iter().any(|op| covers(op) || touches(op)) + { + return false; + } + // Up to the export sequence, EXEC only narrows or returns to a value saved since + // `open`. Inside the guarded span the value was saved after the guard, so EXEC + // stays within the lanes the guard kept; afterwards it stays within those it + // started with. The export sequence narrows from there. + let narrowed = insns.iter().enumerate().take(exports.start).skip(open + 1).all(|(at, op)| { + if !exec(op) { + return true; + } + if (op.mnemonic.starts_with("v_cmpx_") && op.aux.sdwa.is_none()) || op.mnemonic == "s_and_saveexec_b64" { + return true; + } + let since = if at > guard && at < close { guard } else { open }; + restore(op).and_then(|pair| saved(at, pair)).is_some_and(|save| save >= since) + }); + if !narrowed { + return false; + } + let (tested, from, end) = (test.offset, insns[first].offset, insns[close].offset); + // Branches before the 16-bit write stay on their side of the guard. When the + // guard's own branch is taken, no lane is active. + let entered = insns[..first].iter().enumerate().all(|(at, op)| match target(op) { + None => true, + Some(None) => false, + Some(Some(t)) if at == guard + 1 => t > from, + Some(Some(t)) if at < guard => t <= tested, + Some(Some(t)) => t > tested && t <= from, + }); + if !entered { + return false; + } + // From the 16-bit write on, no path comes back into the span that ends at + // `last`, and none from after the block comes back into it. When `last` is the + // full write, no path leaves the span before it, and EXEC does not change in + // it, so the full write reaches every lane the 16-bit write did. + let closed = |last: usize, full: bool| { + let to = insns[last].offset; + insns.iter().enumerate().skip(first).all(|(at, op)| match target(op) { + None => true, + Some(None) => false, + Some(Some(t)) if at < last => t > from && (t <= to || !full), + Some(Some(t)) => t > to && (at < close || t > end), + }) && !(full && insns[first..=last].iter().any(exec)) + }; + let mut last_read = first; + for (at, op) in insns.iter().enumerate().skip(first + 1) { + if op.mnemonic == "v_nop" { + continue; + } + if covers(op) { + return false; + } + let read = op.src.contains(&this); + if read && !low_half_read(op) { + return false; + } + if read { + last_read = at; + } + if write(op) && !half_write(op) { + return full_write(op) && closed(at, true); + } + } + closed(last_read, false) +} + /// The logical 64-lane wave is split across desktop invocations. A first-lane /// broadcast can be scalarized only when its source is already uniform. fn validate_lane_ops(body: &[Insn], own: &BTreeSet, wave_control: bool, swizzles: bool) -> Result<(), String> { diff --git a/tools/shader-compiler/src/hlsl/mesh_exports.rs b/tools/shader-compiler/src/hlsl/mesh_exports.rs index dc4ed156..f0c6c56c 100644 --- a/tools/shader-compiler/src/hlsl/mesh_exports.rs +++ b/tools/shader-compiler/src/hlsl/mesh_exports.rs @@ -5,6 +5,8 @@ use Opnd::{ConstInt as I, ExecLo, Literal, Scc, Sgpr as S, VccLo, Vgpr as V, M0} pub(super) struct MeshExports { pub start: usize, + /// The first instruction after the export sequence's vertex-count guard. + pub vertex_start: usize, pub lane_index: Opnd, pub vertices: Opnd, pub primitives: Opnd, @@ -423,6 +425,7 @@ pub(super) fn recognize( } seq.write(S(0), "s_and_saveexec_b64", &[S(0)])?; let end_vertices = seq.branch("s_cbranch_execz")?; + let vertex_start = seq.at; let mut vertex_exports = Vec::new(); let mut targets = 0u64; // Registers the program sets for later exports. The emitter reads the values directly. @@ -514,6 +517,7 @@ pub(super) fn recognize( }; Ok(MeshExports { start, + vertex_start, lane_index, vertices, primitives, diff --git a/tools/shader-compiler/src/tests/hlsl/mesh.rs b/tools/shader-compiler/src/tests/hlsl/mesh.rs index d0243c37..554f5008 100644 --- a/tools/shader-compiler/src/tests/hlsl/mesh.rs +++ b/tools/shader-compiler/src/tests/hlsl/mesh.rs @@ -61,22 +61,24 @@ fn class5_descriptor_load_uses_the_guest_heap_index() { /// One register holds both output counts, so the compiler checks it once and /// combines each mask with itself. Assembled with llvm-mc for wave64. +const ONE_COUNT: [u32; 70] = [ + 0x7e3c0280, 0xbf068014, 0x8580807e, 0xb5940080, 0x8582807e, 0x88800000, + 0x88820202, 0x88800002, 0xd5010001, 0x00010280, 0x7e000501, 0x87000081, + 0xbf068100, 0xbe80047e, 0x8582807e, 0xd5010001, 0x00090214, 0x8984c102, + 0x7e0c0501, 0x7da40080, 0xbf88000d, 0x8f078c06, 0x8aea027e, 0x88060607, + 0xbefc0306, 0xbf900009, 0xbf8c0000, 0xbf870006, 0xbf8a0000, 0x7e027081, + 0xf80008c0, 0x00000000, 0xf8000941, 0x00000001, 0xbf8cff0f, 0xbefe0400, + 0xbf8a0000, 0x7d880014, 0x8780046a, 0xbe862400, 0xbf880012, 0xd5480001, + 0x02291513, 0xd5480002, 0x02292913, 0x363026ff, 0x000003ff, 0x7d860214, + 0xd4c30002, 0x00020414, 0xd4c30000, 0x00023014, 0x8882026a, 0x88800200, + 0xd5010001, 0x0001ff13, 0x80000000, 0xf8000941, 0x00000001, 0xbf8cff0f, + 0xbefe0406, 0x7d880014, 0x8780046a, 0xbe802400, 0xbf880004, 0xf80008cf, + 0x33323130, 0xf800020f, 0x1211100f, 0xbf810000, +]; + #[test] fn one_count_for_vertices_and_primitives_is_recognized() { - let words: [u32; 70] = [ - 0x7e3c0280, 0xbf068014, 0x8580807e, 0xb5940080, 0x8582807e, 0x88800000, - 0x88820202, 0x88800002, 0xd5010001, 0x00010280, 0x7e000501, 0x87000081, - 0xbf068100, 0xbe80047e, 0x8582807e, 0xd5010001, 0x00090214, 0x8984c102, - 0x7e0c0501, 0x7da40080, 0xbf88000d, 0x8f078c06, 0x8aea027e, 0x88060607, - 0xbefc0306, 0xbf900009, 0xbf8c0000, 0xbf870006, 0xbf8a0000, 0x7e027081, - 0xf80008c0, 0x00000000, 0xf8000941, 0x00000001, 0xbf8cff0f, 0xbefe0400, - 0xbf8a0000, 0x7d880014, 0x8780046a, 0xbe862400, 0xbf880012, 0xd5480001, - 0x02291513, 0xd5480002, 0x02292913, 0x363026ff, 0x000003ff, 0x7d860214, - 0xd4c30002, 0x00020414, 0xd4c30000, 0x00023014, 0x8882026a, 0x88800200, - 0xd5010001, 0x0001ff13, 0x80000000, 0xf8000941, 0x00000001, 0xbf8cff0f, - 0xbefe0406, 0x7d880014, 0x8780046a, 0xbe802400, 0xbf880004, 0xf80008cf, - 0x33323130, 0xf800020f, 0x1211100f, 0xbf810000, - ]; + let words = ONE_COUNT; let recognize = |words: &[u32]| { let bytes = words.iter().flat_map(|w| w.to_le_bytes()).collect::>(); super::super::mesh_exports::recognize(&disassemble(&bytes), 128, None) @@ -96,3 +98,250 @@ fn one_count_for_vertices_and_primitives_is_recognized() { mixed[5] = 0x88800200; assert!(recognize(&mixed).is_err()); } + +const HALF: u32 = 0x7e0e1501; // v_cvt_f16_f32 v7, v1: bits 31:16 keep the launch value +const LOW: u32 = 0x7e101707; // v_cvt_f32_f16 v8, v7: reads bits 15:0 +const WIDEN: u32 = 0x7e0e1707; // v_cvt_f32_f16 v7, v7: a full write +const COPY: u32 = 0x7e100307; // v_mov_b32 v8, v7: reads all 32 bits +const END: u32 = 0xbf810000; // s_endpgm +const OPEN: u32 = 0xbeac047e; // s_mov_b64 s[44:45], exec +const GUARD: u32 = 0x7da8002e; // v_cmpx_gt_u32 s46, v0: the vertex count against the lane +const CLOSE: u32 = 0xbefe042c; // s_mov_b64 exec, s[44:45] +const SAVE: u32 = 0xbe84047e; // s_mov_b64 s[4:5], exec +const RESTORE: u32 = 0xbefe0404; // s_mov_b64 exec, s[4:5] +const NARROW: u32 = 0x7da40280; // v_cmpx_eq_u32 0, v1 + +fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +/// `body` in the block the vertex-count guard opens, then `after`. +fn guarded(body: &[u32], after: &[u32]) -> Vec { + let mut words = vec![OPEN, GUARD, 0xbf880000 | body.len() as u32]; // s_cbranch_execz to CLOSE + words.extend(body); + words.push(CLOSE); + words.extend(after); + words.push(END); + words +} + +/// Whether v7 keeps only unread launch bits, with the export sequence from word +/// `start` and its vertex exports from word `vertices`. +fn kept_from(words: &[u32], start: usize, vertices: usize) -> bool { + let insns = disassemble(&bytes(words)); + let at = |word: usize| insns.iter().position(|op| op.offset == 4 * word).unwrap_or(insns.len()); + let exports = super::mesh_exports::MeshExports { + start: at(start), + vertex_start: at(vertices), + lane_index: Opnd::Vgpr(0), + vertices: Opnd::Sgpr(46), + primitives: Opnd::Sgpr(48), + connectivity: Opnd::Vgpr(19), + guarded_connectivity: Opnd::Vgpr(1), + connectivity_without_primitive: Opnd::Sgpr(48), + vertex_exports: Vec::new(), + primitive_exports: Vec::new(), + }; + kept_half_unread(&insns, 7, &exports) +} + +/// The same, for a program without an export sequence. +fn kept(words: &[u32]) -> bool { + kept_from(words, words.len(), words.len()) +} + +#[test] +fn a_half_result_hides_only_launch_bits_no_reader_takes() { + assert!(kept(&guarded(&[HALF, LOW], &[]))); + assert!(kept(&guarded(&[HALF, WIDEN, COPY], &[]))); + assert!(kept(&guarded(&[HALF, 0xd7110008, 0x00020307], &[])), "v_pack_b32_f16 v8, v7, v1"); + assert!(kept(&guarded(&[HALF, 0xe0341000, 0x80000206, LOW], &[])), "a load addressed by v6 alone"); + assert!(kept(&guarded(&[HALF, 0xd7600007, 0x00010100, LOW], &[])), "v_readlane_b32 writes s7"); + assert!(!kept(&guarded(&[HALF, COPY], &[]))); + assert!(!kept(&guarded(&[COPY, HALF, LOW], &[])), "the launch value is read first"); + assert!(!kept(&guarded(&[HALF, 0xd7110808, 0x00020307], &[])), "op_sel reads the kept high half"); + assert!(!kept(&guarded(&[HALF, 0x560e0501], &[])), "v_fmac_f32 accumulates into v7"); + assert!(!kept(&guarded(&[HALF, 0xe0741000, 0x80000600], &[])), "buffer_store_dwordx2 v[6:7]"); + assert!(!kept(&guarded(&[HALF, 0xe0303000, 0x80000206, LOW], &[])), "an idxen offen address v[6:7]"); + // A path around the full write, or lanes it skips, still see the launch bits. + assert!(!kept(&guarded(&[HALF, 0xbf840001, WIDEN, COPY], &[])), "s_cbranch_scc0 past the full write"); + assert!(!kept(&guarded(&[HALF, NARROW, WIDEN, COPY], &[])), "v_cmpx_eq_u32 before the full write"); +} + +#[test] +fn a_half_result_is_kept_only_behind_the_vertex_count_guard() { + // The recorded shape: the block narrows further and opens another for the + // primitive count after it closes. + let nested = [HALF, SAVE, NARROW, 0xbf880001, LOW, RESTORE, LOW]; + let primitives = [0xbe80047e, 0x7da80030, 0xbefe0400]; // s_mov_b64 s[0:1], exec; v_cmpx_gt_u32 s48, v0; s_mov_b64 exec, s[0:1] + assert!(kept(&guarded(&nested, &primitives))); + // Without the guard, or with one that tests another count or lane, lanes past + // the vertex count never execute the 16-bit write. + assert!(!kept(&[HALF, LOW, END])); + assert!(!kept(&guarded(&[HALF, LOW], &[]).iter().map(|&w| if w == GUARD { 0x7da80030 } else { w }).collect::>()), "s48 counts primitives"); + assert!(!kept(&guarded(&[HALF, LOW], &[]).iter().map(|&w| if w == GUARD { 0x7da8022e } else { w }).collect::>()), "v1 is not the lane"); + assert!(!kept(&guarded(&[0x812e812e, HALF, LOW], &[])), "s_add_i32 s46, s46, 1 after the guard"); + assert!(!kept(&guarded(&[HALF, LOW], &[0x7e000301])), "v_mov_b32 v0, v1 after the guard"); + // (A) A branch from before the 16-bit write to after the full write. + assert!(!kept(&[0xbf840002, HALF, WIDEN, COPY, END]), "s_cbranch_scc0 +2 without a guard"); + assert!(!kept(&guarded(&[0xbf840002, HALF, WIDEN, COPY], &[])), "s_cbranch_scc0 +2 inside the block"); + // (B) An s_and_saveexec_b64 before the 16-bit write, restored after the full write. + let and_saveexec = 0xbe84246a; // s_and_saveexec_b64 s[4:5], vcc + assert!(!kept(&[and_saveexec, HALF, WIDEN, RESTORE, COPY, END])); + assert!(!kept(&guarded(&[and_saveexec, HALF, WIDEN, RESTORE, COPY], &[]))); + // (C) The same with v_cmpx. + assert!(!kept(&[SAVE, NARROW, HALF, WIDEN, RESTORE, COPY, END])); + assert!(!kept(&guarded(&[SAVE, NARROW, HALF, WIDEN, RESTORE, COPY], &[]))); + // (D) EXEC narrowed around the 16-bit write only, then a low-half read. + assert!(!kept(&[SAVE, NARROW, HALF, RESTORE, LOW, END])); + assert!(!kept(&guarded(&[SAVE, NARROW, HALF, RESTORE, LOW], &[]))); + // EXEC widens again inside the block. + assert!(!kept(&guarded(&[HALF, CLOSE, LOW], &[])), "the block's own restore, early"); + assert!(!kept(&guarded(&[HALF, 0xbefe04c1, LOW], &[])), "s_mov_b64 exec, -1"); + // After the block every lane runs, and lanes past the count hold the launch value. + assert!(!kept(&guarded(&[HALF], &[LOW]))); + // s_branch from after the block back to the copy inside it. + assert!(!kept(&guarded(&[HALF, WIDEN, COPY], &[0xbf82fffd]))); +} + +#[test] +fn a_kept_half_reaches_only_the_vertex_exports() { + // An export sequence from word 6: a primitive part, then the vertex exports from word 7. + let program = |primitive: u32| guarded(&[HALF, WIDEN], &[primitive, 0xf80008cf, 0x33323107]); // exp pos0 v7, v49, v50, v51 done + assert!(kept_from(&program(0xbf800000), 6, 7), "s_nop"); + assert!(!kept_from(&program(COPY), 6, 7), "the primitive exports run lanes past the vertex count"); +} + +#[test] +fn a_guarded_half_result_in_a_recognized_program() { + // The guard, the 16-bit write and the full write, then a 128-vertex export + // sequence with the vertex count in s46 and the primitive count in s48, as in + // the recorded programs. Its position export reads v7. + let mut words = vec![OPEN, GUARD, 0xbf880002, HALF, WIDEN, CLOSE]; + words.extend(separate_count_exports()); + let check = |words: &[u32]| { + let insns = disassemble(&bytes(words)); + let exports = super::mesh_exports::recognize(&insns, 128, None).unwrap(); + assert_eq!((exports.vertices, exports.lane_index), (Opnd::Sgpr(46), Opnd::Vgpr(0))); + kept_half_unread(&insns, 7, &exports) + }; + assert!(check(&words)); + let mut primitive_guard = words.clone(); + primitive_guard[1] = 0x7da80030; // v_cmpx_gt_u32 s48, v0 + assert!(!check(&primitive_guard)); +} + +#[test] +fn a_guarded_half_result_ahead_of_one_shared_count() { + // One register, s20, is both counts. The vertex exports still test it against + // v0, so a guard on it keeps the same lanes they run; no other register could + // stand for the vertex count. The position export reads v7. + let guard = 0x7da80014; // v_cmpx_gt_u32 s20, v0 + let program = |block: &[u32], after: &[u32], exports: &[u32]| { + let mut words = vec![OPEN, guard, 0xbf880000 | block.len() as u32]; + words.extend(block); + words.push(CLOSE); + words.extend(after); + words.extend(exports); + let insns = disassemble(&bytes(&words)); + let found = super::mesh_exports::recognize(&insns, 128, None).unwrap_or_else(|reason| panic!("{reason}")); + assert_eq!((found.vertices, found.primitives, found.lane_index), (Opnd::Sgpr(20), Opnd::Sgpr(20), Opnd::Vgpr(0))); + (insns, found) + }; + let kept = |(insns, found): (Vec, super::mesh_exports::MeshExports)| kept_half_unread(&insns, 7, &found); + let mut position = ONE_COUNT; + assert_eq!(position[66], 0x33323130); + position[66] = 0x33323107; // exp pos0 v7, v49, v50, v51 done + // The allocation's s_cmpk_gt_u32 s20, 0x80 reads the count and does not write it. + assert!(kept(program(&[HALF, WIDEN], &[], &position))); + assert!(kept(program(&[HALF, LOW, WIDEN], &[], &position))); + // A guard on a register that is not the count, or on another lane. + let other = |(mut insns, found): (Vec, super::mesh_exports::MeshExports), word: u32| { + insns[1] = disassemble(&bytes(&[word])).remove(0); + insns[1].offset = 4; + kept_half_unread(&insns, 7, &found) + }; + assert!(!other(program(&[HALF, WIDEN], &[], &position), GUARD), "s46 is not the count"); + assert!(!other(program(&[HALF, WIDEN], &[], &position), 0x7da80214), "v_cmpx_gt_u32 s20, v1"); + // The count rewritten between the guard and the exports. + assert!(!kept(program(&[HALF, WIDEN], &[0x81148114], &position)), "s_add_i32 s20, s20, 1"); + // Lanes past the count read the register after the block. + assert!(!kept(program(&[HALF], &[LOW], &position))); + assert!(!kept(program(&[HALF, WIDEN], &[0x7e100507], &position)), "v_readfirstlane_b32 s8, v7"); + // A swizzle takes the register whole, from other lanes. + assert!(!kept(program(&[HALF, 0xd8d40000, 0x08000007, WIDEN], &[], &position)), "ds_swizzle_b32 v8, v7"); + // The primitive part reads v7 as the packed triangle. With one count its lanes + // are those of the guard, but the proof stops at the vertex exports. + let mut triangle = position; + assert_eq!((triangle[42], triangle[44], triangle[45], triangle[55]), (0x02291513, 0x02292913, 0x363026ff, 0x0001ff13)); + (triangle[42], triangle[44], triangle[45], triangle[55]) = (0x02291507, 0x02292907, 0x36300eff, 0x0001ff07); + assert!(!kept(program(&[HALF, WIDEN], &[], &triangle))); +} + +/// A 128-vertex export sequence with separate counts, assembled with +/// `llvm-mc -mcpu=gfx1030 -mattr=+wavefrontsize64`. +fn separate_count_exports() -> Vec { + vec![ + 0xbf06802e, // s_cmp_eq_u32 s46, 0 + 0xb0060080, // s_movk_i32 s6, 0x80 + 0x8580807e, // s_cselect_b64 s[0:1], exec, 0 + 0xbf068030, // s_cmp_eq_u32 s48, 0 + 0x8582807e, // s_cselect_b64 s[2:3], exec, 0 + 0xbf0a2e06, // s_cmp_lt_u32 s6, s46 + 0x8584807e, // s_cselect_b64 s[4:5], exec, 0 + 0xbf0a3006, // s_cmp_lt_u32 s6, s48 + 0x8586807e, // s_cselect_b64 s[6:7], exec, 0 + 0x88800200, // s_or_b64 s[0:1], s[0:1], s[2:3] + 0x88820604, // s_or_b64 s[2:3], s[4:5], s[6:7] + 0x88800002, // s_or_b64 s[0:1], s[2:3], s[0:1] + 0xd5010001, 0x00010280, // v_cndmask_b32_e64 v1, 0, 1, s[0:1] + 0x7e000501, // v_readfirstlane_b32 s0, v1 + 0x87000081, // s_and_b32 s0, 1, s0 + 0xbf068100, // s_cmp_eq_u32 s0, 1 + 0xbe80047e, // s_mov_b64 s[0:1], exec + 0x8582807e, // s_cselect_b64 s[2:3], exec, 0 + 0xd5010002, 0x0009022e, // v_cndmask_b32_e64 v2, s46, 1, s[2:3] + 0xd5010003, 0x00090230, // v_cndmask_b32_e64 v3, s48, 1, s[2:3] + 0x8984c102, // s_xor_b64 s[4:5], s[2:3], -1 + 0x7e0c0502, // v_readfirstlane_b32 s6, v2 + 0x7e0e0503, // v_readfirstlane_b32 s7, v3 + 0x7da40080, // v_cmpx_eq_u32_e32 0, v0 + 0xbf88000d, // s_cbranch_execz restore + 0x8f078c07, // s_lshl_b32 s7, s7, 12 + 0x8aea027e, // s_andn2_b64 vcc, exec, s[2:3] + 0x88060607, // s_or_b32 s6, s7, s6 + 0xbefc0306, // s_mov_b32 m0, s6 + 0xbf900009, // s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) + 0xbf8c0000, // s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0) + 0xbf870006, // s_cbranch_vccnz restore + 0xbf8a0000, // s_barrier + 0x7e027081, // v_bfrev_b32_e32 v1, 1 + 0xf80008c0, 0x00000000, // exp pos0 off, off, off, off done + 0xf8000941, 0x00000001, // exp prim v1, off, off, off done + 0xbf8cff0f, // s_waitcnt expcnt(0) + 0xbefe0400, // s_mov_b64 exec, s[0:1] + 0xbf8a0000, // s_barrier + 0x7d880030, // v_cmp_gt_u32_e32 vcc, s48, v0 + 0x8780046a, // s_and_b64 s[0:1], vcc, s[4:5] + 0xbe862400, // s_and_saveexec_b64 s[6:7], s[0:1] + 0xbf880012, // s_cbranch_execz vertices + 0xd5480001, 0x02291513, // v_bfe_u32 v1, v19, 10, 10 + 0xd5480002, 0x02292913, // v_bfe_u32 v2, v19, 20, 10 + 0x363026ff, 0x000003ff, // v_and_b32_e32 v24, 0x3ff, v19 + 0x7d86022e, // v_cmp_le_u32_e32 vcc, s46, v1 + 0xd4c30002, 0x0002042e, // v_cmp_le_u32_e64 s[2:3], s46, v2 + 0xd4c30000, 0x0002302e, // v_cmp_le_u32_e64 s[0:1], s46, v24 + 0x8882026a, // s_or_b64 s[2:3], vcc, s[2:3] + 0x88800200, // s_or_b64 s[0:1], s[0:1], s[2:3] + 0xd5010001, 0x0001ff13, 0x80000000, // v_cndmask_b32_e64 v1, v19, 0x80000000, s[0:1] + 0xf8000941, 0x00000001, // exp prim v1, off, off, off done + 0xbf8cff0f, // s_waitcnt expcnt(0) + 0xbefe0406, // s_mov_b64 exec, s[6:7] + 0x7d88002e, // v_cmp_gt_u32_e32 vcc, s46, v0 + 0x8780046a, // s_and_b64 s[0:1], vcc, s[4:5] + 0xbe802400, // s_and_saveexec_b64 s[0:1], s[0:1] + 0xbf880002, // s_cbranch_execz end + 0xf80008cf, 0x33323107, // exp pos0 v7, v49, v50, v51 done: v7 from the 16-bit block + 0xbf810000, // s_endpgm + ] +}