diff --git a/docs/design.md b/docs/design.md index 3f2d522517..18e2549dc5 100644 --- a/docs/design.md +++ b/docs/design.md @@ -282,7 +282,7 @@ How the generated SPIR-V expects the runtime to work: | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | -| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). | +| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings (when the llvm-mc messages give one offset per rejected word, `shader_ir.parse_file`'s `invalid_at`, those words are skipped exactly and nothing is searched forward: a forward search let a data word printed as a copy of a later instruction take that instruction's place and lose every one after it; counted on the 1.0.2.1 pipeline library with #327's vcc-tuple decoding, 36 compute programs that stopped at "cannot re-anchor" now translate and pass `spirv-val`, none lost; `tests/semantic/test_reanchor_llvm_offsets.py`), translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). | | VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. | | Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). One difference is repaired instead of refused: a `v_fma_mix*` literal that llvm-mc prints cut to its low 16 bits (and re-encodes with a zero high half). llvm-mc 23.1.5 prints some of these literals in full as `lit(V)` (an f32 source, or a low half that is an inline constant; LLVM 21 printed the inline constant and dropped the literal word) and still re-encodes only the low half: `tools/shader_ir.py` reads `lit(V)` as V, and the same repair applies (5,733 such operands in the pipeline library, [shader_library.md](shader_library.md)). When the 8 instruction bytes match (`same_encoding` with all three sources counted as used, so a live `s0` can't pass as an inline 0) and the printed literal is the stored one's low half, every source the bytes encode as the literal (SRC field `0xff`) takes the stored 32 bits, so a source with `op_sel_hi` and `op_sel` set reads the high half instead of +0.0. Seen in one program of the FidelityFX DLL's `FSPX` code ([fspx.md](fspx.md)): src0 the low half, src2 the high half; the game's clean listings have no such difference (the count above). That the hardware gives op_sel's high half of the literal to that source is not measured; it is what Mesa's ACO compiler relies on (public: `optimize_constants()` in `src/amd/compiler/aco_optimizer.cpp`, Mesa `main` at `bb986060`, packs two constants as the two f16 halves of one literal, read through `v_fma_mix`'s `op_sel_hi` with the second source extracting the high half), and what the console compiler emitted here. `tools/fma_mix_literal_probe.py --oracle hw` measures it on an AMD GPU (the instruction's exact bytes through `tools/hw_oracle`; not run on one yet). `tests/semantic/test_fma_mix_literal.py` (the value through the interpreter, the re-anchoring path, an inline constant with the literal's printed value left alone, and the refused cases, a live source printed as inline 0 among them). A second shape is repaired too (`mix_inline_literal`): LLVM 21's form above. llvm-mc 21.1.8 (`-mcpu=gfx1013`) prints a `v_fma_mix*` literal whose low 16 bits are the f16 value of an inline constant as that constant and re-encodes the instruction in **8** bytes: every SRC field that held `0xff` holds the inline code, and the literal word is gone (`0x3f800000`, 1.0 as an f32 source, prints as `0`; `0x3c003800` as `0.5`, losing the high half 1.0). Swept with llvm-mc 21.1.8 over all 65,536 low halves under three high halves: exactly 90 low halves print this way (0..64, -1..-16, ±0.5, ±1.0, ±2.0, ±4.0, 1/(2π) as f16: `MIX_INLINE_F16`), whatever the high half; llvm-mc 23.1.6 prints all of them as `lit(V)`. The printed 8 bytes are 4 short of what the decoder read, so the later offsets of a clean listing were 4 low and its first such instruction was refused as a dropped field (one FSPX program, `tupacfan04`'s count in #8683). When every differing SRC field is `0xff` in the blob and the inline code of the stored literal's low half in the print, and the rest of the 8 bytes match exactly (`same_encoding`, all three sources live), each such source reads the stored 32 bits with the stored neg and abs (`NEG_HI`) bits, the instruction takes the 12 stored bytes, and the following offsets move up by 4 (also on the re-anchoring path). Any other difference stays `Unsupported`. CPU-checked by `tests/semantic/test_fma_mix_literal.py` (`FmaMixInlineLiteralTest`: an f32 source, two f16 halves, neg and abs, all 90 codes, both listing paths, the refused cases). | | Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | diff --git a/tests/semantic/test_reanchor_llvm_offsets.py b/tests/semantic/test_reanchor_llvm_offsets.py new file mode 100644 index 0000000000..b16e61f56f --- /dev/null +++ b/tests/semantic/test_reanchor_llvm_offsets.py @@ -0,0 +1,84 @@ +"""Re-anchoring uses llvm-mc's own offsets for the words it rejected. + +When a listing reports undecodable words, translate() puts every printed instruction back at its offset in the +blob. It used to search forward for the printed bytes, so a data word that llvm-mc printed as a copy of a later +instruction (its printed bytes are not the bytes it read) took that later instruction's place, and every +instruction after it lost its place. shader_ir.parse_file now reads the byte offset of each rejected word from the +llvm-mc messages (tools/shader_disasm.py feeds one line of "0xNN " bytes, five characters a byte), and the +translator skips exactly those words. Hand-built encodings, no game data. + + python -I tests/semantic/test_reanchor_llvm_offsets.py -v +""" +import os +import struct +import sys +import tempfile +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 + +import shader_ir # noqa: E402 (support puts tools/ on sys.path) + +NAME = "ps_reanchor_llvm_offsets" +CODE_START = 0x100 + +MOV_V2 = ("v_mov_b32_e32 v2, 2.0", "f4 02 04 7e") +BRANCH = ("s_branch 2", "02 00 82 bf") # to 0x108 + 2 * 4 = 0x110, over the two data words +BAD = "ff ff ff ff" # 0x108: rejected by llvm-mc, not printed +DATA = "12 34 56 78" # 0x10c: data that llvm-mc printed as the next instruction +MOV_V1 = ("v_mov_b32_e32 v1, v2", "02 03 02 7e") # 0x110 +EXP = ("exp mrt0 v1, v1, v1, v1 done vm", "0f 18 00 f8 01 01 01 01") +END = ("s_endpgm", "00 00 81 bf") + + +def code(data=DATA): + return b"".join(bytes.fromhex(x) for x in (MOV_V2[1], BRANCH[1], BAD, data, MOV_V1[1], EXP[1], END[1])) + + +def listing(bad_offset=8, messages=True): + printed = [MOV_V2, BRANCH, MOV_V1, MOV_V1, EXP, END] # the data word printed with MOV_V1's text and bytes + size = len(code()) + lines = [f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + size:x} (scan), gfx1030, 1 invalid words"] + for text, enc in printed: + lines.append(f"\t{text:<40}; encoding: [{','.join(f'0x{b:02x}' for b in bytes.fromhex(enc))}]") + if messages: + lines += ["", "; --- llvm-mc messages ---", + f"; :1:{bad_offset * 5 + 1}: warning: invalid instruction encoding"] + return ("\n".join(lines) + "\n").encode("utf-8") + + +def blob(data=DATA): + return bytes(CODE_START) + code(data) + + +def f2u(x): + return struct.unpack(" len(blob): + raise Unsupported("undecodable words (cannot re-anchor)") + else: + ins["normalized"] = True + ins["pc"] = pos + pos += len(enc) + continue skipped, at = 0, pos while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) diff --git a/tools/shader_ir.py b/tools/shader_ir.py index 2a4db1b0dd..d16a153d1e 100644 --- a/tools/shader_ir.py +++ b/tools/shader_ir.py @@ -16,6 +16,7 @@ ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]") HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)") +INVALID_AT = re.compile(r":1:(\d+): warning: invalid instruction encoding") SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc", "src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit", "src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch", @@ -265,6 +266,9 @@ def parse_file(path): info["insns"].append(ins) tail = "\n".join(lines) info["invalid"] = tail.count("invalid instruction encoding") + # Where llvm-mc rejected a word: tools/shader_disasm.py feeds it one line of "0xNN " bytes (5 characters a byte) + # starting at code_start, so the message column gives the byte offset. The decoder then moves on by 4 bytes. + info["invalid_at"] = sorted({info["code_start"] + (int(c) - 1) // 5 for c in INVALID_AT.findall(tail)}) return info