diff options
| author | Tyrannys <80750971+Tyrannys@users.noreply.github.com> | 2026-11-24 10:24:48 -0600 |
|---|---|---|
| committer | Tyrannys <80750971+Tyrannys@users.noreply.github.com> | 2026-11-24 10:24:48 -0600 |
| commit | 2f5b49c4e03c6a1fb09098c4eaf54fe4e732907a (patch) | |
| tree | f0685b18074b54be24561b592eb0401ef17eabf5 | |
| parent | d0da7dade8b688f2e0f7f23f4155d6cbb438809e (diff) | |
rdna2spirv: re-anchor from llvm-mc's own offsets of the rejected words
After undecodable words, translate() put each printed instruction back at its
blob offset by searching forward for its printed bytes. A data word llvm-mc
printed as a copy of a later instruction (printed bytes are not the bytes
read) took that later instruction's place, and every instruction after it
lost its place: "undecodable words (cannot re-anchor)".
shader_ir.parse_file now reads the byte offset of each rejected word from the
llvm-mc messages (shader_disasm.py feeds one line of "0xNN " bytes, five
characters a byte) as info["invalid_at"]. When there is one offset per
rejected word, the translator skips exactly those words and searches nothing;
a listed word whose bytes are the next instruction is not skipped, so a
listing with wrong or hand-written messages reads as before.
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 that translated before is lost.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | docs/design.md | 2 | ||||
| -rw-r--r-- | tests/semantic/test_reanchor_llvm_offsets.py | 84 | ||||
| -rw-r--r-- | tools/rdna2spirv.py | 26 | ||||
| -rw-r--r-- | tools/shader_ir.py | 4 |
4 files changed, 115 insertions, 1 deletions
diff --git a/docs/design.md b/docs/design.md index 3f2d52251..18e2549dc 100644 --- a/docs/design.md +++ b/docs/design.md | |||
| @@ -282,7 +282,7 @@ How the generated SPIR-V expects the runtime to work: | |||
| 282 | | 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). | | 282 | | 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). | |
| 283 | | 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. | | 283 | | 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. | |
| 284 | | 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. | | 284 | | 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. | |
| 285 | | 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`). | | 285 | | 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`). | |
| 286 | | 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. | | 286 | | 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. | |
| 287 | | 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). | | 287 | | 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). | |
| 288 | | 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`). | | 288 | | 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 000000000..b16e61f56 --- /dev/null +++ b/tests/semantic/test_reanchor_llvm_offsets.py | |||
| @@ -0,0 +1,84 @@ | |||
| 1 | """Re-anchoring uses llvm-mc's own offsets for the words it rejected. | ||
| 2 | |||
| 3 | When a listing reports undecodable words, translate() puts every printed instruction back at its offset in the | ||
| 4 | blob. It used to search forward for the printed bytes, so a data word that llvm-mc printed as a copy of a later | ||
| 5 | instruction (its printed bytes are not the bytes it read) took that later instruction's place, and every | ||
| 6 | instruction after it lost its place. shader_ir.parse_file now reads the byte offset of each rejected word from the | ||
| 7 | llvm-mc messages (tools/shader_disasm.py feeds one line of "0xNN " bytes, five characters a byte), and the | ||
| 8 | translator skips exactly those words. Hand-built encodings, no game data. | ||
| 9 | |||
| 10 | python -I tests/semantic/test_reanchor_llvm_offsets.py -v | ||
| 11 | """ | ||
| 12 | import os | ||
| 13 | import struct | ||
| 14 | import sys | ||
| 15 | import tempfile | ||
| 16 | import unittest | ||
| 17 | |||
| 18 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 19 | if HERE not in sys.path: | ||
| 20 | sys.path.insert(0, HERE) | ||
| 21 | |||
| 22 | from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402 | ||
| 23 | |||
| 24 | import shader_ir # noqa: E402 (support puts tools/ on sys.path) | ||
| 25 | |||
| 26 | NAME = "ps_reanchor_llvm_offsets" | ||
| 27 | CODE_START = 0x100 | ||
| 28 | |||
| 29 | MOV_V2 = ("v_mov_b32_e32 v2, 2.0", "f4 02 04 7e") | ||
| 30 | BRANCH = ("s_branch 2", "02 00 82 bf") # to 0x108 + 2 * 4 = 0x110, over the two data words | ||
| 31 | BAD = "ff ff ff ff" # 0x108: rejected by llvm-mc, not printed | ||
| 32 | DATA = "12 34 56 78" # 0x10c: data that llvm-mc printed as the next instruction | ||
| 33 | MOV_V1 = ("v_mov_b32_e32 v1, v2", "02 03 02 7e") # 0x110 | ||
| 34 | EXP = ("exp mrt0 v1, v1, v1, v1 done vm", "0f 18 00 f8 01 01 01 01") | ||
| 35 | END = ("s_endpgm", "00 00 81 bf") | ||
| 36 | |||
| 37 | |||
| 38 | def code(data=DATA): | ||
| 39 | return b"".join(bytes.fromhex(x) for x in (MOV_V2[1], BRANCH[1], BAD, data, MOV_V1[1], EXP[1], END[1])) | ||
| 40 | |||
| 41 | |||
| 42 | def listing(bad_offset=8, messages=True): | ||
| 43 | printed = [MOV_V2, BRANCH, MOV_V1, MOV_V1, EXP, END] # the data word printed with MOV_V1's text and bytes | ||
| 44 | size = len(code()) | ||
| 45 | lines = [f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + size:x} (scan), gfx1030, 1 invalid words"] | ||
| 46 | for text, enc in printed: | ||
| 47 | lines.append(f"\t{text:<40}; encoding: [{','.join(f'0x{b:02x}' for b in bytes.fromhex(enc))}]") | ||
| 48 | if messages: | ||
| 49 | lines += ["", "; --- llvm-mc messages ---", | ||
| 50 | f"; <stdin>:1:{bad_offset * 5 + 1}: warning: invalid instruction encoding"] | ||
| 51 | return ("\n".join(lines) + "\n").encode("utf-8") | ||
| 52 | |||
| 53 | |||
| 54 | def blob(data=DATA): | ||
| 55 | return bytes(CODE_START) + code(data) | ||
| 56 | |||
| 57 | |||
| 58 | def f2u(x): | ||
| 59 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 60 | |||
| 61 | |||
| 62 | class ReanchorFromLlvmOffsets(unittest.TestCase): | ||
| 63 | def test_parse_file_reads_the_offsets(self): | ||
| 64 | with tempfile.TemporaryDirectory() as tmp: | ||
| 65 | path = os.path.join(tmp, NAME + ".s") | ||
| 66 | with open(path, "wb") as f: | ||
| 67 | f.write(listing()) | ||
| 68 | info = shader_ir.parse_file(path) | ||
| 69 | self.assertEqual(info["invalid"], 1) | ||
| 70 | self.assertEqual(info["invalid_at"], [CODE_START + 8]) | ||
| 71 | |||
| 72 | def test_a_data_word_printed_as_a_later_instruction_keeps_its_place(self): | ||
| 73 | out = mrt0_words(translate_listing(NAME, listing(), fssm=blob())) | ||
| 74 | self.assertEqual(out[0], f2u(2.0)) | ||
| 75 | |||
| 76 | def test_messages_that_do_not_match_the_blob_fall_back(self): | ||
| 77 | # The offset names a word whose bytes are the instruction itself: it is not skipped, so a listing whose | ||
| 78 | # messages are wrong (or hand-written) still anchors as before. | ||
| 79 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 80 | translate_listing(NAME, listing(bad_offset=0), fssm=blob()) | ||
| 81 | |||
| 82 | |||
| 83 | if __name__ == "__main__": | ||
| 84 | unittest.main() | ||
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae..250a67920 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py | |||
| @@ -17386,9 +17386,35 @@ def translate(path): | |||
| 17386 | # translate only code reachable from entry; a branch into data is rejected below. | 17386 | # translate only code reachable from entry; a branch into data is rejected below. |
| 17387 | blob = native_blob(path, info["name"]) | 17387 | blob = native_blob(path, info["name"]) |
| 17388 | pos = info["code_start"] | 17388 | pos = info["code_start"] |
| 17389 | # llvm-mc's own messages say where it rejected a word, and it moves on by 4 bytes after each: with them the | ||
| 17390 | # stream is anchored exactly, with no forward search (which can match a later copy of the same encoding when | ||
| 17391 | # the printed bytes are not the bytes read, and then loses every instruction after it). A listed offset whose | ||
| 17392 | # bytes are the next instruction is not skipped, so a listing whose messages do not match its blob still reads. | ||
| 17393 | bad = set(info.get("invalid_at") or ()) | ||
| 17394 | exact = bool(bad) and len(bad) == info["invalid"] | ||
| 17389 | for ins in insns: | 17395 | for ins in insns: |
| 17390 | enc = bytes.fromhex(ins["enc"]) | 17396 | enc = bytes.fromhex(ins["enc"]) |
| 17391 | op, operand_count = ins["op"], len(ins["args"]) | 17397 | op, operand_count = ins["op"], len(ins["args"]) |
| 17398 | if exact: | ||
| 17399 | while pos in bad and not same_encoding(blob[pos:pos + len(enc)], enc, op, operand_count): | ||
| 17400 | pos += 4 | ||
| 17401 | window = blob[pos:pos + len(enc)] | ||
| 17402 | if not same_encoding(window, enc, op, operand_count): | ||
| 17403 | literal = mix_literal(window, enc, base_op(op)) | ||
| 17404 | if literal is not None: | ||
| 17405 | restore_mix_literal(ins, window, literal) | ||
| 17406 | else: | ||
| 17407 | literal = mix_inline_literal(blob[pos:pos + 12], enc, base_op(op)) | ||
| 17408 | if literal is not None: | ||
| 17409 | restore_mix_inline_literal(ins, blob[pos:pos + 12], literal) | ||
| 17410 | enc = blob[pos:pos + 12] | ||
| 17411 | elif pos + len(enc) > len(blob): | ||
| 17412 | raise Unsupported("undecodable words (cannot re-anchor)") | ||
| 17413 | else: | ||
| 17414 | ins["normalized"] = True | ||
| 17415 | ins["pc"] = pos | ||
| 17416 | pos += len(enc) | ||
| 17417 | continue | ||
| 17392 | skipped, at = 0, pos | 17418 | skipped, at = 0, pos |
| 17393 | while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): | 17419 | while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): |
| 17394 | literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) | 17420 | 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 2a4db1b0d..d16a153d1 100644 --- a/tools/shader_ir.py +++ b/tools/shader_ir.py | |||
| @@ -16,6 +16,7 @@ from collections import Counter | |||
| 16 | 16 | ||
| 17 | ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]") | 17 | ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]") |
| 18 | HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)") | 18 | HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)") |
| 19 | INVALID_AT = re.compile(r"<stdin>:1:(\d+): warning: invalid instruction encoding") | ||
| 19 | SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc", | 20 | SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc", |
| 20 | "src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit", | 21 | "src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit", |
| 21 | "src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch", | 22 | "src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch", |
| @@ -265,6 +266,9 @@ def parse_file(path): | |||
| 265 | info["insns"].append(ins) | 266 | info["insns"].append(ins) |
| 266 | tail = "\n".join(lines) | 267 | tail = "\n".join(lines) |
| 267 | info["invalid"] = tail.count("invalid instruction encoding") | 268 | info["invalid"] = tail.count("invalid instruction encoding") |
| 269 | # Where llvm-mc rejected a word: tools/shader_disasm.py feeds it one line of "0xNN " bytes (5 characters a byte) | ||
| 270 | # starting at code_start, so the message column gives the byte offset. The decoder then moves on by 4 bytes. | ||
| 271 | info["invalid_at"] = sorted({info["code_start"] + (int(c) - 1) // 5 for c in INVALID_AT.findall(tail)}) | ||
| 268 | return info | 272 | return info |
| 269 | 273 | ||
| 270 | 274 | ||