From 7349d8322fe48677df2d1884d48b72c7be804922 Mon Sep 17 00:00:00 2001 From: Pavel Kirilin Date: Fri, 27 Nov 2026 00:02:29 +0100 Subject: [PATCH 1/2] xshader: accept uniform loops around compute swizzles for single-wave groups Signed-off-by: Pavel Kirilin --- .../support/compute_swizzle_fixture.rs | 18 +++++++++++ .../src/hlsl/driver/pipeline.rs | 8 +++++ .../src/tests/hlsl/compute_swizzle.rs | 30 +++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs b/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs index d4a5b359..31825f4e 100644 --- a/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs +++ b/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs @@ -5,6 +5,24 @@ use super::{ShaderExtract, Stage}; /// in one 64-lane group. As in LLVM's encoding, the source occupies the ADDR field. pub fn shader(offset: u32, word0_extra: u32) -> ShaderExtract { let words = [0xd8d4_0000 | offset | word0_extra, 0x0000_0001, 0xbf8c_c07f, 0xbf81_0000]; + build(words.to_vec()) +} + +/// The same exchange, wrapped in a backward branch that keeps it in a loop. +/// Operand is the SOP1 back-edge: op 5 is a uniform SCC skip (s_cbranch_scc1), +/// op 7 a per-lane VCC one (s_cbranch_vccnz). Both jump back to 0x00. +pub fn shader_loop(offset: u32, word0_extra: u32, op: u32) -> ShaderExtract { + let words = [ + 0xd8d4_0000 | offset | word0_extra, + 0x0000_0001, + 0xbf80_0000 | (op << 16) | 0xfffd, // s_cbranch_scc1/vccnz -> 0x00 (back-edge) + 0xbf8c_c07f, // s_waitcnt + 0xbf81_0000, // s_endpgm + ]; + build(words.to_vec()) +} + +fn build(words: Vec) -> ShaderExtract { let isa: Vec = words.iter().flat_map(|word| word.to_le_bytes()).collect(); ShaderExtract { flat_inputs: Vec::new(), flat_outputs: Vec::new(), stage: Stage::Compute, diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index bdd08ede..173e12ba 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -409,7 +409,15 @@ fn translate_outputs_once_impl(ex: &ShaderExtract, feeds_ps: Option<&InputInterp } // Moving a shared exchange out of a forward guest branch is safe once every // invocation rejoins. A backward branch could execute it different numbers of times. + // A loop back-edge is safe for a shared exchange when every invocation in the + // group runs it the same number of times: the group is a single wave (so SCC and + // EXEC are group-uniform) and the branch is uniform per wave (never a per-lane + // VCC). Anything else keeps the conservative rejection. + let single_wave = count <= 64; for branch in em.insns.iter().filter(|i| i.enc == Enc::Sopp && Emitter::branch_cond(i.op).is_some() && i.aux.imm < 0) { + if single_wave && !matches!(branch.op, 6 | 7) { + continue; + } let head = branch.offset as i64 + 4 + 4 * branch.aux.imm; if em.insns.iter().any(|i| exchanges(i) && (head..=branch.offset as i64).contains(&(i.offset as i64))) { return Err("compute swizzle inside a loop".into()); diff --git a/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs b/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs index 26cbf428..1d39518d 100644 --- a/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs +++ b/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs @@ -42,6 +42,36 @@ fn other_high_offset_bits_and_gds_stay_refused() { } } +#[test] +fn uniform_scc_loop_around_the_exchange_translates() { + // A 64-lane single wave: an SCC back-edge (uniform, never per-lane) means + // every invocation runs the loop and the shared exchange the same number of + // times, so the loop is accepted. + let ex = fixture::shader_loop(0x041f, 0, 5); + assert_eq!(disassemble(&ex.isa)[0].mnemonic, "ds_swizzle_b32"); + let hlsl = translate(&ex).map(|t| t.hlsl) + .expect("uniform SCC loop over a compute swizzle translates"); + assert!(hlsl.contains("tb_swizzle"), "{hlsl}"); +} + +#[test] +fn unconditional_loop_around_the_exchange_translates() { + let ex = fixture::shader_loop(0x041f, 0, 2); + let hlsl = translate(&ex).map(|t| t.hlsl) + .expect("unconditional loop over a compute swizzle translates"); + assert!(hlsl.contains("tb_swizzle"), "{hlsl}"); +} + +#[test] +fn divergent_vcc_loop_around_the_exchange_is_refused() { + // A VCC back-edge can run lane-selectively: lanes in the loop body run the + // exchange a different number of times, which is unsafe. + let error = translate(&fixture::shader_loop(0x041f, 0, 7)) + .map(|t| t.hlsl) + .unwrap_err(); + assert!(error.contains("compute swizzle inside a loop"), "{error}"); +} + #[test] fn paired_wave64_lowers_quad_and_bitmask_swizzles_without_shared_memory() { use crate::hlsl::translate_paired_wave64; From a27ca0ae9ed772daa2cb0d643c76389ab758a258 Mon Sep 17 00:00:00 2001 From: Pavel Kirilin Date: Fri, 27 Nov 2026 01:00:30 +0100 Subject: [PATCH 2/2] Fixed PR comments. Signed-off-by: Pavel Kirilin --- tools/check_compute_swizzle_loop.py | 150 ++++++++++++++++++ tools/check_translator_gpu.py | 1 + .../examples/compute_swizzle_loop.rs | 15 ++ .../support/compute_swizzle_fixture.rs | 60 ++++++- tools/shader-compiler/src/hlsl.rs | 7 + .../src/hlsl/driver/pipeline.rs | 61 ++++++- .../src/hlsl/emitter/bindings.rs | 4 + .../src/hlsl/emitter/control_flow.rs | 33 +++- .../src/hlsl/emitter/exchange.rs | 13 +- .../shader-compiler/src/hlsl/emitter/setup.rs | 2 + .../src/tests/hlsl/compute_swizzle.rs | 53 ++++++- 11 files changed, 380 insertions(+), 19 deletions(-) create mode 100644 tools/check_compute_swizzle_loop.py create mode 100644 tools/shader-compiler/examples/compute_swizzle_loop.rs diff --git a/tools/check_compute_swizzle_loop.py b/tools/check_compute_swizzle_loop.py new file mode 100644 index 00000000..69bb5f8b --- /dev/null +++ b/tools/check_compute_swizzle_loop.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Run the loop-around-the-exchange synthetic compute DS_SWIZZLE_B32 on a GPU. + +A 32-lane group whose loop runs four iterations and exits some lanes early +through a per-thread execz exit before the loop. The loop keeps every lane in +the loop (a whole-wave vote), publishes zero from the finished lanes, and only +the finished lanes keep their seed value. The instrumentation replaces the +fixture's seed line with a seed-carrying input so both the finished and the +active lanes run deterministically; every output word is compared with a CPU +model of the model. No game data is required. + +Usage (same arguments as tools/check_compute_swizzle.py): + python tools/check_compute_swizzle_loop.py \ + --emitter build/shader-compiler/x86_64-unknown-linux-gnu/release/examples/compute_swizzle_loop \ + --provider ... --proton ... --prefix ... --compiler-dir ... \ + --adapter --work --output +""" +import argparse +import json +import random +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from build import find_dxc +from frosty_gpu_guest import run_gpu_guest +from project_tuxbox.inspect import digest + +LANES = 32 +VIEW = 96 # first word of the guest's UAV view +UNTOUCHED = 0x5a5a0000 + +# Bit-mask mode, swap neighbours. Same offset the straight-line check uses. +OFFSET = 0x041f + + +def partner(offset, lane): + if offset & 0x8000: + return (lane & ~3) | ((offset >> (2 * (lane & 3))) & 3) + return (lane & ~31) | (((lane & (offset & 31)) | ((offset >> 5) & 31)) ^ ((offset >> 10) & 31)) + + +def instrument(hlsl): + replacements = { + " v0 = gtid.x; v1 = gtid.y; v2 = gtid.z;": ( + " uint input = output[gtid.x];\n" + " exec_lo = input >> 31;\n" + f" v0 = {UNTOUCHED:#x}u | gtid.x; v1 = input & 0x7fffffffu; v2 = gtid.z;" + ), + f" // 0x0020 s_endpgm": f" output[{LANES}u + gtid.x] = v0;\n // 0x0020 s_endpgm", + } + for original, replacement in replacements.items(): + if hlsl.count(original) != 1: + raise ValueError(f"unexpected fixture: {original}") + hlsl = hlsl.replace(original, replacement) + return "RWBuffer output : register(u0);\n" + hlsl + + +def masks(): + rng = random.Random(0x5357495a) + full = (1 << LANES) - 1 + yield "full", full + yield "odd", full & 0xaaaaaaaa + yield "lane_zero", 1 + yield "empty", 0 + for i in range(4): + yield f"random{i}", rng.getrandbits(LANES) + + +def seed_and_expected(offset, mask, values): + seed = [0x76540000 + i for i in range(384)] + active = [(mask >> lane) & 1 for lane in range(LANES)] + seed[VIEW:VIEW + LANES] = [v | (a << 31) for v, a in zip(values, active)] + expected = seed.copy() + for lane in range(LANES): + source = partner(offset, lane) + if active[lane]: + result = values[source] if active[source] else 0 + else: + result = UNTOUCHED | lane + expected[VIEW + LANES + lane] = result + return struct.pack("<384I", *seed), struct.pack("<384I", *expected) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("emitter", "provider", "proton", "prefix", "compiler-dir", "work", "output"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--adapter", required=True) + args = parser.parse_args() + work = args.work.resolve() + work.mkdir(parents=True, exist_ok=True) + dxc = Path(find_dxc(None)).resolve() + rng = random.Random(0x51554144) + with TemporaryDirectory(dir=work) as tmp: + trial = Path(tmp) + expected = {} + shaders = {} + emitted = subprocess.check_output([args.emitter.resolve(), f"{OFFSET:04x}"], text=True, timeout=30) + source = trial / "swizzle_loop.hlsl" + source.write_text(instrument(emitted)) + blob = trial / "swizzle_loop.cso" + subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", blob, source], check=True, timeout=30) + subprocess.run([dxc.with_name("dxv"), blob], check=True, timeout=30) + shaders[f"{OFFSET:#06x}"] = dict(hlsl_sha256=digest(source), dxil_sha256=digest(blob)) + for case, mask in masks(): + name = f"swizzle_loop_{case}" + values = [rng.getrandbits(31) for _ in range(LANES)] + seed, expected[name] = seed_and_expected(OFFSET, mask, values) + (trial / f"{name}.seed").write_bytes(seed) + (trial / f"{name}.cso").hardlink_to(blob) + (trial / "cases.txt").write_text("".join(f"{name} 0 uint 1\n" for name in expected)) + exe, status, fields = run_gpu_guest( + ROOT / "tools/reference/independent-shaders/compute.cpp", "compute-swizzle-loop.exe", + trial, work, args.proton.resolve(), args.prefix, args.provider, args.compiler_dir, + ) + rows = [] + for name, reference in expected.items(): + path = trial / f"{name}.bin" + actual = path.read_bytes() if path.is_file() else b"" + rows.append(dict(case=name, matched=actual == reference, + readback_sha256=digest(path) if path.is_file() else None)) + passed = status == 0 and fields.get("adapter") == args.adapter and all(row["matched"] for row in rows) + report = dict( + passed=passed, + scope="Synthetic loop around a compute ds_swizzle_b32: per-thread early exit, whole-wave loop vote", + offset=f"{OFFSET:#06x}", + adapter=fields.get("adapter"), proton=(args.proton / "version").read_text().strip(), + guest_exit=status, cases=len(rows), compared_words=len(rows) * 384, + result_words=len(rows) * LANES, input_words=len(rows) * LANES, + emitter_sha256=digest(args.emitter), shaders=shaders, + dxc_sha256=digest(dxc), guest_sha256=digest(exe), + d3d12_dlls={name: digest(trial / name) for name in ("d3d12.dll", "d3d12core.dll")}, + rows=rows, + ) + if fields.get("error"): + report["error"] = fields["error"] + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + if not passed: + raise SystemExit(f"GPU readback failed: {args.output}") + print(f"PASS: {report['cases']} cases, {report['compared_words']} words, adapter {report['adapter']}") + + +if __name__ == "__main__": + main() diff --git a/tools/check_translator_gpu.py b/tools/check_translator_gpu.py index 9780cdc4..0d923541 100644 --- a/tools/check_translator_gpu.py +++ b/tools/check_translator_gpu.py @@ -50,6 +50,7 @@ def assembled(tool, *extra): "half-exact": assembled("check_half_exact_gpu"), "f64": assembled("check_f64_exact_gpu"), "swizzle": Check("check_compute_swizzle", emitter="compute_swizzle"), + "swizzle-loop": Check("check_compute_swizzle_loop", emitter="compute_swizzle_loop"), "readlane": Check("check_readlane_gpu", emitter="readlane_probe", dxc=True), **{f"wave-extrema-{width}": Check("check_wave_extrema", emitter="wave_extrema", dxc=True, extra=("--width", str(width))) diff --git a/tools/shader-compiler/examples/compute_swizzle_loop.rs b/tools/shader-compiler/examples/compute_swizzle_loop.rs new file mode 100644 index 00000000..f74814ef --- /dev/null +++ b/tools/shader-compiler/examples/compute_swizzle_loop.rs @@ -0,0 +1,15 @@ +//! Emit the synthetic loop-around-the-exchange compute DS_SWIZZLE_B32 program. +use tuxbox_xshader::{hlsl, ShaderExtract, Stage}; + +mod fixture { + include!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/support/compute_swizzle_fixture.rs")); +} + +fn main() { + let offset = std::env::args().nth(1).expect("swizzle offset"); + let offset = u32::from_str_radix(offset.trim_start_matches("0x"), 16).expect("hexadecimal offset"); + assert!(offset <= 0xffff); + let translated = hlsl::translate(&fixture::shader_loop_exit_countdown(offset)) + .expect("translate synthetic loop swizzle"); + print!("{}", translated.hlsl); +} diff --git a/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs b/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs index 31825f4e..414b716c 100644 --- a/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs +++ b/tools/shader-compiler/examples/support/compute_swizzle_fixture.rs @@ -5,12 +5,14 @@ use super::{ShaderExtract, Stage}; /// in one 64-lane group. As in LLVM's encoding, the source occupies the ADDR field. pub fn shader(offset: u32, word0_extra: u32) -> ShaderExtract { let words = [0xd8d4_0000 | offset | word0_extra, 0x0000_0001, 0xbf8c_c07f, 0xbf81_0000]; - build(words.to_vec()) + build(words.to_vec(), [0, 64, 1, 1]) } /// The same exchange, wrapped in a backward branch that keeps it in a loop. /// Operand is the SOP1 back-edge: op 5 is a uniform SCC skip (s_cbranch_scc1), /// op 7 a per-lane VCC one (s_cbranch_vccnz). Both jump back to 0x00. +/// In a single 32-lane wave, the group is one host wave, which is what makes a +/// uniform back-edge safe. pub fn shader_loop(offset: u32, word0_extra: u32, op: u32) -> ShaderExtract { let words = [ 0xd8d4_0000 | offset | word0_extra, @@ -19,10 +21,38 @@ pub fn shader_loop(offset: u32, word0_extra: u32, op: u32) -> ShaderExtract { 0xbf8c_c07f, // s_waitcnt 0xbf81_0000, // s_endpgm ]; - build(words.to_vec()) + build(words.to_vec(), [0, 32, 1, 1]) } -fn build(words: Vec) -> ShaderExtract { +/// The same exchange in a 64-thread group (two host waves), wrapped in the same +/// SCC back-edge: unsafe even though every thread in the group shares the SCC. +pub fn shader_loop_64(offset: u32, word0_extra: u32) -> ShaderExtract { + let words = [ + 0xd8d4_0000 | offset | word0_extra, + 0x0000_0001, + 0xbf85_fffd, // s_cbranch_scc1 -> 0x00 (back-edge) + 0xbf8c_c07f, + 0xbf81_0000, + ]; + build(words.to_vec(), [0, 64, 1, 1]) +} + +/// A loop whose head is entered through a per-thread EXEC-empty exit: the guest +/// may leave the loop from one thread while others stay. One host wave, one +/// exchange, one unconditional s_branch back-edge. +pub fn shader_loop_exit_guard(offset: u32) -> ShaderExtract { + let words = [ + 0xbf88_0003, // s_cbranch_execz -> 0x10 (leaves the loop) + 0xd8d4_0000 | offset, + 0x0000_0001, + 0xbf82_fffc, // s_branch -> 0x00 (back to the start) + 0xbf8c_c07f, // s_waitcnt + 0xbf81_0000, // s_endpgm + ]; + build(words.to_vec(), [0, 32, 1, 1]) +} + +fn build(words: Vec, preamble: [u32; 4]) -> ShaderExtract { let isa: Vec = words.iter().flat_map(|word| word.to_le_bytes()).collect(); ShaderExtract { flat_inputs: Vec::new(), flat_outputs: Vec::new(), stage: Stage::Compute, @@ -37,7 +67,7 @@ fn build(words: Vec) -> ShaderExtract { isa, isa_offset_in_fssm: 0, psv_threads: None, - isa_preamble: [0, 64, 1, 1], + isa_preamble: preamble, has_input_sig: false, has_output_sig: false, has_psv0: false, @@ -51,3 +81,25 @@ fn build(words: Vec) -> ShaderExtract { root_sig: None, } } + +/// A countdown loop around the exchange with a per-thread early exit. +/// +/// The loop head is the ds_swizzle (two dwords); after it, the count is +/// decremented and the SCC taken to the back-edge, so the loop runs exactly +/// four iterations. The execz exit branch points past the loop to s_endpgm, so +/// a lane that is not active leaves the loop on its first iteration while the +/// remaining lanes run to completion. 32-lane group (single host wave). +pub fn shader_loop_exit_countdown(offset: u32) -> ShaderExtract { + let words = [ + 0xbe8a_0384, // s_mov_b32 s10, 4 (loop counter) + 0xbf88_0006, // s_cbranch_execz -> 0x0020 (per-thread exit past the loop) + 0xd8d4_0000 | offset, // ds_swizzle_b32 (2 dwords) + 0x0000_0001, + 0x818a_810a, // s_sub_i32 s10, s10, 1 + 0xbf07_800a, // s_cmp_lg_u32 s10, 0 (scc = s10 != 0) + 0xbf85_fffb, // s_cbranch_scc1 -> 0x0008 (back-edge, -5 dwords) + 0xbf8c_c07f, // s_waitcnt + 0xbf81_0000, // s_endpgm + ]; + build(words.to_vec(), [0, 32, 1, 1]) +} diff --git a/tools/shader-compiler/src/hlsl.rs b/tools/shader-compiler/src/hlsl.rs index 5d9a5a73..ecbae35d 100644 --- a/tools/shader-compiler/src/hlsl.rs +++ b/tools/shader-compiler/src/hlsl.rs @@ -366,6 +366,13 @@ struct Emitter<'a> { chosen_samplers: BTreeSet, /// Instruction ranges of a mesh program's loops. loop_ranges: Vec<(usize, usize)>, + /// Back-edge instruction indices proven safe for a shared exchange + /// (single-wave group, uniform back-edge, no other branch in body). + /// Back-edge indices of loops whose single-wave group runs an exchange the + /// same number of times: only these vote in the emitted while loop. + accepted_swizzle_loops: BTreeSet, + /// Nesting stack of whether each open loop is an accepted swizzle loop. + in_accepted_swizzle_loop_stack: Vec, fspx_wave: Option, hair_multisample: bool, hoist_wave_exchanges: bool, diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index 173e12ba..1bbbe800 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -7,6 +7,51 @@ pub(in crate::hlsl) fn compute_group(ex: &ShaderExtract) -> [u32; 3] { [x.max(1), y.max(1), z.max(1)] } +/// Decide whether the loop closing at the backward branch `index` keeps a shared +/// exchange safe. +/// +/// Every invocation in the group must execute the loop the same number of times, +/// or the group would dead-lock at the exchange's barriers (or observe half-written +/// shared memory). That holds for a single 32-lane host wave with a uniform +/// back-edge (unconditional or SCC) and no other branch in the loop body: +/// SCC is then identical for every thread in the wave, and no per-invocation +/// exit exists. +/// +/// Refusals kept for everything else: +/// - VCC branches (per-lane exit) and EXEC branches (per-thread bit in this emitter), +/// - inverted conditions (s_cbranch_execz / s_cbranch_vccz): the console takes the +/// branch only when the whole wave's mask is zero, but a vote over a per-lane +/// condition repeats while any single lane's bit is clear, so it needs a +/// uniform condition rather than a vote it cannot keep in step, +/// - multi-wave groups (independent SCC per host wave), +/// - any other branch inside the body (forward rejoins, continues, nested loops), +/// since any of those can skip the exchange or a barrier on a per-invocation basis. +fn exchange_loop_safe(insns: &[crate::rdna2::Insn], count: u32, branch_index: usize, head: i64) -> bool { + if count > 32 { + return false; + } + let branch = &insns[branch_index]; + // Unconditional (2) and SCC branches (4, 5) are uniform for the wave. Anything + // else - per-lane VCC/EXEC, or the inverted (taken-when-zero) polarities - is refused. + if !matches!(branch.op, 2 | 4 | 5) { + return false; + } + let back = branch.offset as i64; + for (index, ins) in insns.iter().enumerate() { + if index == branch_index { + continue; + } + let from = ins.offset as i64; + if from < head || from > back { + continue; + } + if ins.enc == Enc::Sopp && (Emitter::branch_cond(ins.op).is_some() || ins.op == 1) { + return false; + } + } + true +} + pub fn translate(ex: &ShaderExtract) -> Result { translate_linked(ex, None) } @@ -409,20 +454,20 @@ fn translate_outputs_once_impl(ex: &ShaderExtract, feeds_ps: Option<&InputInterp } // Moving a shared exchange out of a forward guest branch is safe once every // invocation rejoins. A backward branch could execute it different numbers of times. - // A loop back-edge is safe for a shared exchange when every invocation in the - // group runs it the same number of times: the group is a single wave (so SCC and - // EXEC are group-uniform) and the branch is uniform per wave (never a per-lane - // VCC). Anything else keeps the conservative rejection. - let single_wave = count <= 64; - for branch in em.insns.iter().filter(|i| i.enc == Enc::Sopp && Emitter::branch_cond(i.op).is_some() && i.aux.imm < 0) { - if single_wave && !matches!(branch.op, 6 | 7) { + // Only the loops proven safe here keep a whole-wave vote in the emitter; every + // other loop emits the per-thread condition it always has. + let mut accepted_swizzle_loops = std::collections::BTreeSet::new(); + for (index, branch) in em.insns.iter().enumerate().filter(|(_, i)| i.enc == Enc::Sopp && Emitter::branch_cond(i.op).is_some() && i.aux.imm < 0) { + let head = branch.offset as i64 + 4 + 4 * branch.aux.imm; + if exchange_loop_safe(&em.insns, count, index, head) { + accepted_swizzle_loops.insert(index); continue; } - let head = branch.offset as i64 + 4 + 4 * branch.aux.imm; if em.insns.iter().any(|i| exchanges(i) && (head..=branch.offset as i64).contains(&(i.offset as i64))) { return Err("compute swizzle inside a loop".into()); } } + em.accepted_swizzle_loops = accepted_swizzle_loops; } if (em.compute_swizzle || em.indexed_lane) && wave_cull::lds_words(&em).is_none() && em.insns.iter().any(|i| i.enc == Enc::Ds && i.mnemonic != "ds_swizzle_b32") { diff --git a/tools/shader-compiler/src/hlsl/emitter/bindings.rs b/tools/shader-compiler/src/hlsl/emitter/bindings.rs index 41ccc680..4f2f1d0a 100644 --- a/tools/shader-compiler/src/hlsl/emitter/bindings.rs +++ b/tools/shader-compiler/src/hlsl/emitter/bindings.rs @@ -104,6 +104,10 @@ impl<'a> Emitter<'a> { self.loop_ranges.iter().any(|&(head, back)| (head..=back).contains(&idx)) } + pub(in crate::hlsl) fn in_accepted_swizzle_loop(&self) -> bool { + self.in_accepted_swizzle_loop_stack.last().copied().unwrap_or(false) + } + pub(in crate::hlsl) fn space_suffix(&self, kind: u32, register: u32) -> String { match self.binding_spaces.get(&(kind, register)) { Some(space) if *space != 0 => format!(", space{space}"), diff --git a/tools/shader-compiler/src/hlsl/emitter/control_flow.rs b/tools/shader-compiler/src/hlsl/emitter/control_flow.rs index 837efcae..f83774c1 100644 --- a/tools/shader-compiler/src/hlsl/emitter/control_flow.rs +++ b/tools/shader-compiler/src/hlsl/emitter/control_flow.rs @@ -150,6 +150,7 @@ impl<'a> Emitter<'a> { // The back edge can store the index after a use. Bind again inside the loop. self.drop_heap_handles(); self.loop_depth += 1; + self.in_accepted_swizzle_loop_stack.push(self.accepted_swizzle_loops.contains(&b)); self.line(&format!("tb_c{b} = false;")); } let mut active: Vec = @@ -333,6 +334,29 @@ impl<'a> Emitter<'a> { cur.clear(); } if back.contains_key(&i) { + let head = back[&i]; + // A loop whose body holds any group rendezvous must keep every lane + // together until the last one is done: a per-thread exit that leaves + // the loop early makes the lane stop hitting the barriers the other + // lanes wait on. Only the loops the pipeline proved safe for a shared + // exchange get the whole-wave vote: other loops keep their per-thread + // condition, exactly as they emitted before this feature existed. + let vote = self.accepted_swizzle_loops.contains(&i) && self.insns[head..=i].iter().enumerate().any(|(j, ins2)| { + let idx = head + j; + exchanges(ins2) + || ins2.mnemonic == "s_barrier" + || ins2.mnemonic == "tb_first_exec_lane" + || ins2.mnemonic == "tb_indexed_readlane" + || (self.single_wave32 && ins2.enc == Enc::Ds) + || lds_waits.contains(&idx) + || restored_waits.contains(&idx) + }); + if vote { + // Evaluate the back-edge condition unconditionally: the while + // condition below votes over it, which must not be guarded. + self.end_guard(&mut open); + cur.clear(); + } // Evaluate the back-edge condition inside the guard (a skipped branch is not taken). let cond = wave_cull::branch_condition(self, ins, Self::branch_cond(ins.op).unwrap_or("false")); self.line(&format!("tb_c{i} = ({cond});")); @@ -343,12 +367,10 @@ impl<'a> Emitter<'a> { self.end_guard(&mut open); cur.clear(); // Clear the flags of labels inside this loop body for the next iteration. - let head = back[&i]; for t in labels.iter().filter(|&&t| t > head && t <= i) { self.line(&format!("j{t} = false;")); } let exits: Vec = labels.iter().filter(|&&t| t > i).map(|t| format!("j{t}")).collect(); - let exit = if exits.is_empty() { String::new() } else { format!(" && !({})", exits.join(self.flag_or())) }; let guard = if self.wave_cull || self.light_grid || probe_trace || self.wave_bounded_latches.contains(&i) || self.packed.as_ref().is_some_and(|p| p.copy_backedges.contains(&i) || p.bounded_backedges.contains(&i)) @@ -361,10 +383,17 @@ impl<'a> Emitter<'a> { // The guest iterates cb0[12] views. Retired lanes must // participate in the barriers for each remaining view. self.line("} while (++cull_view < cb0[3].x);"); + } else if vote { + // Keep the whole wave in the loop while any lane still needs to + // run; finished lanes stay in the loop, masked, and still hit the barriers. + let exit = if exits.is_empty() { String::new() } else { format!(" && !({})", exits.join(self.flag_or())) }; + self.line(&format!("}} while (WaveActiveAnyTrue(tb_c{i}{exit}){guard});")); } else { + let exit = if exits.is_empty() { String::new() } else { format!(" && !({})", exits.join(self.flag_or())) }; self.line(&format!("}} while (tb_c{i}{exit}{guard});")); } self.loop_depth = self.loop_depth.saturating_sub(1); + self.in_accepted_swizzle_loop_stack.pop(); self.drop_heap_handles(); } } diff --git a/tools/shader-compiler/src/hlsl/emitter/exchange.rs b/tools/shader-compiler/src/hlsl/emitter/exchange.rs index 719d0e3e..49383139 100644 --- a/tools/shader-compiler/src/hlsl/emitter/exchange.rs +++ b/tools/shader-compiler/src/hlsl/emitter/exchange.rs @@ -50,8 +50,17 @@ impl<'a> Emitter<'a> { } // READLANE ignores EXEC. Publish each lane's actual VGPR even when // that lane skipped the guest branch, then guard only the load on - // active skip flags and mask the selector to 0..width-1. - self.line(&format!("tb_swizzle[tb_lane] = {};", r(&ins.src[0])?)); + // active skip flags and mask the selector to 0..width-1. Inside an + // accepted loop the lane was kept in the loop but already finished: + // mask the publish too, so the remaining lanes read a zero. + let value = r(&ins.src[0])?; + let value = if self.in_accepted_swizzle_loop() && !active.is_empty() { + let guard: Vec<_> = active.iter().map(|label| format!("!j{label}")).collect(); + format!("({}) ? {value} : 0u", guard.join(" && ")) + } else { + value + }; + self.line(&format!("tb_swizzle[tb_lane] = {value};")); self.line("GroupMemoryBarrierWithGroupSync();"); let load = format!("tb_swizzle_read((tb_lane & ~{mask}u) | ({} & {mask}u))", r(&ins.src[1])?); if active.is_empty() { diff --git a/tools/shader-compiler/src/hlsl/emitter/setup.rs b/tools/shader-compiler/src/hlsl/emitter/setup.rs index 736cc0ba..a69673de 100644 --- a/tools/shader-compiler/src/hlsl/emitter/setup.rs +++ b/tools/shader-compiler/src/hlsl/emitter/setup.rs @@ -22,6 +22,8 @@ impl<'a> Emitter<'a> { lds_tile: lds_tile::LdsTile::recognize(ex, &insns), packed: None, loop_depth: 0, + accepted_swizzle_loops: BTreeSet::new(), + in_accepted_swizzle_loop_stack: Vec::new(), ex, insns, res: HashMap::new(), diff --git a/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs b/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs index 1d39518d..c15dbf9c 100644 --- a/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs +++ b/tools/shader-compiler/src/tests/hlsl/compute_swizzle.rs @@ -44,14 +44,15 @@ fn other_high_offset_bits_and_gds_stay_refused() { #[test] fn uniform_scc_loop_around_the_exchange_translates() { - // A 64-lane single wave: an SCC back-edge (uniform, never per-lane) means - // every invocation runs the loop and the shared exchange the same number of - // times, so the loop is accepted. + // A 32-thread, single-wave group: an SCC back-edge (uniform, never per-lane) + // means every invocation runs the loop and the shared exchange the same + // number of times, so the loop is accepted. let ex = fixture::shader_loop(0x041f, 0, 5); assert_eq!(disassemble(&ex.isa)[0].mnemonic, "ds_swizzle_b32"); let hlsl = translate(&ex).map(|t| t.hlsl) .expect("uniform SCC loop over a compute swizzle translates"); assert!(hlsl.contains("tb_swizzle"), "{hlsl}"); + assert!(hlsl.contains("GroupMemoryBarrierWithGroupSync()"), "{hlsl}"); } #[test] @@ -72,6 +73,52 @@ fn divergent_vcc_loop_around_the_exchange_is_refused() { assert!(error.contains("compute swizzle inside a loop"), "{error}"); } +#[test] +fn per_thread_execz_back_edge_is_refused() { + // This emitter keeps EXEC as a per-thread bit, so an execz back-edge is + // per-invocation: threads can leave the loop on different iterations. + let error = translate(&fixture::shader_loop(0x041f, 0, 8)) + .map(|t| t.hlsl) + .unwrap_err(); + assert!(error.contains("compute swizzle inside a loop"), "{error}"); +} + +#[test] +fn multi_wave_group_is_refused() { + // A 64-thread group runs two 32-lane waves with independent SCC registers, + // so a uniform-SCC back-edge is no longer group-uniform. + let error = translate(&fixture::shader_loop_64(0x041f, 0)) + .map(|t| t.hlsl) + .unwrap_err(); + assert!(error.contains("compute swizzle inside a loop"), "{error}"); +} + +#[test] +fn forward_exit_inside_the_loop_is_refused() { + // A per-thread forward exit out of the loop body leaves the barrier count + // mismatched: threads that leave stop reaching the exchange while others + // keep iterating. + let error = translate(&fixture::shader_loop_exit_guard(0x041f)) + .map(|t| t.hlsl) + .unwrap_err(); + assert!(error.contains("compute swizzle inside a loop"), "{error}"); +} + +#[test] +fn countdown_loop_with_early_exit_translates() { + // A countdown loop around the exchange with a per-thread early exit before + // the loop: the emitted loop keeps every lane together (a whole-wave vote), + // masks the publish on the exit flag and keeps the finished lanes' exchange + // contributions at zero. This is the GPU control driver. + let ex = fixture::shader_loop_exit_countdown(0x041f); + let hlsl = translate(&ex).map(|t| t.hlsl) + .expect("countdown loop with per-thread exit translates"); + assert!(hlsl.contains("tb_swizzle"), "{hlsl}"); + assert!(hlsl.contains("WaveActiveAnyTrue(tb_c"), "{hlsl}"); + assert!(hlsl.contains("!j7"), "{hlsl}"); // masked publish + assert!(hlsl.contains("GroupMemoryBarrierWithGroupSync()"), "{hlsl}"); +} + #[test] fn paired_wave64_lowers_quad_and_bitmask_swizzles_without_shared_memory() { use crate::hlsl::translate_paired_wave64;