diff --git a/docs/design.md b/docs/design.md index daeb4eb425..b929f29993 100644 --- a/docs/design.md +++ b/docs/design.md @@ -306,7 +306,7 @@ How the generated SPIR-V expects the runtime to work: | 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). **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. GPU-checked by `runtime/test/shaders/cs_global_mem_ext.asm` for two of the ten ops (one lane, `saddr` addressing, on a Radeon 610M (gfx1036, RADV, Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), Linux): `global_store_short` at byte 3 of a dword changes only its two bytes, across both dwords, and `global_load_sbyte_d16_hi` sign-extends a byte into the high half of `vdst` and keeps the low half. **Not GPU-verified:** the other eight ops and an inactive lane. | | 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). | | Pipeline-library scalar operands | A scalar load may use VCC as a 64-bit pointer. In wave32 programs using that operand, scalar pair moves and XORs preserve both address words. Read its low and high data words, gathering a native wave's mask bits when a half is mask-valued. An emulated wave64 mask-valued pointer is refused. Where LLVM rejects a scalar, image or buffer tuple ending in VCC, recover the tuple from its original bytes before following branches. Hand-built memory and decoder cases in `test_library_compute_forms.py` and `test_vcc_tuple_fallback.py`. | -| 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 3ef944a528..8cf131ca48 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -223,8 +223,13 @@ 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. They are decoded for the program's own wave size: in wave64 a + swallowed VOP3 compare writes an SGPR pair. 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_library_compute_forms.py b/tests/semantic/test_library_compute_forms.py index e8a62444ce..0e1c84bf40 100644 --- a/tests/semantic/test_library_compute_forms.py +++ b/tests/semantic/test_library_compute_forms.py @@ -43,7 +43,7 @@ def test_short_prologue_has_two_literals(self): def test_recovered_vcc_tuple(self): code = raw_words(fixture("vcc_tuple_word")) - self.assertEqual(rdna2spirv.restore_skipped_instructions([], code, 0, len(code))[0]["args"][0]["r"], + self.assertEqual(rdna2spirv.restore_vcc_tuples([], code, 0, len(code))[0]["args"][0]["r"], [104, 105, "vcc_lo", "vcc_hi"]) def run_wave32(self, name, memory): @@ -94,8 +94,9 @@ def test_vopc_dpp_encoded_fields_and_recovery(self): self.assertEqual((row["op"], row["args"][0]["t"], row["args"][1]["r"], row["args"][2]["r"]), ("v_cmp_gt_f32_dpp", "vcc_lo" if wave32 else "vcc", 7, 12)) self.assertIn(control, row["mods"]) - junk = {"pc": 4, "enc": blob[4:].hex()} - recovered, = rdna2spirv.restore_skipped_instructions([junk], blob, 0, len(blob)) + # a listing entry as llvm-mc prints the second word: restore_vcc_tuples reads its op, as it does a real one + junk = {"pc": 4, "enc": blob[4:].hex(), "op": "s_nop", "args": [{"k": "imm", "v": 0}], "mods": []} + recovered, = rdna2spirv.restore_vcc_tuples([junk], blob, 0, len(blob), wave32=wave32) self.assertEqual((recovered["pc"], recovered["enc"]), (0, blob.hex())) self.assertFalse(rdna2_decode.decode_bytes(blob[:4])["insns"]) diff --git a/tests/semantic/test_vcc_tuple_fallback.py b/tests/semantic/test_vcc_tuple_fallback.py index 8df6e2a9cc..9b614f3812 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 @@ -136,6 +139,65 @@ 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_swallowed_compare_in_wave64_writes_a_pair(self): + # The junk exp covers the tuple's second word and the compare's first; the compare's second prints on its own. + program = SET_SGPR_V + [ + ("s_mov_b32 s12, 0", "80 03 8c be"), ("s_mov_b32 s13, 0", "80 03 8d be"), + (None, LOAD_X8_VCC), + ("v_cmp_gt_u32_e64 s[12:13], 40, v0", "0c 00 c4 d4 a8 00 02 00"), + WAIT, + ("s_bcnt1_i32_b64 s10, s[12:13]", "0c 10 8a be"), + ("v_mov_b32_e32 v10, s10", "0a 02 14 7e"), + ("v_lshlrev_b32_e32 v6, 2, v0", "82 00 0c 34"), + ("v_add_nc_u32_e32 v6, 0x3000, v6", "ff 0c 0c 4a 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"), + ] + data, blob = listing_and_blob(program) + blob = bytearray(blob) + struct.pack_into("<4I", blob, 0x138, 0x88, 64, 1, 1) + struct.pack_into("> 8 & 255) + + def restore_ops(self, words, printed): + blob = bytes.fromhex("".join(words)) + insns = [{"pc": pc, "enc": blob[pc:pc + n].hex(), "op": op, "args": args} for pc, n, op, args in printed] + return [i["pc"] for i in rdna2spirv.restore_vcc_tuples(insns, blob, 0, len(blob))] + + def test_a_swallowed_branch_is_followed(self): + # the s_branch at 8, in the first tuple's junk, is the only way to the second tuple at 16 + words = [LOAD_X8_VCC, self.branch("s_branch", 1), self.BAD, LOAD_X8_VCC, self.END] + self.assertEqual(self.restore_ops(words, [(4, 8, "x", []), (24, 4, "s_endpgm", [])]), [0, 8, 16, 24]) + + def test_a_branch_to_a_swallowed_instruction_does_not_hide_it(self): + # 0: scc1 -> 16 (swallowed), then the jump to 24, from where the tuple at 8 is reached last + imm = [{"k": "imm", "v": 3}] + words = [self.branch("s_cbranch_scc1", 3), self.branch("s_branch", 4), LOAD_X8_VCC, self.MOV, self.END, + self.branch("s_cbranch_scc1", -6), self.END] + printed = [(0, 4, "s_cbranch_scc1", imm), (4, 4, "s_branch", [{"k": "imm", "v": 4}]), + (12, 8, "x", []), (20, 4, "s_endpgm", []), + (24, 4, "s_cbranch_scc1", [{"k": "imm", "v": -5}]), (28, 4, "s_endpgm", [])] + self.assertEqual(self.restore_ops(words, printed), [0, 4, 8, 16, 20, 24, 28]) + # the same with the branches to the two taken in the other order + printed[0], printed[4] = (0, 4, "s_cbranch_scc1", [{"k": "imm", "v": 1}]), (24, 4, "s_cbranch_scc1", + [{"k": "imm", "v": -3}]) + self.assertEqual(self.restore_ops(words, printed), [0, 4, 8, 16, 20, 24, 28]) + + def test_what_follows_a_branched_into_tuple_is_dropped_with_it(self): + # a branch lands on the tuple's second word, so neither the tuple nor the words after it are taken for code + words = [self.branch("s_cbranch_scc1", 1), LOAD_X8_VCC, self.MOV, self.END] + printed = [(0, 4, "s_cbranch_scc1", [{"k": "imm", "v": 1}]), (8, 8, "x", []), (16, 4, "s_endpgm", [])] + self.assertEqual(self.restore_ops(words, printed), [0, 8, 16]) + + 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() diff --git a/tests/test_rdna2spirv_decode.py b/tests/test_rdna2spirv_decode.py index dc1f0ed9e5..25be275301 100644 --- a/tests/test_rdna2spirv_decode.py +++ b/tests/test_rdna2spirv_decode.py @@ -387,7 +387,7 @@ def test_fall_through_into_undecodable_words_is_refused(self): export = [0x0F, 0x18, 0x00, 0xF8, 0x00, 0x01, 0x00, 0x01] endpgm = [0x00, 0x00, 0x81, 0xBF] # The word of the finding was [0x00,0x50,0x16,0xCC, 0x01,0x05,0x0E,0x0C]; the translator recovers that one - # v_dot4_i32_i8 form from the program's words now (restore_skipped_instructions), so it is no longer a gap. + # v_dot4_i32_i8 form from the program's words now (rdna2spirv.skipped_form), so it is no longer a gap. # This is the same instruction with another op_sel, which is not recovered and stays skipped. gap = [0x00, 0x58, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 936de535a9..f3b7691a08 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17524,6 +17524,110 @@ def restore_mix_inline_literal(ins, raw, literal): ins["enc"] = raw.hex() +def skipped_form(ins, blob, at): + """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that + restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare in DPP + form (docs/design.md, "DPP on a VOPC compare"), or the measured v_dot4_i32_i8 with op_sel 2 / op_sel_hi 5 and no + clamp or neg, all reserved bits clear (tedin7, upstream PR #281; docs/fspx.md). shader_disasm.py prints the last + two itself; this covers a listing made without that pass (#984).""" + op = ins["op"] + if op.startswith("v_cmp_") and op.endswith("_f32_dpp"): + return True + if op == "v_dot4_i32_i8" and int.from_bytes(blob[at:at + 4], "little") >> 8 == 0xCC1650 and blob[at + 7] >> 3 == 1: + return True + return any(a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in ins["args"]) + + +def restore_vcc_tuples(insns, blob, code_start, code_end, wave32=True): + """Decode from the blob the instructions llvm-mc rejects because a scalar tuple runs into vcc. + + SGPRs 106 and 107 are vcc, and llvm-mc refuses to print a tuple that crosses into them (s_buffer_load_dwordx8 into + 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. 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. + + 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. wave32 is the + shader's wave size: a swallowed VOP3 compare writes one SGPR in wave32 and a pair in wave64.""" + import rdna2_decode + 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 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) + 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)) + runs, restored_covered, reachable_targets = [], set(), set() # runs: a tuple and the instructions after it + seen, work = set(), [code_start] + while work: + at = work.pop() + run = None # the run the previous instruction was restored into, or None after a printed one + while code_start <= at < stop and at not in seen: + ins = by_pc.get(at) + if ins is not None: + run = None + else: + # inside junk llvm-mc printed, not at a start: the words after a restored instruction are code + resync = run is not None and at in printed and at not in starts + if at in restored_covered or (at in covered and not resync): + break + found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)], wave32=wave32)["insns"][:1] + if not (found and found[0]["pc"] == 0 and (resync or skipped_form(found[0], blob, at))): + break + ins = found[0] + end = at + len(ins["enc"]) // 2 + if end > stop or any(o in restored_covered for o in range(at, end, 4)): + break + ins["pc"] = at + if not resync: + run = [] + runs.append(run) + run.append(ins) + restored_covered.update(range(at, end, 4)) + seen.add(at) + op = base_op(ins["op"]) + 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 at + 4 * (v - 0x10000 if v & 0x8000 else v) + reachable_targets.add(tgt) + work.append(tgt) + # shortcut: a swallowed far branch is not followed, so a tuple only it reaches stays refused + if op in ("s_branch", "s_endpgm", "s_setpc_b64"): + break + restored = [] + for run in runs: + for r in run: + if any(o in reachable_targets for o in range(r["pc"] + 4, r["pc"] + len(r["enc"]) // 2, 4)): + break # not an instruction, so the words after it are not known to be code either + restored.append(r) + if not restored: + return insns + spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored] + kept = [i for i in insns if not any(i["pc"] < hi and i["pc"] + len(i["enc"]) // 2 > lo for lo, hi in spans)] + return sorted(kept + restored, key=lambda i: i["pc"]) + + def widen_wave64_masks(insns): """In place: the lane-mask SGPR operands of VALU instructions become the pairs they are in wave64. @@ -17547,55 +17651,6 @@ def widen_wave64_masks(insns): for i in at: if i < len(a) and a[i]["k"] == "sgpr" and a[i].get("n", 1) == 1: a[i] = dict(a[i], n=2) -# Adapted from tedin7 via Andretuta, ubiquitarianism/leonida PR #327. -def restore_skipped_instructions(insns, blob, code_start, code_end): - """Recover known LLVM gaps from their original instruction words. - - llvm-mc rejects a tuple that reaches SGPRs 106 and 107 (s_load_dwordx8 into s[100:107], an image resource in - 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. Recover VCC tuples, DPP comparisons and the measured signed-byte dot half swap. - 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)) - 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 ( - (found[0]["op"].startswith("v_cmp_") and found[0]["op"].endswith("_f32_dpp")) - # tedin7 (upstream PR #281): LLVM skips this VOP3P form. Admit only opcode 0x16, - # op_sel=2, op_sel_hi=5, no clamp or neg, with all reserved encoding bits clear. - or (found[0]["op"] == "v_dot4_i32_i8" and - int.from_bytes(blob[at:at + 4], "little") >> 8 == 0xCC1650 and blob[at + 7] >> 3 == 1) - 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 - at += 4 - if not restored: - return insns - # Both streams are in program order. A shader can contain thousands of recovered tuples. - spans = iter((r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored) - span = next(spans, None) - kept = [] - for ins in insns: - pc = ins["pc"] - while span and span[1] <= pc: - span = next(spans, None) - if not span or pc + len(ins["enc"]) // 2 <= span[0]: - kept.append(ins) - return sorted(kept + restored, key=lambda i: i["pc"]) def output_signature(path, name): @@ -17823,6 +17878,36 @@ def fspx_wave_size(path, name): return None if not isinstance(wave32, bool) else (32 if wave32 else 64) +def fssm_wave_size(path, name): + """32 or 64 from the FSSM header flags, or None when the program has no FSSM blob.""" + try: + with open(native_paths(path, name)[0], "rb") as f: + return fssm_header.wave_size(f.read(fssm_header.WAVE_FLAGS_OFFSET + 4)) + except OSError: + return None + + +def wave_markers(insns): + """The wave size the code itself shows: (strict wave64 ops, any wave64 use, any wave32 EXEC op).""" + w64_marks = {base_op(i["op"]) for i in insns + if WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]]))} + code_w64 = bool(w64_marks) or any(base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") + for x in i["args"]) for i in insns) + code_w32 = any(WAVE32_RE.search(i["op"]) for i in insns) + return w64_marks, code_w64, code_w32 + + +def marker_wave64(path, name, stage, insns): + """Whether a program whose header and dispatch state hold no wave size is wave64, from its code.""" + w64_marks, code_w64, code_w32 = wave_markers(insns) + if (stage in ("vs", "ps") and code_w64 and code_w32 and not (w64_marks - {"s_bfm_b64"}) + and os.path.isfile(native_paths(path, name)[1]) and source_wave_size(path, name) == 32): + # A library program can use s_bfm_b64 as scalar data. Use the matching source's + # wave32 flags only when this program's own EXEC instructions corroborate them. + return False + return code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) + + def translate(path): info = parse_file(path) stage = stage_of(info["name"], path) @@ -17902,7 +17987,11 @@ def translate(path): ins["normalized"] = True ins["pc"] = at pos = at + len(enc) - insns = restore_skipped_instructions(insns, blob, info["code_start"], info.get("code_end")) + wave = fssm_wave_size(path, info["name"]) or fspx_wave_size(path, info["name"]) + if wave is None: + matched = [i for i in insns if not i.get("normalized")] + wave = 64 if marker_wave64(path, info["name"], stage, matched) else 32 + insns = restore_vcc_tuples(insns, blob, info["code_start"], info.get("code_end"), wave32=wave == 32) insns = fold_far_branches(insns) insns = reachable_code(insns, info.get("code_end")) if any(i.get("normalized") for i in insns): @@ -17924,23 +18013,12 @@ def translate(path): g.round_mode = any(i["op"] == "s_round_mode" or (i["op"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "")) for i in insns) - w64_marks = {base_op(i["op"]) for i in insns - if WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]]))} - strict_w64 = bool(w64_marks) - code_w64 = strict_w64 or any(base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") - for x in i["args"]) for i in insns) - code_w32 = any(WAVE32_RE.search(i["op"]) for i in insns) + w64_marks, code_w64, code_w32 = wave_markers(insns) # Authoritative wave size from the FSSM header flags at 0xD4 bit 5 (0x20 = wave32, 0 = wave64; # verified with 0 contradictions across all 26,503 corpus blobs). Falls back to the code-marker # heuristic (+ wave64 default for NGG mesh shaders) when no FSSM sidecar is present (FSPX or # synthetic listings). - fssm_path, fspx_path, _ = native_paths(path, info["name"]) - fssm_ws = None - try: - with open(fssm_path, "rb") as f: - fssm_ws = fssm_header.wave_size(f.read(fssm_header.WAVE_FLAGS_OFFSET + 4)) - except OSError: - pass + fssm_ws = fssm_wave_size(path, info["name"]) # An FSPX program (the FidelityFX DLL's) has no FSSM header; its kind-0 dispatch state carries the wave size # instead (word 4 bit 20 = wave32, docs/fspx.md). Only the strict markers count against it: a _b64 op on vcc or # exec is not one, since these programs move vcc as an ordinary SGPR pair (s_mov_b64 vcc, s[..]) in wave32 code. @@ -17959,13 +18037,8 @@ def translate(path): if fspx_ws == 64 and code_w32: raise Unsupported("FSPX wave64 dispatch state contradicts wave32 code") g.wave64 = fspx_ws == 64 - elif (stage in ("vs", "ps") and code_w64 and code_w32 and not (w64_marks - {"s_bfm_b64"}) - and os.path.isfile(fspx_path) and source_wave_size(path, info["name"]) == 32): - # A library program can use s_bfm_b64 as scalar data. Use the matching source's - # wave32 flags only when this program's own EXEC instructions corroborate them. - g.wave64 = False else: - g.wave64 = code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) + g.wave64 = marker_wave64(path, info["name"], stage, insns) if g.wave64: widen_wave64_masks(insns) # A wave32 program using VCC as an SMEM pointer needs both scalar words. Mark its pair producers