diff --git a/docs/design.md b/docs/design.md index 3f2d522517..ff682e4911 100644 --- a/docs/design.md +++ b/docs/design.md @@ -286,7 +286,7 @@ How the generated SPIR-V expects the runtime to work: | VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. | | Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). One difference is repaired instead of refused: a `v_fma_mix*` literal that llvm-mc prints cut to its low 16 bits (and re-encodes with a zero high half). llvm-mc 23.1.5 prints some of these literals in full as `lit(V)` (an f32 source, or a low half that is an inline constant; LLVM 21 printed the inline constant and dropped the literal word) and still re-encodes only the low half: `tools/shader_ir.py` reads `lit(V)` as V, and the same repair applies (5,733 such operands in the pipeline library, [shader_library.md](shader_library.md)). When the 8 instruction bytes match (`same_encoding` with all three sources counted as used, so a live `s0` can't pass as an inline 0) and the printed literal is the stored one's low half, every source the bytes encode as the literal (SRC field `0xff`) takes the stored 32 bits, so a source with `op_sel_hi` and `op_sel` set reads the high half instead of +0.0. Seen in one program of the FidelityFX DLL's `FSPX` code ([fspx.md](fspx.md)): src0 the low half, src2 the high half; the game's clean listings have no such difference (the count above). That the hardware gives op_sel's high half of the literal to that source is not measured; it is what Mesa's ACO compiler relies on (public: `optimize_constants()` in `src/amd/compiler/aco_optimizer.cpp`, Mesa `main` at `bb986060`, packs two constants as the two f16 halves of one literal, read through `v_fma_mix`'s `op_sel_hi` with the second source extracting the high half), and what the console compiler emitted here. `tools/fma_mix_literal_probe.py --oracle hw` measures it on an AMD GPU (the instruction's exact bytes through `tools/hw_oracle`; not run on one yet). `tests/semantic/test_fma_mix_literal.py` (the value through the interpreter, the re-anchoring path, an inline constant with the literal's printed value left alone, and the refused cases, a live source printed as inline 0 among them). A second shape is repaired too (`mix_inline_literal`): LLVM 21's form above. llvm-mc 21.1.8 (`-mcpu=gfx1013`) prints a `v_fma_mix*` literal whose low 16 bits are the f16 value of an inline constant as that constant and re-encodes the instruction in **8** bytes: every SRC field that held `0xff` holds the inline code, and the literal word is gone (`0x3f800000`, 1.0 as an f32 source, prints as `0`; `0x3c003800` as `0.5`, losing the high half 1.0). Swept with llvm-mc 21.1.8 over all 65,536 low halves under three high halves: exactly 90 low halves print this way (0..64, -1..-16, ±0.5, ±1.0, ±2.0, ±4.0, 1/(2π) as f16: `MIX_INLINE_F16`), whatever the high half; llvm-mc 23.1.6 prints all of them as `lit(V)`. The printed 8 bytes are 4 short of what the decoder read, so the later offsets of a clean listing were 4 low and its first such instruction was refused as a dropped field (one FSPX program, `tupacfan04`'s count in #8683). When every differing SRC field is `0xff` in the blob and the inline code of the stored literal's low half in the print, and the rest of the 8 bytes match exactly (`same_encoding`, all three sources live), each such source reads the stored 32 bits with the stored neg and abs (`NEG_HI`) bits, the instruction takes the 12 stored bytes, and the following offsets move up by 4 (also on the re-anchoring path). Any other difference stays `Unsupported`. CPU-checked by `tests/semantic/test_fma_mix_literal.py` (`FmaMixInlineLiteralTest`: an f32 source, two f16 halves, neg and abs, all 90 codes, both listing paths, the refused cases). | | Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | -| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 \|\| M > DATA) ? DATA : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** | +| Global atomics (`global_atomic_*`, 32-bit and 64-bit `_x2`) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword (or 64-bit element with `_x2` using `Int64Atomics`), device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 || M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas`. With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP} (`cmpswap_x2` takes 4 VGPRs {DATA[63:0], CMP[63:0]}): `M = (M == CMP) ? DATA : M`. `_x2` forms (`and`, `or`, `xor`, `swap`, `add`, `sub`, `smin`, `smax`, `umin`, `umax`, `cmpswap`) lower directly to native SPIR-V 64-bit atomics (`OpAtomicIAdd`, `OpAtomicISub`, `OpAtomicUMin`, `OpAtomicUMax`, `OpAtomicSMin`, `OpAtomicSMax`, `OpAtomicAnd`, `OpAtomicOr`, `OpAtomicXor`, `OpAtomicExchange`, `OpAtomicCompareExchange` on `%ulong` / `%long`) under `OpCapability Int64Atomics`, eliminating multi-dword tearing. Active unaligned lanes (`addr % 8 != 0` for `_x2`, `addr % 4 != 0` for 32-bit) leave memory untouched and return 0. Still `Unsupported`: `inc`/`dec_x2`, `fmin`/`fmax_x2`, `fcmpswap`, and `slc`/`dlc`. CPU-checked by `tests/semantic/test_global_atomics.py` and `tests/semantic/test_global_atomics_x2.py` (all eleven ops on full 64-bit value grid with and without `glc`, `cmpswap_x2` match/mismatch, unaligned address handling, signed offsets, seeded values, rejected invalid forms), and validated with `spirv-val`. **Not GPU-verified.** | | `global_atomic_csub`, `buffer_atomic_csub` (GFX10.3) | `tmp = M; M = (DATA > tmp) ? 0 : tmp - DATA`, unsigned: a subtract clamped at 0 that never wraps; with `glc` the old M comes back. Measured on gfx1036 by @Vonsek (#3193): 162/162 (memory, data) pairs over both forms. Same `OpAtomicCompareExchange` loop as `inc`/`dec` (`Gen.atomic_inc_dec_cas`), so exact under contention; operands, inactive lanes, buffer bounds and `glc` as `inc`/`dec`. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_atomic_csub.py` (a 9×9 value grid, no `glc`, buffer bounds, 32 lanes on one dword against 32 sequential subtracts, seeded values). The translation is not GPU-verified. | | Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** | @@ -494,8 +494,8 @@ How the generated SPIR-V expects the runtime to work: | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | | 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`. | +| `buffer_atomic_*_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]`. All eleven operations (`and`, `or`, `xor`, `swap`, `add`, `sub`, `smin`, `smax`, `umin`, `umax`, `cmpswap`) lower directly to native SPIR-V 64-bit atomics (`OpAtomicIAdd`, `OpAtomicISub`, `OpAtomicUMin`, `OpAtomicUMax`, `OpAtomicSMin`, `OpAtomicSMax`, `OpAtomicAnd`, `OpAtomicOr`, `OpAtomicXor`, `OpAtomicExchange`, `OpAtomicCompareExchange` on `%ulong` / `%long`) under `OpCapability Int64Atomics`, exact across multi-lane contention with no tearing. `cmpswap_x2` takes `vdata` as a 4-VGPR quad `{DATA[63:0], CMP[63:0]}` and returns the old 64-bit value to `vdata[0:1]` with `glc`. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt", fixed_fmt=62)`). An out-of-range, unaligned (`addr % 8 != 0`), or inactive lane leaves memory untouched and returns 0 with `glc` (inactive preserves `vdata`). Still `Unsupported`: `inc`/`dec_x2` and `fmin`/`fmax_x2`. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (all eleven ops with and without `glc`, `cmpswap_x2` match and mismatch, element ending exactly at `num_records`, partial and full OOB, unaligned offsets, seeded values, rejected forms) and validated with `spirv-val`. **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, `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`. | | 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). | diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 015be20388..552684e399 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -860,29 +860,46 @@ def sval(x): p = pointers[a[1]] if p[0] == "pc": raise UnsupportedConstruct(f"{op} on a PushConstant") - if types.bits(a[0]) != 32: - raise UnsupportedConstruct(f"{op} on a non-32-bit integer") + b = types.bits(a[0]) + if b not in (32, 64): + raise UnsupportedConstruct(f"{op} on a non-32/64-bit integer") + mask = (1 << b) - 1 if p[0] == "psb": - old = memory.get(psb_word(p[1]), 0) + if b == 64: + old = memory.get(psb_word(p[1]), 0) | (memory.get(psb_word(p[1] + 4), 0) << 32) + else: + old = memory.get(psb_word(p[1]), 0) else: old = deref(p) - if isinstance(old, bool) or not isinstance(old, int) or old > MASK: - raise UnsupportedConstruct(f"{op} on a variable element that is not a 32-bit integer") + if isinstance(old, bool) or not isinstance(old, int) or old > mask: + raise UnsupportedConstruct(f"{op} on a variable element that is not an integer") if op == "OpAtomicLoad": values[res] = old continue if op == "OpAtomicCompareExchange": - new = val(a[5]) if old == val(a[6]) & MASK else old + new = val(a[5]) if old == (val(a[6]) & mask) else old else: - v = val(a[4]) & MASK - new = {"OpAtomicIAdd": old + v, "OpAtomicISub": old - v, "OpAtomicUMin": min(old, v), - "OpAtomicUMax": max(old, v), "OpAtomicSMin": old if _s32(old) <= _s32(v) else v, - "OpAtomicSMax": old if _s32(old) >= _s32(v) else v, "OpAtomicAnd": old & v, - "OpAtomicOr": old | v, "OpAtomicXor": old ^ v, "OpAtomicExchange": v}[op] + v = val(a[4]) & mask + if b == 64: + def _s64(x): + return x - (1 << 64) if (x >> 63) else x + new = {"OpAtomicIAdd": old + v, "OpAtomicISub": old - v, "OpAtomicUMin": min(old, v), + "OpAtomicUMax": max(old, v), "OpAtomicSMin": old if _s64(old) <= _s64(v) else v, + "OpAtomicSMax": old if _s64(old) >= _s64(v) else v, "OpAtomicAnd": old & v, + "OpAtomicOr": old | v, "OpAtomicXor": old ^ v, "OpAtomicExchange": v}[op] + else: + new = {"OpAtomicIAdd": old + v, "OpAtomicISub": old - v, "OpAtomicUMin": min(old, v), + "OpAtomicUMax": max(old, v), "OpAtomicSMin": old if _s32(old) <= _s32(v) else v, + "OpAtomicSMax": old if _s32(old) >= _s32(v) else v, "OpAtomicAnd": old & v, + "OpAtomicOr": old | v, "OpAtomicXor": old ^ v, "OpAtomicExchange": v}[op] if p[0] == "psb": - memory[p[1]] = new & MASK + if b == 64: + memory[psb_word(p[1])] = new & MASK + memory[psb_word(p[1] + 4)] = (new >> 32) & MASK + else: + memory[psb_word(p[1])] = new & MASK else: - p[0][p[1]] = new & MASK + p[0][p[1]] = new & mask values[res] = old elif op == "OpAtomicStore": # , no result: with invocations run one at a time, a plain store of diff --git a/tests/semantic/test_buffer_atomics_x2.py b/tests/semantic/test_buffer_atomics_x2.py index 1fb130fcc4..cb48f35e7a 100644 --- a/tests/semantic/test_buffer_atomics_x2.py +++ b/tests/semantic/test_buffer_atomics_x2.py @@ -1,10 +1,9 @@ -"""Value tests for RDNA2 buffer_atomic_{and,or,xor,swap}_x2, run through spirv_mini_interp on the CPU. +"""Value tests for RDNA2 64-bit buffer atomics (buffer_atomic_*_x2), run through spirv_mini_interp on the CPU. M = op(M, DATA) on the 64-bit element (two dwords, low first) at the MUBUF address; with glc the old 64 bits come -back in vdata[0:1]. The translator does one 32-bit atomic per dword (exact memory for a bitwise op, and for an exchange -by one lane at a time: two lanes swapping into one element at once can tear it) and checks bounds for the whole 8-byte -element, all or nothing. The V# here is raw (OOB_SELECT 3): an access is in range -when offset + 8 <= num_records. Standard library only; no GPU, no game files. +back in vdata[0:1]. Lowered to native SPIR-V 64-bit atomics (OpAtomicIAdd, OpAtomicCompareExchange, OpAtomicUMin/SMin, etc.) +with OpCapability Int64Atomics. Bounds check covers the whole 8-byte element all or nothing (fixed_fmt=62). +Standard library only; no GPU, no game files. """ import os import random @@ -24,12 +23,31 @@ import spirv_mini_interp as si # noqa: E402 M32 = 0xFFFFFFFF +M64 = (1 << 64) - 1 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 63) else v + + +MODEL = { + "and": lambda m, d: m & d, + "or": lambda m, d: m | d, + "xor": lambda m, d: m ^ d, + "swap": lambda m, d: d, + "add": lambda m, d: (m + d) & M64, + "sub": lambda m, d: (m - d) & M64, + "umin": lambda m, d: min(m, d), + "umax": lambda m, d: max(m, d), + "smin": lambda m, d: m if s64(m) <= s64(d) else d, + "smax": lambda m, d: m if s64(m) >= s64(d) else d, +} +VALUES = [0, M64, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0, + 0x7FFFFFFF_FFFFFFFF, 0x80000000_00000000, 0xFEDCBA98_76543210] ELEM, OUT, RECORDS = 0x40, 0x80, 0x100 # byte offsets in the buffer (base 0), num_records @@ -71,6 +89,17 @@ def atomic_x2(kind, m, d, glc=True, offset=ELEM, records=RECORDS): return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(offset), mem.get(offset + 4)) +def atomic_cmpswap_x2(m, data, cmp_val, glc=True, offset=ELEM, records=RECORDS): + body = ["s_mov_b32 s8, 0", "s_mov_b32 s9, 0", f"s_mov_b32 s10, {records:#x}", "s_mov_b32 s11, 0x31016fac", + f"v_mov_b32_e32 v1, {offset:#x}", + f"v_mov_b32_e32 v2, {data & M32:#x}", f"v_mov_b32_e32 v3, {data >> 32:#x}", + f"v_mov_b32_e32 v4, {cmp_val & M32:#x}", f"v_mov_b32_e32 v5, {cmp_val >> 32:#x}", + f"buffer_atomic_cmpswap_x2 v[2:5], v1, s[8:11], 0 offen" + (" glc" if glc else ""), "s_waitcnt vmcnt(0)", + f"v_mov_b32_e32 v6, {OUT:#x}", "s_mov_b32 s10, 0x1000", "buffer_store_dwordx2 v[2:3], v6, s[8:11], 0 offen"] + mem = run(body, {offset: m & M32, offset + 4: m >> 32}) + return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(offset), mem.get(offset + 4)) + + class BufferAtomicsX2(unittest.TestCase): def test_returning_forms(self): for kind, fn in MODEL.items(): @@ -79,6 +108,15 @@ def test_returning_forms(self): with self.subTest(op=kind, m=hex(m), d=hex(d)): self.assertEqual(atomic_x2(kind, m, d), (split(m), split(fn(m, d)))) + def test_cmpswap_x2_match_and_mismatch(self): + m, d = 0x12345678_9ABCDEF0, 0xAABBCCDD_11223344 + # Match: memory updated, returns old m + self.assertEqual(atomic_cmpswap_x2(m, d, m, glc=True), (split(m), split(d))) + # Mismatch: memory unchanged, returns old m + self.assertEqual(atomic_cmpswap_x2(m, d, 0xDEADBEEF, glc=True), (split(m), split(m))) + # Without glc: vdata kept, memory updated + self.assertEqual(atomic_cmpswap_x2(m, d, m, glc=False), (split(d), split(d))) + def test_without_glc_vdata_is_kept(self): m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF for kind, fn in MODEL.items(): @@ -89,22 +127,31 @@ def test_bounds_cover_the_whole_element(self): m, d = 0x11111111_22222222, 0x0F0F0F0F_F0F0F0F0 # ends exactly at num_records: in range self.assertEqual(atomic_x2("xor", m, d, offset=RECORDS - 8), (split(m), split(m ^ d))) + self.assertEqual(atomic_x2("add", m, d, offset=RECORDS - 8), (split(m), split((m + d) & M64))) # only the low dword in range, or none: memory unchanged, the returned value is 0 (as buffer_atomic) for offset in (RECORDS - 4, RECORDS): with self.subTest(offset=hex(offset)): self.assertEqual(atomic_x2("xor", m, d, offset=offset), ((0, 0), split(m))) + def test_unaligned_address_returns_zero(self): + m, d = 0x12345678_9ABCDEF0, 0x01010101_02020202 + # ELEM + 4 is unaligned (offset % 8 == 4) + vdst, mem = atomic_x2("add", m, d, offset=ELEM + 4) + self.assertEqual(vdst, (0, 0)) + self.assertEqual(mem, split(m)) + def test_seeded(self): rng = random.Random(0xB0A2) - for _ in range(12): + for _ in range(20): kind, m, d = rng.choice(list(MODEL)), rng.getrandbits(64), rng.getrandbits(64) with self.subTest(op=kind, m=hex(m), d=hex(d)): self.assertEqual(atomic_x2(kind, m, d), (split(m), split(MODEL[kind](m, d)))) - def test_carrying_forms_and_bad_data_rejected(self): - for line in ("buffer_atomic_add_x2 v[2:3], v1, s[8:11], 0 offen glc", - "buffer_atomic_cmpswap_x2 v[2:5], v1, s[8:11], 0 offen glc", - "buffer_atomic_or_x2 v2, v1, s[8:11], 0 offen glc"): + def test_bad_data_and_forms_rejected(self): + for line in ("buffer_atomic_or_x2 v2, v1, s[8:11], 0 offen glc", + "buffer_atomic_cmpswap_x2 v[2:3], v1, s[8:11], 0 offen glc", + "buffer_atomic_inc_x2 v[2:3], v1, s[8:11], 0 offen glc", + "buffer_atomic_fmin_x2 v[2:3], v1, s[8:11], 0 offen glc"): with self.subTest(line=line): with self.assertRaises(rdna2spirv.Unsupported): translate(["v_mov_b32_e32 v1, 0", line]) diff --git a/tests/semantic/test_global_atomics.py b/tests/semantic/test_global_atomics.py index 5afcdef9fc..2c7758bf0c 100644 --- a/tests/semantic/test_global_atomics.py +++ b/tests/semantic/test_global_atomics.py @@ -124,7 +124,7 @@ def test_seeded(self): self.assertEqual(atomic(kind, m, d), (m, MODEL[kind](m, d))) def test_rejected_forms(self): - for line in ("global_atomic_add_x2 v[4:5], v1, v[2:3], s[0:1] glc", "global_atomic_inc_x2 v[4:5], v1, v[2:3], s[0:1] glc", + for line in ("global_atomic_inc_x2 v[4:5], v1, v[2:3], s[0:1] glc", "global_atomic_fmin_x2 v[4:5], v1, v[2:3], s[0:1] glc", "global_atomic_add v5, v1, v2, s[0:1] glc slc", "global_atomic_cmpswap v5, v1, v2, s[0:1] glc"): diff --git a/tests/semantic/test_global_atomics_x2.py b/tests/semantic/test_global_atomics_x2.py index d0da12d5bf..031a059178 100644 --- a/tests/semantic/test_global_atomics_x2.py +++ b/tests/semantic/test_global_atomics_x2.py @@ -1,9 +1,8 @@ -"""Value tests for RDNA2 global_atomic_{and,or,xor,swap}_x2, run through spirv_mini_interp on the CPU. +"""Value tests for RDNA2 64-bit global atomics (global_atomic_*_x2), run through spirv_mini_interp on the CPU. M = op(M, DATA) on the 64-bit element at the global_* address (two dwords, low first); with glc the old 64 bits land in -vdst[0:1]. The translator does one 32-bit atomic per dword, which leaves the same memory for a bitwise op, and for an -exchange by one lane at a time (two lanes swapping into one element at once can tear it). The carrying and comparing -_x2 forms stay Unsupported. Standard library only; no GPU, no game files. +vdst[0:1]. Lowered to native SPIR-V 64-bit atomics (OpAtomicIAdd, OpAtomicCompareExchange, OpAtomicUMin/SMin, etc.) +with OpCapability Int64Atomics. Standard library only; no GPU, no game files. """ import os import random @@ -18,17 +17,51 @@ import rdna2spirv # noqa: E402 M32 = 0xFFFFFFFF -MODEL = {"and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d, "swap": lambda m, d: d} -VALUES = [0, (1 << 64) - 1, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0] +M64 = (1 << 64) - 1 -def atomic_x2(kind, m, d, glc=True, offset=0): - body = [f"v_mov_b32_e32 v1, {TARGET - offset:#x}", f"v_mov_b32_e32 v2, {d & M32:#x}", +def s64(v): + return v - (1 << 64) if (v >> 63) else v + + +MODEL = { + "and": lambda m, d: m & d, + "or": lambda m, d: m | d, + "xor": lambda m, d: m ^ d, + "swap": lambda m, d: d, + "add": lambda m, d: (m + d) & M64, + "sub": lambda m, d: (m - d) & M64, + "umin": lambda m, d: min(m, d), + "umax": lambda m, d: max(m, d), + "smin": lambda m, d: m if s64(m) <= s64(d) else d, + "smax": lambda m, d: m if s64(m) >= s64(d) else d, +} +VALUES = [0, M64, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0, + 0x7FFFFFFF_FFFFFFFF, 0x80000000_00000000, 0xFEDCBA98_76543210] + + +def atomic_x2(kind, m, d, glc=True, offset=0, target=TARGET): + body = [f"v_mov_b32_e32 v1, {target - offset:#x}", f"v_mov_b32_e32 v2, {d & M32:#x}", f"v_mov_b32_e32 v3, {d >> 32:#x}", "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef"] off = f" offset:{offset}" if offset else "" body.append(f"global_atomic_{kind}_x2 v[6:7], v1, v[2:3], s[0:1]{off} glc" if glc else f"global_atomic_{kind}_x2 v1, v[2:3], s[0:1]{off}") body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v8, {OUT:#x}", "global_store_dwordx2 v8, v[6:7], s[0:1]"] + mem = run(body, {target: m & M32, target + 4: m >> 32}) + return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(target), mem.get(target + 4)) + + +def atomic_cmpswap_x2(m, data, cmp_val, glc=True, offset=0): + body = [f"v_mov_b32_e32 v1, {TARGET - offset:#x}", + f"v_mov_b32_e32 v2, {data & M32:#x}", + f"v_mov_b32_e32 v3, {data >> 32:#x}", + f"v_mov_b32_e32 v4, {cmp_val & M32:#x}", + f"v_mov_b32_e32 v5, {cmp_val >> 32:#x}", + "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef"] + off = f" offset:{offset}" if offset else "" + body.append(f"global_atomic_cmpswap_x2 v[6:7], v1, v[2:5], s[0:1]{off} glc" if glc else + f"global_atomic_cmpswap_x2 v1, v[2:5], s[0:1]{off}") + body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v8, {OUT:#x}", "global_store_dwordx2 v8, v[6:7], s[0:1]"] mem = run(body, {TARGET: m & M32, TARGET + 4: m >> 32}) return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(TARGET), mem.get(TARGET + 4)) @@ -45,6 +78,15 @@ def test_returning_forms(self): with self.subTest(op=kind, m=hex(m), d=hex(d)): self.assertEqual(atomic_x2(kind, m, d), (split(m), split(fn(m, d)))) + def test_cmpswap_x2_match_and_mismatch(self): + m, d = 0x12345678_9ABCDEF0, 0xAABBCCDD_11223344 + # Match: memory changes to data, returns old m + self.assertEqual(atomic_cmpswap_x2(m, d, m, glc=True), (split(m), split(d))) + # Mismatch: memory unchanged, returns old m + self.assertEqual(atomic_cmpswap_x2(m, d, 0xDEADBEEF, glc=True), (split(m), split(m))) + # Without glc: vdst preserved, memory updated + self.assertEqual(atomic_cmpswap_x2(m, d, m, glc=False), ((0xDEAD, 0xBEEF), split(d))) + def test_without_glc_vdst_is_kept(self): m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF for kind, fn in MODEL.items(): @@ -54,18 +96,31 @@ def test_without_glc_vdst_is_kept(self): def test_offset_and_seeded(self): self.assertEqual(atomic_x2("xor", 0x11111111_22222222, 0x0000FFFF_FFFF0000, offset=-8), (split(0x11111111_22222222), split(0x11111111_22222222 ^ 0x0000FFFF_FFFF0000))) + self.assertEqual(atomic_x2("add", 0x00000001_FFFFFFFF, 1, offset=-8), + (split(0x00000001_FFFFFFFF), split(0x00000002_00000000))) rng = random.Random(0x6A72) - for _ in range(12): + for _ in range(20): kind, m, d = rng.choice(list(MODEL)), rng.getrandbits(64), rng.getrandbits(64) with self.subTest(op=kind, m=hex(m), d=hex(d)): self.assertEqual(atomic_x2(kind, m, d), (split(m), split(MODEL[kind](m, d)))) - def test_carrying_and_comparing_forms_rejected(self): - for kind in ("add", "sub", "smin", "umax", "cmpswap"): + def test_unaligned_address_returns_zero(self): + m, d = 0x12345678_9ABCDEF0, 0x55555555_AAAAAAA0 + # TARGET + 4 is unaligned for 8-byte atomic (addr % 8 == 4) + vdst, mem = atomic_x2("add", m, d, target=TARGET + 4) + self.assertEqual(vdst, (0, 0)) + self.assertEqual(mem, split(m)) + + def test_rejected_forms(self): + for kind in ("inc", "dec", "csub", "fmin", "fmax"): with self.subTest(op=kind): with self.assertRaises(rdna2spirv.Unsupported): translate(["v_mov_b32_e32 v1, 0", f"global_atomic_{kind}_x2 v[6:7], v1, v[2:3], s[0:1] glc"]) - with self.assertRaises(rdna2spirv.Unsupported): # a single VGPR is not a 64-bit vdst + # cmpswap_x2 requires 4 VGPRs for vdata, not 2 + with self.assertRaises(rdna2spirv.Unsupported): + translate(["v_mov_b32_e32 v1, 0", "global_atomic_cmpswap_x2 v[6:7], v1, v[2:3], s[0:1] glc"]) + # single VGPR destination is not valid for 64-bit atomic + with self.assertRaises(rdna2spirv.Unsupported): translate(["v_mov_b32_e32 v1, 0", "global_atomic_or_x2 v6, v1, v[2:3], s[0:1] glc"]) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae8..689de9b594 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -280,6 +280,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.f16_half_outs = {} # VS/MS, --f16-interp-fallback: param n -> its two decoded-half output names self.ij_capture = {} # computed-I/J pairs: pair key -> the I float id the p1 loaded (SHADER-177) self.uses_psb = False + self.uses_int64_atomics = False self.uses_active = False self.vm_latch = False # PS: EXEC can change after a `vm` or color export, so EXEC at those is kept self.col_latched = [] # PS with vm_latch: the color targets (mrtN) whose export EXEC is kept @@ -2919,7 +2920,7 @@ def global_atomic(self, op, a, mods): forms (add/sub/min/max carry or compare across the dwords, cmpswap_x2 compares all 64 bits) and inc/dec stay Unsupported. fcmpswap compares as binary32 (float_cmpswap_loop).""" kind = op[len("global_atomic_"):] - if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): + if kind.endswith("_x2"): return self.global_atomic_x2(op, kind[:-3], a, mods) if kind in ("fmin", "fmax"): return self.global_atomic_float(op, kind, a, mods) @@ -2988,20 +2989,44 @@ def global_atomic_float(self, op, kind, a, mods): if vdst is not None: self.dst(vdst, old) + def pack_u64(self, lo, hi): + """Pack two 32-bit uint values (lo, hi) into a 64-bit %ulong.""" + l64, h64, t, val64 = (self.tmp() for _ in range(4)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{val64} = OpBitwiseOr %ulong {t} {l64}") + return val64 + + def unpack_u64(self, v64): + """Unpack a 64-bit %ulong into low and high 32-bit %uint values.""" + rlo, rh, rhi = (self.tmp() for _ in range(3)) + self.emit(f"{rlo} = OpUConvert %uint {v64}") + self.emit(f"{rh} = OpShiftRightLogical %ulong {v64} %c64_32") + self.emit(f"{rhi} = OpUConvert %uint {rh}") + return rlo, rhi + def global_atomic_x2(self, op, kind, a, mods): - """global_atomic_{and,or,xor,swap}_x2 (see global_atomic): one 32-bit atomic per dword of the element.""" - if any(m in mods for m in ("slc", "dlc", "lds")): + """global_atomic__x2 [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: 64-bit atomic at the global_* address + (RDNA2 ISA, FLAT/GLOBAL). With glc the pre-op value lands in vdst[0:1]. cmpswap_x2 takes vdata as a 4-VGPR quad + {DATA[63:0], CMP[63:0]}: M = (M == CMP) ? DATA : M. Inactive lanes don't touch memory and keep vdst; active + unaligned lanes (addr % 8 != 0) leave memory untouched and write (0, 0) to vdst (measured natively on gfx1036). + Lowered to native SPIR-V Int64Atomics operations (OpAtomicIAdd, OpAtomicCompareExchange, etc.) on + PhysicalStorageBuffer.""" + if kind not in self.BUF_ATOMICS or any(m in mods for m in ("slc", "dlc", "lds")): raise Unsupported(op + " form") rtn = "glc" in mods if len(a) != (4 if rtn else 3): raise Unsupported(op + " operands") vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2 or \ + expected_n = 4 if kind == "cmpswap" else 2 + if vdata["k"] != "vgpr" or vdata.get("n", 1) != expected_n or \ (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 2)): raise Unsupported(op + " operands") full = self.global_address(op, vaddr, saddr, mods) - vals = [self.load_reg("vgpr", vdata["r"] + w) for w in range(2)] - spv = self.BUF_ATOMICS[kind][0] + vals = [self.load_reg("vgpr", vdata["r"] + w) for w in range(expected_n)] + val64 = self.pack_u64(vals[0], vals[1]) + cmp64 = self.pack_u64(vals[2], vals[3]) if kind == "cmpswap" else None al = self.atomic_aligned(full, 8) cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") @@ -3010,24 +3035,36 @@ def global_atomic_x2(self, op, kind, a, mods): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - res = [] - for w in range(2): - p, r = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") - self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") - res.append(r) + self.uses_int64_atomics = True + self.uses_psb = True + res64 = self.tmp() + if kind in ("smin", "smax"): + ptr_long, p_long, val_long, res_long = (self.tmp() for _ in range(4)) + self.emit(f"{ptr_long} = OpConvertUToPtr %_ptr_PSB_arr_long {self.host_addr(full)}") + self.emit(f"{p_long} = OpAccessChain %_ptr_PSB_long {ptr_long} {self.cu(0)}") + self.emit(f"{val_long} = OpBitcast %long {val64}") + spv = "OpAtomicSMin" if kind == "smin" else "OpAtomicSMax" + self.emit(f"{res_long} = {spv} %long {p_long} {self.cu(1)} {self.cu(0)} {val_long}") + self.emit(f"{res64} = OpBitcast %ulong {res_long}") + elif kind == "cmpswap": + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr_ulong {self.host_addr(full)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_ulong {ptr} {self.cu(0)}") + self.emit(f"{res64} = OpAtomicCompareExchange %ulong {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val64} {cmp64}") + else: + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr_ulong {self.host_addr(full)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_ulong {ptr} {self.cu(0)}") + spv = self.BUF_ATOMICS[kind][0] + self.emit(f"{res64} = {spv} %ulong {p} {self.cu(1)} {self.cu(0)} {val64}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") - olds = [] - for w in range(2): # both OpPhi first: they must open the merge block - old = self.tmp() - self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") - olds.append(old) + old64 = self.tmp() + self.emit(f"{old64} = OpPhi %ulong {res64} {lbl_do} {self.cl(0)} {pre}") if vdst is not None: - for w in range(2): - self.dst({"k": "vgpr", "r": vdst["r"] + w, "n": 1}, olds[w]) + rlo, rhi = self.unpack_u64(old64) + self.dst({"k": "vgpr", "r": vdst["r"], "n": 1}, rlo) + self.dst({"k": "vgpr", "r": vdst["r"] + 1, "n": 1}, rhi) def float_cmpswap_loop(self, p, new, cmp, scope): """tmp = M; M = (tmp == CMP as binary32) ? NEW : tmp; returns tmp (RDNA2 ISA, *_FCMPSWAP / DS_CMPST_F32). A @@ -3061,7 +3098,7 @@ def buffer_atomic(self, op, a, mods): address). With 'glc' the pre-op value is returned in vdata. Inactive lanes don't touch memory and keep vdata; active OOB or unaligned (addr % 4 != 0) lanes leave memory untouched and write 0 with glc (measured on gfx1036).""" kind = op[len("buffer_atomic_"):] - if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): + if kind.endswith("_x2"): return self.buffer_atomic_x2(op, kind[:-3], a, mods) if kind in ("fmin", "fmax"): return self.buffer_atomic_float(op, kind, a, mods) @@ -3130,19 +3167,21 @@ def buffer_atomic_float(self, op, kind, a, mods): self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) def buffer_atomic_x2(self, op, kind, a, mods): - """buffer_atomic_{and,or,xor,swap}_x2 vdata[0:1], vaddr, s[V#], soffset: M = op(M, DATA) on the 64-bit element - (two dwords, low first); with glc the old 64 bits are returned in vdata. Each dword is its own 32-bit atomic, so - no Int64 atomics are needed. That leaves the same memory for a bitwise op, whose bits are independent, but an - exchange can tear: 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). The returned pair is two reads, so another lane's 64-bit op on the same element - between them could be seen half done. Measured natively on RDNA2 (gfx1036, wave32 & wave64): the bounds check - covers the whole 8-byte element all or nothing (fixed_fmt=62) and addresses with (addr & 7) != 0 are dropped - (memory untouched, active glc returns (0, 0), inactive preserves vdata).""" + """buffer_atomic__x2 vdata, vaddr, s[V#], soffset ...: 64-bit atomic at the element address (MUBUF). + With glc the old 64 bits come back in vdata[0:1]. cmpswap_x2 takes vdata as a 4-VGPR quad + {DATA[63:0], CMP[63:0]}. The bounds check covers the whole 8-byte element all or nothing (fixed_fmt=62) + and addresses with (addr & 7) != 0 leave memory untouched (active glc returns (0, 0), inactive preserves vdata). + Lowered to native SPIR-V Int64Atomics operations on PhysicalStorageBuffer.""" + if kind not in self.BUF_ATOMICS: + raise Unsupported(op + " form") vd = a[0] - if vd["k"] != "vgpr" or vd.get("n", 1) != 2: + expected_n = 4 if kind == "cmpswap" else 2 + if vd["k"] != "vgpr" or vd.get("n", 1) != expected_n: raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods, elem="fmt", fixed_fmt=62) # step: as buffer_atomic - vals = [self.load_reg("vgpr", vd["r"] + w) for w in range(2)] + vals = [self.load_reg("vgpr", vd["r"] + w) for w in range(expected_n)] + val64 = self.pack_u64(vals[0], vals[1]) + cmp64 = self.pack_u64(vals[2], vals[3]) if kind == "cmpswap" else None al = self.atomic_aligned(addr, 8) ok, cond = self.tmp(), self.tmp() self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") @@ -3152,25 +3191,36 @@ def buffer_atomic_x2(self, op, kind, a, mods): self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") - res = [] - for w in range(2): - p, r = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") - self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") - res.append(r) + self.uses_int64_atomics = True + self.uses_psb = True + res64 = self.tmp() + if kind in ("smin", "smax"): + ptr_long, p_long, val_long, res_long = (self.tmp() for _ in range(4)) + self.emit(f"{ptr_long} = OpConvertUToPtr %_ptr_PSB_arr_long {self.host_addr(addr)}") + self.emit(f"{p_long} = OpAccessChain %_ptr_PSB_long {ptr_long} {self.cu(0)}") + self.emit(f"{val_long} = OpBitcast %long {val64}") + spv = "OpAtomicSMin" if kind == "smin" else "OpAtomicSMax" + self.emit(f"{res_long} = {spv} %long {p_long} {self.cu(1)} {self.cu(0)} {val_long}") + self.emit(f"{res64} = OpBitcast %ulong {res_long}") + elif kind == "cmpswap": + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr_ulong {self.host_addr(addr)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_ulong {ptr} {self.cu(0)}") + self.emit(f"{res64} = OpAtomicCompareExchange %ulong {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val64} {cmp64}") + else: + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr_ulong {self.host_addr(addr)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_ulong {ptr} {self.cu(0)}") + spv = self.BUF_ATOMICS[kind][0] + self.emit(f"{res64} = {spv} %ulong {p} {self.cu(1)} {self.cu(0)} {val64}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") - olds = [] - for w in range(2): # both OpPhi first: they must open the merge block - old = self.tmp() - # an inactive, out-of-range or unaligned lane skips the atomic (active gets 0, inactive keeps vdata via dst) - self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") - olds.append(old) + old64 = self.tmp() + self.emit(f"{old64} = OpPhi %ulong {res64} {lbl_do} {self.cl(0)} {pre}") if "glc" in mods: - for w in range(2): - self.dst({"k": "vgpr", "r": vd["r"] + w, "n": 1}, olds[w]) + rlo, rhi = self.unpack_u64(old64) + self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, rlo) + self.dst({"k": "vgpr", "r": vd["r"] + 1, "n": 1}, rhi) def current_label_placeholder(self): """Label of the block currently being emitted (needed for OpPhi). Blocks are opened by OpLabel lines; @@ -15467,6 +15517,8 @@ def assemble(gen): caps += [c for c in ("GroupNonUniform", "GroupNonUniformArithmetic") if c not in caps] if gen.uses_quad: caps += [c for c in ("GroupNonUniform", "GroupNonUniformQuad") if c not in caps] + if gen.uses_int64_atomics: + caps.append("Int64Atomics") if gen.uses_f64: caps.append("Float64") if gen.uses_fma_khr: @@ -15630,6 +15682,14 @@ def assemble(gen): "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] dec.append("OpDecorate %rt_uint ArrayStride 4") + if gen.uses_int64_atomics: + types += ["%rt_ulong = OpTypeRuntimeArray %ulong", + "%_ptr_PSB_arr_ulong = OpTypePointer PhysicalStorageBuffer %rt_ulong", + "%_ptr_PSB_ulong = OpTypePointer PhysicalStorageBuffer %ulong", + "%rt_long = OpTypeRuntimeArray %long", + "%_ptr_PSB_arr_long = OpTypePointer PhysicalStorageBuffer %rt_long", + "%_ptr_PSB_long = OpTypePointer PhysicalStorageBuffer %long"] + dec += ["OpDecorate %rt_ulong ArrayStride 8", "OpDecorate %rt_long ArrayStride 8"] types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(gen.lconsts.items())] if tex: # Bindless set 0: images (binding 0), samplers (binding 1), descriptor hash table (binding 2).