diff --git a/docs/design.md b/docs/design.md index 7b7797ae67..c9aafe0be0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -499,12 +499,14 @@ How the generated SPIR-V expects the runtime to work: | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | | `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | +| Wave64 graphics: a uniform vote under whole-quad EXEC (SHADER-W64-WQM-UVOTE) | SHADER-10 (the row above) takes a `vccz`/`vccnz` on a wave-uniform compare for no lane vote only while EXEC is the launch mask. A pixel shader that needs derivatives starts with `s_wqm_b64 exec, exec`, and LLVM branches on uniform conditions inside that region in the same form: `v_cmp_* sN, ` / `s_and_b64 vcc, exec, s[N:N+1]` / `s_cbranch_vccnz` (or the compare straight into VCC). **That is exact too, for a compare of immediates and scalars**: it is the same in every lane, so its mask is every lane of EXEC or none; EXEC is the whole quads of the launch mask, a quad is four consecutive lanes and never straddles the two 32-lane halves, and a half that runs has a launch lane, so EXEC has a lane in every half that runs and each half votes as the wave does. Both sides of the branch may then have code and scalars of their own (if/else, a uniform loop back edge), as under the launch mask. `tools/wave64_halves.py` carries it as a dataflow fact (`q`: EXEC is the whole quads of the launch mask), set by `s_wqm_b64 exec, exec` while EXEC is the launch mask and dropped by every other write to EXEC; `uniform_cmp` and the `s_and_b64 .., exec, ..` of a uniform mask accept it next to the launch mask. **What stays tier C, and why**: a VGPR source, even one SHADER-10 calls uniform (it was written under the launch mask, and the helper lanes EXEC now includes never got it, so they compare what they held; a VGPR written inside the region is refused as well, because the analysis does not tell the two apart); the whole quads of a narrowed EXEC, and any narrowing after the `s_wqm_b64` (a half can be empty); whole quads saved and put back later, or made in a register and copied to EXEC (only the write by `s_wqm_b64 exec, exec` is modelled); and a compare on a path where a scalar was read out of a uniform VGPR from a lane the launch mask may not have written, by `v_readlane_b32` at any time or by `v_readfirstlane_b32` while EXEC was not the launch mask (`qr`, kept for the rest of the path: SHADER-10 treats such a scalar as uniform, this rule does not build on that). **Corpus** (1.0.2.1, all 26,503, `wave64_halves.analyse` on every wave64 VS/PS/GS, with SHADER-W64-SDST-PAIR on `main` `3ed8e50b7` as the baseline, because the listings name the compare's destination by one register and without that rule the vote is hidden behind `tainted-branch`): **452 pixel shaders go from tier C to A**, no shader moves the other way and no vertex or geometry shader moves: A 5,267 to 5,719, B 397, C 7,741 to 7,289 (PS 3,545/34/7,395 to 3,997/34/6,943). Reasons: `unsafe-vote-branch` 7,362 to 6,861, `tainted-exec` 5,829 to 5,793, `stale-scalar` 3,287 to 3,254, the others unchanged; 802 shaders still have `unsafe-vote-branch` as their only reason. CPU-checked by `tests/semantic/test_wave64_halves_wqm_uvote.py`: the accepted forms in both printed forms of the destination, ten near misses that stay tier C, and a vertex and a pixel shader run on the wave interpreter as one wave of 64 lanes and as two of 32, equal and equal to the derived words with s4 = 9 and s4 = 1 (every lane covered there: the interpreters do not model a helper lane in a quad swap, so partial coverage rests on the argument above). GPU-checked by `ps_w64_a_wqm_uniform_vote` (`w64_graphics.py`: an if/else on a compare into VCC, the LLVM form through an SGPR pair and a loop closed by the vote, all under `s_wqm_b64 exec, exec`, EXEC put back before the export), which gives the words its header derives on an NVIDIA GeForce RTX 4070 Ti (Linux, driver 620.70.06, 32 only). That device has one subgroup size, so the 64-lane image was not drawn there and the full-screen draw has no partly covered quad; the run confirms the translated SPIR-V against the ISA reference, not native RDNA2 behaviour. | | GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, 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), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | | 8/16-bit MUBUF d16 loads and stores | (The plain `buffer_load_{u,s}byte`/`{u,s}short` are `Gen.buffer_load_sub`'s; `tests/semantic/test_buffer_sub_dword.py` checks them too.) The `_d16` loads (`buffer_load_{u,s}byte_d16[_hi]`, `buffer_load_short_d16[_hi]`) write one 16-bit half of `vdata` (`_hi` the high one; a byte zero- or sign-extended to 16 bits) and keep the other. `buffer_store_byte`/`short` write the low 8/16 bits of `vdata` (the `_d16_hi` forms its high half). The address is `buffer_address`'s, and the bounds check covers the access's own size, 1 or 2 bytes, as for a typed element of that size (`elem="fmt"`, format 1 or 7). Out of range, a load gives 0 (in the half it writes, for d16; **not measured** for d16) and a store writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact; in a swizzled buffer the next dword is `step` bytes on. A store merges each byte into its dword with atomic and/or, as buffer byte format stores do. Inactive lanes neither load nor store, and the first-read analysis counts a d16 load's `vdata` as read. Until 2026-11-22 these ten raised `Unsupported`. CPU-checked by `tests/semantic/test_buffer_sub_dword.py` (every op at byte offsets 0 to 7, the edge of `num_records`, an inactive lane, rejected forms). GPU fixture `cs_w32_buffer_sub16` (the six d16 loads with their kept half and the sign extension, the two `_d16_hi` stores taking bits 23:16 / 31:16), passes on llvmpipe (Mesa 26.0.8) and on an NVIDIA RTX 5090 (595.99.02, @tylerstraub on #1864), all eight words; GPU fixture `cs_w32_buffer_store_sub` for the plain `buffer_store_byte`/`buffer_store_short` (Box16Rehydration's blocker, @YaBulochka on #1864), including a short at byte 3 that writes its high byte into the next dword, passes on llvmpipe with LLVM 21 and 23, and on an Apple M4 (MoltenVK 1.4.2) once the second dword of a 16-bit load is indexed from the first one's pointer instead of a second pointer converted from the same address, which Apple's compiler read as 0 (@sovljanskii on #1864). | | Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | | `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 ` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. | | Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) | +| Wave64 VALU mask operands | The listings come from llvm-mc without `+wavefrontsize64`, so a VALU instruction's lane-mask SGPR is printed as one register (`v_cmp_gt_u32_e64 s8`, the `s10` of `v_cndmask_b32_e64`) where the wave64 hardware writes or reads the pair (`s[8:9]`, RDNA2 ISA VOP3A/VOP3B SDST). `widen_wave64_masks` makes it the pair before analysis: `v_cmp_*_e64`/`_sdwa` SDST, the carry out and in of `v_*_co_*`, `v_div_scale`, `v_mad_[ui]64_[ui]32`, the mask of `v_cndmask`. Before, the high register kept its old value and a later `s_mov_b64 exec, s[8:9]` gave lanes 32..63 its bits. Confirmed by `tests/semantic/test_wave64_single_sdst.py` (both printed forms translate to the same module, all 64 lanes run) and on an RTX 5080, where the pipeline-library program `lib_cs_03141` hung the GPU. | | Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). | | 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. | | VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | diff --git a/runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm b/runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm new file mode 100644 index 0000000000..51f320e8e7 --- /dev/null +++ b/runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm @@ -0,0 +1,53 @@ +; SHADER-W64-WQM-UVOTE tier A: votes on a compare of scalars while EXEC is the whole quads of the launch mask +; (docs/design.md, "Wave64 graphics: a uniform vote under whole-quad EXEC"). A pixel shader that needs derivatives +; starts with s_wqm_b64 exec, exec: the helper lanes of every quad that has a covered pixel come on. A v_cmp of +; scalars and constants there is the same in every lane, so its mask is every lane of EXEC or none, and EXEC has a +; lane in every 32-lane half that runs (a quad never straddles the halves): each half votes as the whole wave does, +; and both sides of the branch may have code of their own, scalars included. s4 is a user SGPR (the test sets it to +; 9 with VKH_SGPRS=0,0,0,0,9). x = floor(u * 64) on the 64x64 target of vs_ids. +; (1) s_cbranch_vccz if/else on 5 < s4 (yes), the compare written straight to VCC: the yes side sets v6 = 7 and +; s20 = 11, the no side v6 = 5 and s20 = 22; both are read after the join. r0 = x + 7, r1 = 11. +; (2) the LLVM form v_cmp_e64 s[14:15] + s_and_b64 vcc, exec, s[14:15] + s_cbranch_vccnz on 50 < s4 (no): the no +; side sets v8 = 3 and s21 = 33, the yes side v8 = 4 and s21 = 44. r2 = s21 + v8 = 36. +; (3) a loop whose back edge is s_cbranch_vccnz on s22 < s4 (s22 the trip count, an SGPR carried across the back +; edge): s4 = 9 iterations of v9 += 2, then v9 += s22. r3 = 2 * 9 + 9 = 27. +; EXEC goes back to the launch mask before the export. The words are those of ps_w64_a_uniform_vote, whose compares +; read a VGPR under the launch mask; here no VGPR is compared, because one written under the launch mask is not +; uniform over the helper lanes. +; Run: VKH_SGPRS=0,0,0,0,9 vk_harness vs_ids.spv ps_w64_a_wqm_uniform_vote.spv out.raw with VKH_SUBGROUP_SIZE=64 +; and 32: equal, and equal to the expected words (x + 7, 11, 36, 27). +; mattr: +wavefrontsize64,-wavefrontsize32 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_mul_f32_e32 v2, 0x42800000, v2 +v_cvt_u32_f32_e32 v2, v2 +s_mov_b64 s[10:11], exec +s_wqm_b64 exec, exec +v_cmp_lt_u32_e64 vcc, 5, s4 +s_cbranch_vccz 3 +v_mov_b32_e32 v6, 7 +s_mov_b32 s20, 11 +s_branch 2 +v_mov_b32_e32 v6, 5 +s_mov_b32 s20, 22 +v_add_nc_u32_e32 v6, v6, v2 +v_mov_b32_e32 v7, s20 +v_cmp_lt_u32_e64 s[14:15], 50, s4 +s_and_b64 vcc, exec, s[14:15] +s_cbranch_vccnz 3 +v_mov_b32_e32 v8, 3 +s_mov_b32 s21, 33 +s_branch 2 +v_mov_b32_e32 v8, 4 +s_mov_b32 s21, 44 +v_add_nc_u32_e32 v8, s21, v8 +s_mov_b32 s22, 0 +v_mov_b32_e32 v9, 0 +s_add_u32 s22, s22, 1 +v_add_nc_u32_e32 v9, 2, v9 +v_cmp_gt_u32_e64 vcc, s4, s22 +s_cbranch_vccnz -5 +v_add_nc_u32_e32 v9, s22, v9 +s_and_b64 exec, exec, s[10:11] +exp mrt0 v6, v7, v8, v9 done vm +s_endpgm diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py index 649fc4630b..e28d03d2f8 100644 --- a/runtime/test/shaders/w64_graphics.py +++ b/runtime/test/shaders/w64_graphics.py @@ -187,6 +187,8 @@ def _gs_a_ring(i): # gs_w64_* fixtur "ps_w64_a_swizzle": ("A", _a_swizzle, {}), "ps_w64_a_bpermute": ("A", _a_bpermute, {}), "ps_w64_a_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}), + # SHADER-W64-WQM-UVOTE: the same votes on compares of scalars under s_wqm_b64 exec, exec (the same words) + "ps_w64_a_wqm_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}), "ps_w64_a_discard": ("A", _a_discard, {}), "ps_w64_b_waterfall": ("B", _b_waterfall, {}), diff --git a/tests/semantic/test_wave64_halves_wqm_uvote.py b/tests/semantic/test_wave64_halves_wqm_uvote.py new file mode 100644 index 0000000000..2ab68a69fd --- /dev/null +++ b/tests/semantic/test_wave64_halves_wqm_uvote.py @@ -0,0 +1,188 @@ +"""SHADER-W64-WQM-UVOTE: a vote on a compare of scalars under whole-quad EXEC is no lane vote (tools/wave64_halves.py). + +A pixel shader that needs derivatives starts with `s_wqm_b64 exec, exec`: EXEC becomes the whole quads of the launch +mask, helper lanes included. LLVM then branches on wave-uniform conditions inside that region the way it does +anywhere else: `v_cmp_* sN, ` / `s_and_b64 vcc, exec, s[N:N+1]` / `s_cbranch_vccnz`. SHADER-10 accepted that +form only while EXEC was the launch mask itself and called it `unsafe-vote-branch` here. + +It is as exact under the whole quads. The compare reads immediates and scalars only, so it is the same in every +lane: its mask is every lane of EXEC or none. A quad is four consecutive lanes and never straddles the two 32-lane +halves, and a half that runs has a launch lane, so EXEC has a lane in every half that runs: each half votes as the +wave does, and either side of the branch may define scalars that are read after the join. + +What stays tier C, and why (`NearMisses`): a VGPR source, even one SHADER-10 calls uniform, because it was written +under the launch mask and the helper lanes never got it; whole quads of a narrowed EXEC, or a narrowing after the +`s_wqm_b64`, because a half can then be empty; a scalar that was read out of such a VGPR with v_readlane or, under +whole-quad EXEC, with v_readfirstlane, because the lane read may be one the launch mask did not write; `s_wqm_b64` +into a register that is copied to EXEC afterwards (not modelled). + +Hand-written programs, no game data. Classification in both printed forms of the compare's destination (the game's +listings name one register, SHADER-W64-SDST-PAIR); execution on the strict wave interpreter (spirv_wave_interp): a +vertex shader and a pixel shader as one wave of 64 lanes and as two of 32, equal and equal to the words derived here. +The GPU twin is runtime/test/shaders/ps_w64_a_wqm_uniform_vote.asm (w64_graphics.py). + + python -I tests/semantic/test_wave64_halves_wqm_uvote.py +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import support # noqa: E402,F401 (sets the tools path) +import spirv_wave_interp as wi # noqa: E402 +from test_wave64_halves import UNIFORM, meta_of, out_param, ps, run_cut, vs # noqa: E402 + +WQM = ["s_wqm_b64 exec, exec"] +# if 5 < s4: v6 = 7, s20 = 1, else v6 = 5, s20 = 2; s20 is read after the join +SIDES = ["v_mov_b32_e32 v6, 5", "s_mov_b32 s20, 2", "s_branch 2", "v_mov_b32_e32 v6, 7", "s_mov_b32 s20, 1"] +ONE_REGISTER = ["v_cmp_lt_u32_e64 s14, 5, s4", "s_and_b64 vcc, exec, s[14:15]", "s_cbranch_vccnz 3"] + SIDES +PAIR = ["v_cmp_lt_u32_e64 s[14:15], 5, s4"] + ONE_REGISTER[1:] +VCC = ["v_cmp_lt_u32_e64 vcc, 5, s4", "s_cbranch_vccnz 3"] + SIDES # the compare straight into VCC +READ = ["v_add_nc_u32_e32 v7, s20, v0"] + + +class Classification(unittest.TestCase): + def tier(self, name, lines, stage=ps): + (tier, reasons, idioms), _ = meta_of(name, stage(lines)) + return tier, reasons, idioms + + def test_a_scalar_compare_under_whole_quads(self): + for name, vote in (("one_register", ONE_REGISTER), ("pair", PAIR), ("vcc", VCC)): + with self.subTest(name): + self.assertEqual(self.tier("ps_wqm_uv_" + name, WQM + vote + READ), ("A", [], [])) + + def test_a_exec_restored_after_the_vote(self): + # the usual shape: derivatives region, then EXEC back to the launch mask saved at the top (PRO saves it) + self.assertEqual(self.tier("ps_wqm_uv_restore", WQM + ONE_REGISTER + ["s_and_b64 exec, exec, s[10:11]"] + READ), + ("A", [], [])) + + def test_a_uniform_loop_back_edge(self): + # s22 counts the trips in an SGPR across the back edge: every half runs s4 of them, as the wave does + self.assertEqual(self.tier("ps_wqm_uv_loop", WQM + [ + "s_mov_b32 s22, 0", "s_add_u32 s22, s22, 1", "v_add_nc_u32_e32 v6, 3, v6", + "v_cmp_gt_u32_e64 vcc, s4, s22", "s_cbranch_vccnz -5", "v_add_nc_u32_e32 v7, s22, v0"]), ("A", [], [])) + + def test_a_vertex_shader(self): + self.assertEqual(self.tier("vs_wqm_uv", WQM + ONE_REGISTER + READ, vs), ("A", [], [])) + + def test_launch_mask_form_is_unchanged(self): + self.assertEqual(self.tier("ps_uv_launch", ONE_REGISTER + READ), ("A", [], [])) + + +class NearMisses(unittest.TestCase): + """Each program differs from an accepted one in one respect and must stay tier C.""" + + def refused(self, name, lines, idioms=()): + (tier, reasons, got_idioms), _ = meta_of(name, ps(lines)) + self.assertEqual(tier, "C", f"{name}: {reasons} {got_idioms}") + self.assertIn("unsafe-vote-branch", reasons, name) + for idiom in idioms: + self.assertIn(idiom, got_idioms, name) + + def test_c_vgpr_written_under_the_launch_mask(self): + # v1 = s4 in the launch lanes only; the helper lanes compare what they held before + self.refused("ps_wqm_c_vgpr", ["v_mov_b32_e32 v1, s4"] + WQM + ["v_cmp_lt_u32_e64 s14, 5, v1"] + + ONE_REGISTER[1:] + READ) + + def test_c_vgpr_written_under_the_whole_quads(self): + # uniform over EXEC in fact, but st["ua"] also holds VGPRs of the launch mask: not told apart, refused + self.refused("ps_wqm_c_vgpr_inside", WQM + ["v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e64 s14, 5, v1"] + + ONE_REGISTER[1:] + READ) + + def test_c_whole_quads_of_a_narrowed_exec(self): + # EXEC narrowed to x < 32 first: a half without such a pixel has no lane, votes no and keeps its own s20 + self.refused("ps_wqm_c_narrowed_before", ["v_cmp_gt_u32_e32 vcc, 32, v0", "s_and_b64 exec, exec, vcc"] + + WQM + ONE_REGISTER + READ) + + def test_c_narrowed_after_the_whole_quads(self): + self.refused("ps_wqm_c_narrowed_after", WQM + ["v_cmp_gt_u32_e32 vcc, 32, v0", "s_and_b64 exec, exec, vcc"] + + ONE_REGISTER + READ) + + def test_c_saved_and_restored_whole_quads(self): + # EXEC is the whole quads again after the restore, but only the write by s_wqm_b64 itself is modelled + self.refused("ps_wqm_c_restored", WQM + ["s_mov_b64 s[12:13], exec", "v_cmp_gt_u32_e32 vcc, 32, v0", + "s_and_b64 exec, exec, vcc", "s_mov_b64 exec, s[12:13]"] + + ONE_REGISTER + READ) + + def test_c_whole_quads_through_a_register(self): + self.refused("ps_wqm_c_register", ["s_wqm_b64 s[12:13], exec", "s_mov_b64 exec, s[12:13]"] + + ONE_REGISTER + READ) + + def test_c_scalar_read_with_readlane_from_a_uniform_vgpr(self): + # lane 40 may be a lane the launch mask did not write; SHADER-10 calls s4 uniform, this rule does not use it + self.refused("ps_wqm_c_readlane", ["v_mov_b32_e32 v1, s4", "v_readlane_b32 s4, v1, 40"] + WQM + + ONE_REGISTER + READ, idioms=["readlane-uniform"]) + + def test_c_scalar_read_with_readfirstlane_under_whole_quads(self): + # the first lane of EXEC can be a helper lane, which v1 = s4 never reached + self.refused("ps_wqm_c_readfirstlane", ["v_mov_b32_e32 v1, s4"] + WQM + ["v_readfirstlane_b32 s4, v1"] + + ONE_REGISTER + READ, idioms=["readfirstlane-uniform"]) + + def test_c_such_a_scalar_stays_refused_in_a_second_region(self): + self.refused("ps_wqm_c_second_region", ["v_mov_b32_e32 v1, s4"] + WQM + [ + "v_readfirstlane_b32 s4, v1", "s_mov_b64 exec, s[10:11]"] + WQM + ONE_REGISTER + READ) + + def test_c_tainted_scalar(self): + (tier, reasons, _), _ = meta_of("ps_wqm_c_tainted", ps(WQM + [ + "v_readfirstlane_b32 s4, v0"] + ONE_REGISTER + READ)) + self.assertEqual((tier, reasons), ("C", ["waterfall-scalar"])) + + def test_readfirstlane_under_the_launch_mask_does_not_spoil_it(self): + # read while EXEC is the launch mask: the first lane is a launch lane, s21 is the uniform value + (tier, reasons, idioms), _ = meta_of("ps_wqm_b_rfl_launch", ps( + ["v_mov_b32_e32 v1, s4", "v_readfirstlane_b32 s21, v1"] + WQM + + ["v_cmp_lt_u32_e64 s14, 5, s21"] + ONE_REGISTER[1:] + READ)) + self.assertEqual((tier, reasons, idioms), ("B", [], ["readfirstlane-uniform"])) + + +class VertexExecution(unittest.TestCase): + """One wave of 64 lanes against two of 32 on the strict wave interpreter (vertex index = global lane).""" + + def test_words_equal_and_as_derived(self): + for name, vote in (("one_register", ONE_REGISTER), ("pair", PAIR), ("vcc", VCC)): + for push in UNIFORM: + with self.subTest(name, s4=push[4]): + (tier, reasons, _), asm = meta_of("vs_wqm_uv_" + name, vs(WQM + vote + READ)) + self.assertEqual((tier, reasons), ("A", [])) + whole, halves = out_param(run_cut(asm, 64, push)), out_param(run_cut(asm, 32, push)) + self.assertEqual(whole, halves) + want = (lambda k: (7, 1 + k)) if push[4] > 5 else (lambda k: (5, 2 + k)) + self.assertEqual([w[:2] for w in whole], [want(k) for k in range(64)]) + + +# a pixel program: v2 = the pixel's own number (a flat attribute), exported next to what the vote chose +PIXEL = ["v_interp_mov_f32_e32 v2, p0, attr0.x", "v_cvt_u32_f32_e32 v2, v2"] + WQM + ONE_REGISTER + [ + "v_add_nc_u32_e32 v7, s20, v2", "s_and_b64 exec, exec, s[10:11]"] + + +def run_pixels(asm, wave, s4): + """mrt0 of pixels 0..63 run as 64 / wave waves of `wave` lanes, pixel p in lane p % wave of wave p // wave.""" + words = [] + for first in range(0, 64, wave): + res = wi.run_wave(asm, wave=wave, push_constants=[0, 0, 0, 0, s4], + inputs={0: lambda lane, first=first: (float(first + lane), 0.0, 0.0, 0.0)}) + words += [tuple(next(v for name, v in out.items() if name.endswith("mrt0"))) for out in res["outputs"]] + return words + + +class PixelExecution(unittest.TestCase): + """One wave of 64 pixels against two of 32 on the strict wave interpreter, which runs the quad swaps that + `s_wqm_b64` is translated to. Every lane is covered here (the interpreters do not model a helper lane that + takes part in a quad swap), so this checks the translated vote and scalars, not partial coverage: that part is + the argument in the module docstring.""" + + def test_pixels_equal_and_as_derived(self): + (tier, reasons, _), asm = meta_of("ps_wqm_uv_pixels", ps(PIXEL)) + self.assertEqual((tier, reasons), ("A", [])) + self.assertIn("OpGroupNonUniformQuadSwap", asm) + for s4 in (9, 1): + with self.subTest(s4=s4): + whole, halves = run_pixels(asm, 64, s4), run_pixels(asm, 32, s4) + self.assertEqual(whole, halves) + want = (lambda p: (7, 1 + p, 0, 0)) if s4 > 5 else (lambda p: (5, 2 + p, 0, 0)) + self.assertEqual(whole, [want(p) for p in range(64)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_wave64_single_sdst.py b/tests/semantic/test_wave64_single_sdst.py new file mode 100644 index 0000000000..040a1572e4 --- /dev/null +++ b/tests/semantic/test_wave64_single_sdst.py @@ -0,0 +1,87 @@ +"""Wave64: a lane mask the listing names by its low SGPR only is the pair. + +The shader listings come from llvm-mc without +wavefrontsize64, which prints the wave32 form of a VALU instruction's +lane-mask operands: `v_cmp_gt_u32_e64 s8, ...` for the s[8:9] a wave64 writes, `v_cndmask_b32_e64 ..., s10` for the +s[10:11] it reads. Scalar 64-bit instructions print pairs, so the same mask is read as s[8:9] afterwards; before the +high register was stale and lanes 32..63 took their EXEC bits from it. A pipeline-library compute shader of the +retail title looped for ever on a 32-wide GPU because of it. + +Synthetic programs, no game data. + + python -I tests/semantic/test_wave64_single_sdst.py -v +""" +import os +import re +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import test_wave64_emulate_opt as emulated # noqa: E402 + +rdna2spirv = emulated.rdna2spirv + +STALE = [("s_mov_b32 s9, 0x100001", 8), ("s_mov_b32 s11, 0x40", 8)] # what the high registers held before +STORE = [ + ("s_mov_b64 exec, -1", 4), + ("v_lshlrev_b32_e32 v6, 2, v0", 4), + ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), + ("s_endpgm", 4), +] +MASK_MOVED_TO_EXEC = STALE + [ + ("v_mov_b32_e32 v5, 0", 4), + ("v_cmp_gt_u32_e64 s8, 48, v0", 8), # lanes 0..47 + ("s_mov_b64 exec, s[8:9]", 4), + ("v_mov_b32_e32 v5, 1", 4), +] + STORE +CARRY_AND_SELECT = STALE + [ + ("v_add_co_u32_e64 v1, s8, -40, v0", 8), # carry out of lane + 0xffffffd8: lanes 40..63 + ("s_mov_b64 s[10:11], s[8:9]", 4), + ("v_cndmask_b32_e64 v5, 2, 3, s10", 8), + ("s_mov_b64 exec, s[10:11]", 4), + ("v_add_co_ci_u32_e64 v5, s8, v5, 4, s10", 8), # + 4 + the carry in, which those lanes have +] + STORE +PAIRS = re.compile(r"\b(v_cmp_gt_u32_e64 )s8,|(v_add_co(?:_ci)?_u32_e64 v\d, )s8,|(, )s10$") + + +def printed_as_wave64(program): + """The program as llvm-mc prints it with +wavefrontsize64.""" + def pair(m): + return f"{m.group(1)}s[8:9]," if m.group(1) else f"{m.group(2)}s[8:9]," if m.group(2) else ", s[10:11]" + return [(PAIRS.sub(pair, text) if text.startswith("v_") else text, size) for text, size in program] + + +class SingleSdstTest(unittest.TestCase): + def run_program(self, name, program): + for emulate in (True, False): + spv, _ = emulated._translate_encoded(name, program, (64, 1, 1), emulate=emulate) + wide, _ = emulated._translate_encoded(name, printed_as_wave64(program), (64, 1, 1), emulate=emulate) + self.assertEqual(spv, wide, "the two forms of the listing are the same program") + spv, _ = emulated._translate_encoded(name, program, (64, 1, 1), emulate=True) + memory, _ = emulated.run_emulated_workgroup(spv, (64, 1, 1), push_constants=emulated.VSHARP + [0] * 28) + return [memory[4 * lane] for lane in range(64)] + + def test_compare_destination_read_as_a_pair(self): + self.assertNotEqual(MASK_MOVED_TO_EXEC, printed_as_wave64(MASK_MOVED_TO_EXEC)) + self.assertEqual(self.run_program("cs_w64_cmp_single", MASK_MOVED_TO_EXEC), [1] * 48 + [0] * 16) + + def test_carry_out_carry_in_and_select_mask(self): + self.assertEqual(self.run_program("cs_w64_carry_single", CARRY_AND_SELECT), [2] * 40 + [8] * 24) + + def test_wave32_keeps_single_registers(self): + insns = [{"op": "v_cmp_gt_u32_e64", "args": [{"k": "sgpr", "r": 8}, {"k": "imm", "v": 1}, {"k": "vgpr", "r": 0}]}] + rdna2spirv.widen_wave64_masks(insns) + self.assertEqual(insns[0]["args"][0], {"k": "sgpr", "r": 8, "n": 2}) + # translate() calls it for wave64 programs only; an e32 compare and VCC are left as they are + other = [{"op": "v_cmp_gt_u32_e32", "args": [{"k": "special", "t": "vcc_lo"}, {"k": "imm", "v": 1}, {"k": "vgpr", "r": 0}]}, + {"op": "v_readlane_b32", "args": [{"k": "sgpr", "r": 8}, {"k": "vgpr", "r": 0}, {"k": "sgpr", "r": 2}]}, + {"op": "v_cmpx_eq_u32_e64", "args": [{"k": "sgpr", "r": 4}, {"k": "vgpr", "r": 0}]}] + before = [dict(i, args=list(i["args"])) for i in other] + rdna2spirv.widen_wave64_masks(other) + self.assertEqual(other, before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_wave64_halves_fixtures.py b/tests/test_wave64_halves_fixtures.py index 40b04f5789..6fa1e00c76 100644 --- a/tests/test_wave64_halves_fixtures.py +++ b/tests/test_wave64_halves_fixtures.py @@ -36,6 +36,7 @@ "ps_w64_a_swizzle": ("A", [], []), "ps_w64_a_bpermute": ("A", [], []), "ps_w64_a_uniform_vote": ("A", [], []), + "ps_w64_a_wqm_uniform_vote": ("A", [], []), "ps_w64_a_discard": ("A", [], []), "ps_w64_b_waterfall": ("B", [], ["waterfall"]), diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 825d4a43f0..7717aadb7f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -17204,6 +17204,30 @@ def restore_mix_inline_literal(ins, raw, literal): ins["enc"] = raw.hex() +def widen_wave64_masks(insns): + """In place: the lane-mask SGPR operands of VALU instructions become the pairs they are in wave64. + + The listings come from llvm-mc without +wavefrontsize64, so it prints the wave32 form: v_cmp_*_e64 s8 where the + wave64 hardware writes s[8:9], and reads s[10:11] for the s10 of v_cndmask_b32_e64. Taken literally the high SGPR + keeps its old value, and the next s_mov_b64 exec, s[8:9] gives lanes 32..63 the wrong bits.""" + for ins in insns: + op, a = base_op(ins["op"]), ins["args"] + if op.startswith("v_cmp") and len(a) == 3: + at = (0,) + elif op.startswith("v_") and "_co_ci_" in op: + at = (1, 4) + elif op.startswith("v_") and "_co_" in op or op in ("v_mad_u64_u32", "v_mad_i64_i32", + "v_div_scale_f32", "v_div_scale_f64"): + at = (1,) + elif op in ("v_cndmask_b32", "v_cndmask_b16"): + at = (3,) + else: + continue + 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) + + def output_signature(path, name): """OSG1 elements as (register, system value), one per register (first element wins).""" d = shader_container(path, name) @@ -17534,6 +17558,8 @@ def translate(path): g.wave64 = False else: g.wave64 = code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) + if g.wave64: + widen_wave64_masks(insns) if stage == "gs": ins_by_reg = {} for reg, mask, sv, ctype in input_signature(path, info["name"]): diff --git a/tools/wave64_halves.py b/tools/wave64_halves.py index 9b5305344b..565605c982 100644 --- a/tools/wave64_halves.py +++ b/tools/wave64_halves.py @@ -10,7 +10,8 @@ "uniform_readlane": {id(ins), ...}} A nothing wave-wide is consumed except votes that only skip lane-masked work, votes on a wave-uniform compare - (a v_cmp of untainted scalars and constants with EXEC the launch mask: every half votes as the wave does), + (a v_cmp of untainted scalars and constants with EXEC the launch mask, or its whole quads after + `s_wqm_b64 exec, exec` when no VGPR is compared: every half votes as the wave does), whole-quad masks and per-lane arithmetic: exact as translated, on any subgroup size. B also uses a wave-wide idiom whose result is invariant by construction: a waterfall loop, a wave-aggregated atomic (ballot count, one atomic from the first lane, rank), a v_readfirstlane / v_readlane of a value that @@ -448,6 +449,7 @@ def join(self, a, b, blk=0): u = a["u"] & b["u"] ua = (a["ua"] & b["ua"]) if a["x"] == b["x"] else u return {"t": t, "g": g, "x": x, "xg": a["xg"] if a["xg"] == b["xg"] else None, "f": a["f"] and b["f"], + "q": a["q"] and b["q"], "qr": a["qr"] or b["qr"], "u": u, "ua": ua, "l": {k: v for k, v in a["l"].items() if b["l"].get(k) == v}, "r": self.union_map(a["r"], b["r"]), "b": self.union_map(a["b"], b["b"])} @@ -456,13 +458,14 @@ def union_map(a, b): return {k: a.get(k, frozenset()) | b.get(k, frozenset()) for k in set(a) | set(b)} def entry(self): - return {"t": {}, "g": {}, "x": ("e",), "xg": None, "f": True, "u": frozenset(), "ua": frozenset(), "l": {}, - "r": {}, "b": {}} + return {"t": {}, "g": {}, "x": ("e",), "xg": None, "f": True, "q": False, "qr": False, "u": frozenset(), + "ua": frozenset(), "l": {}, "r": {}, "b": {}} # ---- the transfer function ---- def block(self, n, st, ev): - st = {"t": dict(st["t"]), "g": dict(st["g"]), "x": st["x"], "xg": st["xg"], "f": st["f"], "u": st["u"], - "ua": st["ua"], "l": dict(st["l"]), "r": dict(st["r"]), "b": dict(st["b"])} + st = {"t": dict(st["t"]), "g": dict(st["g"]), "x": st["x"], "xg": st["xg"], "f": st["f"], "q": st["q"], + "qr": st["qr"], "u": st["u"], "ua": st["ua"], "l": dict(st["l"]), "r": dict(st["r"]), + "b": dict(st["b"])} for i, ins in enumerate(self.blocks[n]): self.step(n, i, ins, st, ev) return st @@ -850,6 +853,8 @@ def bits_violation(t, allowed=0): vr = a[1]["r"] if a[1].get("k") == "vgpr" else None if vr is not None and vr in st["u"]: idiom("readfirstlane-uniform") + if not st["f"]: + self.read_past_launch(st) put(a[0], tv) elif vr is not None and vr in st["ua"]: # Uniform over active lanes only: if a half has EXEC == 0 here, v_readfirstlane returns lane 0's @@ -875,6 +880,7 @@ def bits_violation(t, allowed=0): idiom("readlane-uniform") if ev is not None: ev["uniform_readlane"].add(id(ins)) + self.read_past_launch(st) put(a[0], self.rd(st, ins, a[1])) elif vr is not None and a[2].get("k") == "imm" and (vr, a[2]["v"] & 63) in st["l"] \ and ((a[2]["v"] & 63) < 32 or vr in self.pure_spill_vgprs): @@ -971,9 +977,11 @@ def bits_violation(t, allowed=0): elif r and r[0] in st["g"] and st["g"][r[0]][0] in ("mask", "elect", "wfmask", "uvote"): tag = st["g"][r[0]] elif op == "s_and_b64" and not t_src and all( - (_regs(x) == ["exec"] and st["f"]) or (_regs(x) and all(st["g"].get(r) == UVOTE for r in _regs(x))) + (_regs(x) == ["exec"] and (st["f"] or st["q"])) + or (_regs(x) and all(st["g"].get(r) == UVOTE for r in _regs(x))) for x in srcs) and any(_regs(x) != ["exec"] for x in srcs): - # a uniform compare ANDed with EXEC while EXEC is the launch mask (LLVM: s_and_b64 vcc, exec, s[..]) + # a uniform compare ANDed with EXEC while EXEC is the launch mask or its whole quads (LLVM: + # s_and_b64 vcc, exec, s[..]); either way the result is no lane or a set with a lane in every half tag = UVOTE put(dests[0], t_src, tag) if not op.startswith(("s_mov", "s_cselect")): # those leave SCC as it was: no vote on their dest @@ -1202,8 +1210,14 @@ def uniform_cmp(self, st, ins, srcs, uses, tj): """Whether a v_cmp writes a wave-uniform lane mask: EXEC is the launch mask and every source is the same in every lane (an immediate, a scalar that is no lane mask, a VGPR written from those with EXEC the launch mask) and carries no taint, so the mask is every launch lane or none, in the wave and in each half alike. A value - read with v_readfirstlane from a varying VGPR is tainted (waterfall-scalar), so it is not one.""" - if tj or uses or not st["f"] or not srcs: + read with v_readfirstlane from a varying VGPR is tainted (waterfall-scalar), so it is not one. + + SHADER-W64-WQM-UVOTE: the same holds while EXEC is the whole quads of the launch mask (st["q"]) when every + source is an immediate or a scalar: the mask is every lane of EXEC or none, and EXEC has a lane in every + half that runs, because a quad never straddles the halves and a half that runs has a launch lane. A VGPR is + refused there even when st["u"] calls it uniform: it was written under the launch mask, and the helper lanes + EXEC now includes never got that value, so they compare whatever they hold.""" + if tj or uses or not (st["f"] or st["q"]) or not srcs: return False for x in srcs: k = x.get("k") @@ -1211,11 +1225,19 @@ def uniform_cmp(self, st, ins, srcs, uses, tj): continue if self.rd(st, ins, x) or self.is_mask(ins, x): return False - if k == "sgpr" or (k == "vgpr" and all(r[1] in st["u"] for r in _regs(x))): + if k == "sgpr" or (k == "vgpr" and st["f"] and all(r[1] in st["u"] for r in _regs(x))): continue return False return True + @staticmethod + def read_past_launch(st): + """A scalar was read from a lane of a uniform VGPR (st["u"]: written under the launch mask) that the launch + mask may not have written: v_readfirstlane while EXEC is not the launch mask, v_readlane at any time. The + tiers treat that scalar as uniform; SHADER-W64-WQM-UVOTE does not build on it, so from here on EXEC is never + again "the whole quads of the launch mask" on this path.""" + st["q"], st["qr"] = False, True + def cmp_tag(self, st, ins, op, srcs, t_src, idiom): """(tag, taint) of the lane mask a v_cmp / v_cmpx writes. The two recognised comparisons: a waterfall scalar against the VGPR it was read from (every lane of the mask owns that value), and a lane rank @@ -1237,6 +1259,11 @@ def exec_write(self, n, i, ins, op, a, dests, srcs, st, ev, violation, idiom, t_ T = st["t"] site = ("n", n, i) old = st["x"] + # SHADER-W64-WQM-UVOTE: `s_wqm_b64 exec, exec` while EXEC is the launch mask leaves the whole quads of the + # launch mask (helper lanes on); every other write to EXEC ends that + quads = st["f"] and not st["qr"] and op == "s_wqm_b64" and len(a) == 2 and not _half(a[0]) \ + and all(x.get("k") == "special" and x.get("t") == "exec" for x in a) + st["q"] = False if any(_half(x) for x in dests + srcs) or (op.startswith("s_") and op.endswith("_b32")): violation("mask-half") if any(op.startswith(p) for p in SAVEEXEC): @@ -1286,7 +1313,7 @@ def exec_write(self, n, i, ins, op, a, dests, srcs, st, ev, violation, idiom, t_ else: st["x"] = site self.tok[site] = (None, None, False) - st["xg"], st["f"] = None, False + st["xg"], st["f"], st["q"] = None, False, quads st["ua"] = st["u"] if mt & ~0: for b, name in NAMES.items(): @@ -1381,8 +1408,8 @@ def vote(self, n, ins, op, reg, on_taken, ev, st): A VCC that is a wave-uniform compare (UVOTE: every launch lane or none) is no lane vote: each half votes as the wave does, so either side may have code of its own and scalars it defines are not stale. EXEC must have - been the launch mask at the compare: under a narrowed EXEC a half with no active lane votes no while the - wave votes yes.""" + been the launch mask at the compare (or its whole quads, for a compare of scalars: uniform_cmp): under a + narrowed EXEC a half with no active lane votes no while the wave votes yes.""" # st only for s_cbranch_vccz/vccnz: an SCC vote was taken on the mask as it was then, and VCC may since hold # another value (a later v_cmp writes no SCC) if reg == "vcc" and st is not None and st["g"].get("vcc") == UVOTE and not st["t"].get("vcc", 0) \