From 4b9a89124a470d266f0ed314db17a79fc45957be Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:08:08 -0600 Subject: [PATCH 01/18] fspx_unpack: code_range takes the 24-byte prologue of some pipeline-library programs 50 of the 2,684 library programs in shaders.rpf (1.0.2.1) start with two VOP3 opcode-0x180 words (words 0 and 3) instead of three, and their code starts at word 6. code_range only knew the 36-byte form, so it disassembled them from word 0 and they never decoded: 1 of the 50 translated. With the 24-byte form all 50 disassemble with 0 invalid words and 49 translate and pass spirv-val. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- docs/fspx.md | 6 ++++++ tests/test_fspx_unpack.py | 10 ++++++++++ tools/fspx_unpack.py | 20 ++++++++++++++++---- tools/shader_library.py | 2 +- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/docs/fspx.md b/docs/fspx.md index a603545e93..a7efdbb520 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -136,6 +136,12 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0 and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2. - `tools/fspx_unpack.py` disassembles from the end of the prologue. + - **A 24-byte variant**: some programs of the pipeline library in `shaders.rpf` (`tools/shader_library.py`) carry + only the first two of those words, at words 0 and 3, and their code starts at word 6 (`s_inst_prefetch` in all of + them). Counted on the 1.0.2.1 library: 50 of 2,684 programs; read from word 0 they never decode (the prologue + words are invalid encodings and the rest desyncs), and only 1 of the 50 translated. With `code_range` taking + the 24-byte form, all 50 disassemble with 0 invalid words and 49 translate and pass `spirv-val` (the other one + stops at `s_sethalt`). A program whose words 0, 3 and 6 are all prologue words still takes the 36-byte form. - **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 946da380cf..8b34502499 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -144,6 +144,16 @@ def test_code_range(self): self.assertEqual(fspx_unpack.code_range(program(with_prologue=False)), (0, 12 + 4)) self.assertEqual(fspx_unpack.code_range(program(endpgm=False))[1], None) + def test_short_prologue(self): + # Two VOP3 opcode-0x180 words (0 and 3), then code: the 24-byte prologue of some pipeline-library programs. + code = prologue()[:24] + V_MOV * 3 + ENDPGM + self.assertEqual(fspx_unpack.code_range(code), (24, 24 + 12 + 4)) + # Only word 0 is not a prologue. + code = prologue()[:12] + V_MOV * 6 + ENDPGM + self.assertEqual(fspx_unpack.code_range(code)[0], 0) + # The long one still wins when word 6 is a prologue word too. + self.assertEqual(fspx_unpack.code_range(program())[0], 36) + def test_unaligned_endpgm_bytes_are_not_the_end(self): code = prologue() + b"\0\0" + ENDPGM + b"\0\0" + V_MOV + ENDPGM start, end = fspx_unpack.code_range(code) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index 5cb94813e7..5ce01f9a60 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -24,7 +24,7 @@ DIR/fspx/.json the decoded kind-0 entry, the directory and the code range DIR/fspx/.code the kind-6 program DIR/fspx/.state the kind-0 entry as it is (its SHA-256 is the index's fspx_state_sha256) - DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue + DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue (36 or 24 bytes) """ import argparse import json @@ -46,6 +46,11 @@ # kind-7 hash; llvm-mc rejects them. Measured on all 29 shaders of the 1.0.2.1 DLL (docs/fspx.md). PROLOGUE_WORDS = (0, 3, 6) PROLOGUE_SIZE = 36 +# Some programs of the pipeline library in shaders.rpf carry only two of those words (0 and 3): a 24-byte prologue, with +# the code starting at word 6 (50 of the 2,684 library programs of 1.0.2.1, docs/fspx.md). Read from word 0 they never +# decode. +SHORT_PROLOGUE_WORDS = (0, 3) +SHORT_PROLOGUE_SIZE = 24 STAGE_COMPUTE = 5 # PSVRuntimeInfo1 ShaderStage (DirectX): 5 = compute @@ -141,10 +146,17 @@ def decode_kind0(b: bytes) -> dict: def code_range(code: bytes): - """(start, end) of the instructions in a kind-6 program: after the 36-byte prologue when it is there, through + """(start, end) of the instructions in a kind-6 program: after the 36- or 24-byte prologue when it is there, through the first s_endpgm. end is None when the program has no s_endpgm.""" words = struct.unpack_from(f"<{len(code) // 4}I", code) - start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0 + def vop3_180(ks): + return all(words[k] >> 16 == 0xD580 for k in ks) + if len(words) > 8 and vop3_180(PROLOGUE_WORDS): + start = PROLOGUE_SIZE + elif len(words) > 6 and vop3_180(SHORT_PROLOGUE_WORDS): + start = SHORT_PROLOGUE_SIZE + else: + start = 0 pos = code.find(ENDPGM, start) while pos >= 0 and pos % 4: pos = code.find(ENDPGM, pos + 1) @@ -169,7 +181,7 @@ def unpack_payload(payload: bytes): meta = { "version": struct.unpack_from(" 0}, **decode_kind0(blob[0]), } return (meta, blob), 0 diff --git a/tools/shader_library.py b/tools/shader_library.py index 233e6ba565..d6e768a93d 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -354,7 +354,7 @@ def extraction_paths(): code = program(b, lib, i) start, end = code_range(code) meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), - "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} + "code": {"start": start, "end": end, "prologue": start > 0}} state = blob(b, lib, cs_state[i]) if i in cs_state else None if state is not None: meta.update(fspx_unpack.decode_kind0(state)) From ebcb0acad599f0199b827a7ebc8008585aaa5dd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 08:42:05 -0800 Subject: [PATCH 02/18] tools: decode the pipeline-library compute programs llvm-mc refuses llvm-mc 21 cannot decode SMEM loads whose SOFFSET is null (0x7D), so whole pipeline-library compute programs of 1.0.2.1 came out with invalid words and failed to translate. For compute programs, shader_disasm now falls back to rdna2_decode when that decodes more of the program, and rdna2_decode reads VOPC with DPP16/DPP8 as the 8-byte form it is. rdna2spirv: - SMEM with vcc as its base reads the vcc_lo/vcc_hi pair. - s_flbit_i32_b64 of a lane mask reads the wave's 64-bit mask (18 library programs), as s_ff1_i32_b64 already does. - s_bitreplicate_b64_b32 of a lane mask into plain scalar data replicates the wave's mask word (6 library programs); into exec/vcc it stays Unsupported. test_salu_flbit_64: the lane-mask case now translates (the subgroup op is outside the single-invocation interpreter), so the test checks that. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_salu_flbit_64.py | 6 ++++-- tools/fspx_unpack.py | 2 +- tools/rdna2_decode.py | 26 ++++++++++++++++++++++++++ tools/rdna2spirv.py | 21 ++++++++++++++++----- tools/shader_disasm.py | 14 +++++++++++++- tools/shader_library.py | 2 +- 6 files changed, 61 insertions(+), 10 deletions(-) diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py index faf480eb32..cf11818075 100644 --- a/tests/semantic/test_salu_flbit_64.py +++ b/tests/semantic/test_salu_flbit_64.py @@ -123,8 +123,10 @@ def test_inline_source(self): self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63) self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32) - def test_lane_mask_source_is_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): + def test_lane_mask_source_translates(self): + # exec is a lane mask: the count comes from the subgroup's 64-bit mask (Gen.wave_mask), which the + # single-invocation interpreter cannot run, so this checks that it translates instead of being refused. + with self.assertRaises(si.UnsupportedConstruct): run_lines(["s_flbit_i32_b64 s0, exec"]) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index 5cb94813e7..cc1d5de819 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -254,7 +254,7 @@ def main(argv=None) -> int: listing = None if disasm and meta["code"]["end"]: start, end = meta["code"]["start"], meta["code"]["end"] - asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) + asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu, compute=True) if not asm.strip(): reason = (err.strip().splitlines() or ["no output"])[0] print(f"{name}: {reason}", file=sys.stderr) diff --git a/tools/rdna2_decode.py b/tools/rdna2_decode.py index d503784657..b95d7ad22c 100644 --- a/tools/rdna2_decode.py +++ b/tools/rdna2_decode.py @@ -562,6 +562,32 @@ def finish(op: str, args: list, mods: list, nbytes: int) -> tuple[dict, int]: dst_op = _sreg(sdst, 1 if wave32 else 2) if sd else _vcc_operand(wave32) args = [dst_op, s0, s1] if not name.startswith("v_cmpx_") else [s0, s1] return finish(name + "_sdwa", args, mods, 8) + if is_dpp16 or is_dpp8: + # VOPC with DPP (src0 = 0xFA / 0xE9 / 0xEA): 8 bytes, as for VOP1/VOP2. Read as 4 before, the DPP word + # became an invalid instruction (lib_cs_01473 of the 1.0.2.1 pipeline library: v_cmp_gt_f32 quad_perm). + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 8) & 0x1FF + s0["neg"], s0["abs"] = bool((w1 >> 20) & 1), bool((w1 >> 21) & 1) + s1["neg"], s1["abs"] = bool((w1 >> 22) & 1), bool((w1 >> 23) & 1) + mods.append(_format_dpp16_ctrl(ctrl)) + mods.append(f"row_mask:0x{(w1 >> 28) & 0xF:x}") + mods.append(f"bank_mask:0x{(w1 >> 24) & 0xF:x}") + if (w1 >> 19) & 1: + mods.append("bound_ctrl:1") + if (w1 >> 18) & 1: + mods.append("fi:1") + else: + lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)] + mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]") + if src0 == 234: + mods.append("fi:1") + args = [_vcc_operand(wave32), s0, s1] if not name.startswith("v_cmpx_") else [s0, s1] + return finish(name + "_dpp", args, mods, 8) lit = None nbytes = 4 if src0 == 255: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 8d91dac70e..1cf8a7a90f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7584,8 +7584,15 @@ def _insn(self, ins): d, x = a[0], a[1] wide_src = op == "s_quadmask_b64" wide_dst = op != "s_quadmask_b32" + mask_words = None if self.is_mask_op(x): - raise Unsupported(op + " on a lane mask") + # s_bitreplicate_b64_b32 of a 32-bit lane mask into plain scalar data (6 pipeline-library programs of + # 1.0.2.1): the wave's mask word as data, then replicated as any scalar (wave_mask, as s_ff1 reads it). + if op != "s_bitreplicate_b64_b32" or (d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc"))): + raise Unsupported(op + " on a lane mask") + lo, hi = self.wave_mask(x) + half = self.mask_half(x) if self.wave64 else None + mask_words = [hi if half == "hi" else lo] if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): if op != "s_bitreplicate_b64_b32" or d["t"] != "exec": raise Unsupported(op + " on a lane mask") @@ -7598,7 +7605,9 @@ def _insn(self, ins): self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") self.set_exec(bit) return - if wide_src: + if mask_words is not None: + words = mask_words + elif wide_src: lo, hi = self.src64_data(x, op) words = [lo, hi] else: @@ -8348,11 +8357,13 @@ def sel(c, t, f): # Leading-bit count of a 64-bit value, from bit 63 down: b64 counts the zeros before the first 1; i64 # counts the bits before the first one that differs from the sign bit (b64 of ~S0 when S0 < 0). -1 when # there is none (0, and for i64 also -1). SCC is not written. The pair is 64-bit data (as for - # s_lshl_b64); a lane-mask source stays Unsupported (#210). + # s_lshl_b64); a lane-mask source reads the wave mask (Gen.wave_mask). x = a[1] if self.holds_lane_mask(x): - raise Unsupported(op + " of a lane mask") - if x["k"] == "sgpr" and x.get("n") == 2: + # The wave's mask as its 64 bits, as s_ff1_i32_b64 of a lane mask reads it (18 pipeline-library + # programs of 1.0.2.1: the highest active lane, 63 - lane). + lo, hi = self.wave_mask(x) + elif x["k"] == "sgpr" and x.get("n") == 2: lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) elif x["k"] == "imm": v = x["v"] & 0xFFFFFFFFFFFFFFFF diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index a119e74aaf..4436c117da 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -87,7 +87,19 @@ def probe(mcpu: str) -> None: f"{install_hint()}") -def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): +def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True, compute: bool = False): + """`compute`: a pipeline-library or FSPX compute program. llvm-mc 21 does not decode SMEM loads whose SOFFSET is + SGPR_NULL (0x7D, e.g. s_load_dwordx8 ... 0xd60 with soffset null): it reports the first dword invalid, then reads + the second (0xFA......) as an 8-byte EXP and the rest of the listing goes out of step (gfx1013 and gfx1030 alike). + In 749 of the 2,684 library programs of 1.0.2.1 that refused 945 programs ('fall-through into undecodable + words'). tools/rdna2_decode.py decodes them; such a program takes its listing when it has fewer invalid words.""" + if compute and backend != "python": + asm, bad, err = disasm(code, mcpu, backend=backend, wave32=wave32) + if bad: + py_asm, py_bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) + if py_bad < bad: + return py_asm, py_bad, "" + return asm, bad, err if backend == "python": asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) return asm, bad, "" diff --git a/tools/shader_library.py b/tools/shader_library.py index 233e6ba565..a491589070 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -392,7 +392,7 @@ def extraction_paths(): def one(job): entry, name, code, start, end = job - asm, invalid, err = disasm.disasm(code, a.mcpu) + asm, invalid, err = disasm.disasm(code, a.mcpu, compute=True) entry["invalid_words"] = invalid with open(os.path.join(disasm_dir, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") From bf0c4d99ce4fca375a89538d200efdd7cb70f84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 09:02:59 -0800 Subject: [PATCH 03/18] tests: fspx_unpack takes the decoder listing when llvm-mc reports invalid words Co-Authored-By: Claude Opus 5.5 --- tests/test_fspx_unpack.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 946da380cf..e16111af89 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -214,7 +214,9 @@ def test_empty_disassembly_writes_no_listing(self): self.assertEqual(os.listdir(os.path.join(out, "disasm")), []) self.assertEqual(os.listdir(os.path.join(out, "fspx")), []) - def test_disassembly_with_invalid_words_keeps_listing(self): + def test_disassembly_with_invalid_words_takes_the_decoder_listing(self): + # llvm-mc reports an invalid word in a program tools/rdna2_decode.py decodes whole: the compute fallback of + # shader_disasm.disasm takes the decoder's listing (fewer invalid words), without llvm-mc's messages. result, out = self.disassemble("import sys\n" "print('\\ts_endpgm')\n" "sys.stderr.write('warning: invalid instruction encoding\\n')\n") @@ -222,9 +224,10 @@ def test_disassembly_with_invalid_words_keeps_listing(self): self.assertEqual(result.stderr, "") with open(os.path.join(out, "disasm", "one.s"), encoding="utf-8") as f: listing = f.read() - self.assertIn("1 invalid words", listing) - self.assertIn("\ts_endpgm", listing) - self.assertIn("warning: invalid instruction encoding", listing) + self.assertIn("0 invalid words", listing) + self.assertIn("v_mov_b32", listing) + self.assertIn("s_endpgm", listing) + self.assertNotIn("warning: invalid instruction encoding", listing) def test_clean_disassembly_keeps_listing(self): result, out = self.disassemble("print('\\ts_endpgm')\n") From bec14f22599924c9d6d98b76714e00b6e0cc798a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCzgar=20Koray=20Gen=C3=A7?= Date: Tue, 24 Nov 2026 09:17:13 -0800 Subject: [PATCH 04/18] tools: the last pipeline-library compute programs of 1.0.2.1 The retail boot reached 50 pipeline-library compute programs that had no translation. Dumped from the running game, they all translate and pass spirv-val after these changes: - fspx_unpack.code_range: some programs carry a 24-byte hash prologue (two VOP3 words, then s_inst_prefetch) instead of 36 bytes; two or three hash words now count (shader_library uses the same range). - fspx_unpack --last-endpgm: early exits branch past the first s_endpgm, and data after the code can hold s_endpgm words, so a program ends at the first s_endpgm whose listing keeps every branch inside the code. - rdna2spirv: v_cmp_*_dpp into vcc (12 compares in reductions), taken when every lane writes (full row/bank masks with bound_ctrl:1, or DPP8). - rdna2spirv: s_bitreplicate_b64_b32 of a constant into vcc (6 programs), as the exec form does. Co-Authored-By: Claude Opus 5.5 --- .../test_salu_quadmask_bitreplicate.py | 9 +++ tests/test_fspx_unpack.py | 21 ++++++ tools/fspx_unpack.py | 74 +++++++++++++++++-- tools/rdna2spirv.py | 27 +++++-- tools/shader_library.py | 2 +- 5 files changed, 122 insertions(+), 11 deletions(-) diff --git a/tests/semantic/test_salu_quadmask_bitreplicate.py b/tests/semantic/test_salu_quadmask_bitreplicate.py index 9fa67cbbfb..6ededcbb6f 100644 --- a/tests/semantic/test_salu_quadmask_bitreplicate.py +++ b/tests/semantic/test_salu_quadmask_bitreplicate.py @@ -155,6 +155,15 @@ def test_seeded(self): self.assertEqual(run([f"s_mov_b32 s2, {lo:#x}", "s_bitreplicate_b64_b32 s[10:11], s2"])[:2], (bitreplicate(lo) & M32, bitreplicate(lo) >> 32)) + def test_bitreplicate_constant_into_vcc(self): + # Lane L's VCC bit is source bit L // 2; the single invocation is lane 0, so source bit 0 decides. + for x, want in ((0x0F0F0F0F, 1), (0x33333332, 0), (0x1, 1), (0x2, 0)): + with self.subTest(x=hex(x)): + spv = translate([f"s_bitreplicate_b64_b32 vcc, {x:#x}", + "v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, vcc", + "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], 0x40000000 + want) + def test_lane_masks_rejected(self): for lines in (["v_cmp_gt_u32_e32 vcc, 5, v0", "s_quadmask_b64 s[10:11], vcc"], ["s_quadmask_b32 s10, exec_lo"], diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index e16111af89..852b70cbf4 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -144,6 +144,27 @@ def test_code_range(self): self.assertEqual(fspx_unpack.code_range(program(with_prologue=False)), (0, 12 + 4)) self.assertEqual(fspx_unpack.code_range(program(endpgm=False))[1], None) + def test_two_word_prologue(self): + # Some pipeline-library programs carry two hash words (24 bytes), then their code. + code = prologue()[:24] + V_MOV * 3 + ENDPGM + S_NOP * 4 + self.assertEqual(fspx_unpack.code_range(code), (24, 24 + 12 + 4)) + # One VOP3 word alone is not a prologue. + code = prologue()[:12] + V_MOV * 3 + ENDPGM + S_NOP * 4 + self.assertEqual(fspx_unpack.code_range(code)[0], 0) + + def test_code_range_last(self): + code = prologue() + V_MOV * 3 + ENDPGM + V_MOV + ENDPGM + S_NOP + self.assertEqual(fspx_unpack.code_range(code), (36, 36 + 12 + 4)) + self.assertEqual(fspx_unpack.code_range_last(code), (36, 36 + 12 + 4 + 4 + 4)) + + def test_branch_targets_inside(self): + enc = "; encoding: [0x00,0x00,0x00,0x00]" + listing = f"\ts_cbranch_execz 1 {enc}\n\ts_nop 0 {enc}\n\ts_endpgm {enc}\n" + self.assertTrue(fspx_unpack.branch_targets_inside(listing, 12)) # 0 + 4 + 4 = 8: inside + self.assertFalse(fspx_unpack.branch_targets_inside(listing, 8)) # 8 is past an 8-byte range + back = f"\ts_nop 0 {enc}\n\ts_branch 65534 {enc}\n" # -2: 4 + 4 - 8 = 0 + self.assertTrue(fspx_unpack.branch_targets_inside(back, 8)) + def test_unaligned_endpgm_bytes_are_not_the_end(self): code = prologue() + b"\0\0" + ENDPGM + b"\0\0" + V_MOV + ENDPGM start, end = fspx_unpack.code_range(code) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index cc1d5de819..a2a8f09740 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -144,13 +144,32 @@ def code_range(code: bytes): """(start, end) of the instructions in a kind-6 program: after the 36-byte prologue when it is there, through the first s_endpgm. end is None when the program has no s_endpgm.""" words = struct.unpack_from(f"<{len(code) // 4}I", code) - start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0 + # Most programs carry three hash words; some pipeline-library programs of 1.0.2.1 carry two (a 24-byte prologue, + # then s_inst_prefetch), measured on the 50 programs the runtime found untranslated. Two or three count. + hash_words = 0 + while hash_words < len(PROLOGUE_WORDS) and len(words) > PROLOGUE_WORDS[hash_words] + 2 and \ + words[PROLOGUE_WORDS[hash_words]] >> 16 == 0xD580: + hash_words += 1 + start = hash_words * PROLOGUE_SIZE // len(PROLOGUE_WORDS) if hash_words >= 2 and len(words) > 8 else 0 pos = code.find(ENDPGM, start) while pos >= 0 and pos % 4: pos = code.find(ENDPGM, pos + 1) return start, (pos + 4 if pos >= 0 else None) +def code_range_last(code: bytes): + """code_range through the last 4-byte-aligned s_endpgm instead of the first, as shader_library.code_range: a + program with an early exit branches to code after its first s_endpgm (28 of the 50 pipeline-library programs the + runtime dumped as untranslated: "branch target outside code").""" + start, first = code_range(code) + if first is None: + return start, None + last = code.rfind(ENDPGM) + while last >= first and (last - start) % 4: + last = code.rfind(ENDPGM, 0, last) + return start, max(first, last + 4) + + def psv_stage(container_parts: dict): """PSVRuntimeInfo1 ShaderStage, or None (PSV0 = u32 size of the runtime info, then the info).""" psv = container_parts.get(b"PSV0", b"") @@ -160,16 +179,53 @@ def psv_stage(container_parts: dict): return psv[4 + 24] if size > 24 and len(psv) > 4 + 24 else None -def unpack_payload(payload: bytes): +def branch_targets_inside(asm: str, size: int) -> bool: + """Whether every s_branch / s_cbranch_* of a shader_disasm.py listing lands inside [0, size).""" + pc = 0 + for line in asm.splitlines(): + if "; encoding: [" not in line: + continue + text, enc = line.split("; encoding: [", 1) + length = enc.count(",") + 1 + parts = text.split() + if parts and (parts[0] == "s_branch" or parts[0].startswith("s_cbranch_")) and len(parts) > 1: + try: + k = int(parts[1].rstrip(","), 0) + except ValueError: + k = None + if k is not None: + if k > 0x7FFF: + k -= 0x10000 + target = pc + 4 + 4 * k + if not 0 <= target < size: + return False + pc += length + return True + + +def branch_closed_end(code: bytes, start: int, mcpu: str, disasm) -> int | None: + """The end (after its s_endpgm) of the shortest range from `start` through an aligned s_endpgm whose branches all + stay inside it, or None. Tried from the first s_endpgm on.""" + pos = code.find(ENDPGM, start) + while pos >= 0: + if (pos - start) % 4 == 0: + asm, invalid, _ = disasm.disasm(code[start:pos + 4], mcpu, compute=True) + if asm.strip() and branch_targets_inside(asm, pos + 4 - start): + return pos + 4 + pos = code.find(ENDPGM, pos + 1) + return None + + +def unpack_payload(payload: bytes, last_endpgm: bool = False): status, entries = parse_fspx(payload) if status: return None, status blob = {k: payload[o:o + s] for k, (o, s) in entries.items()} - start, end = code_range(blob[6]) + start, end = (code_range_last if last_endpgm else code_range)(blob[6]) meta = { "version": struct.unpack_from(" 0}, **decode_kind0(blob[0]), } return (meta, blob), 0 @@ -183,6 +239,9 @@ def main(argv=None) -> int: ap.add_argument("--mcpu", default="gfx1030", help="llvm-mc CPU for --disasm (default gfx1030: the programs use v_dot4 instructions, which " "gfx1010 and gfx1013 do not decode)") + ap.add_argument("--last-endpgm", action="store_true", + help="end each program at its last s_endpgm, not its first (pipeline-library programs the " + "runtime dumped with LEONIDA_DUMP_MISSING: early exits branch past the first)") a = ap.parse_args(argv) # An output in the input folder can replace a .dxbc input and, when the input is the folder itself, # os.makedirs writes there before open() tries to read the folder as a file. Refuse before either. @@ -231,7 +290,7 @@ def main(argv=None) -> int: continue for n, (off, container, payload) in enumerate(items): name = f"{stem}_{n:02d}" if len(items) > 1 else stem - got, status = unpack_payload(payload) + got, status = unpack_payload(payload, a.last_endpgm) if not got: print(f"{name}: FSPX status {status}", file=sys.stderr) bad += 1 @@ -254,6 +313,11 @@ def main(argv=None) -> int: listing = None if disasm and meta["code"]["end"]: start, end = meta["code"]["start"], meta["code"]["end"] + if a.last_endpgm: + # The last s_endpgm can lie in data after the code; the first s_endpgm whose listing keeps + # every branch inside the code is the program's end. + end = branch_closed_end(blob[6], start, a.mcpu, disasm) or end + meta["code"]["end"] = end asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu, compute=True) if not asm.strip(): reason = (err.strip().splitlines() or ["no output"])[0] diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1cf8a7a90f..748f10f3fb 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7253,7 +7253,15 @@ def selectors(key, count, limit): args = [dict(a) for a in ins["args"]] if len(args) < 2: raise Unsupported("DPP operands") - if args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: + # VOPC with DPP (v_cmp_*_dpp vcc, ...: 12 compares in pipeline-library reductions of 1.0.2.1) writes a lane + # mask, which the DPP write guard (VGPR stores) does not cover: taken when every lane writes, i.e. full row + # and bank masks with bound_ctrl:1 or DPP8, so no lane keeps its old bit. + lane_mask_dst = (args[0].get("k") == "special" and args[0].get("t", "") in ("vcc", "vcc_lo") + and base_op(ins["op"]).startswith("v_cmp_")) + if lane_mask_dst: + if row_mask != 0xF or bank_mask != 0xF or not (bound or dpp8 is not None): + raise Unsupported("DPP compare with a partial write mask") + elif args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: raise Unsupported("DPP destination") if args[1].get("n", 1) != 1: raise Unsupported("DPP 64-bit source") @@ -7433,7 +7441,7 @@ def selectors(key, count, limit): self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") args[1] = {"k": "ssa", "v": src0} previous = self.dpp_guard - self.dpp_guard = write + self.dpp_guard = None if lane_mask_dst else write try: return self._insn({**ins, "args": args}) finally: @@ -7594,16 +7602,25 @@ def _insn(self, ins): half = self.mask_half(x) if self.wave64 else None mask_words = [hi if half == "hi" else lo] if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): - if op != "s_bitreplicate_b64_b32" or d["t"] != "exec": + if op != "s_bitreplicate_b64_b32" or d["t"] not in ("exec", "vcc") or mask_words is not None: raise Unsupported(op + " on a lane mask") - # EXEC's bit for lane L comes from scalar-source bit L // 2. + # EXEC's (or VCC's) bit for lane L comes from scalar-source bit L // 2. VCC from a constant + # (s_bitreplicate_b64_b32 vcc, 0xf0f0f0f: 6 pipeline-library programs of 1.0.2.1) is a lane mask + # each invocation holds as 0 or ~0, as a compare leaves it. shift, shifted, bit = (self.tmp() for _ in range(3)) lane = self.wave_lane() word = self.src_u(x) self.emit(f"{shift} = OpShiftRightLogical %uint {lane} {self.cu(1)}") self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}") self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") - self.set_exec(bit) + # As a lane mask (0 or ~0): set_exec takes this lane's bit of the value it is given (lane_bit_on), + # which a mask answers for every lane and a plain 0/1 only for lanes 0 and 32. + mask = self.tmp() + self.emit(f"{mask} = OpISub %uint {self.cu(0)} {bit}") + if d["t"] == "vcc": + self.emit(f"OpStore %vcc {mask}") + else: + self.set_exec(mask) return if mask_words is not None: words = mask_words diff --git a/tools/shader_library.py b/tools/shader_library.py index a491589070..193eb6a2cb 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -354,7 +354,7 @@ def extraction_paths(): code = program(b, lib, i) start, end = code_range(code) meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), - "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} + "code": {"start": start, "end": end, "prologue": start > 0}} state = blob(b, lib, cs_state[i]) if i in cs_state else None if state is not None: meta.update(fspx_unpack.decode_kind0(state)) From 4e1ca11a650afd3f187adba55a7938a74b32f009 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 23:35:37 +0100 Subject: [PATCH 05/18] fix: shader_disasm prints the v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 words llvm-mc rejects, so the FSR4 FSPX programs translate The FidelityFX upscaler programs hold 89 such words in 8 programs (docs/fspx.md); the translator already models the form but the listing could not carry it, so the programs were refused as a fall-through into undecodable words. --- docs/fspx.md | 9 + tests/semantic/test_alu_dot4_i8.py | 4 +- .../semantic/test_fspx_dot4_op_sel_disasm.py | 157 ++++++++++++++++++ tools/shader_disasm.py | 56 +++++++ 4 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 tests/semantic/test_fspx_dot4_op_sel_disasm.py diff --git a/docs/fspx.md b/docs/fspx.md index a603545e93..12025a239b 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -149,6 +149,15 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. + - `tools/shader_disasm.py` (so `fspx_unpack.py --disasm` and `make_game.py`) prints such a word as + `v_dot4_i32_i8 vD, a, b, c op_sel:[0,1,0] op_sel_hi:[1,0,1]` with its real encoding. A dword pair that llvm-mc + rejected, with exactly opcode 0x16, `op_sel` 2, `op_sel_hi` 5, no `clamp` and no `neg`, is decoded with the two + fields at their defaults and then given the fields and the encoding back, so the translator reads it and its + encoding check against the blob passes. Any other `op_sel`/`op_sel_hi` value, `clamp` or `neg` is still + undecodable (only this one was measured). A pair llvm-mc accepted, such as a literal followed by an instruction, + is never touched. `tests/semantic/test_fspx_dot4_op_sel_disasm.py` checks it with llvm-mc (the 5 measured + operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because + that needs the package's DLL. ## Kind 7: records diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py index 23c73bdaa0..ffefcbbd48 100644 --- a/tests/semantic/test_alu_dot4_i8.py +++ b/tests/semantic/test_alu_dot4_i8.py @@ -15,8 +15,8 @@ op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can -carry it. +ops. `ref_op_sel` reproduces them. A listing carries the form since tools/shader_disasm.py prints it +(tests/semantic/test_fspx_dot4_op_sel_disasm.py). neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py new file mode 100644 index 0000000000..7ff52527f4 --- /dev/null +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -0,0 +1,157 @@ +"""The FidelityFX upscaler's programs (docs/fspx.md) hold 89 v_dot4_i32_i8 words with op_sel 2 and op_sel_hi 5, which +llvm-mc does not decode: it rejects the first dword, reads the second as another instruction, and the translator then +refuses the program ("fall-through into undecodable words"), so 9 of the 29 programs had no pipeline and the DLL's +next pipeline call faulted. tools/shader_disasm.py now prints such a word as the instruction it is, with its +op_sel/op_sel_hi fields and its real encoding, so the translator reads it and checks it against the blob. + +Each case assembles a small program with llvm-mc, turns one v_dot4_i32_i8 into the op_sel 2 / op_sel_hi 5 form by +setting those fields in its two dwords, disassembles the bytes with shader_disasm, and translates the listing in the +FSPX layout (disasm/, fspx/.code and .json). The expected words are the ones measured on gfx1036 +(MEASURED_OP_SEL in test_alu_dot4_i8.py). They need llvm-mc with the AMDGPU target (LLVM_MC, or llvm-mc on PATH) and +skip without it. No GPU and no game files. + + python -I tests/semantic/test_fspx_dot4_op_sel_disasm.py +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from test_alu_dot4_i8 import MEASURED_OP_SEL, ref # noqa: E402 + +MCPU = "gfx1030" # fspx_unpack.py's default: LLVM decodes v_dot4_i32_i8 for it and not for gfx1013 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) << 14 + w1 = w1 & ~(3 << 27) | (op_sel_hi & 3) << 27 + return struct.pack("<2I", w0, w1) + + +def program(a, b, addend, middle): + """Code bytes of: v8 = the v_dot4_i32_i8 given by `middle` (its two dwords), v9 = the plain v_dot4_i32_i8 on the + same registers, both written to mrt0. Returns (code, byte offset of the first dot4).""" + head = b"".join(assemble(line) for line in ( + f"v_mov_b32_e32 v1, 0x{a:08x}", f"v_mov_b32_e32 v2, 0x{b:08x}", f"v_mov_b32_e32 v3, 0x{addend:08x}")) + tail = b"".join(assemble(line) for line in ( + "v_dot4_i32_i8 v9, v1, v2, v3", "exp mrt0 v8, v9, v8, v9 done vm", "s_endpgm")) + return head + middle + tail, len(head) + + +def translate_fspx(name, listing, code): + """SPIR-V assembly for a listing in the FSPX layout, with the code bytes it was disassembled from beside it.""" + with tempfile.TemporaryDirectory() as tmp: + for d in ("disasm", "fspx"): + os.mkdir(os.path.join(tmp, d)) + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: + f.write(code) + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f: + json.dump({}, f) + src = os.path.join(tmp, "disasm", name + ".s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +def listing_of(name, code): + asm, bad, err = shader_disasm.disasm(code, MCPU) + return f"; {name} code 0x0..0x{len(code):x} (fspx), {MCPU}, {bad} invalid words\n" + asm, bad + + +@unittest.skipUnless(llvm_decodes_v_dot4(), "needs llvm-mc with the AMDGPU target that decodes v_dot4_i32_i8") +class Dot4OpSelListing(unittest.TestCase): + def plain_pair(self): + return assemble("v_dot4_i32_i8 v8, v1, v2, v3") + + def test_the_listing_carries_the_op_sel_word_and_the_program_runs(self): + for a, b, addend, measured in MEASURED_OP_SEL: + with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): + middle = with_op_sel(self.plain_pair(), 2, 5) + code, at = program(a, b, addend, middle) + listing, bad = listing_of("ps_fspx_dot4_op_sel", code) + self.assertEqual(bad, 0, listing) + lines = [ln for ln in listing.splitlines() if "v_dot4_i32_i8" in ln] + self.assertEqual(len(lines), 2, listing) + self.assertIn("v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", lines[0]) + self.assertIn("encoding: [" + ",".join(f"0x{x:02x}" for x in middle) + "]", lines[0]) + self.assertNotIn("op_sel", lines[1]) # the plain instruction next to it stays plain + words = support_words(translate_fspx("ps_fspx_dot4_op_sel", listing, code)) + self.assertEqual(words, [measured, ref(a, b, addend), measured, ref(a, b, addend)]) + + def test_other_op_sel_values_stay_undecodable(self): + # Only op_sel 2 / op_sel_hi 5 was measured on hardware; anything else is still rejected, never guessed. + for op_sel, op_sel_hi in ((1, 5), (4, 5), (2, 7), (0, 5), (2, 4)): + with self.subTest(op_sel=op_sel, op_sel_hi=op_sel_hi): + code, _ = program(1, 1, 0, with_op_sel(self.plain_pair(), op_sel, op_sel_hi)) + listing, bad = listing_of("ps_fspx_dot4_other", code) + self.assertNotIn("op_sel:[0,1,0] op_sel_hi:[1,0,1]", listing) + with self.assertRaises(rdna2spirv.Unsupported): # undecodable, or printed without a dropped field + translate_fspx("ps_fspx_dot4_other", listing, code) + + def test_a_clamp_or_neg_bit_on_the_word_stays_undecodable(self): + for name, shift, dword in (("clamp", 15, 0), ("neg_hi", 8, 0), ("neg_lo", 29, 1)): + with self.subTest(field=name): + middle = list(struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5))) + middle[dword] |= 1 << shift + code, _ = program(1, 1, 0, struct.pack("<2I", *middle)) + listing, bad = listing_of("ps_fspx_dot4_mods", code) + self.assertGreaterEqual(bad, 1) + self.assertNotIn("op_sel:[0,1,0]", listing) + + def test_data_that_looks_like_the_word_is_left_alone(self): + # The same two dwords as a 32-bit literal and the instruction after it decode with no invalid word, so they + # are not touched: only a word llvm-mc rejected is read as v_dot4_i32_i8. + pair = struct.unpack("<2I", with_op_sel(self.plain_pair(), 2, 5)) + code = (assemble("v_mov_b32_e32 v4, 0x%08x" % pair[0]) + assemble("v_fmac_legacy_f32 v7, v1, v2") + + assemble("s_endpgm")) + self.assertEqual(struct.unpack_from("<2I", code, 4), pair) + listing, bad = listing_of("ps_fspx_dot4_literal", code) + self.assertEqual(bad, 0, listing) + self.assertNotIn("op_sel", listing) + + +def support_words(spv): + out = si.run_fragment(spv) + return list(out["%out_mrt0"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 67a10ec13d..09d0246352 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -30,6 +30,7 @@ TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" +DOT4_I8_OPCODE = 0x16 # VOP3P v_dot4_i32_i8 PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with FAILED = [] # (path, first stderr line) for shaders that produced no disassembly @@ -97,6 +98,9 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True fixed = with_vopc_dpp(code, mcpu, err) if fixed: return fixed + fixed = with_dot4_op_sel(code, mcpu, bad, err) + if fixed: + return fixed return asm, bad, err @@ -184,6 +188,58 @@ def with_vopc_dpp(code: bytes, mcpu: str, err: str): return None +def dot4_op_sel_words(code: bytes, offsets) -> dict: + """{offset: (word0, word1)} of the dword pairs at `offsets` that are v_dot4_i32_i8 with op_sel 2 and op_sel_hi 5, + no clamp and no neg: the form 89 words of the FidelityFX upscaler's programs take (docs/fspx.md). llvm-mc has no + decoding for it, and a plain v_dot4_i32_i8 has op_sel 0 and op_sel_hi 7. Only this combination is recognised: + its result was measured on hardware (tests/semantic/test_alu_dot4_i8.py), the other op_sel values were not.""" + found = {} + for at in sorted(offsets): + if at % 4 or at + 8 > len(code): + continue + w0, w1 = struct.unpack_from("<2I", code, at) + if (w0 >> 23 == 0x198 and (w0 >> 16) & 0x7F == DOT4_I8_OPCODE and (w0 >> 8) & 7 == 0 # VOP3P, neg_hi + and (w0 >> 11) & 7 == 2 and (w0 >> 14) & 1 == 1 and (w0 >> 15) & 1 == 0 # op_sel, hi[2], clamp + and (w1 >> 27) & 3 == 1 and (w1 >> 29) & 7 == 0): # op_sel_hi[1:0], neg_lo + found[at] = (w0, w1) + return found + + +def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): + """The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction + it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their + defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the + translator then reads the instruction and checks its encoding against the blob. A word that is not printed as + v_dot4_i32_i8 at an instruction boundary was not an instruction (it sits in a literal or in data), so it is + left as it was and the pass runs again without it.""" + words = dot4_op_sel_words(code, invalid_offsets(err)) + while words and bad: + patched = bytearray(code) + for at, (w0, w1) in words.items(): + struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27)) + asm, bad2, err2 = run_mc(bytes(patched), mcpu) + if not asm.strip(): + return None + invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), [] + for line in asm.split("\n"): + enc = ENCODING.search(line) + if not enc: + lines.append(line) + continue + while pos in invalid: + pos += 4 + if pos in words and line.lstrip("\t").startswith("v_dot4_i32_i8 "): + hit.add(pos) + w0, w1 = words[pos] + original = ",".join(f"0x{b:02x}" for b in struct.pack("<2I", w0, w1)) + line = line[:enc.start()].rstrip() + " op_sel:[0,1,0] op_sel_hi:[1,0,1]" + line = f"{line:<40}; encoding: [{original}]" + lines.append(line) + pos += len(enc.group(1).split(",")) + if hit == set(words): + return "\n".join(lines), bad2, err2 + words = {at: w for at, w in words.items() if at in hit} + return None MAX_DATA_DWORDS = 1 << 16 From 570db1d58f67a3b899cc60f53055eeb86fc8ac3d Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:13:57 -0600 Subject: [PATCH 06/18] shader_library: keep each state of a compute program, select by code hash (TOOLS-LIBRARY-COMPUTE-BY-HASH) The run time finds a pipeline-library compute program by the SHA-256 of its code and of its record's state blob. shader_library.py kept one state per program, the last record's, so when two compute records used one program with different state blobs only one of the two pairs got an entry and a .state file. Each distinct state of a program is now written: the first under the program's name, each further one as _state_, with its own .code, .json, .state, listing and index entry. library.json names the entry of each record. A program with one state, the case of every program in the measured 1.0.2.1 library, is written exactly as before. --compute-hashes FILE writes only the compute programs whose code has one of the SHA-256 digests listed in FILE, with every state they are used with. It cannot be combined with --stages, and a digest no compute program has is an error before anything is written. tests/test_shader_library.py gets three tests on a synthetic library; all three fail on the base. The standard-library tests and the translator suite add no failing file. No retail library was read for this change. AI-assisted (Claude Code). Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- docs/shader_library.md | 9 ++- tests/test_shader_library.py | 123 +++++++++++++++++++++++++++++++++++ tools/shader_library.py | 12 ++-- 3 files changed, 138 insertions(+), 6 deletions(-) diff --git a/docs/shader_library.md b/docs/shader_library.md index 3ef944a528..8a971203f7 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -152,8 +152,11 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv * It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one - (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and + blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, + every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, + 2,693 records). A program that records use with different state blobs is written once per distinct state, the + first under its name and each further one as `_state_`, so each pair of keys has an entry + (the library measured above has no such program). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -162,6 +165,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv interface. * `--save` writes the reassembled library. A saved file is also accepted as input. * `--stages` limits the output to some stages. +* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed + in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error. The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest diff --git a/tests/test_shader_library.py b/tests/test_shader_library.py index 8410be28a8..db5fa57f7a 100644 --- a/tests/test_shader_library.py +++ b/tests/test_shader_library.py @@ -388,6 +388,129 @@ def test_compute_missing_state_removes_stale_state_and_skips_none_blob(self): self.assertIn("fspx_code_sha256", meta) self.assertNotIn("fspx_state_sha256", meta) + def two_state_library(self): + """Program 0 with three state blobs, two of them the same bytes, and once without a state; program 1 with one + of those blobs; program 2 in a graphics pipeline. Returns (library, the two distinct states, program 0).""" + first, second = kind0(), kind0(threads=(32, 1, 1)) + code = prog(3) + compute = [(0, NONE, 0, NONE), (1, NONE, 0, NONE), (2, NONE, 0, NONE), (NONE, NONE, 0, NONE), + (1, NONE, 1, NONE)] + lib = build([(NONE, NONE, {0: (2, 3)})], compute, [first, second, first, layout_blob(2, D_PS)], + [code, prog(4), prog(5)]) + return lib, (first, second), code + + # The entries of that library's compute programs: program 0, its second state (blob 1) and program 1. + TWO_STATE_NAMES = [sl.program_name(0, {"cs"}), sl.program_name(0, {"cs"}) + "_state_1", sl.program_name(1, {"cs"})] + + def test_program_with_two_states_gets_an_entry_for_each(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + # A further state is an output like any other: --save must not name it. + names = self.TWO_STATE_NAMES + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".state"), "--stages", "cs") + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--stages", "cs") + self.assertEqual(rc, 0) + self.assertIn("3 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual([(e["file"], e["program"], e["threads"]) for e in index], + [(names[0] + ".dxbc", 0, [8, 8, 1]), (names[1] + ".dxbc", 0, [32, 1, 1]), + (names[2] + ".dxbc", 1, [32, 1, 1])]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + for name in names[:2]: + with open(os.path.join(out, "fspx", name + ".code"), "rb") as f: + self.assertEqual(f.read(), code) + # Both entries of program 0 have its code key, and each its own state key. + metas = [shader_meta.collect(os.path.join(out, "disasm", n + ".s"), n, [[]], [[]]) for n in names[:2]] + self.assertEqual({m["fspx_code_sha256"] for m in metas}, {hashlib.sha256(code).hexdigest()}) + self.assertEqual([m["fspx_state_sha256"] for m in metas], + [hashlib.sha256(first).hexdigest(), hashlib.sha256(second).hexdigest()]) + # Every record names the entry with its state; the one without a state names the program. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + self.assertEqual([c["program"] for c in json.load(f)["compute"]], + [names[0], names[1], names[0], names[0], names[2]]) + + def test_compute_hashes_select_programs_by_their_code(self): + lib, (first, second), code = self.two_state_library() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + hashes = os.path.join(tmp, "hashes.txt") + with open(hashes, "w", encoding="utf-8", newline="\n") as f: + f.write("\n " + hashlib.sha256(code).hexdigest().upper() + "\n\n") + out = os.path.join(tmp, "out") + names = self.TWO_STATE_NAMES[:2] + self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".code"), + "--compute-hashes", hashes) + self.assertFalse(os.path.exists(out)) + rc, text = self.run_main(src, "--out", out, "--compute-hashes", hashes) + self.assertEqual(rc, 0) + self.assertIn("2 written", text) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + self.assertEqual([e["file"] for e in json.load(f)], [n + ".dxbc" for n in names]) + self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))), + sorted(n + ext for n in names for ext in (".code", ".json", ".state"))) + for name, state in zip(names, (first, second)): + with open(os.path.join(out, "fspx", name + ".state"), "rb") as f: + self.assertEqual(f.read(), state) + # The tables are the library's, whatever was selected. + with open(os.path.join(out, "library.json"), encoding="utf-8") as f: + summary = json.load(f) + self.assertEqual([c["program"] for c in summary["compute"]], + [names[0], names[1], names[0], names[0], self.TWO_STATE_NAMES[2]]) + self.assertEqual(summary["graphics"][0]["stages"], {"ps": sl.program_name(2, {"ps"})}) + + def test_compute_hashes_are_checked_before_anything_is_written(self): + lib, _, code = self.two_state_library() + digest = hashlib.sha256(code).hexdigest() + pixel = hashlib.sha256(sl.program(lib, sl.parse(lib), 2)).hexdigest() + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "lib.bin") + with open(src, "wb") as f: + f.write(lib) + out = os.path.join(tmp, "out") + listed = os.path.join(tmp, "hashes.txt") + + def usage_error(text, *args): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as caught: + self.run_main(src, *args) + self.assertEqual(caught.exception.code, 2) + return err.getvalue() + + self.assertIn("not allowed with", usage_error(digest, "--out", out, "--stages", "cs", + "--compute-hashes", listed)) + self.assertIn("--compute-hashes needs --out", usage_error(digest, "--save", os.path.join(tmp, "l.bin"), + "--compute-hashes", listed)) + for text in ("", "\n", digest[:-1], digest + " not-a-digest", "0x" + digest): + with self.subTest(text=text): + self.assertIn("cannot read --compute-hashes", usage_error(text, "--out", out, + "--compute-hashes", listed)) + self.assertIn("cannot read --compute-hashes", + usage_error(digest, "--out", out, "--compute-hashes", os.path.join(tmp, "missing.txt"))) + # A digest no compute program has, here an unknown one and a pixel program's. + for text in (digest + "\n" + "0" * 64, pixel): + with self.subTest(text=text): + with open(listed, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + with self.assertRaises(sl.LibraryError) as caught: + self.run_main(src, "--out", out, "--compute-hashes", listed) + self.assertIn("match no compute program", str(caught.exception)) + self.assertFalse(os.path.exists(out)) + self.assertFalse(os.path.exists(os.path.join(tmp, "l.bin"))) + def test_same_code_with_distinct_states_gets_distinct_state_keys(self): code = prog(0x44556677) s_a, s_b = kind0(threads=(32, 1, 1)), kind0(threads=(64, 1, 1)) diff --git a/tools/shader_library.py b/tools/shader_library.py index a74a820bb7..b1f928292d 100644 --- a/tools/shader_library.py +++ b/tools/shader_library.py @@ -270,7 +270,10 @@ def compute_variants(b: bytes, lib: dict, names: dict): i, state_id = rec["program"], rec["state"] if i is None: continue - state = blob(b, lib, state_id) if state_id is not None else None + if state_id is None: + by_record[i, None] = names[i] + continue + state = blob(b, lib, state_id) states = variants.setdefault(i, {}) if state not in states: states[state] = names[i] if not states else f"{names[i]}_state_{state_id}" @@ -301,7 +304,7 @@ def main(argv=None) -> int: if not a.out and not a.save: ap.error("give --out, --save or both") hashes = None - if a.compute_hashes: + if a.compute_hashes is not None: if not a.out: ap.error("--compute-hashes needs --out") try: @@ -310,7 +313,7 @@ def main(argv=None) -> int: except (OSError, UnicodeError) as error: ap.error(f"cannot read --compute-hashes: {error}") if not hashes or any(not re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes): - ap.error("--compute-hashes needs at least one SHA-256 digest") + ap.error("cannot read --compute-hashes: expected one or more SHA-256 digests of 64 hex digits") with open(a.src, "rb") as f: head = f.read(4) f.seek(0) @@ -346,7 +349,8 @@ def main(argv=None) -> int: selected = [i for i in selected if matching[i] in hashes] missing = hashes - {matching[i] for i in selected} if missing: - raise LibraryError(f"{len(missing)} requested compute code hashes not found in the pipeline library") + raise LibraryError(f"{len(missing)} of the {len(hashes)} --compute-hashes digests match no compute " + f"program of the library, first {min(missing)}") carve_errors = [] sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None From 9dd0be280c01f46464af38d67bf9236b8f783840 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:50:26 -0500 Subject: [PATCH 07/18] test_vcc_tuple_fallback: widened scalar load with an SGPR offset, buffer store through a vcc resource restore_vcc_tuples (#674) already decodes these words from the blob (the console's 112-SGPR file is wider than llvm-mc's 106); these cases pin the two forms its tests did not cover: s_buffer_load_dwordx8 into s[100:107] with an SGPR soffset and an immediate offset, and buffer_store_dword with its resource in s[104:107]. Encodings built from the field layout. The forms come from luizwidmer/palmetto (GPL-3.0). --- tests/semantic/test_vcc_tuple_fallback.py | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 9b614f3812..3aa66c9def 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -139,6 +139,39 @@ def test_image_resource_in_vcc(self): with self.subTest(printed_as=variant): self.assertIn("OpFunctionCall %uint %desc_lookup_fn", translate(program, variant)) + def test_load_with_register_offset_into_vcc(self): + # The widened scalar load with an SGPR soffset and an immediate offset (the form luizwidmer/palmetto's + # docs/boot_frontier.md measured in an FSPX program, built here from the field layout, not copied): + # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[4:7], s12 offset:0x40 reads BASE + 0x40 + s12. + load = "02 19 2c f4 40 00 00 18" + program = [SET_SGPR_V[0], SET_SGPR_V[1], ("s_mov_b32 s6, 0x100", "ff 03 86 be 00 01 00 00"), SET_SGPR_V[3], + ("s_mov_b32 s12, 32", "a0 03 8c be"), + (None, load), WAIT, + ("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, s105", "69 02 16 7e"), + ("v_mov_b32_e32 v12, vcc_lo", "6a 02 18 7e"), ("v_mov_b32_e32 v13, vcc_hi", "6b 02 1a 7e"), + ] + STORE_X4 + words = [0x22220000 + i for i in range(8)] + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), {BASE + 0x60 + 4 * i: w for i, w in enumerate(words)}) + self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], [words[0], words[5], words[6], words[7]]) + + def test_buffer_store_with_resource_in_vcc(self): + # buffer_store_dword v11, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen: a store through the widened resource too. + store = "00 10 70 e0 01 0b 1a 80" + program = SET_SGPR_V + [ + (None, LOAD_X4_VCC), WAIT, + ("v_mov_b32_e32 v1, 4", "84 02 02 7e"), + ("v_mov_b32_e32 v11, 0x5a5a1234", "ff 02 16 7e 34 12 5a 5a"), + (None, store), WAIT_V, + ("s_endpgm", "00 00 81 bf"), + ] + memory = {BASE + 4 * i: w for i, w in enumerate([OUT, 0, 16, 0x30000000])} + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), memory) + self.assertEqual(mem.get(OUT + 4), 0x5A5A1234) + def test_junk_that_swallows_the_next_instructions(self): # The junk at the tuple's second word is longer than that word, so it covers the s_mov_b32 after the tuple # (and the first word of the 8-byte one after that, whose literal then prints as junk too). None of them is From 970837c7534c840070805699f1d80236c61b5e88 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:31:42 -0500 Subject: [PATCH 08/18] d3d12_xs: null-resource texture barriers and null-view RTV clears on the console list List slot 146 (Barrier -> GCL7 80): a texture barrier with no resource, which the console takes as a global barrier, is forwarded as a D3D12_GLOBAL_BARRIER with the same sync and access; a mixed texture group is split into runs in order, in storage that lives for the call. Calls with nothing to convert keep the title's pointer. A group array that cannot be read safely (null with a nonzero count, an unknown group type, absurd counts) is refused whole and logged once per reason. List slot 52 (ClearRenderTargetView -> PC 48): the device proxy marks the real handle when CreateRenderTargetView gets no resource (moved by RTV descriptor copies, cleared by a view made with a resource), and the clear of a marked view is skipped, as on the console. Other views keep today's path. Before this, both calls put the PC list in its error state, so Close failed and ExecuteCommandLists dropped the submission. xs_proxy_mock_test models that error state in its mock list and covers both paths; the two old slot-146 cases that passed garbage words now pass valid ones. The null-resource barrier and null-view clear behaviour were first reported by luizwidmer/palmetto. --- docs/d3d12_vulkan.md | 4 + runtime/shims/d3d12_xs_device.cpp | 205 +++++++++++++++++++- runtime/test/xs_proxy_mock_test.cpp | 286 +++++++++++++++++++++++++++- 3 files changed, 489 insertions(+), 6 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e23985ecb3..350504ec49 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3926,8 +3926,12 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | | Enhanced barriers | Public Xbox Series `D3D12_BARRIER_GROUP` | `VK_KHR_synchronization2`; implement directly. | +| List slot 146: texture barrier with no resource | The retail title records `D3D12_BARRIER_TYPE_TEXTURE` barriers whose `pResource` is null in its `Barrier(NumBarrierGroups, pBarrierGroups)` calls; on the console such a barrier is a global memory and execution barrier | `d3d12_xs_device.cpp` turns each into a `D3D12_GLOBAL_BARRIER` with the same `SyncBefore`/`SyncAfter`/`AccessBefore`/`AccessAfter` (layouts, subresource range and flags dropped) before it calls GCL7 `Barrier` (PC slot 80). A texture group with both kinds is split into runs, in order, in storage that lives for the call; a call with nothing to convert goes through with the title's own pointer. Without this the PC list goes into its error state, `Close` fails and `ExecuteCommandLists` drops the submission. A group array the proxy cannot read safely (null with a nonzero count, a group type it does not know, more than 1,024 groups or 65,536 barriers in one group) is refused whole, nothing recorded, and logged once per reason. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | +| List slot 52: clear of an RTV made with no resource | The title creates some render-target views with `CreateRenderTargetView(nullptr, ...)` and clears them every frame; on the console that clear does nothing | The device proxy marks the real handle when device slot 20 gets no resource; a view made there with a resource removes the mark, and `CopyDescriptors`/`CopyDescriptorsSimple` of RTVs move it with the descriptors. List slot 52 skips the clear of a marked view (logged the first time) and the list stays valid. The mark is the proxy's own because the real descriptor cannot tell: the Vulkan layer writes the same empty record for a view it could not make, and a PC runtime's handles are opaque. Any other view, valid or not, still reaches `ClearRenderTargetView` (PC slot 48); RTV records the title copies with its own `memcpy` are not followed. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | | XDXR batched/streaming BVH | `XboxBvhBuilder.dll` exports | See 4.8. | +The null-resource barrier and null-view clear behaviour were first reported by luizwidmer/palmetto. + ### 4.10 Debug markers and private data Games and middleware call these every frame (PIX events), so they must be cheap and never fail. Implemented diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 60d7c62f30..bad017bfd4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -116,6 +116,14 @@ struct DeviceProxy { // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. std::atomic console_layout{0}; // 0 unknown, 1 older, 2 newer + // The real (translated) CPU handles that hold a render-target view the title created with no resource (device + // slot 20 with a null resource), for console list slot 52: on the console, clearing such a view does nothing. + // The real device's descriptor cannot tell (the Vulkan layer writes the same empty record for a view it could not + // make, and the PC runtime's handles are opaque), so the proxy keeps the mark itself. A view made there with a + // resource, or a descriptor copy over it, removes it. + std::mutex null_rtv_lock; + std::set null_rtvs; + std::atomic null_rtv_count{0}; // null_rtvs.size(), read without the lock on the clear path // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers // compiled against the PC headers. bool console_lists = true; @@ -372,6 +380,71 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { } } +// ---- Render-target views made with no resource (DeviceProxy::null_rtvs) ---- + +// Device slot 20 wrote an RTV at the real handle `ptr`: marked when the title passed no resource, unmarked otherwise. +void mark_null_rtv(DeviceProxy* device, SIZE_T ptr, bool no_resource) { + if (!ptr || (!no_resource && device->null_rtv_count.load(std::memory_order_acquire) == 0)) return; + std::lock_guard lock(device->null_rtv_lock); + try { + if (no_resource) + device->null_rtvs.insert(ptr); + else + device->null_rtvs.erase(ptr); + } catch (const std::bad_alloc&) { + // The mark is lost: a clear of this view keeps the PC list's answer, as before the mark existed. + } + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + +bool is_null_rtv(DeviceProxy* device, SIZE_T ptr) { + if (!ptr || device->null_rtv_count.load(std::memory_order_acquire) == 0) return false; + std::lock_guard lock(device->null_rtv_lock); + return device->null_rtvs.count(ptr) != 0; +} + +// A descriptor copy moves the marks with the descriptors: `count` RTV descriptors from the real handle `src` to +// `dest`, `increment` bytes apart. Caller holds null_rtv_lock. +void copy_null_rtv_marks_locked(DeviceProxy* device, SIZE_T dest, SIZE_T src, UINT count, UINT increment) { + for (UINT i = 0; i < count; ++i) { + const SIZE_T to = dest + static_cast(i) * increment; + if (device->null_rtvs.count(src + static_cast(i) * increment)) + device->null_rtvs.insert(to); + else + device->null_rtvs.erase(to); + } +} + +// CopyDescriptors / CopyDescriptorsSimple of RTVs, after the copy, with the handles the real device got. A null +// size array means ranges of one descriptor, as in D3D12. Nothing to do while no view is marked: a copy can only +// move a mark, never make one. +void copy_null_rtv_marks(DeviceProxy* device, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, + const UINT* dest_sizes, UINT num_src, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, + const UINT* src_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) { + if (type != D3D12_DESCRIPTOR_HEAP_TYPE_RTV || device->null_rtv_count.load(std::memory_order_acquire) == 0) return; + if (!dest_starts || !src_starts) return; + const UINT increment = device->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + if (!increment) return; + std::lock_guard lock(device->null_rtv_lock); + try { + UINT d = 0, s = 0, d_used = 0, s_used = 0; + while (d < num_dest && s < num_src) { + const UINT d_size = dest_sizes ? dest_sizes[d] : 1; + const UINT s_size = src_sizes ? src_sizes[s] : 1; + if (d_used == d_size) { ++d; d_used = 0; continue; } + if (s_used == s_size) { ++s; s_used = 0; continue; } + const UINT d_left = d_size - d_used, s_left = s_size - s_used; + const UINT run = d_left < s_left ? d_left : s_left; + copy_null_rtv_marks_locked(device, dest_starts[d].ptr + static_cast(d_used) * increment, + src_starts[s].ptr + static_cast(s_used) * increment, run, increment); + d_used += run; + s_used += run; + } + } catch (const std::bad_alloc&) { + } + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -2486,6 +2559,101 @@ unsigned detect_list_slot_count(IUnknown* real) { return 9; } +// ---- Console list slot 146: Barrier(NumBarrierGroups, pBarrierGroups) -> GCL7 Barrier (PC 80) ---- +// +// The title records texture barriers with no resource, which the console takes as a global memory and execution +// barrier. A PC texture barrier needs a resource (the Vulkan layer's list goes into its error state, so Close fails +// and the submission is dropped), so each such barrier becomes a D3D12_GLOBAL_BARRIER with the same sync and access; +// its layouts, subresource range and flags have nothing to apply to. A texture group with both kinds is split into +// runs in their order: texture runs point into the title's array, global runs into the call's own storage. A call +// with nothing to convert is forwarded with the title's own pointer. +constexpr UINT32 kMaxConsoleBarrierGroups = 1024; // the measured calls pass one group +constexpr UINT32 kMaxConsoleBarriersPerGroup = 65536; + +struct ConsoleBarrierStorage { // lives for one call, on the recording thread's stack + std::vector groups; + std::vector globals; +}; + +// The groups to forward: `in` when nothing needs converting, `storage.groups` when something does, null with +// `reason` set when the array cannot be read safely and the call is refused. `out_count` is the group count to pass. +const D3D12_BARRIER_GROUP* console_barrier_groups(UINT32 count, const D3D12_BARRIER_GROUP* in, + ConsoleBarrierStorage& storage, UINT32& out_count, + const char*& reason) { + const auto refuse = [&reason](const char* why) -> const D3D12_BARRIER_GROUP* { + reason = why; + return nullptr; + }; + out_count = count; + if (count == 0) return in; // nothing to read: the PC call is a no-op either way + if (!in) return refuse("null group array with a nonzero count"); + if (count > kMaxConsoleBarrierGroups) return refuse("group count over the limit"); + std::size_t null_textures = 0, texture_barriers = 0; + for (UINT32 g = 0; g < count; ++g) { + const D3D12_BARRIER_GROUP& group = in[g]; + if (group.Type != D3D12_BARRIER_TYPE_GLOBAL && group.Type != D3D12_BARRIER_TYPE_TEXTURE && + group.Type != D3D12_BARRIER_TYPE_BUFFER) + return refuse("unknown barrier group type"); + if (group.NumBarriers > kMaxConsoleBarriersPerGroup) return refuse("barrier count over the limit"); + if (group.NumBarriers && !group.pGlobalBarriers) // the union's pointer, whichever member the type names + return refuse("null barrier array with a nonzero count"); + if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) continue; + texture_barriers += group.NumBarriers; + for (UINT32 i = 0; i < group.NumBarriers; ++i) + if (!group.pTextureBarriers[i].pResource) ++null_textures; + } + if (null_textures == 0) return in; + try { + storage.globals.reserve(null_textures); // exact: the groups point into it, so it never reallocates + storage.groups.reserve(count + texture_barriers); + for (UINT32 g = 0; g < count; ++g) { + const D3D12_BARRIER_GROUP& group = in[g]; + if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) { + storage.groups.push_back(group); + continue; + } + const D3D12_TEXTURE_BARRIER* barriers = group.pTextureBarriers; + for (UINT32 i = 0; i < group.NumBarriers;) { + const UINT32 start = i; + const bool no_resource = !barriers[i].pResource; + while (i < group.NumBarriers && !barriers[i].pResource == no_resource) ++i; + D3D12_BARRIER_GROUP run{}; + run.NumBarriers = i - start; + if (no_resource) { + run.Type = D3D12_BARRIER_TYPE_GLOBAL; + run.pGlobalBarriers = storage.globals.data() + storage.globals.size(); + for (UINT32 k = start; k < i; ++k) + storage.globals.push_back(D3D12_GLOBAL_BARRIER{barriers[k].SyncBefore, barriers[k].SyncAfter, + barriers[k].AccessBefore, + barriers[k].AccessAfter}); + } else { + run.Type = D3D12_BARRIER_TYPE_TEXTURE; + run.pTextureBarriers = barriers + start; + } + storage.groups.push_back(run); + } + } + } catch (const std::bad_alloc&) { + return refuse("out of memory converting the groups"); + } + out_count = static_cast(storage.groups.size()); + return storage.groups.data(); +} + +// Logged once per reason. The call is dropped whole: nothing of it reaches the PC list. +void log_refused_barrier(const char* reason, UINT32 count, const void* groups) { + static std::mutex lock; + static std::set seen; // the reasons are string literals + std::lock_guard guard(lock); + try { + if (!seen.insert(reason).second) return; + } catch (const std::bad_alloc&) { + return; + } + std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier) refused, nothing recorded: %s (%u groups at %p)\n", + reason, count, groups); +} + template std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -2635,6 +2803,36 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle. a1 = static_cast( translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a1)}).ptr); + // A view the title made with no resource: the console clear does nothing, and the PC list would + // take the view as invalid and fail its Close. Any other view goes to the PC list as before. + if (is_null_rtv(self->device, static_cast(a1))) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: list slot 52 (ClearRenderTargetView) of a view made with " + "no resource skipped, as on the console (handle 0x%llx)\n", + static_cast(a1)); + return 0; + } + } else if constexpr (Slot == kConsoleBarrier) { + // Barrier(NumBarrierGroups, pBarrierGroups): console_barrier_groups above. + ConsoleBarrierStorage storage; + UINT32 count = 0; + const char* reason = nullptr; + const D3D12_BARRIER_GROUP* groups = console_barrier_groups( + static_cast(a1), reinterpret_cast(a2), storage, count, reason); + if (reason) { + log_refused_barrier(reason, static_cast(a1), reinterpret_cast(a2)); + return 0; + } + if (groups && groups == storage.groups.data()) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier): texture barriers with no " + "resource recorded as global barriers, as on the console\n"); + } + return reinterpret_cast(real_vtable[pc])(self->real, count, + reinterpret_cast(groups), a3, a4, + a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) { // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects, // pRects): keep GPU handle, translate CPU handle. @@ -3492,7 +3690,9 @@ void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resourc void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(20); - self->real->CreateRenderTargetView(resource, desc, translate_cpu_handle(self, dest)); + const D3D12_CPU_DESCRIPTOR_HANDLE real_dest = translate_cpu_handle(self, dest); + self->real->CreateRenderTargetView(resource, desc, real_dest); + mark_null_rtv(self, real_dest.ptr, resource == nullptr); // for console list slot 52 (DeviceProxy::null_rtvs) } void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, @@ -3513,6 +3713,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE note_slot(23); if (g_custom_range_count.load(std::memory_order_acquire) == 0) { self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); + copy_null_rtv_marks(self, num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); return; } constexpr UINT kInline = 32; @@ -3547,6 +3748,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); for (UINT i = 0; dest_starts && i < num_dest; ++i) local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); + copy_null_rtv_marks(self, num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); } void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, @@ -3556,6 +3758,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); local_write_through(self, dest_start, num_descriptors); + copy_null_rtv_marks(self, 1, &dest, &num_descriptors, 1, &src, &num_descriptors, type); // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there if (leonida::local_diagnostics()) { static std::atomic copies{0}; diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index d1dd93461c..cfc1865846 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -131,11 +131,62 @@ struct Mock { UINT clear_dsv_num_rects; const D3D12_RECT* clear_dsv_rects; D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) + // list: set by a call the Vulkan layer's list takes as invalid (a texture barrier with no resource at slot 80, a + // clear at slot 48 of a view made with no resource); Close (slot 9) then fails, as that list's does. + bool list_error; + // list slot 80 (Barrier): what the last call carried, copied (the proxy's converted groups live for the call). + UINT barrier_group_count; + D3D12_BARRIER_TYPE barrier_group_types[4]; + UINT barrier_group_sizes[4]; + UINT barrier_global_count; + D3D12_GLOBAL_BARRIER barrier_globals[8]; + UINT barrier_texture_count; + D3D12_TEXTURE_BARRIER barrier_textures[8]; }; Mock g_pool[256]; unsigned g_pool_used = 0; +// The real handles the mock device last wrote an RTV with no resource at (device slot 20). A mock list's clear of one +// sets list_error, as the Vulkan layer's empty view record does. +SIZE_T g_mock_null_rtvs[16]; +unsigned g_mock_null_rtv_count = 0; + +void mock_note_rtv(SIZE_T handle, bool no_resource) { + for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) + if (g_mock_null_rtvs[i] == handle) g_mock_null_rtvs[i--] = g_mock_null_rtvs[--g_mock_null_rtv_count]; + if (no_resource && g_mock_null_rtv_count < std::size(g_mock_null_rtvs)) + g_mock_null_rtvs[g_mock_null_rtv_count++] = handle; +} + +bool mock_is_null_rtv(SIZE_T handle) { + for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) + if (g_mock_null_rtvs[i] == handle) return true; + return false; +} + +void mock_barrier(Mock* m, std::uint64_t count, std::uint64_t groups_word) { + const auto* groups = reinterpret_cast(groups_word); + m->barrier_group_count = static_cast(count); + m->barrier_global_count = m->barrier_texture_count = 0; + for (UINT g = 0; groups && g < static_cast(count); ++g) { + const D3D12_BARRIER_GROUP& group = groups[g]; + if (g < std::size(m->barrier_group_types)) { + m->barrier_group_types[g] = group.Type; + m->barrier_group_sizes[g] = group.NumBarriers; + } + for (UINT i = 0; i < group.NumBarriers; ++i) { + if (group.Type == D3D12_BARRIER_TYPE_GLOBAL && m->barrier_global_count < std::size(m->barrier_globals)) { + m->barrier_globals[m->barrier_global_count++] = group.pGlobalBarriers[i]; + } else if (group.Type == D3D12_BARRIER_TYPE_TEXTURE) { + if (!group.pTextureBarriers[i].pResource) m->list_error = true; + if (m->barrier_texture_count < std::size(m->barrier_textures)) + m->barrier_textures[m->barrier_texture_count++] = group.pTextureBarriers[i]; + } + } + } +} + void** mock_vtable(); void** mock_list_vtable(); @@ -347,6 +398,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1) std::memcpy(&m->queue_desc, reinterpret_cast(a1), sizeof(m->queue_desc)); return static_cast(mock_create(m, Kind::queue, a2, a3)); case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator + case 20: mock_note_rtv(static_cast(a3), a1 == 0); break; // CreateRenderTargetView(res, desc, dest) // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some // builds and which picks the list mock's chain breadth from full_chain_lists. @@ -468,6 +520,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { m->om_has_dsv = dsv != nullptr; m->om_dsv = dsv ? dsv->ptr : 0; } + if (m->kind == Kind::list || m->kind == Kind::command_list) { + if (slot == 9) return static_cast(m->list_error ? E_INVALIDARG : S_OK); // Close + if (slot == 48 && mock_is_null_rtv(static_cast(a1))) m->list_error = true; // ClearRenderTargetView + if (slot == 80) mock_barrier(m, a1, a2); // Barrier + } return S_OK; } @@ -2243,7 +2300,8 @@ int check_lists() { so_view.BufferFilledSizeLocation = p2; EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. - EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 + // Enhanced Barrier -> GCL7 80; an empty call (no groups) goes through as the PC no-op it is. + EXPECT(hr_of(raw(list, 146, 0, 0)) == S_OK && real->calls[80] == 1); EXPECT(release(list) == 0 && real->refs == 0); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(xs::device_proxy_ref_count(device) == device_refs); @@ -3926,10 +3984,18 @@ int check_console_command_list() { EXPECT(xs::is_command_list_proxy(list7_proxy)); Mock* real_list7 = reinterpret_cast(xs::command_list_proxy_real_list(list7_proxy)); EXPECT(real_list7 != nullptr); - // Console slot 146 -> PC slot 80 (since 80 < 81 slots) - raw(list7_proxy, 146, 0x9999, 0, 0, 0); - EXPECT(real_list7->calls[80] == 1); - EXPECT(real_list7->args[80][0] == 0x9999); + // Console slot 146 -> PC slot 80 (since 80 < 81 slots): a valid group goes through with the title's pointer. + { + const D3D12_GLOBAL_BARRIER global{D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS}; + D3D12_BARRIER_GROUP group{}; + group.Type = D3D12_BARRIER_TYPE_GLOBAL; + group.NumBarriers = 1; + group.pGlobalBarriers = &global; + raw(list7_proxy, 146, 1, word(&group), 0, 0); + EXPECT(real_list7->calls[80] == 1); + EXPECT(real_list7->args[80][0] == 1 && real_list7->args[80][1] == word(&group)); + } EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); // Clean up @@ -3949,6 +4015,215 @@ int check_console_command_list() { return 0; } +// ---- Console list slots 146 and 52: what the console takes as a no-op or a global barrier ---- +// +// The mock list stands in for the Vulkan layer's: a texture barrier with no resource, or a clear of a view made with +// no resource, puts it in its error state and its Close fails (checked directly on the mock first, so the cases +// below mean something). Through the proxy the barrier becomes a global barrier and the clear is skipped. +int check_console_null_barrier_and_clear() { + g_mock_null_rtv_count = 0; + Mock* mock = nullptr; + void* device = make_device(mock, 9, true, true, /*full_chain_lists=*/true); + EXPECT(device); + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK); + void* list = nullptr; + EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), + word(&list))) == S_OK); + Mock* const real = reinterpret_cast(xs::list_proxy_real_list(list)); + EXPECT(real && real->kind == Kind::list); + Mock* const texture_a = new_mock(Kind::resource); // never dereferenced: only the pointers are compared + Mock* const texture_b = new_mock(Kind::resource); + auto* const resource_a = reinterpret_cast(texture_a); + auto* const resource_b = reinterpret_cast(texture_b); + + // A texture barrier with no resource, as the title records it: render target to pixel-shader read. + D3D12_TEXTURE_BARRIER no_resource{}; + no_resource.SyncBefore = D3D12_BARRIER_SYNC_RENDER_TARGET; + no_resource.SyncAfter = D3D12_BARRIER_SYNC_PIXEL_SHADING; + no_resource.AccessBefore = D3D12_BARRIER_ACCESS_RENDER_TARGET; + no_resource.AccessAfter = D3D12_BARRIER_ACCESS_SHADER_RESOURCE; + no_resource.LayoutBefore = D3D12_BARRIER_LAYOUT_RENDER_TARGET; + no_resource.LayoutAfter = D3D12_BARRIER_LAYOUT_SHADER_RESOURCE; + no_resource.Subresources.IndexOrFirstMipLevel = 0xffffffffu; + D3D12_BARRIER_GROUP texture_group{}; + texture_group.Type = D3D12_BARRIER_TYPE_TEXTURE; + texture_group.NumBarriers = 1; + texture_group.pTextureBarriers = &no_resource; + + // The mock models the PC list: the same group sent to it directly fails its Close. + raw(real, 80, 1, word(&texture_group)); + EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); + real->list_error = false; + real->calls[80] = 0; + + // 1. Through the proxy: one global barrier with the same sync and access, in the call's own storage; the + // title's group and barrier are not written; Close succeeds. + EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK); + EXPECT(real->calls[80] == 1 && real->args[80][0] == 1 && real->args[80][1] != word(&texture_group)); + EXPECT(real->barrier_group_count == 1 && real->barrier_group_types[0] == D3D12_BARRIER_TYPE_GLOBAL && + real->barrier_group_sizes[0] == 1 && real->barrier_global_count == 1 && real->barrier_texture_count == 0); + EXPECT(real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && + real->barrier_globals[0].SyncAfter == D3D12_BARRIER_SYNC_PIXEL_SHADING && + real->barrier_globals[0].AccessBefore == D3D12_BARRIER_ACCESS_RENDER_TARGET && + real->barrier_globals[0].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); + EXPECT(texture_group.Type == D3D12_BARRIER_TYPE_TEXTURE && texture_group.pTextureBarriers == &no_resource && + !no_resource.pResource); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 2. Valid barriers pass unchanged: a texture group with resources goes through with the title's own pointer. + D3D12_TEXTURE_BARRIER with_resource[2] = {no_resource, no_resource}; + with_resource[0].pResource = resource_a; + with_resource[1].pResource = resource_b; + with_resource[1].Subresources = {2, 1, 0, 1, 0, 1}; + D3D12_BARRIER_GROUP valid_group{}; + valid_group.Type = D3D12_BARRIER_TYPE_TEXTURE; + valid_group.NumBarriers = 2; + valid_group.pTextureBarriers = with_resource; + EXPECT(hr_of(raw(list, 146, 1, word(&valid_group))) == S_OK); + EXPECT(real->calls[80] == 2 && real->args[80][0] == 1 && real->args[80][1] == word(&valid_group)); + EXPECT(real->barrier_texture_count == 2 && real->barrier_global_count == 0 && + real->barrier_textures[0].pResource == resource_a && real->barrier_textures[1].pResource == resource_b && + real->barrier_textures[1].LayoutAfter == D3D12_BARRIER_LAYOUT_SHADER_RESOURCE && + real->barrier_textures[1].Subresources.IndexOrFirstMipLevel == 2); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 3. Mixed: a buffer group, then a texture group of [resource, none, none, resource]. The buffer group passes as + // it is and the texture group splits into texture(1), global(2), texture(1), in order. + const D3D12_BUFFER_BARRIER buffer{D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + resource_a, 0, UINT64_MAX}; + D3D12_TEXTURE_BARRIER mixed[4] = {with_resource[0], no_resource, no_resource, with_resource[1]}; + mixed[2].SyncBefore = D3D12_BARRIER_SYNC_COMPUTE_SHADING; + mixed[2].AccessBefore = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS; + D3D12_BARRIER_GROUP mixed_groups[2]{}; + mixed_groups[0].Type = D3D12_BARRIER_TYPE_BUFFER; + mixed_groups[0].NumBarriers = 1; + mixed_groups[0].pBufferBarriers = &buffer; + mixed_groups[1].Type = D3D12_BARRIER_TYPE_TEXTURE; + mixed_groups[1].NumBarriers = 4; + mixed_groups[1].pTextureBarriers = mixed; + EXPECT(hr_of(raw(list, 146, 2, word(mixed_groups))) == S_OK); + EXPECT(real->calls[80] == 3 && real->args[80][0] == 4); + EXPECT(real->barrier_group_types[0] == D3D12_BARRIER_TYPE_BUFFER && real->barrier_group_sizes[0] == 1 && + real->barrier_group_types[1] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[1] == 1 && + real->barrier_group_types[2] == D3D12_BARRIER_TYPE_GLOBAL && real->barrier_group_sizes[2] == 2 && + real->barrier_group_types[3] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[3] == 1); + EXPECT(real->barrier_texture_count == 2 && real->barrier_textures[0].pResource == resource_a && + real->barrier_textures[1].pResource == resource_b); + EXPECT(real->barrier_global_count == 2 && + real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && + real->barrier_globals[1].SyncBefore == D3D12_BARRIER_SYNC_COMPUTE_SHADING && + real->barrier_globals[1].AccessBefore == D3D12_BARRIER_ACCESS_UNORDERED_ACCESS && + real->barrier_globals[1].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 4. Arrays that cannot be read safely are refused whole: nothing reaches the list, which stays valid and keeps + // taking calls. + D3D12_BARRIER_GROUP unknown_type = texture_group; + reinterpret_cast(unknown_type.Type) = 7; + D3D12_BARRIER_GROUP null_barriers{}; + null_barriers.Type = D3D12_BARRIER_TYPE_TEXTURE; + null_barriers.NumBarriers = 3; + D3D12_BARRIER_GROUP huge_group = valid_group; + huge_group.NumBarriers = 0x10000000u; + EXPECT(hr_of(raw(list, 146, 1, 0)) == S_OK); // null array, nonzero count + EXPECT(hr_of(raw(list, 146, 1, word(&unknown_type))) == S_OK); // a group type the layer does not know + EXPECT(hr_of(raw(list, 146, 1, word(&null_barriers))) == S_OK); // null barrier array, nonzero count + EXPECT(hr_of(raw(list, 146, 1, word(&huge_group))) == S_OK); // barrier count over the limit + EXPECT(hr_of(raw(list, 146, 0x40000000u, word(&valid_group))) == S_OK); // group count over the limit + // A malformed group after a convertible one refuses the call as well: nothing of it is recorded. + D3D12_BARRIER_GROUP half_bad[2] = {texture_group, unknown_type}; + EXPECT(hr_of(raw(list, 146, 2, word(half_bad))) == S_OK); + EXPECT(real->calls[80] == 3 && !real->list_error); + EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK && real->calls[80] == 4); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // 5. ClearRenderTargetView (console 52 -> PC 48) of a view made with no resource is skipped; a view made with a + // resource is still cleared. No custom heap range here, so the handles reach the device unchanged. + const SIZE_T rtv_none = kMockHeapCpuStart + 0x1000; + const SIZE_T rtv_real = rtv_none + kMockDescriptorInc; + const SIZE_T rtv_copy = rtv_none + 4 * kMockDescriptorInc; + const FLOAT color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + raw(device, 20, 0, 0, rtv_none); // CreateRenderTargetView(nullptr, nullptr, handle) + raw(device, 20, word(resource_a), 0, rtv_real); + EXPECT(mock->calls[20] == 2 && mock_is_null_rtv(rtv_none) && !mock_is_null_rtv(rtv_real)); + raw(real, 48, rtv_none, word(color), 0, 0); // the mock's model: the direct clear fails the list + EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); + real->list_error = false; + real->calls[48] = 0; + + EXPECT(hr_of(raw(list, 52, rtv_none, word(color), 0, 0)) == S_OK && real->calls[48] == 0); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + const D3D12_RECT rect{0, 0, 4, 4}; + raw(list, 52, rtv_real, word(color), 1, word(&rect)); + EXPECT(real->calls[48] == 1 && real->args[48][0] == rtv_real && real->args[48][1] == word(color) && + real->args[48][2] == 1 && real->args[48][3] == word(&rect)); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // A view made again at the same handle with a resource is cleared from then on. + raw(device, 20, word(resource_b), 0, rtv_none); + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == 2 && real->args[48][0] == rtv_none); + raw(device, 20, 0, 0, rtv_none); // and with no resource again: skipped again + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == 2); + + // Descriptor copies move the mark: CopyDescriptorsSimple of the empty view, then of the real one over it. + raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 2); + raw(device, 24, 1, rtv_copy, rtv_real, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 3 && real->args[48][0] == rtv_copy); + // A copy of another heap type leaves the RTV marks alone. + raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 4); + // CopyDescriptors with ranges: one destination range of two from two source ranges of one (empty, then real). + const D3D12_CPU_DESCRIPTOR_HANDLE dest_starts[1] = {{rtv_copy}}; + const UINT dest_sizes[1] = {2}; + const D3D12_CPU_DESCRIPTOR_HANDLE src_starts[2] = {{rtv_none}, {rtv_real}}; + const UINT src_sizes[2] = {1, 1}; + raw10(device, 23, {1, word(dest_starts), word(dest_sizes), 2, word(src_starts), word(src_sizes), + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 0, 0, 0}); + EXPECT(mock->calls[23] == 1); + raw(list, 52, rtv_copy, word(color), 0, 0); + EXPECT(real->calls[48] == 4); + raw(list, 52, rtv_copy + kMockDescriptorInc, word(color), 0, 0); + EXPECT(real->calls[48] == 5 && real->args[48][0] == rtv_copy + kMockDescriptorInc); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + + // The marks are the device's own: another device's clear at a handle marked on the first is forwarded (its mock + // list then takes the view as invalid, which is what that device was told). + Mock* other_mock = nullptr; + void* other = make_device(other_mock, 9, true, true, true); + EXPECT(other); + void* other_allocator = nullptr; + EXPECT(hr_of(raw(other, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&other_allocator))) == S_OK); + void* other_list = nullptr; + EXPECT(hr_of(raw(other, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(other_allocator), 0, word(&gcl_iid), + word(&other_list))) == S_OK); + Mock* const other_real = reinterpret_cast(xs::list_proxy_real_list(other_list)); + raw(other_list, 52, rtv_none, word(color), 0, 0); + EXPECT(other_real->calls[48] == 1 && other_real->args[48][0] == rtv_none); + + EXPECT(release(other_list) == 0 && other_real->refs == 0); + EXPECT(release(other_allocator) == 0); + EXPECT(release(other) == 0 && other_mock->refs == 0); + EXPECT(release(list) == 0 && real->refs == 0); + EXPECT(release(allocator) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + g_mock_null_rtv_count = 0; + std::printf("%s: list slot 146 turns texture barriers with no resource into global barriers (valid groups pass " + "unchanged, unreadable ones are refused whole) and slot 52 skips the clear of an RTV made with no " + "resource; the list stays valid\n", + g_label); + return 0; +} + // ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- struct MockPresenter { @@ -4099,6 +4374,7 @@ int main(int argc, char** argv) { check_slot74() || check_xbox_queue_slots() || check_list_cpu_handles() || + check_console_null_barrier_and_clear() || check_presentation_wiring() || check_queue_copy_page_mappings()) return 1; if (check_placed_resource_x()) return 1; From 62d8f38ae96c023eee8bb633d4f179d0bb93943c Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:51:57 -0500 Subject: [PATCH 09/18] rdna2spirv: a v_dot4_i32_i8 printed with default op_sel takes the stored fields llvm-mc decodes a VOP3P v_dot4_i32_i8 whose op_sel_hi is not [1,1,1] (op_sel bit 1 clear) but prints and re-encodes it with op_sel 0 / op_sel_hi 7, so translate() refused it as a dropped field. When those two fields are the only difference between the stored and the printed bytes, they are now read from the blob, in check_printed_encodings and in both re-anchoring paths, and the v_dot4_i32_i8 rule applies them as measured on gfx1036 (a non-default S2 half stays refused). Any other difference is still refused. This replaces #984's restore_dot4_inline_sel, which took one case of the same form (op_sel_hi [1,0,1] with an inline integer S1); that case is covered by the general check. The words llvm-mc rejects (op_sel 2 / op_sel_hi 5) are printed by shader_disasm.py (#1317) and recovered from the blob by skipped_form. The approach comes from luizwidmer/palmetto (GPL-3.0). Test: tests/semantic/test_dot4_printed_op_sel.py, hand-built words; design.md contract row and docs/fspx.md updated. --- docs/design.md | 2 +- docs/fspx.md | 7 +- tests/semantic/test_dot4_printed_op_sel.py | 117 +++++++++++++++++++++ tools/rdna2spirv.py | 65 +++++++++--- 4 files changed, 170 insertions(+), 21 deletions(-) create mode 100644 tests/semantic/test_dot4_printed_op_sel.py diff --git a/docs/design.md b/docs/design.md index b929f29993..d010053e2c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -424,7 +424,7 @@ How the generated SPIR-V expects the runtime to work: | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The translator recovers the measured unclamped form from a gap in the listing and restores the stored high-half selector when LLVM normalizes an inline integer on S1. | +| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. A word `llvm-mc` does decode but prints with the default fields (op_sel_hi other than `[1,1,1]` with op_sel bit 1 clear: it re-encodes op_sel 0 / op_sel_hi 7, so the text names the wrong halves) takes the stored op_sel and op_sel_hi from the blob, in a clean listing (`check_printed_encodings`) and when re-anchoring, only when those two fields are the whole difference (`dot4_op_sel_fields`); anything else is still refused as a dropped field. Found in an FSPX program by luizwidmer/palmetto (GPL-3.0, ported); the fields are applied by the rule measured above, checked by `tests/semantic/test_dot4_printed_op_sel.py` (hand-built words); not re-counted over the corpus. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The measured unclamped `op_sel` 2 / `op_sel_hi` 5 form is also recovered from the bytes on a gap in a listing that `shader_disasm.py` did not print it into (`skipped_form`, #984). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | diff --git a/docs/fspx.md b/docs/fspx.md index fce76fb827..10c7156c07 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -165,9 +165,10 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because that needs the package's DLL. When a listing lacks that pass, the translator decodes the same exact form from the original bytes on a gap - in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. LLVM can - also print the default high-half selector for an inline integer second source. If that selector is the only - changed bit, the translator preserves the stored low-half replication. + in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. A + `v_dot4_i32_i8` that llvm-mc decodes but prints with the default `op_sel`/`op_sel_hi` (for example an inline + integer second source whose low half is replicated) takes the stored fields from the blob when they are the + only difference (`rdna2spirv.dot4_op_sel_fields`, docs/design.md "Signed-byte dot products"). ## Kind 7: records diff --git a/tests/semantic/test_dot4_printed_op_sel.py b/tests/semantic/test_dot4_printed_op_sel.py new file mode 100644 index 0000000000..85b90feef6 --- /dev/null +++ b/tests/semantic/test_dot4_printed_op_sel.py @@ -0,0 +1,117 @@ +"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults takes the stored fields. + +llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] but prints and re-encodes it with op_sel 0 and +op_sel_hi 7, so the listing names halves the instruction does not read. translate() used to refuse it ("a field the +disassembler dropped"); it now reads the two fields from the blob when they are the only difference +(rdna2spirv.dot4_op_sel_fields), and the v_dot4_i32_i8 rule applies them as measured on gfx1036 +(tests/semantic/test_alu_dot4_i8.py). Ported from luizwidmer/palmetto (GPL-3.0). Hand-built listing and blob, the +encodings assembled from the VOP3P field layout; no game data. + + python -I tests/semantic/test_dot4_printed_op_sel.py -v +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402 + +NAME = "ps_dot4_printed_op_sel" +CODE_START = 0x100 +A, B, C = 0x80FF7F01, 0x12F0FE7F, 0x00001000 + + +def dot4(op_sel=0, op_sel_hi=7, dst=0, srcs=(1, 2, 3)): + """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, v[srcs] with the given op_sel and op_sel_hi.""" + w0 = 0xCC000000 | (0x16 << 16) | ((op_sel_hi >> 2) & 1) << 14 | (op_sel & 7) << 11 | dst + w1 = (op_sel_hi & 3) << 27 | (256 + srcs[2]) << 18 | (256 + srcs[1]) << 9 | (256 + srcs[0]) + return struct.pack("<2I", w0, w1).hex(" ") + + +def v_mov(reg, value): + return (f"v_mov_b32_e32 v{reg}, 0x{value:x}", f"ff {2 * reg:02x} 02 7e " + struct.pack("> off) & 0xFF + return v - 256 if v & 0x80 else v + total = addend + for k in range(4): + half = (op_sel if k < 2 else op_sel_hi) + xo = 16 * ((half >> 0) & 1) + 8 * (k & 1) + yo = 16 * ((half >> 1) & 1) + 8 * (k & 1) + total += byte(a, xo) * byte(b, yo) + return total & 0xFFFFFFFF + + +def translate(stored_dot4, reanchor=False): + printed = SETUP + [PRINTED] + TAIL + stored = SETUP + [("", stored_dot4)] + TAIL + code = b"".join(bytes.fromhex(enc) for _, enc in stored) + data = listing(printed, CODE_START + len(code)) + blob = bytes(CODE_START) + code + if reanchor: # a listing with an undecodable word after the code goes through the re-anchoring path + data += b"; warning: invalid instruction encoding\n" + blob += b"\xff" * 4 + return translate_listing(NAME, data, fssm=blob) + + +class Dot4PrintedOpSelTest(unittest.TestCase): + def test_reference_is_the_plain_dot_product_for_the_defaults(self): + sb = [lambda x, k=k: (((x >> 8 * k) & 0xFF) ^ 0x80) - 0x80 for k in range(4)] + self.assertEqual(ref(A, B, C), (sum(f(A) * f(B) for f in sb) + C) & 0xFFFFFFFF) + + def test_default_fields_translate_as_printed(self): + self.assertEqual(mrt0_words(translate(dot4())), [ref(A, B, C)] * 4) + + def test_stored_op_sel_hi_is_read_from_the_blob(self): + # op_sel_hi [1,0,1]: byte pairs 2..3 of S1 come from its low half. llvm-mc decodes it and prints [1,1,1]. + for reanchor in (False, True): + with self.subTest(reanchor=reanchor): + got = mrt0_words(translate(dot4(op_sel_hi=5), reanchor)) + self.assertEqual(got, [ref(A, B, C, op_sel_hi=5)] * 4) + self.assertNotEqual(ref(A, B, C, op_sel_hi=5), ref(A, B, C)) + + def test_stored_op_sel_on_source_0_is_read_from_the_blob(self): + got = mrt0_words(translate(dot4(op_sel=1, op_sel_hi=6))) + self.assertEqual(got, [ref(A, B, C, op_sel=1, op_sel_hi=6)] * 4) + + def test_a_non_default_s2_half_stays_refused(self): + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=3)) + self.assertIn("op_sel", str(cm.exception)) + + def test_another_difference_is_still_a_dropped_field(self): + # The stored word names v4 as S2, the printed one v3: not an op_sel difference. + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(dot4(op_sel_hi=5, srcs=(1, 2, 4))) + self.assertIn("dropped", str(cm.exception)) + + def test_fields_helper(self): + printed = bytes.fromhex(dot4()) + self.assertEqual(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot4_i32_i8"), (0, 5)) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(printed, printed, "v_dot4_i32_i8")) + self.assertIsNone(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, + "v_dot2_i32_i16")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 08e497bbea..9d926b0302 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17429,19 +17429,6 @@ def same_encoding(raw, printed, op, operand_count): return diff == 0 -def restore_dot4_inline_sel(ins, raw, printed): - """LLVM prints default op_sel_hi on a signed-byte dot with a replicated low inline integer half.""" - if ins["op"] != "v_dot4_i32_i8" or len(raw) != 8 or len(printed) != 8: - return False - w0, w1 = struct.unpack("> 8 != 0xCC1640 or w1 >> 27 != 1 or not 128 <= (w1 >> 9 & 511) <= 208 or - struct.pack("> 16) & 0x7F != 0x16: + return None + op_sel = (w0 >> 11) & 7 + op_sel_hi = ((w1 >> 27) & 3) | (((w0 >> 14) & 1) << 2) + if (op_sel, op_sel_hi) == (0, 7): + return None + if struct.pack("<2I", (w0 & ~(7 << 11)) | (1 << 14), w1 | (3 << 27)) != printed: + return None + return op_sel, op_sel_hi + + +def restore_dot4_op_sel(ins, raw): + """Give ``ins`` the op_sel/op_sel_hi dot4_op_sel_fields reads from the stored bytes, and those bytes as its + encoding; False (``ins`` untouched) when it does not apply. The v_dot4_i32_i8 rule applies the fields as measured + on gfx1036 (docs/design.md, "Signed-byte dot products") and refuses a non-default S2 half.""" + fields = dot4_op_sel_fields(raw, bytes.fromhex(ins["enc"]), ins["op"]) + if fields is None: + return False + op_sel, op_sel_hi = fields + mods = [m for m in ins.get("mods", []) if not m.startswith(("op_sel:", "op_sel_hi:"))] + if op_sel: + mods.append("op_sel:[%s]" % ",".join(str((op_sel >> k) & 1) for k in range(3))) + if op_sel_hi != 7: + mods.append("op_sel_hi:[%s]" % ",".join(str((op_sel_hi >> k) & 1) for k in range(3))) + ins["mods"] = mods + ins["enc"] = raw.hex() + return True + + def skipped_form(ins, blob, at): """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare in DPP @@ -17846,8 +17875,6 @@ def check_printed_encodings(path, info): restore_sdwa_source(ins, raw) shift -= 4 continue - if restore_dot4_inline_sel(ins, raw, enc): - continue literal = mix_literal(raw, enc, base_op(ins["op"])) if literal is not None: restore_mix_literal(ins, raw, literal) @@ -17858,6 +17885,8 @@ def check_printed_encodings(path, info): restore_mix_inline_literal(ins, raw12, literal) shift += 4 continue + if restore_dot4_op_sel(ins, raw): + continue raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " f"{enc.hex()} (a field the disassembler dropped)") @@ -17957,6 +17986,8 @@ def translate(path): if literal is not None: restore_mix_inline_literal(ins, blob[pos:pos + 12], literal) enc = blob[pos:pos + 12] + elif restore_dot4_op_sel(ins, window): + pass elif pos + len(enc) > len(blob): raise Unsupported("undecodable words (cannot re-anchor)") else: @@ -17966,8 +17997,6 @@ def translate(path): continue skipped, at = 0, pos while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): - if restore_dot4_inline_sel(ins, blob[at:at + len(enc)], enc): - break literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) if literal is not None: restore_mix_literal(ins, blob[at:at + len(enc)], literal) @@ -17982,6 +18011,8 @@ def translate(path): restore_mix_inline_literal(ins, blob[at:at + 12], literal) enc = blob[at:at + 12] # the 12 bytes the decoder read: the next one starts after them break + if restore_dot4_op_sel(ins, blob[at:at + len(enc)]): + break at += 4 skipped += 4 if skipped > 4096 or at >= len(blob): From bb0b8848dd2043b0528db8ed53e49c1fe8a57bad Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:54:41 -0500 Subject: [PATCH 10/18] s_bitreplicate_b64_b32 of a lane-mask half into data: test and contract-table sentence #998 added the rule (a 32-bit EXEC/VCC half as S0, read through Gen.wave_mask) without a test or a design.md entry. test_lane_mask_bitreplicate_flbit.py now runs it on every lane of a wave64 in the CPU interpreter, from exec_lo/exec_hi and from a compare's vcc_lo/vcc_hi, against the ISA pseudocode. design.md says it is interpreter-checked only, not measured on hardware, and that a VCC destination stays wave64-only (#984's rule). --- docs/design.md | 2 +- .../test_lane_mask_bitreplicate_flbit.py | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index d010053e2c..fe1bb7bf26 100644 --- a/docs/design.md +++ b/docs/design.md @@ -470,7 +470,7 @@ How the generated SPIR-V expects the runtime to work: | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | | 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair normally carries 64-bit data. In wave64, `s_flbit_i32_b64` can also gather both halves of a lane mask or EXEC before scanning it. The other operations require scalar data. `test_library_compute_forms.py` checks an empty mask and set bits in either half on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` runs EXEC and VCC masks on every lane of a wave64 (the 1.0.2.1 pipeline library reads EXEC this way). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. The source must carry scalar data. Bit replication can also write EXEC, or VCC in wave64. Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` checks VCC, which the 1.0.2.1 pipeline library writes from a constant, on every lane of a wave64. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. Bit replication can also write EXEC, or VCC in wave64 (in wave32 VCC's high word is data, so it stays `Unsupported`). Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` checks VCC, which the 1.0.2.1 pipeline library writes from a constant, on every lane of a wave64. A 32-bit lane-mask source (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`) of `s_bitreplicate_b64_b32` into a scalar (non-EXEC/VCC) destination reads that half of the wave's mask as data (`Gen.wave_mask`, as `s_ff1_i32_b64` reads one) and replicates it as any scalar (#998, for 6 pipeline-library programs of 1.0.2.1). Confirmed only by the CPU interpreter on every lane of a wave64 (`test_lane_mask_bitreplicate_flbit.py`: EXEC halves and a compare's VCC halves, synthetic lines) and by the ISA pseudocode above; not measured on hardware. Any other lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`), and a lane-mask source with an EXEC/VCC destination, raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/tests/semantic/test_lane_mask_bitreplicate_flbit.py b/tests/semantic/test_lane_mask_bitreplicate_flbit.py index 66743bd2cc..ecc55775b2 100644 --- a/tests/semantic/test_lane_mask_bitreplicate_flbit.py +++ b/tests/semantic/test_lane_mask_bitreplicate_flbit.py @@ -4,6 +4,8 @@ RDNA2 ISA, SOP1: - s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. Into VCC, lane L's bit is S0 bit L // 2. + Of a 32-bit lane-mask source (exec_lo/exec_hi, vcc_lo/vcc_hi) into scalar data, S0 is that half of the wave's + mask, read as data (Gen.wave_mask), then replicated as any scalar. - s_flbit_i32_b64: the zeros above the first 1 from bit 63, -1 when S0 is 0. Of EXEC that is 63 minus the wave's last active lane. Synthetic programs only. @@ -60,6 +62,36 @@ def test_flbit_of_vcc(self): "s_endpgm"]) self.assertEqual(mem[OUT_AT], flbit_model((1 << n) - 1)) + def bitreplicate_of(self, setup, src): + mem = run(lane_index() + setup + [f"s_bitreplicate_b64_b32 s[10:11], {src}", "s_mov_b64 exec, -1", + "v_cmpx_eq_u32_e32 0, v1", "v_mov_b32_e32 v20, s10", + "v_mov_b32_e32 v22, s11", f"v_mov_b32_e32 v21, {OUT_AT}", + "buffer_store_dword v20, v21, s[0:3], 0 offen", + "buffer_store_dword v22, v21, s[0:3], 0 offen offset:4", "s_endpgm"]) + return mem[OUT_AT] | mem[OUT_AT + 4] << 32 + + def test_bitreplicate_of_exec_half_into_data(self): + # Every lane that runs the instruction reads the same 32 mask bits; each becomes two bits of s[10:11]. + for mask in (h.ALL64, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000, 0x8000000180000001, 0x0F0F0F0F12345678): + for half, src in ((0, "exec_lo"), (1, "exec_hi")): + with self.subTest(exec=hex(mask), src=src): + word = (mask >> (32 * half)) & 0xFFFFFFFF + got = self.bitreplicate_of([f"s_mov_b32 exec_lo, {mask & 0xFFFFFFFF:#x}", + f"s_mov_b32 exec_hi, {mask >> 32:#x}"], src) + self.assertEqual(got, bitreplicate_model(word)) + + def test_bitreplicate_of_a_compare_into_data(self): + # VCC from a compare: lanes l < n. Its low and high halves replicated as data. + for n in (0, 1, 17, 32, 45, 64): + for half, src in ((0, "vcc_lo"), (1, "vcc_hi")): + with self.subTest(n=n, src=src): + got = self.bitreplicate_of([f"v_cmp_gt_u32_e32 vcc, {n}, v1"], src) + self.assertEqual(got, bitreplicate_model((((1 << n) - 1) >> (32 * half)) & 0xFFFFFFFF)) + + +def bitreplicate_model(word): + return sum(3 << (2 * i) for i in range(32) if (word >> i) & 1) + if __name__ == "__main__": unittest.main() From 3f220075079a3d21d91bd21bf19e1d3122697eff Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:55:05 -0500 Subject: [PATCH 11/18] test_rdna2spirv_decode: the undecodable dot4 word is the measured one with clamp set The two boundary tests need a v_dot4_i32_i8 word that no pass recovers. The measured op_sel 2 / op_sel_hi 5 word is now decoded (skipped_form); the same word with clamp set stays a gap (llvm-mc rejects it, and shader_disasm.py and skipped_form take only the unclamped form), so the tests do not depend on which other op_sel values are measured later. --- tests/test_rdna2spirv_decode.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/test_rdna2spirv_decode.py b/tests/test_rdna2spirv_decode.py index 25be275301..f4bac89f0b 100644 --- a/tests/test_rdna2spirv_decode.py +++ b/tests/test_rdna2spirv_decode.py @@ -386,10 +386,9 @@ def test_fall_through_into_undecodable_words_is_refused(self): mov1 = [0xF2, 0x02, 0x02, 0x7E] export = [0x0F, 0x18, 0x00, 0xF8, 0x00, 0x01, 0x00, 0x01] endpgm = [0x00, 0x00, 0x81, 0xBF] - # The word of the finding was [0x00,0x50,0x16,0xCC, 0x01,0x05,0x0E,0x0C]; the translator recovers that one - # v_dot4_i32_i8 form from the program's words now (rdna2spirv.skipped_form), so it is no longer a gap. - # This is the same instruction with another op_sel, which is not recovered and stays skipped. - gap = [0x00, 0x58, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] + # The finding's word with clamp set: the measured op_sel 2 / op_sel_hi 5 form is now decoded from the blob + # (rdna2spirv.skipped_form), this one is not. + gap = [0x00, 0xD0, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] def enc(words): return ",".join(f"0x{b:02x}" for b in words) @@ -424,7 +423,7 @@ def test_fall_through_into_undecodable_words_at_the_end_of_the_range_is_refused( # code range the header declares, so the path runs into them as well mov0 = [0xF2, 0x02, 0x00, 0x7E] mov1 = [0xF2, 0x02, 0x02, 0x7E] - gap = [0x00, 0x58, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] # a form that is not recovered, as above + gap = [0x00, 0xD0, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] # clamp set: not a form restored from the blob def enc(words): return ",".join(f"0x{b:02x}" for b in words) From f0611b752fd2c7b52f25688be7d6c17909ee3533 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:00:37 -0500 Subject: [PATCH 12/18] Remove the title's executable addresses #984 brought in; read them from the environment #984 (273b3bdf9) put RVAs and file offsets of the retail executable into code, docs and scripts. The code paths that need one now read it from an environment variable and are off when it is unset; the docs and examples say the location is measured locally. - runtime/src/main.cpp: the hang-watchdog kick takes its trap and kick RVAs from LEONIDA_TITLE_WATCHDOG_KICK="," (hex), still only when the trap instruction is at the first one. Unset, the watchdog stays armed, as before by default; LEONIDA_TITLE_WATCHDOG=1 keeps it armed, and LEONIDA_TITLE_WATCHDOG=0 without the RVAs says once that it needs them. The LEONIDA_PEEK example uses placeholders. - runtime/shims/startup_trace.h: the transient-pool dump fires at the int3 that LEONIDA_POOL_DIAG_AT names (`+0x`, as the trace prints it), off when unset. - scripts/windows-boot/boot.ps1: LEONIDA_PEEK's default comes from LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA (no peek when unset), and the RESULT digest matches those values; the examples and README use placeholders. - runtime/README.md documents LEONIDA_TITLE_WATCHDOG_KICK and LEONIDA_POOL_DIAG_AT. - docs/fspx.md, docs/d3d12_vulkan.md, docs/movies.md, docs/embedded_shaders.md and a comment in runtime/shims/d3d12_xs_alloc_size.h drop the addresses and offsets. This follows the same change on the earlier integration branch (#1495). --- docs/d3d12_vulkan.md | 2 +- docs/embedded_shaders.md | 4 +-- docs/fspx.md | 2 +- docs/movies.md | 4 +-- runtime/README.md | 3 +- runtime/shims/d3d12_xs_alloc_size.h | 2 +- runtime/shims/startup_trace.h | 15 ++++++--- runtime/src/main.cpp | 49 ++++++++++++++++++++--------- scripts/windows-boot/README.md | 6 ++-- scripts/windows-boot/boot.ps1 | 14 ++++++--- 10 files changed, 67 insertions(+), 34 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e23985ecb3..3022a79959 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -96,7 +96,7 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye out)`, `n` = 1..4 records of 0x14c bytes: a u32 tag, then the payload at +4) patches a copy of that stream and creates the PSO through the same path. Tags 0 (`D3D12_DEPTH_STENCIL_DESC`, on DEPTH_STENCIL or DEPTH_STENCIL1), 1 (`D3D12_RASTERIZER_DESC`), 2 (`D3D12_BLEND_DESC`) and 3 (sample mask) are the TomBox layout (GPL-3.0, - `create_derived_pso_x`), checked against the title's record writes in the retail build (RVA 0x2479f40): tag 1 is the + `create_derived_pso_x`), checked against the title's record writes in the retail build: tag 1 is the rasterizer (0x2c bytes, always record 0 when present), tag 0 the DEPTH_STENCIL (0x34), tag 2 the BLEND (0x148). Tag 3 (sample mask, from TomBox) is served although that function does not write it. Tag 5 (0x16 bytes: 16 zero bytes, then the StencilReadMask and StencilWriteMask bytes at the DEPTH_STENCIL offsets 0x10/0x11, then zeros) overlays only those two bytes of the base's diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index 6ccdbaf417..04569f7115 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -294,8 +294,8 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build, emulated modules made at the default cap, `RadixAlloc` is refused (`declares 37084 bytes of workgroup memory`, `0x80004001`) after 28 creations. -**Packed pixel shaders.** The executable also holds two native pixel shaders in SGD5 records. Their header file -offsets are `0x688ecf6` and `0x688f17f`. Both stored lengths include the 12-byte header. Raw deflate yields a +**Packed pixel shaders.** The executable also holds two native pixel shaders in SGD5 records (their file offsets +are measured locally and not kept here). Both stored lengths include the 12-byte header. Raw deflate yields a complete DXBC of 1,324 or 1,052 bytes. Their FSSM SHA-256 keys are `cae1e27820adde6a6cb35e308290164ad8cf7107f0fe147d50a2053d7ceeb4b8` and `879cb2e326c5e5333935a0b2b1dd9c3c2adc1b03e546d1f84f993d912b4f66b0`. The first is diff --git a/docs/fspx.md b/docs/fspx.md index 10c7156c07..6493dc2b71 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -250,7 +250,7 @@ with a blob holding the dword 0, so the DLL creates no compute scratch buffer; w Not done here: using kind 0 at run time beyond what the translated module already carries (its thread-group size and `RSRC2`). -**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At `game_scarlett_master.exe+0x2477578`, the retail +**Slot 57 (`DeserializeGraphicsPipelineStateX`, graphics FSPX).** At one call site (measured locally), the retail title calls device slot 57 (`+0x1c8`) with `IID_ID3D12PipelineState` (`{765a30f3-f624-4c6f-a828-ace948622445}`) and a 104-byte description (`+0x00..+0x60`) populated from the zlib-compressed pipeline library in `shaders.rpf` ([shader_library.md](shader_library.md): 25,471 graphics records + 2,693 compute records): diff --git a/docs/movies.md b/docs/movies.md index e8df76d295..f7c1b06183 100644 --- a/docs/movies.md +++ b/docs/movies.md @@ -322,8 +322,8 @@ The loader-side runs behind these numbers are recorded in [`runtime/test/bink_de 1-, 2-, and 4-track samples; later frames were not swept and may return 7,680 or 0 bytes). Which language or mix role the game assigns to track IDs `0, 1, 2, 3` at run time remains unknown. - **Startup playback.** In two boots the title opened the archive twice about 1.2 s after entering the loader. - The separately loaded `Bink2Scarlett.dll` opens metadata at title RVA `0x442ebe6`; playback retains the handle - at `0x442f056` and registers mapped frame buffers at `0x442f9b8`. The frame wrapper at `0x2ef0e0` has a CPU + The separately loaded `Bink2Scarlett.dll` opens the metadata from the title; playback retains the handle + and registers mapped frame buffers. The title's frame wrapper has a CPU multi-worker decode and wait path and a synchronous fallback. Three rotating sets of linear R8 planes (one 3840×2160 and two 1920×1080 per set) reach the slot-133 texture uploader. `VS_Bink` / `PS_BinkNoAlpha` bind the three plane descriptors at table offsets 0x20, 0x40 and 0x60 and draw to an RGBA8 intermediate. The UI diff --git a/runtime/README.md b/runtime/README.md index aa9b2d3081..65b4529b5e 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -334,7 +334,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | | `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | -| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. | +| `LEONIDA_TITLE_WATCHDOG_KICK` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `,` (hex, measured locally and not kept in the repository) makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only when the watchdog's trap instruction is at the first RVA. `LEONIDA_TITLE_WATCHDOG=1` keeps it armed even then. | +| `LEONIDA_POOL_DIAG_AT` | unset | *Diagnostic.* `+0x` of the title's transient-pool assert, as the trace prints it (measured locally): the trace dumps the pool's resource list when that int3 is hit (`shims/startup_trace.h`). | | `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | | `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 7f1948eccd..5dc3a2dc4e 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -175,7 +175,7 @@ inline UINT64 console_depth_stencil_size(const D3D12_RESOURCE_DESC& desc) { // // Why exact: the title keeps this size in its streaming tables and reads exactly that many bytes of the texture // from its archives through DirectStorage; a compressed chunk must be read whole, and the title stops on an int3 -// (game+0x4ffd879) when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a +// when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a // request of 0x2000 bytes for a chunk that spans 0x4000, the PC answer for the texture being half the console's. inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size, UINT64& alignment) { constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index e6dd3c4737..2d404eaff6 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -165,8 +165,10 @@ inline std::string debug_text(const EXCEPTION_RECORD& r) { return utf8_from_ansi(a, static_cast(n ? n - 1 : strlen(a))); } -// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at the int3 at -// game+0x2473e88 the title has just computed the peak of a list of resources with lifetimes against a fixed pool. +// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at that assert's int3 +// the title has just computed the peak of a list of resources with lifetimes against a fixed pool. The int3's +// location is measured locally and not kept here: LEONIDA_POOL_DIAG_AT names it as the trace prints it +// (`+0x`), and the dump is off without it. // rdi = the list (24-byte records: entry pointer, u32 size rounded to 64 KiB), r13 = the count, rax = the peak, // rcx = the pool size. An entry is {record pointer, ..., u32 first pass at +16, u32 last pass at +20}; a record has // its usage word at +14, kind word at +16 and, for a texture, width/height/depth words at +56/+58/+60, the dimension @@ -202,8 +204,13 @@ inline void dump_transient_pool(const CONTEXT& c) { inline void log_exception(const EXCEPTION_POINTERS& info) { const EXCEPTION_RECORD& r = *info.ExceptionRecord; try { - if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && - where(reinterpret_cast(r.ExceptionAddress)).ends_with("master.exe+0x2473e88")) + static const std::string pool_diag_at = [] { + char at[128]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_POOL_DIAG_AT", at, sizeof(at)); + return n && n < sizeof(at) ? std::string(at, n) : std::string(); + }(); + if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && !pool_diag_at.empty() && + where(reinterpret_cast(r.ExceptionAddress)).ends_with(pool_diag_at)) dump_transient_pool(*info.ContextRecord); if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { const ULONG_PTR fallback = wide_fallback; diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 8e37677400..83f5bd70d5 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -32,24 +32,45 @@ namespace { -// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop -// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to -// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than -// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the -// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and -// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a -// second so the title's watchdog never fires. -constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35; -constexpr std::uint32_t kWatchdogKickRva = 0x71b6331; +// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30 +// one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the +// game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold +// cache (first boot after a driver update), and the title then kills itself. By default the watchdog stays armed, as +// on the console. The two places are measured locally and not kept in the repository: +// LEONIDA_TITLE_WATCHDOG_KICK="," (hex) names them, and only when that exact trap instruction +// sits at the first one does a runtime thread set the byte at the second twice a second, so the title's watchdog +// never fires. Unset, or with LEONIDA_TITLE_WATCHDOG=1, the watchdog stays armed. constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 +bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) { + char value[64]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG_KICK", value, sizeof(value)); + if (!n || n >= sizeof(value)) return false; + char* rest = nullptr; + const unsigned long long trap = std::strtoull(value, &rest, 16); + if (!rest || *rest != ',') return false; + const unsigned long long kick = std::strtoull(rest + 1, &rest, 16); + if (!rest || *rest || !trap || !kick || trap > 0xFFFFFFFFull || kick > 0xFFFFFFFFull) return false; + trap_rva = static_cast(trap); + kick_rva = static_cast(kick); + return true; +} + void keep_title_watchdog_kicked(std::uint8_t* base) { - char value[4]{}; - if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return; + char keep[4]{}; + const DWORD keep_length = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)); + if (keep_length == 1 && keep[0] == '1') return; + std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0; + if (!watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva)) { + if (keep_length == 1 && keep[0] == '0') + std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=," + " (hex); the title's hang watchdog stays armed\n"); + return; + } MEMORY_BASIC_INFORMATION trap{}, kick{}; if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) - return; // not the build this was measured on: leave the title's watchdog alone + return; // not the trap the RVAs name: leave the title's watchdog alone const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || !(kick.Protect & writable)) @@ -67,11 +88,11 @@ void keep_title_watchdog_kicked(std::uint8_t* base) { const_cast(byte), 0, nullptr); if (thread) { CloseHandle(thread); - std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG=0; unset or 1 keeps it armed)\n"); + std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG_KICK)\n"); } } -// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the +// LEONIDA_PEEK=":3,," (diagnostic): a thread prints the 8-byte values at these RVAs of the // title's image (":n" = n consecutive values) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this // global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly // that. Reads are checked; nothing is written. diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3a875af4bb..b4ad475665 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md @@ -15,7 +15,7 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GT powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv # Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. -powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818" +powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,," # Every parameter. Get-Help -Full .\scripts\windows-boot\boot.ps1 @@ -38,7 +38,7 @@ Only when your shell has not set them already (`-DryRun` prints the final list): | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | | `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | | `LEONIDA_PIPELINE_CACHE_DIR` | `\pipeline-cache` | one warmed cache shared by every build you boot | -| `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports | +| `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `5` | game state and session state (low dword), the two numbers every RESULT reports | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | @@ -72,7 +72,7 @@ frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). -How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing +How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) section 2 has the healthy sequence with times and section 3 "which blank do you have". diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index d052a79da9..36bcee7a6b 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -66,7 +66,7 @@ .PARAMETER EnvPairs Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with - powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0". + powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=,". Applied after -SetEnv. KEY= removes the variable for this boot. .PARAMETER NoCapture @@ -97,7 +97,7 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv .EXAMPLE - powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898" + powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=," .EXAMPLE powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first @@ -234,7 +234,8 @@ $defaults = [ordered]@{ LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") - LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword) + # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when + # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. LEONIDA_PEEK_SECONDS = "5" LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) LEONIDA_CAPTURE_EVERY = "60" @@ -243,6 +244,9 @@ $defaults = [ordered]@{ DISABLE_VULKAN_OBS_CAPTURE = "1" } if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } +$gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +$sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' +if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } # Per-run values: always this script's (from its parameters), whatever the shell has. $perRun = [ordered]@{ LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) @@ -393,8 +397,8 @@ if (Test-Path -LiteralPath $LogFile) { $game = "?"; $session = "?" foreach ($v in $valRx.Matches($m.Groups[2].Value)) { $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value - if ($rva -eq "7446510") { $game = $val } - elseif ($rva -eq "98f828c" -and $val -ne "?") { + if ($gameStateRva -and $rva -eq $gameStateRva) { $game = $val } + elseif ($sessionStateRva -and $rva -eq $sessionStateRva -and $val -ne "?") { $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword $session = $(if ($low) { $low } else { "0" }) } From 6c8a89dea7e0521714834383a847e36dcf437036 Mon Sep 17 00:00:00 2001 From: ubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:08:50 -0500 Subject: [PATCH 13/18] docs: the scripted-pad route through the first-run pages to the story load (RT-BOOT-COMBINED) The legal-terms page keeps Confirm greyed out until both boxes are ticked, and down stops at Confirm, so an a/down-only script sits there. Record the page order, what each page needs and the retry block that reached the loading screen on native Windows; one README status sentence links it. --- README.md | 5 ++++- docs/README.md | 2 +- docs/first_run_ui.md | 13 +++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 807cabd010..1c7c8459d4 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,10 @@ Original author's Git Mirror: https://git.notrexed.dev/notrexed/Leonida **Early. Nothing is playable yet.** On `main`, the game boots from your own copy on native Windows and on Linux through Proton: it shows the launch movie, the first-run pages and the landing prompt, which respond to a pad or the keyboard pad, then runs the story load to its end and enters the world phase. A first world frame has not been -verified yet on any test machine. [First-run UI on Windows](docs/first_run_ui.md) has the build and launch steps; +verified yet on any test machine. On native Windows a scripted pad alone (`LEONIDA_INPUT_SCRIPT`, no keyboard or +controller) gets through every first-run page, including the legal-terms page whose Confirm waits for both boxes, to +the loading screen of the story load ([the route](docs/first_run_ui.md#through-the-first-run-pages-with-the-scripted-pad)). +[First-run UI on Windows](docs/first_run_ui.md) has the build and launch steps; [the Linux/Proton report](docs/linux_proton.md) has the timings and where it stops. | What | Status | diff --git a/docs/README.md b/docs/README.md index d6bca1754e..2a19ab96d1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -67,7 +67,7 @@ method, scope and caveats. No game data is included. |---|---| | [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. | | [mobile.md](mobile.md) | arm64/mobile path: the x86-64 → arm64 static-recompiler groundwork (`tools/x64_recomp.py`), the `.pdata` coverage census (`tools/recomp_census.py`), and what still blocks iOS. | -| [first_run_ui.md](first_run_ui.md) | Build the Windows integration and display the offline first-run controller prompts. | +| [first_run_ui.md](first_run_ui.md) | Build the Windows integration and display the offline first-run controller prompts; the scripted-pad route through the first-run pages to the story load. | | [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. | | [retail_boot_chain.md](retail_boot_chain.md) | How far `gta6rt --run` gets with the retail executable: the stops in order and what clears each, the physical-page export shapes, and device slots 26, 48 and 73. | | [retail_boot_intel_host.md](retail_boot_intel_host.md) | The retail boot on an Intel host with 16 GB: which stops of the two boot pages hold there with #7111, the commit-limit stop at the 6.1 GiB physical-page request that #7556 clears, the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth (the console mesh-shader subobject among it). | diff --git a/docs/first_run_ui.md b/docs/first_run_ui.md index 66b147ddbb..dbdfde12f4 100644 --- a/docs/first_run_ui.md +++ b/docs/first_run_ui.md @@ -32,6 +32,19 @@ Run the title offline. The Winsock shim permits loopback and the WinHTTP shim re The profile selects Vulkan, a 2 GiB graphics address arena, on-demand pipelines, console root-argument layout, frame pacing and the keyboard gamepad in its focused mode (`LEONIDA_KEYBOARD_PAD=1`: keys count only while the title window has focus, so typing into another program presses nothing on a consent page; scripted presses still run). GPU completion labels (`LEONIDA_GPU_LABELS`) are not part of it: the list values land the title's list writes, and two writers of one address could rewind a counter. Explicit environment settings take precedence; a variable that is set but empty does not count. Speech synthesis through the host's own runtime is not part of the profile: `LEONIDA_LOCAL_SPEECH=1` turns it on, and without it the silent voice answers. The switches are listed in [`runtime/README.md`](../runtime/README.md). The package directory is the working directory. Guest output goes under `first-run-ui/overlay` beside the runtime, and sparse physical-memory backing uses `first-run-ui/xmem` on that volume. Use `--overlay DIR` or the absolute directory in `LEONIDA_XMEM_BACKING_DIR` to choose other writable locations. +## Through the first-run pages with the scripted pad + +Measured on 25 November 2026 on native Windows 11 with `scripts/windows-boot/boot.ps1`, an AMD Radeon RX 6800 (driver 32.0.21030.2001) and the shaders of an existing work folder, using no keyboard or controller, only `LEONIDA_INPUT_SCRIPT` (`-InputScript`). After the landing prompt takes A, the title shows these pages in order. None of them reaches the network: the WinHTTP shim refuses outbound requests. + +1. **Navigation experience** (first-run setup): A on the focused option moves on. +2. **Brightness**: A moves on. +3. **Legal notices**: a list of entries. A on an entry opens it instead of moving on. A repeating `a`, `down`, `down` cycle (one cycle every 10 s) got through. +4. **Legal terms and policies**: two check boxes (privacy policy, terms of service) and a Confirm button. Confirm stays greyed out and ignores A until both boxes are ticked. Focus starts on the first box. `down` stops at Confirm, so a script that only presses `a` and `down` gets stuck there with one box unticked. The page looks stuck but is waiting for the box. The steps that worked are `up` to the unticked box, `a` to tick it, `down` to Confirm, then `a`. While a box is focused, the right stick scrolls the text beside it (`rsdown`). The run that ticked the privacy box had scrolled to the end first; whether the box needs that is not measured. + +Confirm shows one black frame and then a dark loading screen with a spinner. The spinner was still turning when the 400-second run ended, about 100 s after Confirm. The frame rate dropped to about 5 presents a second, the session state left its landing value, and there were no device faults. + +Timings move by 10 to 20 s between runs on the same machine, because the pipeline cache warms up and the landing prompt arrives earlier. A fixed timeline can therefore press A on the wrong item. A later block that goes back with `up` and retries the legal-terms page makes the script more robust. The run above used the cycle up to about 230 s, then `up,up`, fifteen `rsdown`, `a`, `down,down`, `a`, and from 290 s `up,a,down,a`. The second block is the one that confirmed. + ## Contributions The frame-loop stack comes from [#321](https://github.com/ubiquitarianism/leonida/pull/321). The archive and shader catalog, shader translation, depth and texture support, presentation window and rectangle-list changes retain their upstream commits. Native and derived pipeline support incorporates the work of enx, TomBox, LooperSalty and KkelebekK. Four patches of the published [graphics runtime patches](https://github.com/Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches/tree/d9a0bc1b070d8a36c81b182bc67edd7d24b41bf2) (GPL-3.0, author smg, committed as "Codex") are in this integration almost as published, about 390 lines: `graphics-root-layout` (the switch between the two packings of graphics root arguments, `runtime/shims/d3d12_com.h`), `descriptor-table-refresh` (the title's descriptors pulled into a bound table, and the table scan in the submitting device, `runtime/shims/d3d12_xs_device.cpp` and `runtime/src/vulkan_backend.h`), `descriptor-write-through` (descriptors the layer writes also stored at the title's address, `runtime/shims/d3d12_xs_device.cpp` and `.h`) and `sampler-table-refresh` (title-backed sampler tables, `runtime/shims/d3d12_vulkan_device.cpp`), with their tests in `runtime/test/d3d12_title_va_test.cpp` and `runtime/test/d3d12_m2_textured_test.cpp`. Each region names its patch in a comment. From f25bd7765de5e35027b43d36942d1fdfae762ad0 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 21:50:35 -0500 Subject: [PATCH 14/18] shader_disasm: pass wave32 through the dot4 op_sel re-decode (#1317 head) The copy of #1317 in this branch called with_dot4_op_sel(code, mcpu, bad, err) and run_mc(bytes(patched), mcpu) without wave32, so a wave64 program whose v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word was re-decoded printed its lane masks as vcc_lo. Take #1317's current head (62237d0e5, by tedin7): with_dot4_op_sel takes wave32 and hands it to run_mc. Also its newline="\n" on the test's JSON write, and the two blank lines before MAX_DATA_DWORDS. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_fspx_dot4_op_sel_disasm.py | 2 +- tools/shader_disasm.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/semantic/test_fspx_dot4_op_sel_disasm.py b/tests/semantic/test_fspx_dot4_op_sel_disasm.py index 7ff52527f4..f27b9f9403 100644 --- a/tests/semantic/test_fspx_dot4_op_sel_disasm.py +++ b/tests/semantic/test_fspx_dot4_op_sel_disasm.py @@ -81,7 +81,7 @@ def translate_fspx(name, listing, code): f.write(STUB_DXBC) with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: f.write(code) - with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8") as f: + with open(os.path.join(tmp, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: json.dump({}, f) src = os.path.join(tmp, "disasm", name + ".s") with open(src, "w", encoding="utf-8", newline="\n") as f: diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 9b5440e738..a81ae1871f 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -110,7 +110,7 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True fixed = with_vopc_dpp(code, mcpu, err, wave32) if fixed: return fixed - fixed = with_dot4_op_sel(code, mcpu, bad, err) + fixed = with_dot4_op_sel(code, mcpu, bad, err, wave32) if fixed: return fixed return asm, bad, err @@ -221,7 +221,7 @@ def dot4_op_sel_words(code: bytes, offsets) -> dict: return found -def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): +def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str, wave32: bool = True): """The listing of `code` with each rejected v_dot4_i32_i8 op_sel 2 / op_sel_hi 5 word printed as the instruction it is, or None when there is none. llvm-mc rejects the pair, so it is decoded with the two fields at their defaults (op_sel 0, op_sel_hi 7), and each such line gets the real fields and the real encoding back: the @@ -233,7 +233,7 @@ def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): patched = bytearray(code) for at, (w0, w1) in words.items(): struct.pack_into("<2I", patched, at, w0 & ~(7 << 11), w1 | (2 << 27)) - asm, bad2, err2 = run_mc(bytes(patched), mcpu) + asm, bad2, err2 = run_mc(bytes(patched), mcpu, wave32) if not asm.strip(): return None invalid, pos, hit, lines = invalid_offsets(err2), 0, set(), [] @@ -256,6 +256,8 @@ def with_dot4_op_sel(code: bytes, mcpu: str, bad: int, err: str): return "\n".join(lines), bad2, err2 words = {at: w for at, w in words.items() if at in hit} return None + + MAX_DATA_DWORDS = 1 << 16 From 95d1878dc3e4d8036b9f03e71404fc5644cda638 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 21:51:22 -0500 Subject: [PATCH 15/18] fspx_unpack: keep main's literal-form check for the 24-byte prologue (#583 head) The copy of #583 in this branch replaced main's check that both short prologue words are literal-bearing VOP3 opcode-0x180 words (words[k+1] & 0xFFFE0100 == 0x03FE0100, the shape fspx_prologue_probe.py checks) with a looser SRC2 == 0xff test. Keep main's check, as #583's head (3af97a1ec, by Tyrannys) does, with this branch's named constants, and take that head's test_short_prologue (the stricter check refuses 0x03FF0000) and its docs/fspx.md paragraph. Co-Authored-By: Claude Opus 5.5 --- docs/fspx.md | 11 +++++++---- tests/test_fspx_unpack.py | 16 ++++++++++------ tools/fspx_unpack.py | 16 +++++----------- 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/docs/fspx.md b/docs/fspx.md index 5162454658..ec74756a04 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -138,10 +138,13 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. - `tools/fspx_unpack.py` disassembles from the end of the prologue. - **A 24-byte variant**: some programs of the pipeline library in `shaders.rpf` (`tools/shader_library.py`) carry only the first two of those words, at words 0 and 3, and their code starts at word 6 (`s_inst_prefetch` in all of - them). Counted on the 1.0.2.1 library: 50 of 2,684 programs; read from word 0 they never decode (the prologue - words are invalid encodings and the rest desyncs), and only 1 of the 50 translated. With `code_range` taking - the 24-byte form, all 50 disassemble with 0 invalid words and 49 translate and pass `spirv-val` (the other one - stops at `s_sethalt`). A program whose words 0, 3 and 6 are all prologue words still takes the 36-byte form. + them). `code_range` takes that form only when both words are literal-bearing VOP3 opcode-0x180 words of the shape + `tools/fspx_prologue_probe.py` checks (second dword `& 0xFFFE0100 == 0x03FE0100`); a program whose words 0, 3 and + 6 are all prologue words keeps the 36-byte form. Counted on the 1.0.2.1 library with an opcode-only check (#583): + 50 of 2,684 programs; read from word 0 they never decode (the prologue words are invalid encodings and the rest + desyncs), and with the 24-byte start all 50 disassemble with 0 invalid words and 49 translate and pass + `spirv-val` (the other stops at `s_sethalt`). `tests/test_fspx_unpack.py` (`test_short_prologue`) covers the form + and the stricter check. - **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 3aa0cfc471..248a9e37ac 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -145,13 +145,17 @@ def test_code_range(self): self.assertEqual(fspx_unpack.code_range(program(endpgm=False))[1], None) def test_short_prologue(self): - # Two VOP3 opcode-0x180 words (0 and 3), then code: the 24-byte prologue of some pipeline-library programs. - code = prologue()[:24] + V_MOV * 3 + ENDPGM + # The 24-byte prologue of some pipeline-library programs: hash carriers at words 0 and 3 only, each a VOP3 + # opcode-0x180 word with a literal in the form tools/fspx_prologue_probe.py checks, then the code at word 6. + carrier = struct.pack("> 16 == 0xD580 for k in ks) - - def literal_src2(ks): - # each hash word carries its hash as the literal of its third source (SRC2 = 0xff), as #984's fixture shows - return all((words[k + 1] >> 18) & 0x1FF == 0xFF for k in ks) - if len(words) > 8 and vop3_180(PROLOGUE_WORDS): - start = PROLOGUE_SIZE - elif len(words) > 6 and vop3_180(SHORT_PROLOGUE_WORDS) and literal_src2(SHORT_PROLOGUE_WORDS): + start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0 + # Some pipeline programs have only the two hash carriers. Both must be literal-bearing + # VOP3 NOPs of the form in fspx_prologue_probe; the first body instruction starts at byte 24. + if not start and len(words) >= 6 and all( + words[k] >> 16 == 0xD580 and words[k + 1] & 0xFFFE0100 == 0x03FE0100 for k in SHORT_PROLOGUE_WORDS): start = SHORT_PROLOGUE_SIZE - else: - start = 0 pos = code.find(ENDPGM, start) while pos >= 0 and pos % 4: pos = code.find(ENDPGM, pos + 1) From d09286f62401917641de097ae8d700f13a405cfd Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 21:53:14 -0500 Subject: [PATCH 16/18] rdna2spirv: translate only the measured dot4 op_sel forms; keep restore_dot4_inline_sel The general rule from #1495 (dot4_op_sel_fields / restore_dot4_op_sel, ported from luizwidmer/palmetto) took the stored op_sel/op_sel_hi of any v_dot4_i32_i8 that llvm-mc printed with the defaults. That translated op_sel 0 / op_sel_hi 5 with a VGPR second source, a word #1317's test_fspx_dot4_op_sel_disasm.py (case (0, 5)) requires to stay refused: only op_sel 2 / op_sel_hi 5 was measured on gfx1036. The translator suite failed there. Resolve it on the measured side: - drop dot4_op_sel_fields and restore_dot4_op_sel; - keep main's restore_dot4_inline_sel (#984) and its three call sites: the clean-listing check, the forward re-anchor search, and the exact re-anchor window #1662 added today. The general rule does not cover only those cases, so it cannot replace them; - tests/semantic/test_dot4_printed_op_sel.py now checks that the inline-integer form is restored in a clean listing and on re-anchoring, and that op_sel_hi 5 with a VGPR S1, op_sel 1 / op_sel_hi 6, op_sel_hi 4 and a non-default S2 half stay refused; - docs/design.md "Signed-byte dot products" states how each form was confirmed (hardware for op_sel 2 / op_sel_hi 5, a corpus count for the inline-integer form, refused otherwise); docs/fspx.md follows. This also settles the #1662 / #1862 overlap: #1662's call site stays. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/fspx.md | 10 ++- tests/semantic/test_dot4_printed_op_sel.py | 89 +++++++++++++--------- tools/rdna2spirv.py | 52 +------------ 4 files changed, 62 insertions(+), 91 deletions(-) diff --git a/docs/design.md b/docs/design.md index 64719c2394..eee5be2cc4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -442,7 +442,7 @@ How the generated SPIR-V expects the runtime to work: | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Scalar copies through VCC | SGPRs 106 and 107 can hold two data words, including a buffer descriptor's count and format. A 64-bit move through VCC preserves both when its reads within the block use them as data. Predicate users and live-out VCC constrain this inference. A wide scalar load into a tuple ending in VCC writes both physical words. The synthetic descriptor fixture checks numeric copies, a round trip, and a subsequent tuple load on wave32 and emulated wave64. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. A word `llvm-mc` does decode but prints with the default fields (op_sel_hi other than `[1,1,1]` with op_sel bit 1 clear: it re-encodes op_sel 0 / op_sel_hi 7, so the text names the wrong halves) takes the stored op_sel and op_sel_hi from the blob, in a clean listing (`check_printed_encodings`) and when re-anchoring, only when those two fields are the whole difference (`dot4_op_sel_fields`); anything else is still refused as a dropped field. Found in an FSPX program by luizwidmer/palmetto (GPL-3.0, ported); the fields are applied by the rule measured above, checked by `tests/semantic/test_dot4_printed_op_sel.py` (hand-built words); not re-counted over the corpus. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The measured unclamped `op_sel` 2 / `op_sel_hi` 5 form is also recovered from the bytes on a gap in a listing that `shader_disasm.py` did not print it into (`skipped_form`, #984). | +| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. How each `op_sel`/`op_sel_hi` form that can reach the translator is confirmed: (1) `op_sel` 2 / `op_sel_hi` 5 without `clamp` or `neg`, which `llvm-mc` rejects: measured on `gfx1036` (the 5 sets above); `shader_disasm.py` prints it with its real encoding (`tests/semantic/test_fspx_dot4_op_sel_disasm.py`) and `skipped_form` recovers it from a gap in a listing made without that pass. (2) `op_sel` 0 / `op_sel_hi` 5 with an inline integer S1 and no `clamp` or `neg`, which `llvm-mc` decodes but prints with the default `op_sel_hi` 7: `restore_dot4_inline_sel` takes the stored field back, in a clean listing (`check_printed_encodings`) and in both re-anchoring paths; `op_sel_hi[1]` clear makes byte pairs 2..3 read S1's low half, the selection measured in (1), but the word itself was not run on hardware; confirmed by a count over the corpus (29 FidelityFX DLL programs, 1.0.2.1, LLVM 21.1.8: 22 translate without it, 24 with it, all 24 pass `spirv-val`; Code-embedded data row) and pinned by `tests/semantic/test_reanchor_dot4_inline_sel.py`. (3) Every other form `llvm-mc` decodes but prints with the default fields (for example `op_sel_hi` 5 with a VGPR S1, or `op_sel` 1 / `op_sel_hi` 6) is not measured and is refused as a dropped field; `tests/semantic/test_dot4_printed_op_sel.py` checks forms (2) and (3) with hand-built words. A general rule that took the stored fields of any such word (from luizwidmer/palmetto) was not taken for that reason. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). The measured unclamped `op_sel` 2 / `op_sel_hi` 5 form is also recovered from the bytes on a gap in a listing that `shader_disasm.py` did not print it into (`skipped_form`, #984). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | diff --git a/docs/fspx.md b/docs/fspx.md index ec74756a04..fad6b166be 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -168,10 +168,12 @@ program whose kind 0 is too short for word 4 keeps the code heuristic. operand sets, and the forms that stay refused); the 89 words of the real programs are not re-run here, because that needs the package's DLL. When a listing lacks that pass, the translator decodes the same exact form from the original bytes on a gap - in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. A - `v_dot4_i32_i8` that llvm-mc decodes but prints with the default `op_sel`/`op_sel_hi` (for example an inline - integer second source whose low half is replicated) takes the stored fields from the blob when they are the - only difference (`rdna2spirv.dot4_op_sel_fields`, docs/design.md "Signed-byte dot products"). + in the listing (`rdna2spirv.skipped_form`); other undecodable words keep the reachable-code check. LLVM can + also print the default high-half selector for an inline integer second source. If that selector is the only + changed bit, the translator preserves the stored low-half replication (`rdna2spirv.restore_dot4_inline_sel`). + Any other `v_dot4_i32_i8` that llvm-mc decodes but prints with different `op_sel`/`op_sel_hi` fields (for + example `op_sel_hi` 5 with a VGPR second source) is not measured and stays refused as a dropped field + (docs/design.md, "Signed-byte dot products"). ## Kind 7: records diff --git a/tests/semantic/test_dot4_printed_op_sel.py b/tests/semantic/test_dot4_printed_op_sel.py index 85b90feef6..f25c12be66 100644 --- a/tests/semantic/test_dot4_printed_op_sel.py +++ b/tests/semantic/test_dot4_printed_op_sel.py @@ -1,11 +1,13 @@ -"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults takes the stored fields. +"""A v_dot4_i32_i8 whose op_sel/op_sel_hi llvm-mc printed as the defaults: only the measured forms translate. -llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] but prints and re-encodes it with op_sel 0 and -op_sel_hi 7, so the listing names halves the instruction does not read. translate() used to refuse it ("a field the -disassembler dropped"); it now reads the two fields from the blob when they are the only difference -(rdna2spirv.dot4_op_sel_fields), and the v_dot4_i32_i8 rule applies them as measured on gfx1036 -(tests/semantic/test_alu_dot4_i8.py). Ported from luizwidmer/palmetto (GPL-3.0). Hand-built listing and blob, the -encodings assembled from the VOP3P field layout; no game data. +llvm-mc decodes a VOP3P v_dot4_i32_i8 with op_sel_hi other than [1,1,1] (op_sel bit 1 clear) but prints and +re-encodes it with op_sel 0 and op_sel_hi 7, so the listing names halves the instruction does not read. The +translator takes the stored field back for one form only: op_sel_hi 5 with an inline integer second source +(rdna2spirv.restore_dot4_inline_sel, counted over the FidelityFX programs; docs/design.md, "Signed-byte dot +products"). The one form measured on hardware, op_sel 2 / op_sel_hi 5, is a word llvm-mc rejects, which +tools/shader_disasm.py prints (test_fspx_dot4_op_sel_disasm.py). Every other form, such as op_sel_hi 5 with a VGPR +second source, is not measured and stays refused. Hand-built listing and blob, the encodings assembled from the VOP3P +field layout; no game data. python -I tests/semantic/test_dot4_printed_op_sel.py -v """ @@ -23,12 +25,18 @@ NAME = "ps_dot4_printed_op_sel" CODE_START = 0x100 A, B, C = 0x80FF7F01, 0x12F0FE7F, 0x00001000 +INLINE = 5 # inline integer constant 5: source field 128 + 5 + + +def src_field(src): + """VOP3P source field: a VGPR number, or ("int", n) for an inline integer constant 0..64.""" + return 128 + src[1] if isinstance(src, tuple) else 256 + src def dot4(op_sel=0, op_sel_hi=7, dst=0, srcs=(1, 2, 3)): - """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, v[srcs] with the given op_sel and op_sel_hi.""" + """VOP3P v_dot4_i32_i8 (opcode 0x16) vdst, srcs with the given op_sel and op_sel_hi.""" w0 = 0xCC000000 | (0x16 << 16) | ((op_sel_hi >> 2) & 1) << 14 | (op_sel & 7) << 11 | dst - w1 = (op_sel_hi & 3) << 27 | (256 + srcs[2]) << 18 | (256 + srcs[1]) << 9 | (256 + srcs[0]) + w1 = ((op_sel_hi & 3) << 27 | src_field(srcs[2]) << 18 | src_field(srcs[1]) << 9 | src_field(srcs[0])) return struct.pack("<2I", w0, w1).hex(" ") @@ -38,7 +46,8 @@ def v_mov(reg, value): SETUP = [v_mov(1, A), v_mov(2, B), v_mov(3, C)] TAIL = [("exp mrt0 v0, v0, v0, v0 done vm", "0f 18 00 f8 00 00 00 00"), ("s_endpgm", "00 00 81 bf")] -PRINTED = ("v_dot4_i32_i8 v0, v1, v2, v3", dot4()) +PRINTED_VGPR = ("v_dot4_i32_i8 v0, v1, v2, v3", dot4()) +PRINTED_INLINE = (f"v_dot4_i32_i8 v0, v1, {INLINE}, v3", dot4(srcs=(1, ("int", INLINE), 3))) def listing(program, end): @@ -49,6 +58,7 @@ def listing(program, end): def ref(a, b, addend, op_sel=0, op_sel_hi=7): + """Byte pairs 0..1 read the halves op_sel names, pairs 2..3 the halves op_sel_hi names (S0 bit 0, S1 bit 1).""" def byte(x, off): v = (x >> off) & 0xFF return v - 256 if v & 0x80 else v @@ -61,11 +71,11 @@ def byte(x, off): return total & 0xFFFFFFFF -def translate(stored_dot4, reanchor=False): - printed = SETUP + [PRINTED] + TAIL +def translate(stored_dot4, printed=PRINTED_VGPR, reanchor=False): + listed = SETUP + [printed] + TAIL stored = SETUP + [("", stored_dot4)] + TAIL code = b"".join(bytes.fromhex(enc) for _, enc in stored) - data = listing(printed, CODE_START + len(code)) + data = listing(listed, CODE_START + len(code)) blob = bytes(CODE_START) + code if reanchor: # a listing with an undecodable word after the code goes through the re-anchoring path data += b"; warning: invalid instruction encoding\n" @@ -81,36 +91,39 @@ def test_reference_is_the_plain_dot_product_for_the_defaults(self): def test_default_fields_translate_as_printed(self): self.assertEqual(mrt0_words(translate(dot4())), [ref(A, B, C)] * 4) - def test_stored_op_sel_hi_is_read_from_the_blob(self): - # op_sel_hi [1,0,1]: byte pairs 2..3 of S1 come from its low half. llvm-mc decodes it and prints [1,1,1]. + def test_inline_integer_s1_keeps_its_stored_op_sel_hi(self): + # op_sel_hi [1,0,1] with an inline integer S1: byte pairs 2..3 of S1 come from its low half, the halves the + # measured op_sel 2 / op_sel_hi 5 form selects. llvm-mc prints [1,1,1]; restore_dot4_inline_sel takes it back. + stored = dot4(op_sel_hi=5, srcs=(1, ("int", INLINE), 3)) for reanchor in (False, True): with self.subTest(reanchor=reanchor): - got = mrt0_words(translate(dot4(op_sel_hi=5), reanchor)) - self.assertEqual(got, [ref(A, B, C, op_sel_hi=5)] * 4) - self.assertNotEqual(ref(A, B, C, op_sel_hi=5), ref(A, B, C)) - - def test_stored_op_sel_on_source_0_is_read_from_the_blob(self): - got = mrt0_words(translate(dot4(op_sel=1, op_sel_hi=6))) - self.assertEqual(got, [ref(A, B, C, op_sel=1, op_sel_hi=6)] * 4) - - def test_a_non_default_s2_half_stays_refused(self): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate(dot4(op_sel_hi=3)) - self.assertIn("op_sel", str(cm.exception)) - - def test_another_difference_is_still_a_dropped_field(self): - # The stored word names v4 as S2, the printed one v3: not an op_sel difference. + got = mrt0_words(translate(stored, PRINTED_INLINE, reanchor)) + self.assertEqual(got, [ref(A, INLINE, C, op_sel_hi=5)] * 4) + self.assertNotEqual(ref(A, INLINE, C, op_sel_hi=5), ref(A, INLINE, C)) + + def test_unmeasured_forms_stay_refused(self): + # Not measured on hardware and not the inline-integer form: refused, in a clean listing (a dropped field) + # and when re-anchoring (the stored word never matches the printed one). + for name, stored in (("op_sel_hi 5, VGPR S1", dot4(op_sel_hi=5)), + ("op_sel 1 / op_sel_hi 6", dot4(op_sel=1, op_sel_hi=6)), + ("op_sel_hi 4", dot4(op_sel_hi=4)), + ("non-default S2 half", dot4(op_sel_hi=3))): + for reanchor in (False, True): + with self.subTest(form=name, reanchor=reanchor): + with self.assertRaises(rdna2spirv.Unsupported) as cm: + translate(stored, reanchor=reanchor) + if not reanchor: + self.assertIn("dropped", str(cm.exception)) + + def test_inline_form_with_another_difference_is_refused(self): + # The stored word names v4 as S2, the printed one v3: not just the op_sel_hi field. with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate(dot4(op_sel_hi=5, srcs=(1, 2, 4))) + translate(dot4(op_sel_hi=5, srcs=(1, ("int", INLINE), 4)), PRINTED_INLINE) self.assertIn("dropped", str(cm.exception)) - def test_fields_helper(self): - printed = bytes.fromhex(dot4()) - self.assertEqual(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, - "v_dot4_i32_i8"), (0, 5)) - self.assertIsNone(rdna2spirv.dot4_op_sel_fields(printed, printed, "v_dot4_i32_i8")) - self.assertIsNone(rdna2spirv.dot4_op_sel_fields(bytes.fromhex(dot4(op_sel_hi=5)), printed, - "v_dot2_i32_i16")) + def test_the_general_rule_is_not_there(self): + self.assertFalse(hasattr(rdna2spirv, "dot4_op_sel_fields")) + self.assertTrue(callable(rdna2spirv.restore_dot4_inline_sel)) if __name__ == "__main__": diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 2d04043ea0..4311f3100b 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17733,48 +17733,6 @@ def restore_mix_inline_literal(ins, raw, literal): ins["enc"] = raw.hex() -def dot4_op_sel_fields(raw, printed, op): - """(op_sel, op_sel_hi) of a v_dot4_i32_i8 whose stored op_sel fields llvm-mc printed as the defaults, else None. - - llvm-mc decodes a VOP3P v_dot4_i32_i8 (opcode 0x16) whose op_sel_hi is not [1,1,1] (while op_sel bit 1 is clear; - with it set the word is rejected and tools/shader_disasm.py prints it, docs/fspx.md) but prints and re-encodes it - with op_sel 0 and op_sel_hi 7, so its text names halves the instruction does not read. The fields are op_sel (word - 0 bits 13:11) and op_sel_hi (word 1 bits 28:27 for sources 0 and 1, word 0 bit 14 for source 2). Accepted only when - the stored 8 bytes with just those two fields set to the defaults are the printed ones, so every other bit - (opcode, operands, neg, clamp) is what the text says. From luizwidmer/palmetto (GPL-3.0), which found such a - word in an FSPX program (op_sel_hi[1] clear, the rest of the word as printed).""" - if base_op(op) != "v_dot4_i32_i8" or len(raw) != 8 or len(printed) != 8 or raw[3] != 0xCC: - return None - w0, w1 = struct.unpack("<2I", raw) - if (w0 >> 16) & 0x7F != 0x16: - return None - op_sel = (w0 >> 11) & 7 - op_sel_hi = ((w1 >> 27) & 3) | (((w0 >> 14) & 1) << 2) - if (op_sel, op_sel_hi) == (0, 7): - return None - if struct.pack("<2I", (w0 & ~(7 << 11)) | (1 << 14), w1 | (3 << 27)) != printed: - return None - return op_sel, op_sel_hi - - -def restore_dot4_op_sel(ins, raw): - """Give ``ins`` the op_sel/op_sel_hi dot4_op_sel_fields reads from the stored bytes, and those bytes as its - encoding; False (``ins`` untouched) when it does not apply. The v_dot4_i32_i8 rule applies the fields as measured - on gfx1036 (docs/design.md, "Signed-byte dot products") and refuses a non-default S2 half.""" - fields = dot4_op_sel_fields(raw, bytes.fromhex(ins["enc"]), ins["op"]) - if fields is None: - return False - op_sel, op_sel_hi = fields - mods = [m for m in ins.get("mods", []) if not m.startswith(("op_sel:", "op_sel_hi:"))] - if op_sel: - mods.append("op_sel:[%s]" % ",".join(str((op_sel >> k) & 1) for k in range(3))) - if op_sel_hi != 7: - mods.append("op_sel_hi:[%s]" % ",".join(str((op_sel_hi >> k) & 1) for k in range(3))) - ins["mods"] = mods - ins["enc"] = raw.hex() - return True - - def skipped_form(ins, blob, at): """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare in DPP @@ -18086,6 +18044,8 @@ def check_printed_encodings(path, info): restore_sdwa_source(ins, raw) shift -= 4 continue + if restore_dot4_inline_sel(ins, raw, enc): + continue literal = mix_literal(raw, enc, base_op(ins["op"])) if literal is not None: restore_mix_literal(ins, raw, literal) @@ -18096,8 +18056,6 @@ def check_printed_encodings(path, info): restore_mix_inline_literal(ins, raw12, literal) shift += 4 continue - if restore_dot4_op_sel(ins, raw): - continue raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " f"{enc.hex()} (a field the disassembler dropped)") @@ -18245,8 +18203,6 @@ def _translate(path): if literal is not None: restore_mix_inline_literal(ins, blob[pos:pos + 12], literal) enc = blob[pos:pos + 12] - elif restore_dot4_op_sel(ins, window): - pass elif pos + len(enc) > len(blob): raise Unsupported("undecodable words (cannot re-anchor)") else: @@ -18256,6 +18212,8 @@ def _translate(path): continue skipped, at = 0, pos while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): + if restore_dot4_inline_sel(ins, blob[at:at + len(enc)], enc): + break literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) if literal is not None: restore_mix_literal(ins, blob[at:at + len(enc)], literal) @@ -18270,8 +18228,6 @@ def _translate(path): restore_mix_inline_literal(ins, blob[at:at + 12], literal) enc = blob[at:at + 12] # the 12 bytes the decoder read: the next one starts after them break - if restore_dot4_op_sel(ins, blob[at:at + len(enc)]): - break at += 4 skipped += 4 if skipped > 4096 or at >= len(blob): From 7b1fe62850f69bc3ad0b3176aea8dda8168867ea Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 21:55:15 -0500 Subject: [PATCH 17/18] Keep main's watchdog switch and say where the peek default went f0611b752 took the executable's addresses out of the code. Two behaviours changed with it; the removal stays, the changes are now explicit: - runtime/src/main.cpp: the watchdog kick runs again only with LEONIDA_TITLE_WATCHDOG=0, as on main; LEONIDA_TITLE_WATCHDOG_KICK only supplies the two RVAs it needs. Either variable alone leaves the watchdog armed and the loader says so once (before this commit the kick ran whenever LEONIDA_TITLE_WATCHDOG_KICK was set). - scripts/windows-boot/boot.ps1 no longer has the game- and session-state RVAs built in, so LEONIDA_PEEK has no default and the RESULT states read "?" unless LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA are set. The script now warns when they are not, and runtime/README.md (LEONIDA_PEEK, LEONIDA_TITLE_WATCHDOG and _KICK rows), scripts/windows-boot/README.md and docs/first_run_ui.md say so. Co-Authored-By: Claude Opus 5.5 --- docs/first_run_ui.md | 2 +- runtime/README.md | 4 +++- runtime/src/main.cpp | 28 +++++++++++++++++----------- scripts/windows-boot/README.md | 9 ++++++++- scripts/windows-boot/boot.ps1 | 5 +++++ 5 files changed, 34 insertions(+), 14 deletions(-) diff --git a/docs/first_run_ui.md b/docs/first_run_ui.md index dbdfde12f4..fcfe4114b8 100644 --- a/docs/first_run_ui.md +++ b/docs/first_run_ui.md @@ -41,7 +41,7 @@ Measured on 25 November 2026 on native Windows 11 with `scripts/windows-boot/boo 3. **Legal notices**: a list of entries. A on an entry opens it instead of moving on. A repeating `a`, `down`, `down` cycle (one cycle every 10 s) got through. 4. **Legal terms and policies**: two check boxes (privacy policy, terms of service) and a Confirm button. Confirm stays greyed out and ignores A until both boxes are ticked. Focus starts on the first box. `down` stops at Confirm, so a script that only presses `a` and `down` gets stuck there with one box unticked. The page looks stuck but is waiting for the box. The steps that worked are `up` to the unticked box, `a` to tick it, `down` to Confirm, then `a`. While a box is focused, the right stick scrolls the text beside it (`rsdown`). The run that ticked the privacy box had scrolled to the end first; whether the box needs that is not measured. -Confirm shows one black frame and then a dark loading screen with a spinner. The spinner was still turning when the 400-second run ended, about 100 s after Confirm. The frame rate dropped to about 5 presents a second, the session state left its landing value, and there were no device faults. +Confirm shows one black frame and then a dark loading screen with a spinner. The spinner was still turning when the 400-second run ended, about 100 s after Confirm. The frame rate dropped to about 5 presents a second, the session state left its landing value, and there were no device faults. (The game and session states in a `boot.ps1` RESULT now need `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, measured locally: the script no longer has them built in and reports `?` without them; [scripts/windows-boot/README.md](../scripts/windows-boot/README.md).) Timings move by 10 to 20 s between runs on the same machine, because the pipeline cache warms up and the landing prompt arrives earlier. A fixed timeline can therefore press A on the wrong item. A later block that goes back with `up` and retries the legal-terms page makes the script more robust. The run above used the cycle up to about 230 s, then `up,up`, fifteen `rsdown`, `a`, `down,down`, `a`, and from 290 s `up,a,down,a`. The second block is the one that confirmed. diff --git a/runtime/README.md b/runtime/README.md index 8cb2e2a4b7..6d11a59f73 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -348,8 +348,10 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | | `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | -| `LEONIDA_TITLE_WATCHDOG_KICK` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `,` (hex, measured locally and not kept in the repository) makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only when the watchdog's trap instruction is at the first RVA. `LEONIDA_TITLE_WATCHDOG=1` keeps it armed even then. | +| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`). **Since RT-BOOT-COMBINED `0` also needs `LEONIDA_TITLE_WATCHDOG_KICK`**: the watchdog's addresses are no longer built in. With `0` and no `LEONIDA_TITLE_WATCHDOG_KICK`, the loader says once that the watchdog stays armed. | +| `LEONIDA_TITLE_WATCHDOG_KICK` | unset | `,` (hex, measured locally and not kept in the repository): where the watchdog's trap instruction is and the byte the game's main loop sets. Used only with `LEONIDA_TITLE_WATCHDOG=0`, and only when the watchdog's trap instruction is at the first RVA; set without `LEONIDA_TITLE_WATCHDOG=0`, the watchdog stays armed and the loader says so once. | | `LEONIDA_POOL_DIAG_AT` | unset | *Diagnostic.* `+0x` of the title's transient-pool assert, as the trace prints it (measured locally): the trace dumps the pool's resource list when that int3 is hit (`shims/startup_trace.h`). | +| `LEONIDA_PEEK` | unset | *Diagnostic.* `[:n],,...` (hex): a thread prints the 8-byte values at these RVAs of the title's image (`:n` = n consecutive values) every `LEONIDA_PEEK_SECONDS` (`src/main.cpp`). The RVAs are measured locally and not kept in the repository. `scripts/windows-boot/boot.ps1` no longer sets the game-state and session-state RVAs by default: it sets `LEONIDA_PEEK` only from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, and without them its RESULT states read `?` ([scripts/windows-boot/README.md](../scripts/windows-boot/README.md)). | | `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | | `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | | `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 1550039f43..21551e9489 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -44,10 +44,11 @@ namespace { // one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the // game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold // cache (first boot after a driver update), and the title then kills itself. By default the watchdog stays armed, as -// on the console. The two places are measured locally and not kept in the repository: -// LEONIDA_TITLE_WATCHDOG_KICK="," (hex) names them, and only when that exact trap instruction -// sits at the first one does a runtime thread set the byte at the second twice a second, so the title's watchdog -// never fires. Unset, or with LEONIDA_TITLE_WATCHDOG=1, the watchdog stays armed. +// on the console. LEONIDA_TITLE_WATCHDOG=0 asks to keep it from firing, as before. The two places that takes are +// measured locally and not kept in the repository: LEONIDA_TITLE_WATCHDOG_KICK="," (hex) names +// them, and only with both variables, and only when that exact trap instruction sits at the first RVA, does a +// runtime thread set the byte at the second twice a second, so the title's watchdog never fires. Either variable +// alone leaves the watchdog armed and says so once. constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) { @@ -66,13 +67,18 @@ bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) { void keep_title_watchdog_kicked(std::uint8_t* base) { char keep[4]{}; - const DWORD keep_length = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)); - if (keep_length == 1 && keep[0] == '1') return; + const bool disarm = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '0'; std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0; - if (!watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva)) { - if (keep_length == 1 && keep[0] == '0') - std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=," - " (hex); the title's hang watchdog stays armed\n"); + const bool named = watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva); + if (!disarm) { + if (named) + std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG_KICK is set but LEONIDA_TITLE_WATCHDOG is not 0;" + " the title's hang watchdog stays armed\n"); + return; + } + if (!named) { + std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=," + " (hex); the title's hang watchdog stays armed\n"); return; } MEMORY_BASIC_INFORMATION trap{}, kick{}; @@ -96,7 +102,7 @@ void keep_title_watchdog_kicked(std::uint8_t* base) { const_cast(byte), 0, nullptr); if (thread) { CloseHandle(thread); - std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG_KICK)\n"); + std::fprintf(stderr, "[rt] loader: keeping the title's hang watchdog kicked (LEONIDA_TITLE_WATCHDOG=0; unset or 1 keeps it armed)\n"); } } diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index b4ad475665..92121a2110 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md @@ -73,7 +73,14 @@ states only, which is what goes into a RESULT on the board; the logs, traces, ca and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing -screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) +screen waiting for A), `d` after A. + +**Changed: the states need two variables now.** The script used to set `LEONIDA_PEEK` to the game-state and +session-state RVAs by default. Those addresses of the retail executable are no longer kept in the repository, so set +`LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (hex, measured locally) in the shell before the boot. +Without them the script warns, sets no `LEONIDA_PEEK`, and the `states:` line and the RESULT show `game=? +session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest reads only the two RVAs those +variables name. `docs/linux_proton.md` (the same stages apply natively) section 2 has the healthy sequence with times and section 3 "which blank do you have". ## One game at a time diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index 36bcee7a6b..7863054b32 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -247,6 +247,11 @@ if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } $gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' $sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } +else { + # The two RVAs were built in until they were taken out of the repository; say so rather than report "?" silently. + Write-Warning ("LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA are not both set: no LEONIDA_PEEK by default, " + + "so the RESULT game and session states read '?' (scripts/windows-boot/README.md)") +} # Per-run values: always this script's (from its parameters), whatever the shell has. $perRun = [ordered]@{ LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) From b3e541b224e1d0bb691d8b4b5cc719eeea7c7dd7 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 22:03:00 -0500 Subject: [PATCH 18/18] d3d12_xs: drop the null-RTV marks of a descriptor heap when it is released The null-view marks (#1504, by ubiquitarianism) are kept by the real CPU handle. They were moved by descriptor copies and cleared by a view made with a resource, but never dropped when the heap went away, so an RTV heap made later at the same address inherited stale marks and its clears were skipped. The heap proxy now records an RTV heap's real CPU range and heap_release drops the marks in it. The barrier conversion keeps no state across calls, so it needs nothing here. xs_proxy_mock_test: an RTV heap's marked view is skipped while the heap lives and cleared after it is released; a mark outside it stays; a second heap at the same address starts unmarked and marks again. docs/d3d12_vulkan.md says so. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_xs_device.cpp | 24 ++++++++++++++++++++ runtime/test/xs_proxy_mock_test.cpp | 34 +++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 563e7bd421..6076f436d5 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -4270,7 +4270,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | | Enhanced barriers | Public Xbox Series `D3D12_BARRIER_GROUP` | `VK_KHR_synchronization2`; implement directly. | | List slot 146: texture barrier with no resource | The retail title records `D3D12_BARRIER_TYPE_TEXTURE` barriers whose `pResource` is null in its `Barrier(NumBarrierGroups, pBarrierGroups)` calls; on the console such a barrier is a global memory and execution barrier | `d3d12_xs_device.cpp` turns each into a `D3D12_GLOBAL_BARRIER` with the same `SyncBefore`/`SyncAfter`/`AccessBefore`/`AccessAfter` (layouts, subresource range and flags dropped) before it calls GCL7 `Barrier` (PC slot 80). A texture group with both kinds is split into runs, in order, in storage that lives for the call; a call with nothing to convert goes through with the title's own pointer. Without this the PC list goes into its error state, `Close` fails and `ExecuteCommandLists` drops the submission. A group array the proxy cannot read safely (null with a nonzero count, a group type it does not know, more than 1,024 groups or 65,536 barriers in one group) is refused whole, nothing recorded, and logged once per reason. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | -| List slot 52: clear of an RTV made with no resource | The title creates some render-target views with `CreateRenderTargetView(nullptr, ...)` and clears them every frame; on the console that clear does nothing | The device proxy marks the real handle when device slot 20 gets no resource; a view made there with a resource removes the mark, and `CopyDescriptors`/`CopyDescriptorsSimple` of RTVs move it with the descriptors. List slot 52 skips the clear of a marked view (logged the first time) and the list stays valid. The mark is the proxy's own because the real descriptor cannot tell: the Vulkan layer writes the same empty record for a view it could not make, and a PC runtime's handles are opaque. Any other view, valid or not, still reaches `ClearRenderTargetView` (PC slot 48); RTV records the title copies with its own `memcpy` are not followed. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | +| List slot 52: clear of an RTV made with no resource | The title creates some render-target views with `CreateRenderTargetView(nullptr, ...)` and clears them every frame; on the console that clear does nothing | The device proxy marks the real handle when device slot 20 gets no resource; a view made there with a resource removes the mark, and `CopyDescriptors`/`CopyDescriptorsSimple` of RTVs move it with the descriptors. Releasing an RTV heap drops the marks in its real CPU range, so a heap made later at the same address starts unmarked. List slot 52 skips the clear of a marked view (logged the first time) and the list stays valid. The mark is the proxy's own because the real descriptor cannot tell: the Vulkan layer writes the same empty record for a view it could not make, and a PC runtime's handles are opaque. Any other view, valid or not, still reaches `ClearRenderTargetView` (PC slot 48); RTV records the title copies with its own `memcpy` are not followed. **Confirmed by the mock tests only** (`xs_proxy_mock_test`), not by a retail run. | | XDXR batched/streaming BVH | `XboxBvhBuilder.dll` exports | See 4.8. | The null-resource barrier and null-view clear behaviour were first reported by luizwidmer/palmetto. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 9069a73fa1..87cc26dd33 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -203,6 +203,10 @@ struct HeapProxy { SIZE_T custom_byte_size; SIZE_T real_cpu_start; DescriptorHeapBackingFree custom_free; + // An RTV heap's real CPU range, [rtv_real_start, +rtv_real_bytes): the null-view marks in it + // (DeviceProxy::null_rtvs) are dropped when the heap goes, so a later heap at the same address starts unmarked. + SIZE_T rtv_real_start = 0; + SIZE_T rtv_real_bytes = 0; }; struct DescriptorRange { @@ -460,6 +464,16 @@ void copy_null_rtv_marks(DeviceProxy* device, UINT num_dest, const D3D12_CPU_DES device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); } +// An RTV heap was released: its real handles can name another heap's views from now on, so no mark may outlive it. +void drop_null_rtv_marks(DeviceProxy* device, SIZE_T start, SIZE_T bytes) { + if (!device || !start || !bytes || device->null_rtv_count.load(std::memory_order_acquire) == 0) return; + const SIZE_T end = start > (std::numeric_limits::max)() - bytes ? (std::numeric_limits::max)() + : start + bytes; + std::lock_guard lock(device->null_rtv_lock); + device->null_rtvs.erase(device->null_rtvs.lower_bound(start), device->null_rtvs.lower_bound(end)); + device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release); +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -898,6 +912,7 @@ unsigned long heap_release(HeapProxy* self) { const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { if (self->custom_cpu_start != 0) unregister_descriptor_range(self); + drop_null_rtv_marks(self->device, self->rtv_real_start, self->rtv_real_bytes); void* const backing = reinterpret_cast(self->custom_cpu_start); const DescriptorHeapBackingFree free_fn = self->custom_free; ID3D12DescriptorHeap* real = self->real; @@ -4714,6 +4729,15 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, custom_cpu_start ? free_fn : nullptr, stride); + if (SUCCEEDED(hr) && desc && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV && is_heap_proxy(*out)) { + // The null-view marks are kept by real handle (mark_null_rtv); heap_release drops those in this range. + const UINT inc = self->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + auto* proxy = static_cast(*out); + proxy->rtv_real_start = + real_cpu_start ? real_cpu_start : raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; + if (inc && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) + proxy->rtv_real_bytes = static_cast(desc->NumDescriptors) * inc; + } if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap static std::atomic logged{0}; if (logged.fetch_add(1) < 32) diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 453be7cca9..cb350820e9 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -5107,6 +5107,40 @@ int check_console_null_barrier_and_clear() { EXPECT(real->calls[48] == 5 && real->args[48][0] == rtv_copy + kMockDescriptorInc); EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + // Releasing an RTV heap drops the marks in its real range, so a heap made later at the same address starts + // unmarked; a mark outside that range stays. + g_heap_hook.next_ptr = nullptr; // a plain PC heap even if a descriptor-heap hook is registered: real handles + D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{}; + rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + rtv_heap_desc.NumDescriptors = 4; + const IID heap_iid = __uuidof(ID3D12DescriptorHeap); + void* rtv_heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap))))); + EXPECT(rtv_heap && xs::is_heap_proxy(rtv_heap) && raw(rtv_heap, 9) == kMockHeapCpuStart); + const SIZE_T in_heap = kMockHeapCpuStart + 2 * kMockDescriptorInc; + raw(device, 20, 0, 0, in_heap); + const unsigned clears = real->calls[48]; + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears); // marked while the heap lives: skipped + EXPECT(raw(rtv_heap, 2) == 0); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 1 && real->args[48][0] == in_heap); // the mark went with the heap + real->list_error = false; // the mock list still takes its own view there as invalid + raw(list, 52, rtv_none, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 1); // outside the released heap: still skipped + // A second RTV heap at the same address: the view made there with a resource is cleared, and a view made with + // no resource is marked again for as long as that heap lives. + void* rtv_heap2 = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap2))))); + raw(device, 20, word(resource_a), 0, in_heap); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 2 && !real->list_error); + raw(device, 20, 0, 0, in_heap); + raw(list, 52, in_heap, word(color), 0, 0); + EXPECT(real->calls[48] == clears + 2); + EXPECT(raw(rtv_heap2, 2) == 0); + EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); + // The marks are the device's own: another device's clear at a handle marked on the first is forwarded (its mock // list then takes the view as invalid, which is what that device was told). Mock* other_mock = nullptr;