Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions tools/check_compute_swizzle_loop.py
Original file line number Diff line number Diff line change
@@ -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 <name> --work <dir> --output <report>
"""
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<uint> 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()
1 change: 1 addition & 0 deletions tools/check_translator_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
15 changes: 15 additions & 0 deletions tools/shader-compiler/examples/compute_swizzle_loop.rs
Original file line number Diff line number Diff line change
@@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,54 @@ 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(), [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,
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(), [0, 32, 1, 1])
}

/// 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<u32>, preamble: [u32; 4]) -> ShaderExtract {
let isa: Vec<u8> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
ShaderExtract { flat_inputs: Vec::new(), flat_outputs: Vec::new(),
stage: Stage::Compute,
Expand All @@ -19,7 +67,7 @@ pub fn shader(offset: u32, word0_extra: u32) -> 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,
Expand All @@ -33,3 +81,25 @@ pub fn shader(offset: u32, word0_extra: u32) -> 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])
}
7 changes: 7 additions & 0 deletions tools/shader-compiler/src/hlsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,13 @@ struct Emitter<'a> {
chosen_samplers: BTreeSet<usize>,
/// 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<usize>,
/// Nesting stack of whether each open loop is an accepted swizzle loop.
in_accepted_swizzle_loop_stack: Vec<bool>,
fspx_wave: Option<u32>,
hair_multisample: bool,
hoist_wave_exchanges: bool,
Expand Down
55 changes: 54 additions & 1 deletion tools/shader-compiler/src/hlsl/driver/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Translated, String> {
translate_linked(ex, None)
}
Expand Down Expand Up @@ -409,12 +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.
for branch in em.insns.iter().filter(|i| i.enc == Enc::Sopp && Emitter::branch_cond(i.op).is_some() && i.aux.imm < 0) {
// 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;
}
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") {
Expand Down
4 changes: 4 additions & 0 deletions tools/shader-compiler/src/hlsl/emitter/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"),
Expand Down
Loading
Loading