From 772c7bc3f35f5f141d7225b832dbc2e4409f2783 Mon Sep 17 00:00:00 2001 From: hugo <63666848+hugo0024@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:55:45 +0800 Subject: [PATCH] rdna2spirv: ds_permute_b32 stores its shuffles, so every lane runs them (SHADER-PERMUTE-EAGER) Gen.ds_permute lets each destination lane scan the 32 source lanes of its half: per source lane a shuffle of the published target, a shuffle of the data and an OpSelect that keeps the data when the target is this lane. Each shuffle was used once and so was every link of that chain, so SPIRV-Cross (MoltenVK) wrote the 32 steps as one nested ternary under the EXEC ternary of the register write. A lane that takes an outer arm, or is off in EXEC, then runs none of the shuffles inside it (the SHADER-529 mechanism). On an Apple M5 (MoltenVK 1.4.2) tools/lds_fuzz.py --wave 32 --permute had 17 of the 100 programs of seed 31002 differ from the model, every one in a ds_permute_b32 result, mostly 0 where a source lane's data belongs. Both shuffles are now stored to Function variables (Gen.eager), as the DPP rule stores its ballot bit and its shuffle. tests/semantic/test_ds_permute_eager.py checks the three native forms with test_dpp_eager_subgroup.py's model of SPIRV-Cross's single-use forwarding, and the values against test_ds_permute.py's ISA model. Co-Authored-By: Claude Fable 5.2 --- docs/design.md | 2 +- tests/semantic/README.md | 5 + tests/semantic/test_ds_permute_eager.py | 126 ++++++++++++++++++++++++ tools/rdna2spirv.py | 6 ++ 4 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 tests/semantic/test_ds_permute_eager.py diff --git a/docs/design.md b/docs/design.md index 10a08fcc2e..40e418da38 100644 --- a/docs/design.md +++ b/docs/design.md @@ -449,7 +449,7 @@ How the generated SPIR-V expects the runtime to work: | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Wave64 emulation: single-wave barrier fallback | `translate()` re-translates an emulated compute program as the round loop (`Gen.x_scheduler`) when its inline structured form has an `OpControlBarrier` inside a selection or loop construct (`barriers_under_control_flow`), because a barrier only part of the workgroup reaches hangs NVIDIA (Xid 109). That fallback applies **only to multi-wave plans**. A single-wave workgroup (`plan_structured_emulation` mode `inline_all`, `x_lanes == 64`, also a partial group of fewer than 64 threads) is one wave: `%pc` between blocks comes from scalar state and votes read back from `%x_buf`, so every invocation takes the same path, and lane-local `%pc` exists only inside `emit_folded_region`'s `if (%active)` bodies, which emit no exchange and no barrier. Its barriers stay where the exchanges are, at the top level or under `%pc`-only guards. Why: the round loop keeps nearly the whole register file live across its back edge and through a switch over every segment (thousands of cases in large programs); on RADV/ACO (RX 7900 XTX, Mesa 26.3.1, offline `vk_pipeline_check` compiles only) that drove `aco::spill` past a 12 GiB cap (53 GB uncapped) on a large single-wave program the structured form compiles in 7–8.5 min under 3 GiB, and past 12 GiB in 35 s on a 4.9 MB one that compiles in 5 s at 0.3 GiB structured. ACO's static latency for single-wave programs with loops was 17 to 280 times that of the structured form, with VGPR spills each round, and three such programs (loops of up to thousands of iterations, one round per block visited) hung game runs on that GPU. Confirmed by a count over the 1.0.2.1 corpus: of the 820 single-wave emulated compute shaders of the main set that the fallback had put in the round loop, 666 get an `inline_all` plan, and in all 666 every barrier is at the top level or under constructs whose conditions load only `%pc` (none reads `%active`, a VGPR or `local_id`); the other 154 have no plan and stay rounds either way. Re-translated with this rule, exactly those 666 come out structured, the pipeline library's single-wave rounds drop from 818 to 171 (all 297 of them with loops are structured), and the translated and `spirv-val`-valid counts are unchanged (26,503 main, 2,683 library); recompiled, the 4.9 MB program takes 3.6 s at 0.37 GiB. CPU-checked by `tests/semantic/test_wave64_single_wave_barrier.py` (`wave64_single_wave_barrier.asm`: a cross-half `v_readlane_b32` in a uniform loop and a uniform branch, structured and round forms give the same words, every barrier guard loads only `%pc`), `test_wave64_emulate_opt.py` (`cs_inline_64`/`cs_inline_40`, both wave orders) and `test_loop_ballot_barrier.py`. **Not GPU-verified on NVIDIA**, the platform the fallback was written for. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | -| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | +| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Both shuffles are stored to Function variables before the selects read them (`Gen.eager`, SHADER-PERMUTE-EAGER): each is used once, as is every link of the chain, so SPIRV-Cross (MoltenVK) would write the 32 steps as one nested ternary under the EXEC ternary of the register write, where a lane that takes an outer arm or is off runs none of the shuffles inside it. Found by `lds_fuzz.py --wave 32 --permute` on an Apple M5 (MoltenVK 1.4.2): 17 of the 100 programs of seed 31002 differed, every one in a `ds_permute_b32` result, and none does with the stores; `tests/semantic/test_ds_permute_eager.py` checks them. Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | | LDS access order within a wave (`Volatile`) | RDNA2 runs a wave in lockstep with an in-order LDS queue, so a `ds_read` issued after a `ds_write` sees every lane's write with no `s_barrier` between them (`cs_w64x_lds_raw`), and a `ds_write` issued after a `ds_read` does not change what that read returned (`cs_w64x_lds_war`). Translated, a lane is an invocation, and the Vulkan memory model orders nothing between invocations without a barrier or an atomic, so a driver's compiler may move an invocation's load ahead of its own earlier store to another address, or merge two loads of one address. Results consistent with these optimizations were observed with AMD's Windows driver 24.30.46 (LLPC, Vulkan 1.3.302) on a Radeon 880M (RDNA3.5, native 64-wide compute subgroups): on `main` `561b65a8` both tests failed on every run with uninitialized Workgroup memory in all eight words, and in `cs_w64x_lds_war` the second read returned the same words as the first. Rule: every plain LDS `OpLoad` and `OpStore` (`lds_load`, `lds_store` and the two ADDTID forms) carries the `Volatile` memory operand, which prevents elimination, duplication or combination of the access ([SPIR-V memory operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Memory_Access)). This rule applies to plain accesses only. On that GPU and driver `Volatile` on the store alone or on the load alone made `cs_w64x_lds_raw` return its expected words (hand-edited SPIR-V, 3 of 3 runs each, against 0 of 4 unmodified), and with the rule both tests pass: `run_gpu_tests.py` goes from 210 to 212 of 232 passed with none failing (20 skipped), native and with `LEONIDA_W64_EMULATE=1`. An RTX 5070 Laptop (NVIDIA 621.01) gives the same results before and after (183 of 232 native, 214 emulated; `ms_wave_info_s3` fails both times). The operand changes 17 of the 238 test shaders and nothing but those loads and stores. A [full Xbox 1.0.2.1 corpus comparison](https://github.com/ItsNotRexed/Leonida/pull/6714#issuecomment-7107280378) translated and validated all 26,503 shaders at both 561b65a8 and 58deee34. Only the added operands differed in the 484 compute and 5 mesh modules that changed. The RAW and WAR results establish a workaround on the tested driver. Portable ordering between invocations requires synchronization appropriate to the accesses (see #2345). Under `--wave64-emulate` the halves meet at the round barriers as before; the operand is emitted there too. CPU-checked by `tests/semantic/test_lds_volatile.py` (every plain access form on the wave32, wave64 and emulated paths, and no other access is Volatile). | | `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11), and measured on native gfx1100 through `tools/hw_oracle` (hit, miss and hit-to-zero), where GFX11 spells it `ds_cmpstore_b32` with the store value before the compare value. **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). | | `ds_cmpst_f32`/`_rtn_f32`, `global_atomic_fcmpswap`, `buffer_atomic_fcmpswap` | `tmp = M; M = (tmp == CMP as binary32) ? DATA : tmp`, and the returning forms give `tmp` (RDNA2 ISA). The compare is a float compare (`OpFOrdEqual`): −0 matches +0, and a NaN never matches, not even the same bits. `OpAtomicCompareExchange` compares bits, so this is a loop (`Gen.float_cmpswap_loop`): read M, pick DATA or M by the float compare, and swap that in if M still holds what was read. Exact under contention. Operands: `ds_cmpst_f32` takes CMP then DATA, as `ds_cmpst_b32`; the global and buffer forms take `vdata` as {DATA, CMP}, as `cmpswap`. Inactive lanes, bounds and `glc` are as for their integer siblings. **Not measured:** subnormal inputs; the interpreter compares them exactly. `_x2` forms stay `Unsupported`; the image form is #2653's. Until 2026-11-22 all four raised `Unsupported`. CPU-checked by `tests/semantic/test_float_cmpswap.py` (±0, NaN, ∞, a subnormal, no `glc`, buffer bounds, 32 lanes on one dword). GPU-checked by `runtime/test/shaders/cs_w32_fcmpswap.asm` (one lane, on a Radeon 610M (gfx1036, RADV, Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), Linux): `ds_cmpst_rtn_f32` with +0 in memory and CMP −0 stores DATA and returns +0, and with a NaN in memory and the same NaN as CMP leaves the NaN; `ds_cmpst_f32` with an unequal CMP leaves memory; `buffer_atomic_fcmpswap` with `glc`, −0 in memory and CMP +0 stores DATA and returns −0, without `glc` and a CMP one ulp off leaves memory, and with a NaN in memory and as CMP leaves the NaN in memory (the fixture reads that word back since `a672a598`; rerun at `6261ca916` on the RTX 4070 Ti only). **Not GPU-verified:** `global_atomic_fcmpswap`, the matching case of `ds_cmpst_f32`, the value `buffer_atomic_fcmpswap` returns for a NaN, buffer bounds, inactive lanes and contention. | diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 5360ab2443..5ffed1aa8f 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -157,6 +157,11 @@ instruction family per file; the list below describes some of them, not every fi `ds_read2st64_b32`) and runs 32 lanes in lockstep; the 16 words come from a byte-level LDS model of the ISA rules and match what an RTX 4070 SUPER (driver 610.88) wrote. Three SPIR-V sabotages (zero-extending `_i8`/`_i16`, no high-half shift for `_d16_hi`, `st64` offset in dwords) must change the result. +- `test_ds_permute_eager.py` (SHADER-PERMUTE-EAGER) checks that `ds_permute_b32` stores both subgroup shuffles of each + source lane before a select reads them, in a wave32 and a wave64 compute shader and a pixel shader, with + `test_dpp_eager_subgroup.py`'s model of SPIRV-Cross's single-use forwarding; the module with the stores taken out + again has all 64 shuffles in a ternary's arm. It also runs the stored form against `test_ds_permute.py`'s ISA + model with EXEC narrowed, sources that are off and a collision. - `test_negative_controls.py` sabotages the translated SPIR-V text and requires the result to change. - `test_mutations.py` sabotages a temporary copy of `tools/` (13 regressions across SDWA, min3/max3, `v_bfe_i32`, `v_pk_fma_f16`, `v_fma_f16 op_sel`, `v_subrev_co_ci_u32`, `v_cmpx_eq_u64`, `v_mul_i32_i24`, `v_ffbh_i32`, diff --git a/tests/semantic/test_ds_permute_eager.py b/tests/semantic/test_ds_permute_eager.py new file mode 100644 index 0000000000..e6429dc245 --- /dev/null +++ b/tests/semantic/test_ds_permute_eager.py @@ -0,0 +1,126 @@ +"""ds_permute_b32's shuffles run in every lane, also after SPIRV-Cross inlines expressions (SHADER-PERMUTE-EAGER). + +Vulkan has no subgroup scatter, so Gen.ds_permute lets every destination lane scan the 32 source lanes of its half: +per source lane one shuffle of the published target and one of the data, and an OpSelect that keeps the data when +the target is this lane. Each shuffle was used once and so was every link of that chain, and SPIRV-Cross (MoltenVK) +inlines a result that is used once into the expression that uses it. The 32 steps became one nested ternary inside +the EXEC ternary of the register write, + + v10 = active ? (hit31 ? data31 : (hit30 ? data30 : ... )) : v10; + +where a lane that takes an outer arm, or is off in EXEC, runs none of the shuffles inside it, and a lane that reads +from it gets 0 or a stale word. tools/lds_fuzz.py found it on an Apple M5 (MoltenVK 1.4.2): +`--wave 32 --permute --programs 100 --seed 31002` had 17 programs differ, every one in a ds_permute_b32 result, and +none with both shuffles stored (storing the data shuffle alone left 13). Gen.ds_permute now stores both to Function +variables (Gen.eager, as SHADER-529 did for DPP's ballot and shuffle); a store is a statement every lane runs. + +The check is test_dpp_eager_subgroup.py's model of SPIRV-Cross's single-use forwarding, on the three native forms: +a wave32 compute shader, a wave64 one (two wave32 halves) and a pixel shader. The values are test_ds_permute.py's +business and are run here once more with EXEC narrowed, sources that are off and a collision, to show that the +stored shuffles still deliver the same words. --wave64-emulate has no subgroup operation in this rule. + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import os +import re +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import support # noqa: E402 (puts tools/ on the path) +import test_ds_permute as dp # noqa: E402 (the programs, the ISA model and the lockstep runner) +from test_dpp_eager_subgroup import conditional_subgroup_ops # noqa: E402 + +SHUFFLE = re.compile(r"^\s*(%\w+) = OpGroupNonUniformShuffle\b", re.M) + + +def shaders(): + """{label: SPIR-V text} of one ds_permute_b32 after EXEC was narrowed, in each native form.""" + insns = dp.CASES["rotate_by_one"][0] + return { + "wave32 compute": dp.translate_text("cs_perm_eager_w32", dp.program(insns, 0x55555555), 32), + "wave64 compute": dp.translate_text("cs_perm_eager_w64", dp.program(insns, 0x5555555555555555, wave=64), 64), + "pixel": support.translate_lines("ps_perm_eager", [ + "v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 42", "v_mov_b32_e32 v2, 7", "v_cmpx_lt_f32_e32 v0, v8", + "ds_permute_b32 v2, v0, v1", "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"]), + } + + +def uses_of(spvasm, result): + """The instructions that read `result`, as stripped lines.""" + word = re.compile(re.escape(result) + r"(?!\w)") + return [ln.strip() for ln in spvasm.splitlines() + if word.search(ln) and not ln.strip().startswith(result + " =")] + + +class PermuteShufflesRunInEveryLane(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.shaders = shaders() + + def test_no_shuffle_is_left_in_a_conditional_position(self): + for label, spv in self.shaders.items(): + with self.subTest(shader=label): + self.assertEqual(conditional_subgroup_ops(spv), []) + + def test_each_shuffle_is_stored_before_anything_reads_it(self): + for label, spv in self.shaders.items(): + with self.subTest(shader=label): + shuffles = SHUFFLE.findall(spv) + self.assertEqual(len(shuffles), 64) # target and data of 32 source lanes + stored_to = set() + for result in shuffles: + readers = uses_of(spv, result) + self.assertEqual(len(readers), 1, f"{result} is read by {readers}") + store = re.fullmatch(r"OpStore (%eager\d+) " + re.escape(result), readers[0]) + self.assertIsNotNone(store, f"{result} is read by `{readers[0]}`, not stored") + stored_to.add(store.group(1)) + self.assertEqual(len(stored_to), 64) # a variable of its own each: no store hides another + + def test_the_model_of_spirv_cross_sees_an_unstored_shuffle(self): + # The same module with the stores taken out again is what main produced: the check above must not pass it. + spv = self.shaders["wave32 compute"] + for result in SHUFFLE.findall(spv): + store = re.search(r"^\s*OpStore (%eager\d+) " + re.escape(result) + + r"\s*\n\s*(%\w+) = OpLoad %uint \1\s*\n", spv, re.M) + self.assertIsNotNone(store, result) + loaded = store.group(2) + spv = spv.replace(store.group(0), "") + spv = re.sub(re.escape(loaded) + r"(?!\w)", result, spv) + found = conditional_subgroup_ops(spv) + self.assertEqual(len(found), 64) + self.assertEqual({(op, where.split(" %")[0]) for _, op, where in found}, + {("OpGroupNonUniformShuffle", "arm of OpSelect")}) + + +class StoredShufflesDeliverTheSameWords(unittest.TestCase): + """EXEC narrowed, sources that are off and several sources to one lane, against the ISA model.""" + CASES = (("rotate_by_one", 0x0000FFFF), ("inactive_source_does_not_win", 0x55555555), + ("unwritten_lanes_are_zero", 0x00FF00FF), ("all_to_one_lane", 0xFFFF0000)) + + def test_wave32(self): + for name, mask in self.CASES: + with self.subTest(case=name): + insns, addr, off, _ = dp.CASES[name] + got = dp.run(dp.translate_text("cs_" + name, dp.program(insns, mask, off), 32), 32, 32) + want = dp.model([addr(lane) for lane in range(32)], mask, off) + for lane in range(32): + self.assertIn(got[lane], want[lane], f"lane {lane} got {got[lane]}, ISA allows {want[lane]}") + + def test_wave64_on_one_and_on_two_subgroups(self): + for subgroup in (64, 32): + for name, mask in self.CASES: + with self.subTest(case=name, subgroup=subgroup): + insns, addr, off, _ = dp.CASES[name] + mask64 = mask | (mask ^ 0xFFFFFFFF) << 32 # the upper half gets the other lanes + spv = dp.translate_text("cs_h_" + name, dp.program(insns, mask64, off, wave=64), 64) + got = dp.run(spv, 64, subgroup) + want = dp.model([addr(lane) for lane in range(64)], mask64, off, lanes=64) + for lane in range(64): + self.assertIn(got[lane], want[lane], f"lane {lane} got {got[lane]}, ISA allows {want[lane]}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b39c9cd419..a45a146916 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -6319,9 +6319,15 @@ def ds_permute(self, a, mods): # Redirect absent source lanes before the shuffle: even a masked undefined result is undefined. self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}") self.emit(f"{safe_src} = OpSelect %uint {ex} {src} {self_lane}") + # Both shuffles are stored (SHADER-PERMUTE-EAGER). Each is used once, and so is every link of the + # chain, so SPIRV-Cross would write the 32 steps as one nested ternary, hit31 ? data31 : (hit30 ? ...), + # under the EXEC ternary of the write: a lane that takes an outer arm, or is off, would run none of the + # shuffles inside it, and the lanes that read from it get 0 or a stale word (Apple M5, MoltenVK 1.4.2). self.emit(f"{shv} = OpGroupNonUniformShuffle %uint %c3 {tp} {safe_src}") + shv = self.eager("%uint", shv) self.emit(f"{v} = OpSelect %uint {ex} {shv} {self.cu(0)}") self.emit(f"{shd} = OpGroupNonUniformShuffle %uint %c3 {dat} {safe_src}") + shd = self.eager("%uint", shd) self.emit(f"{hit} = OpIEqual %bool {v} {mine}") self.emit(f"{nxt} = OpSelect %uint {hit} {shd} {acc}") acc = nxt