upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 23:06:33 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 23:06:33 -0500
commit66fae9fb8867a80347330aa255ab9f74af0e4fc9 (patch)
tree6efe937e2c61b3a0130f8a7e0cf7ff50bf7ea528
parent0fd05a431a780304a18d468af7636e66e95b2f70 (diff)
parentef777d4b73da0be91b533846c377626896274f24 (diff)
Merge pull request #2977 from omardev29
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # docs/design.md
-rw-r--r--docs/design.md1
-rw-r--r--docs/fspx.md16
-rw-r--r--tests/semantic/test_fma_mix_literal.py120
-rw-r--r--tests/test_fma_mix_literal_probe.py102
-rw-r--r--tools/fma_mix_literal_probe.py279
-rw-r--r--tools/rdna2spirv.py37
6 files changed, 546 insertions, 9 deletions
diff --git a/docs/design.md b/docs/design.md
index 82cdf8c52..ee3bf716c 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -257,6 +257,7 @@ How the generated SPIR-V expects the runtime to work:
257| 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. | 257| 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. |
258| 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. | 258| 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. |
259| 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). | 259| 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). |
260| 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). 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). |
260| 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`). | 261| 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`). |
261| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** | 262| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** |
262| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88). Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** | 263| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88). Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** |
diff --git a/docs/fspx.md b/docs/fspx.md
index 9736133a1..e9f6b0449 100644
--- a/docs/fspx.md
+++ b/docs/fspx.md
@@ -162,15 +162,13 @@ kind 0 at run time beyond what the translated module already carries (its thread
162 162
163## Translation status 163## Translation status
164 164
165With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs: 165With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs (`main` at `aa2988cc` with the
166 166`v_fma_mix*` literal repair in [design.md](design.md), "Printed encodings"):
167- **17 translate and pass `spirv-val`.** 13 of them are the 16 programs that use no dot4 instruction, minus 3 that 167
168 stop at `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. The other 4 use dot4 (design.md, "Signed-byte 168- **27 translate and pass `spirv-val`**, 11 of the 13 programs that use dot4 among them (design.md, "Signed-byte
169 dot products"). 169 dot products"). Without the repair, 26: the `v_fma_mix_f32` it is for is refused.
170- **9 more programs that use dot4 do not translate yet.** The first thing each stops at: 170- **The other 2** (both use dot4) stop at a reachable `v_dot4_i32_i8` VOP3P word with `op_sel` 2 that `llvm-mc` does
171 - 6 at an `s_buffer_load_dwordx8` or `_dwordx16` whose destination range ends in `vcc_lo, vcc_hi`; 171 not decode (the VOP3P words above).
172 - 2 at a reachable word `llvm-mc` does not decode (the VOP3P words above);
173 - 1 at an `src_scc` operand.
174 172
175## Unknown 173## Unknown
176 174
diff --git a/tests/semantic/test_fma_mix_literal.py b/tests/semantic/test_fma_mix_literal.py
new file mode 100644
index 000000000..9719af593
--- /dev/null
+++ b/tests/semantic/test_fma_mix_literal.py
@@ -0,0 +1,120 @@
1"""A v_fma_mix* literal that llvm-mc prints cut to its low half is read from the blob.
2
3A v_fma_mix source read as f16 (op_sel_hi set) takes the half op_sel names, so one 32-bit literal can give src0 its
4low half and src2 its high half. llvm-mc prints that literal as its low 16 bits and re-encodes it with a zero high
5half, so the printed-encoding check (#2026) refused such an instruction, and LLVM's text alone reads the high half as
6+0.0. The translator now takes the literal from the blob when only its high half differs. Hand-built encodings
7(registers and values made up for the test), no game data.
8
9 python -I tests/semantic/test_fma_mix_literal.py -v
10"""
11import os
12import struct
13import sys
14import unittest
15
16HERE = os.path.dirname(os.path.abspath(__file__))
17if HERE not in sys.path:
18 sys.path.insert(0, HERE)
19
20from support import mrt0_words, rdna2spirv, translate_listing # noqa: E402
21
22NAME = "ps_fma_mix_literal"
23CODE_START = 0x100
24# v_mov_b32 v2, 2.0 (VOP1); v_fma_mix_f32 v1, lit, v2, lit with op_sel:[0,0,1] op_sel_hi:[1,0,1]: src0 = the
25# literal's low half as f16, src1 = v2 as f32, src2 = the literal's high half as f16. The stored literal is
26# 0x40004200 (low 3.0, high 2.0); llvm-mc prints 0x4200 and encodes 0x00004200. The text and the printed encodings
27# here are llvm-mc 23.1.5's for these bytes (a low half that is an inline f16 constant, such as 0x3c00, prints as
28# lit(0x...) instead, so it is avoided).
29MOV = ("v_mov_b32_e32 v2, 2.0", "f4 02 04 7e")
30MIX_TEXT = "v_fma_mix_f32 v1, 0x4200, v2, 0x4200 op_sel:[0,0,1] op_sel_hi:[1,0,1]"
31MIX_WORDS = "01 60 20 cc ff 04 fe 0b"
32EXP = ("exp mrt0 v1, v1, v1, v1 done vm", "0f 18 00 f8 01 01 01 01")
33END = ("s_endpgm", "00 00 81 bf")
34
35
36def lit(value):
37 return struct.pack("<I", value).hex(" ")
38
39
40def program(literal, words=MIX_WORDS, text=MIX_TEXT):
41 return [MOV, (text, f"{words} {lit(literal)}"), EXP, END]
42
43
44def listing(prog, invalid=False):
45 size = sum(len(bytes.fromhex(enc)) for _, enc in prog)
46 lines = [f"; {NAME} code 0x{CODE_START:x}..0x{CODE_START + size:x} (scan), gfx1030, "
47 f"{1 if invalid else 0} invalid words"]
48 for text, enc in prog:
49 printed = ",".join(f"0x{b:02x}" for b in bytes.fromhex(enc))
50 lines.append(f"\t{text:<40}; encoding: [{printed}]")
51 if invalid:
52 # translate() takes the re-anchoring path when the listing reports an undecodable word.
53 lines += ["", "; --- llvm-mc messages ---", "; <stdin>:1:1: warning: invalid instruction encoding"]
54 return ("\n".join(lines) + "\n").encode("utf-8")
55
56
57def blob(prog):
58 return bytes(CODE_START) + b"".join(bytes.fromhex(enc) for _, enc in prog)
59
60
61def f2u(x):
62 return struct.unpack("<I", struct.pack("<f", x))[0]
63
64
65PRINTED = program(0x00004200)
66STORED = program(0x40004200)
67
68
69class FmaMixLiteralTest(unittest.TestCase):
70 def run_ps(self, data, fssm):
71 return mrt0_words(translate_listing(NAME, data, fssm=fssm))
72
73 def test_high_half_comes_from_the_blob(self):
74 # fma(3.0, 2.0, 2.0) = 8.0
75 self.assertEqual(self.run_ps(listing(PRINTED), blob(STORED)), [f2u(8.0)] * 4)
76
77 def test_reanchored_listing_takes_it_too(self):
78 self.assertEqual(self.run_ps(listing(PRINTED, invalid=True), blob(STORED)), [f2u(8.0)] * 4)
79
80 def test_without_the_blob_the_printed_literal_is_all_there_is(self):
81 # LLVM's text alone: the high half reads +0.0, fma(3.0, 2.0, 0.0) = 6.0 (what the listing says).
82 self.assertEqual(self.run_ps(listing(PRINTED), None), [f2u(6.0)] * 4)
83
84 def test_printed_low_half_must_match(self):
85 with self.assertRaises(rdna2spirv.Unsupported) as cm:
86 self.run_ps(listing(PRINTED), blob(program(0x40004201)))
87 self.assertIn("v_fma_mix_f32 at 0x104", str(cm.exception))
88
89 def test_any_other_difference_is_still_refused(self):
90 # The stored instruction reads v3 as src1 (SRC1 field 0x103), not the printed v2.
91 other = program(0x40004200, words="01 60 20 cc ff 06 fe 0b")
92 with self.assertRaises(rdna2spirv.Unsupported) as cm:
93 self.run_ps(listing(PRINTED), blob(other))
94 self.assertIn("dropped", str(cm.exception))
95
96 def test_a_live_source_printed_as_inline_zero_is_refused(self):
97 # Stored SRC1 0x000 (s0, a source v_fma_mix reads) against a printed inline 0 (0x080). same_encoding forgives
98 # that for an unused source field; the repair must not, since all three v_fma_mix sources are live.
99 text = "v_fma_mix_f32 v1, 0x4200, 0, 0x4200 op_sel:[0,0,1] op_sel_hi:[1,0,1]"
100 printed = program(0x00004200, words="01 60 20 cc ff 00 fd 0b", text=text)
101 stored = program(0x40004200, words="01 60 20 cc ff 00 fc 0b", text=text)
102 with self.assertRaises(rdna2spirv.Unsupported) as cm:
103 self.run_ps(listing(printed), blob(stored))
104 self.assertIn("v_fma_mix_f32 at 0x104", str(cm.exception))
105
106 def test_an_inline_constant_with_the_printed_value_keeps_it(self):
107 # src0 = v2 (2.0) as f32, src1 = the inline integer 1 as f32, src2 = the literal's high half (op_sel:[0,0,1]
108 # op_sel_hi:[0,0,1]). The stored literal 0x3c000001 prints as 0x1, the same value as src1, so only the
109 # SRC field (0xff) tells the literal's user apart. Hand-written text: llvm-mc 23.1.5 prints this literal as
110 # lit(0x3c000001). fma(2.0, 1.4e-45, 1.0) = 1.0, also with the denormal flushed; src1 overwritten with the
111 # literal would give 2 * 0.0078125 + 1.0.
112 text = "v_fma_mix_f32 v1, v2, 1, 0x1 op_sel:[0,0,1] op_sel_hi:[0,0,1]"
113 words = "01 60 20 cc 02 03 fd 03"
114 printed = program(0x00000001, words=words, text=text)
115 stored = program(0x3C000001, words=words, text=text)
116 self.assertEqual(self.run_ps(listing(printed), blob(stored)), [f2u(1.0)] * 4)
117
118
119if __name__ == "__main__":
120 unittest.main()
diff --git a/tests/test_fma_mix_literal_probe.py b/tests/test_fma_mix_literal_probe.py
new file mode 100644
index 000000000..7b87a0e2a
--- /dev/null
+++ b/tests/test_fma_mix_literal_probe.py
@@ -0,0 +1,102 @@
1"""tools/fma_mix_literal_probe.py: the cases tell the two readings of a split v_fma_mix literal apart, the encodings
2are the ones described, the translator side follows the halves reading, and a missing GPU is exit 77. Standard
3library only; no GPU, no LLVM, no game files.
4
5The expected values are worked out by hand (src1 is v2 = 2.0; f16 0x4000 = 2.0, 0x4200 = 3.0, 0xbc00 = -1.0; f32
60x40400000 = 3.0). No low half is an inline f16 constant, so llvm-mc prints each literal as the plain hex the listing
7uses (an inline one, such as 0x3c00, prints as lit(0x...)):
8
9 A fma(lo 3.0, 2.0, hi 2.0) = 8.0 low reading: fma(3.0, 2.0, 0.0) = 6.0
10 B fma(hi 3.0, 2.0, hi 3.0) = 9.0 low reading: fma(0.0, 2.0, 0.0) = 0.0
11 E fma(2.0, 2.0, hi -1.0) = 3.0 low reading: fma(2.0, 2.0, 0.0) = 4.0
12 C fma(3.0, 2.0, 3.0) = 9.0 either way
13 D fma(3.0, 2.0, 2.0) = 8.0 either way
14"""
15import contextlib
16import io
17import os
18import struct
19import sys
20import unittest
21from unittest import mock
22
23ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24sys.dont_write_bytecode = True
25sys.path.insert(0, os.path.join(ROOT, "tools"))
26sys.path.insert(0, os.path.join(ROOT, "tests", "semantic"))
27
28import fma_mix_literal_probe as probe # noqa: E402
29
30BY_HAND = {"A": (8.0, 6.0), "B": (9.0, 0.0), "E": (3.0, 4.0), "C": (9.0, 9.0), "D": (8.0, 8.0)}
31
32
33def f(word):
34 return struct.unpack("<f", struct.pack("<I", word))[0]
35
36
37class Cases(unittest.TestCase):
38 def test_model_matches_hand_derivation(self):
39 self.assertEqual(sorted(c.name for c in probe.CASES), sorted(BY_HAND))
40 for case in probe.CASES:
41 with self.subTest(case=case.name):
42 self.assertEqual((f(case.expected(probe.HALVES)), f(case.expected(probe.LOW))), BY_HAND[case.name])
43
44 def test_only_the_controls_agree(self):
45 for case in probe.CASES:
46 halves, low = BY_HAND[case.name]
47 self.assertEqual(halves == low, case.what.startswith("control"), case.name)
48
49 def test_printed_literal_is_the_low_half(self):
50 # llvm-mc 23.1.5 re-encodes a v_fma_mix literal with its low 16 bits, also one read as f32 (D).
51 by = {c.name: c for c in probe.CASES}
52 self.assertEqual(by["A"].printed_literal(), 0x4200)
53 self.assertEqual(by["D"].printed_literal(), 0x0000)
54
55
56class Encoding(unittest.TestCase):
57 def test_case_a_fields(self):
58 a = next(c for c in probe.CASES if c.name == "A")
59 w0, w1, lit = a.words(8, 2, a.literal)
60 self.assertEqual(w0 >> 26, 0b110011) # VOP3P
61 self.assertEqual((w0 >> 16) & 0x7F, 0x20) # v_fma_mix_f32
62 self.assertEqual(w0 & 0xFF, 8) # vdst v8
63 self.assertEqual([(w0 >> b) & 1 for b in (11, 12, 13)], [0, 0, 1]) # op_sel
64 self.assertEqual([(w1 >> 27) & 1, (w1 >> 28) & 1, (w0 >> 14) & 1], [1, 0, 1]) # op_sel_hi
65 self.assertEqual([(w1 >> (9 * i)) & 0x1FF for i in range(3)], [0xFF, 0x102, 0xFF])
66 self.assertEqual(lit, 0x40004200)
67
68 def test_hw_kernel_carries_the_exact_words(self):
69 a = next(c for c in probe.CASES if c.name == "A")
70 w0, w1, lit = a.words(8, 2, a.literal)
71 self.assertIn(f".long 0x{w0:08x}, 0x{w1:08x}, 0x{lit:08x}", probe.hw_lines(a))
72
73 def test_listing_prints_llvm_mc_text_and_the_blob_holds_the_literal(self):
74 a = next(c for c in probe.CASES if c.name == "A")
75 text, blob = probe.ps_program(a)
76 self.assertIn("v_fma_mix_f32 v0, 0x4200, v2, 0x4200 op_sel:[0,0,1] op_sel_hi:[1,0,1]", text)
77 self.assertIn(struct.pack("<I", 0x40004200), blob)
78 self.assertNotIn(struct.pack("<I", 0x40004200), text.encode())
79
80
81class Sides(unittest.TestCase):
82 def run_main(self, *argv):
83 out = io.StringIO()
84 with contextlib.redirect_stdout(out):
85 code = probe.main(list(argv))
86 return code, out.getvalue()
87
88 def test_translator_side_follows_the_halves_reading(self):
89 code, out = self.run_main()
90 self.assertEqual(code, 0, out)
91 self.assertIn("translator: follows the halves reading", out)
92
93 def test_missing_hardware_is_77(self):
94 from hw_oracle import runner
95 with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no AMD GPU")):
96 code, out = self.run_main("--oracle", "hw")
97 self.assertEqual(code, 77)
98 self.assertIn("hardware oracle unavailable", out)
99
100
101if __name__ == "__main__":
102 unittest.main()
diff --git a/tools/fma_mix_literal_probe.py b/tools/fma_mix_literal_probe.py
new file mode 100644
index 000000000..ac88cbfcb
--- /dev/null
+++ b/tools/fma_mix_literal_probe.py
@@ -0,0 +1,279 @@
1r"""Does a v_fma_mix source with op_sel_hi and op_sel set read the high half of a 32-bit literal? A probe, standard
2library only.
3
4A v_fma_mix* source read as f16 (op_sel_hi[i] = 1) takes the half op_sel[i] names. When two sources share one 32-bit
5literal, the console compiler (in the FidelityFX DLL's FSPX code) and Mesa's ACO (`optimize_constants()` in
6src/amd/compiler/aco_optimizer.cpp) both put two f16 values in it and give one source the high half. llvm-mc prints
7such a literal as its low 16 bits, so the translator takes it from the blob (docs/design.md, "Printed encodings").
8That the hardware reads the high half that way is the part no one has measured. Two readings:
9
10 halves op_sel picks the half of the 32-bit literal (what the translator does with the blob)
11 low the literal is 16 bits, its high half reads +0.0 (what llvm-mc's text says)
12
13CASES (values made up for the probe; f16 halves written hi:lo):
14
15 A src0 = literal.lo, src2 = literal.hi op_sel:[0,0,1] op_sel_hi:[1,0,1] the shape seen in FSPX code
16 B src0 = literal.hi, src2 = literal.hi op_sel:[1,0,1] op_sel_hi:[1,0,1]
17 E src0 = v (f32), src2 = literal.hi op_sel:[0,0,1] op_sel_hi:[0,0,1]
18 C src0 = literal.lo, src2 = literal.lo control: both readings agree
19 D src0 = literal as f32, src2 = v (f32) control: an f32 literal is the whole 32 bits
20
21src1 is always a VGPR holding 2.0 (f32). Each case computes fma(src0, src1, src2) with values that are exact in f32,
22so rounding plays no part.
23
24Sides:
25 translator tools/rdna2spirv.py on a listing whose printed encodings are llvm-mc's (the literal cut to 16 bits)
26 with the real bytes next to it, run in tests/semantic/spirv_mini_interp.py on the CPU. Always runs.
27 The text and encodings are what llvm-mc 23.1.5 prints for these bytes, except D's text: it prints
28 that f32 literal as lit(0x40400000), which the translator does not parse, so D's listing says
29 0x40400000.
30 hw the instruction's exact bytes (`.long`, since LLVM's assembler can't encode the literal either) on an
31 AMD GPU through tools/hw_oracle (HIP on Windows, libdrm on Linux), one wave32 lane. The measurement.
32
33 python -I tools/fma_mix_literal_probe.py # translator side only
34 python -I tools/fma_mix_literal_probe.py --oracle hw # + the AMD GPU in this machine
35
36Exit code: 0 when every side that ran follows the same reading, 1 when they differ or a side follows neither (or a
37control is wrong), 2 on a harness error, 77 when the hardware side is unavailable. Nothing here reads game files.
38"""
39import argparse
40import os
41import struct
42import subprocess
43import sys
44import tempfile
45import warnings
46
47HERE = os.path.dirname(os.path.abspath(__file__))
48ROOT = os.path.dirname(HERE)
49sys.dont_write_bytecode = True
50TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE
51for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")):
52 if p not in sys.path:
53 sys.path.insert(0, p)
54
55import rdna2spirv # noqa: E402
56import spirv_mini_interp # noqa: E402
57
58STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
59SENTINEL = 0x5A5A5A5A
60HALVES, LOW = "halves", "low"
61OP_FMA_MIX_F32 = 0x20 # VOP3P opcode, as in the console's bytes and LLVM's encoding
62LITERAL = 0xFF # SRC field value for a literal
63V2_VALUE = 2.0
64# The game's MODE as the other probes infer it (fma_mix_probe.py): IEEE 0, DX10_CLAMP 1, f32 denormals flushed,
65# f16 kept.
66HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 0}
67
68
69def h(bits):
70 return struct.unpack("<e", struct.pack("<H", bits & 0xFFFF))[0]
71
72
73def f(word):
74 return struct.unpack("<f", struct.pack("<I", word & 0xFFFFFFFF))[0]
75
76
77def f2u(x):
78 return struct.unpack("<I", struct.pack("<f", x))[0]
79
80
81class Case:
82 def __init__(self, name, srcs, op_sel, op_sel_hi, literal, what):
83 self.name, self.srcs, self.op_sel, self.op_sel_hi = name, srcs, op_sel, op_sel_hi
84 self.literal, self.what = literal, what
85
86 def operand(self, i, reading):
87 """Value of source i under a reading; srcs[i] is 'lit' or 'v'."""
88 if self.srcs[i] == "v":
89 return V2_VALUE
90 if not self.op_sel_hi[i]:
91 return f(self.literal) # f32: the whole literal under either reading
92 if self.op_sel[i] == 0:
93 return h(self.literal)
94 return h(self.literal >> 16) if reading == HALVES else 0.0
95
96 def expected(self, reading):
97 return f2u(self.operand(0, reading) * V2_VALUE + self.operand(2, reading))
98
99 def printed_literal(self):
100 """What llvm-mc re-encodes: the literal's low 16 bits. llvm-mc 23.1.5 does that for every v_fma_mix literal,
101 one that a source reads as f32 (D) too."""
102 return self.literal & 0xFFFF
103
104 def words(self, vdst, vsrc1, literal):
105 """The instruction's three dwords: VOP3P word 0, word 1, literal."""
106 src = [LITERAL if self.srcs[0] == "lit" else 256 + vsrc1, 256 + vsrc1,
107 LITERAL if self.srcs[2] == "lit" else 256 + vsrc1]
108 w0 = (0xCC000000 | OP_FMA_MIX_F32 << 16 | self.op_sel_hi[2] << 14 | self.op_sel[2] << 13 |
109 self.op_sel[1] << 12 | self.op_sel[0] << 11 | vdst)
110 w1 = self.op_sel_hi[1] << 28 | self.op_sel_hi[0] << 27 | src[2] << 18 | src[1] << 9 | src[0]
111 return w0, w1, literal
112
113 def text(self, vdst, vsrc1):
114 f16 = any(self.srcs[i] == "lit" and self.op_sel_hi[i] for i in (0, 2))
115 lit = f"0x{self.printed_literal() if f16 else self.literal:x}" # D: hand-written, see the docstring
116 reg = f"v{vsrc1}"
117 ops = [lit if self.srcs[0] == "lit" else reg, reg, lit if self.srcs[2] == "lit" else reg]
118 mods = [f"{name}:[{','.join(map(str, bits))}]" for name, bits in (("op_sel", self.op_sel),
119 ("op_sel_hi", self.op_sel_hi)) if any(bits)]
120 return " ".join([f"v_fma_mix_f32 v{vdst}, {ops[0]}, {ops[1]}, {ops[2]}"] + mods) # llvm-mc omits [0,0,0]
121
122
123CASES = (
124 Case("A", ("lit", "v", "lit"), (0, 0, 1), (1, 0, 1), 0x40004200, "src0 = lo, src2 = hi (the FSPX shape)"),
125 Case("B", ("lit", "v", "lit"), (1, 0, 1), (1, 0, 1), 0x42004500, "src0 = hi, src2 = hi"),
126 Case("E", ("v", "v", "lit"), (0, 0, 1), (0, 0, 1), 0xBC004200, "src0 = v (f32), src2 = hi"),
127 Case("C", ("lit", "v", "lit"), (0, 0, 0), (1, 0, 1), 0x40004200, "control: src0 = src2 = lo"),
128 Case("D", ("lit", "v", "v"), (0, 0, 0), (0, 0, 0), 0x40400000, "control: src0 = the f32 literal"),
129)
130
131
132def is_control(case):
133 return case.expected(HALVES) == case.expected(LOW)
134
135
136def verdict(results):
137 """(reading or None, report lines) for [(case, word or None)]."""
138 readings, lines = set(), []
139 for case, word in results:
140 want = {r: case.expected(r) for r in (HALVES, LOW)}
141 if word is None:
142 got, tag = "no result", "missing"
143 else:
144 got = f"{f(word):g}"
145 tag = [r for r in (HALVES, LOW) if want[r] == word]
146 tag = ("both (control)" if is_control(case) else tag[0]) if tag else "neither"
147 if tag in (HALVES, LOW):
148 readings.add(tag)
149 elif tag != "both (control)":
150 readings.add(None)
151 lines.append(f" {case.name} {got:<10} halves {f(want[HALVES]):g} low {f(want[LOW]):g} -> {tag:<16} "
152 f"{case.what}")
153 reading = readings.pop() if len(readings) == 1 else None
154 return reading, lines
155
156
157# ---- the translator, on the CPU ----
158
159VOP1_MOV = 0x7E000200 # v_mov_b32 (VOP1 opcode 1); | vdst << 17 | src0
160EXP_MRT0_V0 = "0f 18 00 f8 00 00 00 00"
161S_ENDPGM = "00 00 81 bf"
162CODE_START = 0x100
163
164
165def hexs(*dwords):
166 return " ".join(f"{b:02x}" for w in dwords for b in struct.pack("<I", w))
167
168
169def ps_program(case):
170 """(listing text, blob): llvm-mc's text and encodings for the case, and the real bytes at CODE_START."""
171 mov2 = (f"v_mov_b32_e32 v2, 0x{f2u(V2_VALUE):x}", hexs(VOP1_MOV | 2 << 17 | LITERAL, f2u(V2_VALUE)))
172 mov0 = (f"v_mov_b32_e32 v0, 0x{SENTINEL:x}", hexs(VOP1_MOV | 0 << 17 | LITERAL, SENTINEL))
173 printed = (case.text(0, 2), hexs(*case.words(0, 2, case.printed_literal())))
174 stored = (case.text(0, 2), hexs(*case.words(0, 2, case.literal)))
175 tail = [("exp mrt0 v0, v0, v0, v0 done vm", EXP_MRT0_V0), ("s_endpgm", S_ENDPGM)]
176 shown, real = [mov2, mov0, printed] + tail, [mov2, mov0, stored] + tail
177 size = sum(len(bytes.fromhex(e)) for _, e in shown)
178 lines = [f"; fma_mix_literal_{case.name} code 0x{CODE_START:x}..0x{CODE_START + size:x} (probe), gfx1030, "
179 "0 invalid words"]
180 for text, enc in shown:
181 lines.append(f"\t{text:<48}; encoding: [{','.join('0x' + b for b in enc.split())}]")
182 blob = bytes(CODE_START) + b"".join(bytes.fromhex(e) for _, e in real)
183 return "\n".join(lines) + "\n", blob
184
185
186def run_translator(cases=CASES):
187 out = []
188 with tempfile.TemporaryDirectory(prefix="fma_mix_literal_probe_") as work:
189 for case in cases:
190 name = f"ps_fma_mix_literal_{case.name}"
191 text, blob = ps_program(case)
192 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
193 os.makedirs(os.path.join(work, "fssm"), exist_ok=True)
194 src = os.path.join(work, "disasm", name + ".s")
195 with open(src, "w", encoding="utf-8", newline="\n") as fh:
196 fh.write(text)
197 with open(os.path.join(work, name + ".dxbc"), "wb") as fh:
198 fh.write(STUB_DXBC)
199 with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as fh:
200 fh.write(blob)
201 with warnings.catch_warnings():
202 warnings.simplefilter("ignore", ResourceWarning)
203 spv = rdna2spirv.translate(src)
204 out.append(spirv_mini_interp.run_fragment(spv)["%out_mrt0"][0])
205 return out
206
207
208# ---- the native instruction on an AMD GPU ----
209
210def hw_lines(case):
211 w0, w1, lit = case.words(8, 2, case.literal)
212 return [f"v_mov_b32 v2, 0x{f2u(V2_VALUE):x}", f"v_mov_b32 v8, 0x{SENTINEL:x}",
213 f".long 0x{w0:08x}, 0x{w1:08x}, 0x{lit:08x}", "v_mov_b32 v20, 0",
214 "global_store_b32 v20, v8, s[2:3]", "s_endpgm"]
215
216
217def run_hw(oracle, cases=CASES):
218 from hw_oracle import asm
219 got = oracle.run([asm.Kernel(hw_lines(c), 32, 1, 1, raw=True, mode=HW_MODE) for c in cases], words=1)
220 return [None if isinstance(w, str) else w[0] for w in got], [w for w in got if isinstance(w, str)]
221
222
223# ---- driver ----
224
225def report(side, results):
226 reading, lines = verdict(results)
227 print(f"{side}: {'follows the ' + reading + ' reading' if reading else 'follows neither reading'}")
228 for ln in lines:
229 print(ln)
230 return reading
231
232
233def main(argv=None):
234 ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
235 ap.add_argument("--oracle", default="translator", help="comma-separated sides besides the translator: hw")
236 ap.add_argument("--hw-arch", help="GPU architecture to assemble for (default: detected; LEONIDA_HW_ARCH)")
237 a = ap.parse_args(argv)
238 sides = {s.strip() for s in a.oracle.split(",") if s.strip()} - {"translator"}
239 if sides - {"hw"}:
240 ap.error(f"unknown --oracle side(s): {', '.join(sorted(sides - {'hw'}))}")
241 for case in CASES: # the table itself: three cases that tell the readings apart, two that don't
242 if is_control(case) != case.what.startswith("control"):
243 print(f"harness error: case {case.name} does not discriminate as described")
244 return 2
245 readings = []
246 try:
247 readings.append(report("translator", list(zip(CASES, run_translator()))))
248 if "hw" in sides:
249 from hw_oracle import runner
250 try:
251 oracle = runner.open_oracle(arch=a.hw_arch)
252 except runner.Unavailable as e:
253 print(f"hardware oracle unavailable: {e}")
254 return 77
255 try:
256 print(f"hardware oracle: {oracle.device}")
257 words, rejected = run_hw(oracle)
258 finally:
259 oracle.close()
260 for why in rejected:
261 print(f" {why}")
262 readings.append(report(f"hw (native, {oracle.arch})", list(zip(CASES, words))))
263 except (RuntimeError, OSError, subprocess.SubprocessError, spirv_mini_interp.UnsupportedConstruct,
264 rdna2spirv.Unsupported) as e:
265 print(f"harness error: {e}")
266 return 2
267 if None in readings or len(set(readings)) != 1:
268 print("sides disagree" if None not in readings else "a side follows neither reading")
269 return 1
270 print(f"all sides follow the {readings[0]} reading")
271 return 0
272
273
274if __name__ == "__main__":
275 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
276 sys.stdout.reconfigure(errors="replace")
277 except (AttributeError, ValueError, OSError):
278 pass
279 sys.exit(main())
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 05393d0a9..c5411bb90 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -14484,6 +14484,35 @@ def same_encoding(raw, printed, op, operand_count):
14484 return diff == 0 14484 return diff == 0
14485 14485
14486 14486
14487def mix_literal(raw, printed, op):
14488 """The 32-bit literal of a v_fma_mix* when LLVM printed it cut to its low half, else None.
14489
14490 A v_fma_mix source read as f16 (op_sel_hi set) takes the half op_sel names, so one literal can feed one source its
14491 low half and another its high half (seen in the FidelityFX DLL's FSPX code: src0 low, src2 high, op_sel:[0,0,1]
14492 op_sel_hi:[1,0,1]). llvm-mc prints that literal as its low 16 bits and re-encodes it with a zero high half, which
14493 would read the high half as +0.0. Only that half may differ: the 8 instruction bytes must match (same_encoding
14494 with all three sources counted as used, so nothing is forgiven and a live s0 can't pass as an inline 0) and the
14495 printed literal must be the stored one's low half. That the hardware hands op_sel's high half of the
14496 literal to that source is not measured; Mesa's ACO relies on it (optimize_constants() in aco_optimizer.cpp packs
14497 two constants as the two f16 halves of one literal for v_fma_mix), and the console compiler emitted it here."""
14498 if not op.startswith("v_fma_mix") or len(raw) != 12 or len(printed) != 12 or raw[3] != 0xCC:
14499 return None
14500 if not same_encoding(raw[:8], printed[:8], op, 4): # vdst, src0, src1, src2
14501 return None
14502 stored, shown = int.from_bytes(raw[8:], "little"), int.from_bytes(printed[8:], "little")
14503 if stored == shown or shown != stored & 0xFFFF:
14504 return None
14505 return stored
14506
14507
14508def restore_mix_literal(ins, raw, literal):
14509 """Give every source of ``ins`` that the stored bytes encode as the literal (SRC field 0xff) its 32-bit value."""
14510 w1 = int.from_bytes(raw[4:8], "little")
14511 for i in range(3):
14512 if (w1 >> (9 * i)) & 0x1FF == 0xFF and ins["args"][1 + i].get("k") == "imm":
14513 ins["args"][1 + i] = {**ins["args"][1 + i], "v": literal}
14514
14515
14487def output_signature(path, name): 14516def output_signature(path, name):
14488 """OSG1 elements as (register, system value), one per register (first element wins).""" 14517 """OSG1 elements as (register, system value), one per register (first element wins)."""
14489 dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc") 14518 dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
@@ -14664,6 +14693,10 @@ def check_printed_encodings(path, info):
14664 enc = bytes.fromhex(ins["enc"]) 14693 enc = bytes.fromhex(ins["enc"])
14665 raw = blob[ins["pc"]:ins["pc"] + len(enc)] 14694 raw = blob[ins["pc"]:ins["pc"] + len(enc)]
14666 if not same_encoding(raw, enc, ins["op"], len(ins["args"])): 14695 if not same_encoding(raw, enc, ins["op"], len(ins["args"])):
14696 literal = mix_literal(raw, enc, base_op(ins["op"]))
14697 if literal is not None:
14698 restore_mix_literal(ins, raw, literal)
14699 continue
14667 raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " 14700 raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed "
14668 f"{enc.hex()} (a field the disassembler dropped)") 14701 f"{enc.hex()} (a field the disassembler dropped)")
14669 14702
@@ -14701,6 +14734,10 @@ def translate(path):
14701 op, operand_count = ins["op"], len(ins["args"]) 14734 op, operand_count = ins["op"], len(ins["args"])
14702 skipped, at = 0, pos 14735 skipped, at = 0, pos
14703 while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): 14736 while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count):
14737 literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op))
14738 if literal is not None:
14739 restore_mix_literal(ins, blob[at:at + len(enc)], literal)
14740 break
14704 at += 4 14741 at += 4
14705 skipped += 4 14742 skipped += 4
14706 if skipped > 4096 or at >= len(blob): 14743 if skipped > 4096 or at >= len(blob):