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
1 change: 1 addition & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ How the generated SPIR-V expects the runtime to work:
| Piece | Contract |
|---|---|
| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. |
| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`); **not GPU-verified**. |
| Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. |
| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. |
| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. |
Expand Down
171 changes: 171 additions & 0 deletions tests/semantic/test_sload_vcc_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""Semantic tests for SMEM s_load_dword* using `vcc` (s[106:107]) as the 64-bit base pointer.

RDNA2 SMEM `s_load_dword*` takes a 2-SGPR-aligned 64-bit base address in `SBASE`, which hardware encodes as
`sbase * 2`. Register pair `s[106:107]` is `vcc` (`{vcc_lo, vcc_hi}`), emitted by the compiler when VCC is dead
(79 pipeline-library compute shaders: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, and 1
`s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc`).

Checks SPIR-V generation, 64-bit address construction from `%vcc`/`%vcc_hi`, destination aliasing when `vcc` is
also written, rejection of `s_buffer_load*` with 2-dword `vcc`, and `spirv-as` + `spirv-val` when on PATH.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")

sys.dont_write_bytecode = True
if TOOLS_DIR not in sys.path:
sys.path.insert(0, TOOLS_DIR)
if HERE not in sys.path:
sys.path.insert(0, HERE)

import rdna2spirv # noqa: E402
from shader_ir import parse_line # noqa: E402
import support # noqa: E402


def _assemble_and_validate(spvasm: str) -> None:
spirv_as = shutil.which("spirv-as")
spirv_val = shutil.which("spirv-val")
if not (spirv_as and spirv_val):
return
with tempfile.TemporaryDirectory() as tmp:
asm_path = os.path.join(tmp, "s.spvasm")
spv_path = os.path.join(tmp, "s.spv")
with open(asm_path, "w", encoding="utf-8", newline="\n") as f:
f.write(spvasm)
p1 = subprocess.run([spirv_as, "--target-env", "vulkan1.3", asm_path, "-o", spv_path],
capture_output=True, text=True)
if p1.returncode != 0:
raise AssertionError(f"spirv-as failed:\n{p1.stderr}")
p2 = subprocess.run([spirv_val, "--target-env", "vulkan1.3", spv_path],
capture_output=True, text=True)
if p2.returncode != 0:
raise AssertionError(f"spirv-val failed:\n{p2.stderr}")


def _translate_cs(lines: list[str]) -> str:
with tempfile.TemporaryDirectory() as tmp:
disasm_dir = os.path.join(tmp, "disasm")
fspx_dir = os.path.join(tmp, "fspx")
os.makedirs(disasm_dir)
os.makedirs(fspx_dir)
with open(os.path.join(fspx_dir, "cs_sload_vcc_base.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump({
"threads": [64, 1, 1],
"wave32": True,
"user_sgprs": 8,
"tgid_enable": [1, 0, 0],
"tidig_comp_cnt": 0,
"lds_bytes": 0,
"rsrc2": 0x90,
}, f)
s_path = os.path.join(disasm_dir, "cs_sload_vcc_base.s")
with open(s_path, "w", encoding="utf-8", newline="\n") as f:
f.write("; synthetic compute shader test\n")
for line in lines:
f.write(line + "\n")
res = rdna2spirv.translate(s_path)
return res[0] if isinstance(res, tuple) else res


class SloadVccBaseTest(unittest.TestCase):
def test_scalar_load_reads_vcc_lo_and_vcc_hi_for_64bit_base(self):
for op, dst in (
("s_load_dword", "s10"),
("s_load_dwordx2", "s[10:11]"),
("s_load_dwordx4", "s[12:15]"),
("s_load_dwordx8", "s[16:23]"),
("s_load_dwordx16", "s[24:39]"),
("s_load_dwordx4", "[s104,s105,vcc_lo,vcc_hi]"),
):
with self.subTest(op=op, dst=dst):
g = rdna2spirv.Gen("cs")
ins = parse_line(f"{op} {dst}, vcc, 0x20")
g.scalar_load(ins["op"], ins["args"], ins["mods"])
body = "\n".join(g.body)
self.assertIn("OpLoad %uint %vcc", body)
self.assertIn("OpLoad %uint %vcc_hi", body)
self.assertTrue(g.uses_psb)

def test_s_buffer_load_with_vcc_base_is_still_rejected(self):
# `vcc` is a 2-dword pair, not a 4-dword V# buffer resource descriptor.
g = rdna2spirv.Gen("cs")
ins = parse_line("s_buffer_load_dword s10, vcc, 0x0")
with self.assertRaises(rdna2spirv.Unsupported) as ctx:
g.scalar_load(ins["op"], ins["args"], ins["mods"])
self.assertIn("s_buffer_load without V#", str(ctx.exception))

def test_full_compute_shader_with_vcc_base_validates(self):
spvasm = _translate_cs([
"\ts_mov_b32 vcc_lo, s0",
"\ts_mov_b32 vcc_hi, s1",
"\ts_load_dword s10, vcc, 0x0",
"\ts_load_dwordx4 s[12:15], vcc, 0x10",
"\ts_load_dwordx8 s[16:23], vcc, s2 offset:0x40",
"\ts_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc, 0x80",
"\ts_waitcnt lgkmcnt(0)",
"\tv_mov_b32_e32 v1, s10",
"\tv_add_nc_u32_e32 v1, s12, v1",
"\tv_add_nc_u32_e32 v1, s16, v1",
"\tv_add_nc_u32_e32 v1, vcc_lo, v1",
"\tv_add_nc_u32_e32 v1, vcc_hi, v1",
"\tbuffer_store_dword v1, v0, s[4:7], 0 offen",
"\ts_endpgm",
])
self.assertIn("OpLoad %uint %vcc", spvasm)
self.assertIn("OpLoad %uint %vcc_hi", spvasm)
_assemble_and_validate(spvasm)

def test_vcc_base_pointer_half_order_executes(self):
# Pin vcc_lo as bits [31:0] and vcc_hi as bits [63:32]; swapping or dropping a half reads the wrong address.
spv = support.translate_lines("ps_sload_vcc_order", [
"s_mov_b32 vcc_hi, 0x3",
"s_mov_b32 vcc_lo, 0x2000",
"s_load_dword s10, vcc, 0x4",
"s_waitcnt lgkmcnt(0)",
"v_mov_b32 v4, s10",
"exp mrt0 v4, v4, v4, v4 done vm",
"s_endpgm",
])
_assemble_and_validate(spv)
got = support.mrt0_words(spv, memory={
0x00000003_00002004: 0xCAFEBABE,
0x00002000_00000007: 0xDEADBEEF,
0x00000000_00002004: 0xBAD00001,
})
self.assertEqual(got, [0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE])

def test_vcc_base_aliasing_destination_executes(self):
# Destination [s104,s105,vcc_lo,vcc_hi] aliases the `vcc` base pair; both base halves must be read first.
spv = support.translate_lines("ps_sload_vcc_alias", [
"s_mov_b32 vcc_hi, 0x2",
"s_mov_b32 vcc_lo, 0x4000",
"s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], vcc, 0x10",
"s_waitcnt lgkmcnt(0)",
"v_mov_b32 v4, s104",
"v_mov_b32 v5, s105",
"v_mov_b32 v6, vcc_lo",
"v_mov_b32 v7, vcc_hi",
"exp mrt0 v4, v5, v6, v7 done vm",
"s_endpgm",
])
_assemble_and_validate(spv)
got = support.mrt0_words(spv, memory={
0x00000002_00004010: 0x11223344,
0x00000002_00004014: 0x55667788,
0x00000002_00004018: 0x99AABBCC,
0x00000002_0000401C: 0xDDEEFF00,
})
self.assertEqual(got, [0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00])


if __name__ == "__main__":
unittest.main()
4 changes: 3 additions & 1 deletion tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -12436,7 +12436,9 @@ def scalar_load(self, op, a, mods):
(n == 2 and d["k"] == "special" and d["t"] == "vcc")
slist_dst = d["k"] == "slist" and len(d["r"]) == n
base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr"
else list(base["r"]) if base["k"] == "slist" else None)
else list(base["r"]) if base["k"] == "slist"
else ["vcc_lo", "vcc_hi"] if (base["k"] == "special" and base["t"] == "vcc")
else None)
if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None:
raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}")

Expand Down
Loading