From f605f8aee471020da29f9bf63df5036cd04ccd26 Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:30:46 +0100 Subject: [PATCH 1/3] rdna2spirv: put back the instructions llvm-mc's junk swallowed after a tuple into vcc llvm-mc rejects a scalar tuple that runs into vcc and prints the second word as junk. That junk is often longer than the word, so it also covers the instruction after the tuple, which stayed missing and refused the program with 'fall-through into undecodable words'. The words after a restored tuple are now decoded from the blob until the stream is back at a printed instruction. Pipeline library of 1.0.2.1, 2,684 compute programs: 1,816 -> 2,567 translate and pass spirv-val; the 1,816 modules are byte-identical. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/shader_library.md | 8 +++- tests/semantic/test_vcc_tuple_fallback.py | 31 +++++++++++++++ tools/rdna2spirv.py | 47 ++++++++++++++++------- 4 files changed, 71 insertions(+), 17 deletions(-) diff --git a/docs/design.md b/docs/design.md index ba4c33fa1c..dd724a3837 100644 --- a/docs/design.md +++ b/docs/design.md @@ -291,7 +291,7 @@ How the generated SPIR-V expects the runtime to work: | 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) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). Where llvm-mc rejects such a tuple, `restore_vcc_tuples` decodes it from the blob, and with it the instructions its junk text swallowed, up to the next instruction llvm-mc printed (corpus count: `docs/shader_library.md`, section 5). | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | diff --git a/docs/shader_library.md b/docs/shader_library.md index 483426225f..71de878473 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -168,8 +168,12 @@ What stops the rest, by the translator's message: `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. The translator now decodes these words from the blob with `rdna2_decode` (`restore_vcc_tuples`) and reads them as the `[s100,...,vcc_lo,vcc_hi]` lists it already takes (design.md *Scalar/buffer memory*); synthetic cases are in - `tests/semantic/test_vcc_tuple_fallback.py`. The count above was measured before this change; it has not been - re-run on the real library. + `tests/semantic/test_vcc_tuple_fallback.py`. The junk llvm-mc prints at such a word's second dword is often longer + than that dword (an 8-byte `exp`, say) and swallows the instruction after the tuple too, so the words after a restored + instruction are decoded from the blob until the stream is back at one llvm-mc printed. A word llvm-mc itself rejected + is not taken for swallowed code and stays refused. The table above was measured before both changes. Measured since, + over the 2,684 compute programs (llvm-mc 21.1.8): 1,816 translate with the tuples alone and 2,567 with the swallowed + instructions, all of which pass `spirv-val`; the modules of the 1,816 are byte-identical. * **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`): the existing `check_printed_encodings` refusal. * **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets. diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 67e6bc5211..01938dab40 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -136,6 +136,37 @@ def test_image_resource_in_vcc(self): with self.subTest(printed_as=variant): self.assertIn("OpFunctionCall %uint %desc_lookup_fn", translate(program, variant)) + def test_junk_that_swallows_the_next_instructions(self): + # The junk at the tuple's second word is longer than that word, so it covers the s_mov_b32 after the tuple + # (and the first word of the 8-byte one after that, whose literal then prints as junk too). None of them is + # printed at its own place; all of them are decoded from the blob. + literal = ("s_mov_b32 s11, 0x12345678", "ff 03 8b be 78 56 34 12") + swallowed = ("s_mov_b32 s10, s4", "04 03 8a be") + tail = [WAIT, ("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, vcc_hi", "6b 02 16 7e"), + ("v_mov_b32_e32 v12, s10", "0a 02 18 7e"), ("v_mov_b32_e32 v13, s11", "0b 02 1a 7e")] + STORE_X4 + program = SET_SGPR_V + [(None, LOAD_X8_VCC), swallowed, literal] + tail + hidden = bytes.fromhex(LOAD_X8_VCC)[4:] + bytes.fromhex(swallowed[1]) + bytes.fromhex(literal[1]) + # an exp whose ignored bits are set is printed with other bytes than the blob holds + normalized = bytes.fromhex("60 0d 00 f8 00 00 00 00") + for name, junk in (("8 bytes", [hidden[:8]]), ("12 bytes, then 4", [hidden[:12], hidden[12:]]), + ("8 bytes, normalized", [normalized])): + with self.subTest(junk=name): + data, blob = listing_and_blob(program) + lines = data.decode().splitlines() + first = next(i for i, line in enumerate(lines) if line == INVALID) + after = [] if sum(map(len, junk)) > 8 else lines[first + 3:first + 4] + lines[first:first + 4] = [INVALID] + [f"\ts_nop 0{'':<33}" + encoding(j.hex()) for j in junk] + after + spv = translate_listing(NAME, ("\n".join(lines) + "\n").encode(), fssm=blob) + mem = run(spv, {BASE + 4 * i: 0x11110000 + i for i in range(8)}) + self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], + [0x11110000, 0x11110007, 0x1000, 0x12345678]) + + def test_rejected_word_after_a_tuple_is_still_refused(self): + # inside no printed instruction: llvm-mc rejected the word itself, so it is not taken for swallowed code + program = SET_SGPR_V + [(None, LOAD_X8_VCC), (None, "04 03 8a be 04 03 8a be"), WAIT] + STORE_X4 + with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): + translate(program) + def test_other_undecodable_words_are_still_refused(self): # SHADER-813: a rejected word that is not a tuple into vcc (sdata 112, not a register) stays undecodable, # and the code that runs into it is refused diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 6ab9cf395e..1790e04a63 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17157,25 +17157,44 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): translator takes for these instructions. Every blob dword in the code range that no matched instruction covers is offered to it; the instruction is used only if its operands hold such a list, so no other undecodable word changes. Instructions printed inside the words of a restored one are dropped. The instructions already carry - their blob offsets in "pc"; returns the list sorted by it.""" + their blob offsets in "pc"; returns the list sorted by it. + + The junk can be longer than the second word it starts at, and then it also swallows the instruction after the + tuple, which no printed instruction covers once the junk is dropped. The words after a restored instruction are + therefore decoded the same way until the stream is back at an instruction llvm-mc printed there. A word that + llvm-mc itself rejected, inside no printed instruction, is not one of those and stays undecodable.""" import rdna2_decode - covered = set() + printed, covered, starts = set(), set(), set() + unplaced = None # the pc of the first junk since an instruction that matched the blob for ins in insns: - if not ins.get("normalized"): - covered.update(range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4)) + if ins.get("normalized"): + # Its pc is a lower bound: the word llvm-mc rejected before it was not counted. + unplaced = ins["pc"] if unplaced is None else unplaced + continue + if unplaced is not None: + printed.update(range(unplaced, ins["pc"], 4)) + unplaced = None + words = range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4) + printed.update(words) + starts.add(ins["pc"]) + covered.update(words) stop = min(len(blob), code_end if code_end is not None else len(blob)) restored, at = [], code_start - while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] - if found and found[0]["pc"] == 0 and any( - a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): + resync = False # at follows a restored instruction and is inside junk llvm-mc printed, not at a start + while at + 4 <= stop: + found = None + if resync or at not in covered: + found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] + if found and found[0]["pc"] == 0 and at + len(found[0]["enc"]) // 2 <= stop and (resync or any( + a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"])): ins = found[0] - nbytes = len(ins["enc"]) // 2 - if at + nbytes <= stop: - ins["pc"] = at - restored.append(ins) - at += nbytes - continue + ins["pc"] = at + restored.append(ins) + at += len(ins["enc"]) // 2 + # nothing runs on past these, so the words after them are not known to be code + resync = at in printed and at not in starts and base_op(ins["op"]) not in ("s_branch", "s_endpgm", "s_setpc_b64") + continue + resync = False at += 4 if not restored: return insns From 688674095cba178f3e0ae9d66710f364af4f5d50 Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:45:15 +0100 Subject: [PATCH 2/3] test_vcc_tuple_fallback: cover where a resync starts and stops Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_vcc_tuple_fallback.py | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 01938dab40..6bbf1719ee 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -184,5 +184,61 @@ def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self): self.assertEqual((restored[0]["pc"], len(restored[0]["enc"]) // 2), (0, 12)) +class ResyncTest(unittest.TestCase): + """restore_vcc_tuples on hand-built instruction lists: where the words after a restored tuple are decoded, and + where that stops.""" + LITERAL = "ff 03 8b be 78 56 34 12" # s_mov_b32 s11, 0x12345678 + MOV = "04 03 8a be" # s_mov_b32 s10, s4 + END = "00 00 81 bf" # s_endpgm + BAD = "ff ff ff ff" # no instruction + + def restore(self, words, printed, code_start=0, normalized=()): + """printed, normalized: (pc, bytes) of the instructions llvm-mc listed; returns [(pc, size)] in order.""" + blob = bytes.fromhex("".join(words)) + insns = [{"pc": pc, "enc": blob[pc:pc + n].hex(), "op": "x", "args": []} for pc, n in printed] + insns += [{"pc": pc, "enc": "00" * n, "op": "x", "args": [], "normalized": True} for pc, n in normalized] + insns.sort(key=lambda i: i["pc"]) + out = rdna2spirv.restore_vcc_tuples(insns, blob, code_start, len(blob)) + return [(i["pc"], len(i["enc"]) // 2) for i in out] + + def test_stops_at_a_printed_instruction(self): + # the tuple's junk covers words 1 and 2; the s_mov_b32 at 12 is printed, with its own operands, and stays + words = [LOAD_X8_VCC, self.MOV, self.MOV, self.END] + self.assertEqual(self.restore(words, [(4, 8), (12, 4), (16, 4)]), [(0, 8), (8, 4), (12, 4), (16, 4)]) + blob = bytes.fromhex("".join(words)) + insns = [{"pc": 4, "enc": blob[4:12].hex(), "op": "x", "args": []}, + {"pc": 12, "enc": blob[12:16].hex(), "op": "printed", "args": []}] + self.assertIn("printed", [i["op"] for i in rdna2spirv.restore_vcc_tuples(insns, blob, 0, len(blob))]) + + def test_crosses_a_start_that_is_a_literal_printed_on_its_own(self): + # The 8-byte instruction at 12 runs across a printed start (16): its own literal, which llvm-mc printed as an + # instruction because the junk before it ended there. So a resync may not stop at every printed start. + words = [LOAD_X8_VCC, self.MOV, self.LITERAL, self.END] + self.assertEqual(self.restore(words, [(4, 12), (16, 4), (20, 4)]), [(0, 8), (8, 4), (12, 8), (20, 4)]) + + def test_drops_out_when_a_decode_fails(self): + # a word no decoder takes inside the junk: the s_mov_b32 after it is not picked up again + words = [LOAD_X8_VCC, self.BAD, self.MOV, self.END] + self.assertEqual(self.restore(words, [(4, 12), (16, 4)]), [(0, 8), (16, 4)]) + + def test_two_junk_regions_are_separate(self): + # Two regions of normalized junk with matched instructions between them: the first ends at the match, so the + # rejected word at 20, between the regions, is in neither and is not decoded after the second tuple. + words = [LOAD_X8_VCC, self.MOV, LOAD_X8_VCC, self.MOV, self.MOV, self.END] + self.assertEqual(self.restore(words, [(8, 4), (28, 4)], normalized=[(4, 4), (24, 4)]), + [(0, 8), (8, 4), (12, 8), (24, 4), (28, 4)]) + + def test_nothing_is_decoded_before_a_tuple(self): + # the first words are inside junk of something else: no tuple, so they stay as they are + words = [self.MOV, self.MOV, self.END] + self.assertEqual(self.restore(words, [], normalized=[(0, 8)]), [(0, 8)]) + + def test_resync_to_the_last_word(self): + self.assertEqual(self.restore([LOAD_X8_VCC, self.MOV, self.MOV], [(4, 12)]), [(0, 8), (8, 4), (12, 4)]) + + def test_a_tuple_at_the_very_end_of_the_code(self): + self.assertEqual(self.restore([self.MOV, LOAD_X8_VCC], [(0, 4)]), [(0, 4), (4, 8)]) + + if __name__ == "__main__": unittest.main() From 091cd9680bc90a7bbad8ec0333be3878e198b2e3 Mon Sep 17 00:00:00 2001 From: JARVIX <273200855+jarvixaiassistant-glitch@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:48:02 +0000 Subject: [PATCH 3/3] rdna2spirv: restrict restore_vcc_tuples to reachable offsets and protect branch targets Do not scan unreachable embedded data words skipped by s_branch or after s_endpgm / s_setpc_b64 in restore_vcc_tuples. Walk only offsets reachable from code_start via matched instructions, fall-through, and direct/folded far branches, and discard any restored instruction whose interior dwords are targeted by a reachable branch. Fixes the synthetic edge case reported on #596 / #674 by @Snooozs where an unreachable data word equal to the first dword of an 8-byte vcc-tuple load right before a branch target caused restore_vcc_tuples to swallow the target instruction and fail with 'branch into data'. Adds regression tests covering: skipped data word before a matched branch target, skipped data word before a vcc-tuple load at the branch target, data word after s_endpgm before a branch target, and fall-through into a data word directly before a branch target. --- tests/semantic/test_vcc_tuple_fallback.py | 65 ++++++++++++++++++++++- tools/rdna2spirv.py | 63 ++++++++++++++++------ 2 files changed, 111 insertions(+), 17 deletions(-) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 67e6bc5211..9e8f3452e1 100644 --- a/tests/semantic/test_vcc_tuple_fallback.py +++ b/tests/semantic/test_vcc_tuple_fallback.py @@ -64,8 +64,11 @@ def listing_and_blob(program, variant="invalid"): if text is not None: lines.append(f"\t{text:<40}{encoding(raw)}") continue - second = bytes.fromhex(raw)[4:8] + raw_bytes = bytes.fromhex(raw) lines.append(INVALID) + if len(raw_bytes) == 4: + continue + second = raw_bytes[4:8] if variant == "invalid": lines.append(INVALID) elif variant == "junk": # the second word decodes as an instruction of its own, bytes as stored @@ -152,6 +155,66 @@ def test_nsa_mimg_with_vcc_tuple_does_not_read_past_code_end(self): self.assertEqual(len(restored), 1) self.assertEqual((restored[0]["pc"], len(restored[0]["enc"]) // 2), (0, 12)) + def test_skipped_data_word_before_branch_target_is_not_restored(self): + # An unreachable data word skipped by s_branch whose bytes equal the first dword of a vcc-tuple load must + # not be restored across the branch target instruction that immediately follows it. + program = SET_SGPR_V + [ + ("s_branch 1", "01 00 82 bf"), + (None, "02 19 2c f4"), + ("v_mov_b32_e32 v10, 7", "87 02 14 7e"), + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), + ] + mem = run(translate(program), {}) + self.assertEqual(mem.get(OUT), 7) + + def test_skipped_data_word_before_branch_target_vcc_load(self): + # Same skipped data word right before a real vcc-tuple load at the branch target: the data word is skipped + # and the real vcc-tuple load at the target is restored cleanly across all three listing variants. + program = SET_SGPR_V + [ + ("s_branch 1", "01 00 82 bf"), + (None, "02 19 2c f4"), + (None, LOAD_X8_VCC), WAIT, + ("v_mov_b32_e32 v10, s100", "64 02 14 7e"), ("v_mov_b32_e32 v11, s105", "69 02 16 7e"), + ("v_mov_b32_e32 v12, vcc_lo", "6a 02 18 7e"), ("v_mov_b32_e32 v13, vcc_hi", "6b 02 1a 7e"), + ] + STORE_X4 + words = [0x22220000 + i for i in range(8)] + for variant in PROGRAM_VARIANTS: + with self.subTest(printed_as=variant): + mem = run(translate(program, variant), {BASE + 4 * i: w for i, w in enumerate(words)}) + self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], [words[0], words[5], words[6], words[7]]) + + def test_data_word_after_endpgm_before_branch_target_is_not_restored(self): + # An unreachable data word after s_endpgm right before a branch target is likewise ignored. + program = SET_SGPR_V + [ + ("s_cmp_eq_i32 s4, s4", "04 04 00 bf"), + ("s_cbranch_scc1 2", "02 00 85 bf"), + ("s_endpgm", "00 00 81 bf"), + (None, "02 19 2c f4"), + ("v_mov_b32_e32 v10, 7", "87 02 14 7e"), + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), + ] + mem = run(translate(program), {}) + self.assertEqual(mem.get(OUT), 7) + + def test_fallthrough_into_data_word_before_branch_target_refused(self): + # When fall-through reaches a data word equal to the first dword of a vcc-tuple load right before a branch + # target, restore_vcc_tuples must not swallow the branch target; reachable_code refuses the fall-through. + program = SET_SGPR_V + [ + ("s_cmp_eq_i32 s4, s4", "04 04 00 bf"), + ("s_cbranch_scc1 1", "01 00 85 bf"), + (None, "02 19 2c f4"), + ("v_mov_b32_e32 v10, 7", "87 02 14 7e"), + ("v_mov_b32_e32 v6, 0x3000", "ff 02 0c 7e 00 30 00 00"), + ("global_store_dword v6, v10, s[0:1]", "00 80 70 dc 06 0a 00 00"), + ("s_endpgm", "00 00 81 bf"), + ] + with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): + translate(program) + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index c5135bcd46..b7164d948a 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17153,29 +17153,60 @@ def restore_vcc_tuples(insns, blob, code_start, code_end): s[100:107], a buffer resource in s[104:107]): it skips the first word as invalid and then prints the second word as an instruction of its own, one that is junk or does not match the blob (docs/shader_library.md section 5). The pure-Python decoder reads such a word as a VCCTuple list, [s100,...,s105,vcc_lo,vcc_hi], the form the - translator takes for these instructions. Every blob dword in the code range that no matched instruction covers - is offered to it; the instruction is used only if its operands hold such a list, so no other undecodable word - changes. Instructions printed inside the words of a restored one are dropped. The instructions already carry - their blob offsets in "pc"; returns the list sorted by it.""" + translator takes for these instructions. Only uncovered offsets reached from code_start by fall-through or + branches (including folded far branches) are offered to it, so unreachable embedded data words skipped by a + branch or after s_endpgm are never decoded across a following branch target; the instruction is used only if + its operands hold such a list and no reachable branch targets its interior dwords. Instructions printed inside + the words of a restored one are dropped. The instructions already carry their blob offsets in "pc"; returns + the list sorted by it.""" import rdna2_decode covered = set() for ins in insns: if not ins.get("normalized"): covered.update(range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4)) + folded = fold_far_branches(insns) + by_pc = {ins["pc"]: ins for ins in folded + if all(o in covered for o in range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4))} stop = min(len(blob), code_end if code_end is not None else len(blob)) - restored, at = [], code_start - while at + 8 <= stop: - found = None if at in covered else rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] - if found and found[0]["pc"] == 0 and any( - a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): - ins = found[0] - nbytes = len(ins["enc"]) // 2 - if at + nbytes <= stop: - ins["pc"] = at - restored.append(ins) - at += nbytes + restored, restored_covered, reachable_targets = [], set(), set() + seen, work = set(), [code_start] + while work: + at = work.pop() + while code_start <= at < stop and at not in seen: + seen.add(at) + ins = by_pc.get(at) + if ins is not None: + op = base_op(ins["op"]) + nxt = at + len(ins["enc"]) // 2 + if op in BRANCHES: + imm = next((x for x in ins["args"] if x["k"] == "imm"), None) + v = (imm["v"] & 0xFFFF) if imm else 0 + tgt = ins["target"] if "target" in ins else nxt + 4 * (v - 0x10000 if v & 0x8000 else v) + reachable_targets.add(tgt) + work.append(tgt) + if op == "s_branch": + break + if op in ("s_endpgm", "s_setpc_b64"): + break + at = nxt continue - at += 4 + if at in covered or at in restored_covered or at + 8 > stop: + break + found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)])["insns"][:1] + if found and found[0]["pc"] == 0 and any( + a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in found[0]["args"]): + r = found[0] + nbytes = len(r["enc"]) // 2 + if (at + nbytes <= stop + and not any(o in restored_covered for o in range(at, at + nbytes, 4))): + r["pc"] = at + restored.append(r) + restored_covered.update(range(at, at + nbytes, 4)) + at += nbytes + continue + break + restored = [r for r in restored + if not any(o in reachable_targets for o in range(r["pc"] + 4, r["pc"] + len(r["enc"]) // 2, 4))] if not restored: return insns spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored]