diff --git a/docs/design.md b/docs/design.md index daeb4eb42..e7ba8be5e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -300,7 +300,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) | `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 by default: a bitwise op leaves the same memory that way, with no Int64 atomics. With opt-in `--int64-atomics` (`make_game.py --int64-atomics`, `LEONIDA_INT64_ATOMICS=1`, enabled on the Vulkan device via `VkPhysicalDeviceVulkan12Features::shaderBufferInt64Atomics`), `swap_x2` emits 64-bit `OpAtomicExchange` on `%ulong` (`OpCapability Int64Atomics`) so concurrent 64-bit exchanges cannot tear (`ds_wrxchg_rtn_b64` is unchanged). **Approximation:** without `--int64-atomics`, `swap_x2` can tear between dwords, 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`). 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), `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and `tests/semantic/test_atomic_swap_x2_int64.py`, and validated with `spirv-val` (native and `--wave64-emulate`). **GPU-checked on `--int64-atomics` (`SHADER-868`):** `@aslan2142` verified on AMD Ryzen 9 7950X3D iGPU and Radeon RX 7900 XTX (Mesa 26.3.1 RADV, `shaderBufferInt64Atomics = true`) that default 32-bit swaps tore (`8/8` and `235–423`/`303–436` per run) while `--int64-atomics` had `0/0` tears (`cs_atomic_swap_x2_int64` single-thread fixture also passed on CI `llvmpipe`; the updated 64-thread tearing fixture in `runtime/test/shaders/cs_atomic_swap_x2_int64.asm` is pending CI/hardware re-run). | | `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). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. GPU-checked by `runtime/test/shaders/cs_global_mem_ext.asm` for two of the ten ops (one lane, `saddr` addressing, on a Radeon 610M (gfx1036, RADV, Mesa 26.2.6) and an RTX 4070 Ti (NVIDIA 620.70.06), Linux): `global_store_short` at byte 3 of a dword changes only its two bytes, across both dwords, and `global_load_sbyte_d16_hi` sign-extends a byte into the high half of `vdst` and keeps the low half. **Not GPU-verified:** the other eight ops and an inactive lane. | @@ -513,7 +513,7 @@ 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). GPU-checked by `runtime/test/shaders/cs_w32_cmp_f64.asm`: all 16 predicates of both forms on 256 memory-fed pairs (the product of 16 values: ±inf, ±max, the 1-ULP neighbours of ±1, the smallest subnormals, ±0, the smallest normal, a NaN with its payload in the low dword only, a negative quiet NaN), `tru` with the odd threads off (an inactive lane gets VCC 0 and stays off through `v_cmpx_`), and `lt`/`nge` with `abs`/`neg`, all 1536 heap words exact on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (subgroup 8). That run checks the translated SPIR-V on a driver against IEEE-754, not RDNA2 itself; SGPR-pair and constant operands are not in it. 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.** | +| `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:** without `--int64-atomics`, 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. With `--int64-atomics` the swap is one 64-bit `OpAtomicExchange` on the whole element (capability `Int64Atomics`, enabled through the `shaderBufferInt64Atomics` / `shaderImageInt64Atomics` device features at run time), so the store side no longer tears; the returned pair still comes from two 32-bit reads. **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.** | | Per-lane descriptor selection | The translator executes the first-active-lane read, EXEC selection, scalar descriptor load and remaining-lane retry as ordinary wave instructions. The hand-written `waterfall_table_offset.asm` fixture reads four different buffers and checks every lane on wave32, native wave64 and emulated wave64. The graphics partition analysis accepts an unmodified full-word integer equality as evidence that selected lanes hold the first lane's word. A float comparison accepts both signs of zero. The signed-zero execution fixture produces different raw outputs when a 64-lane group is split and therefore requires tier C. See Marvis's VIctory waterfall analysis (b1c8306, ffe310e) for the distinction between comparing descriptor words and comparing the offset of a descriptor load. | | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | | Wave64 graphics: a uniform vote under whole-quad EXEC (SHADER-W64-WQM-UVOTE) | SHADER-10 (the row above) takes a `vccz`/`vccnz` on a wave-uniform compare for no lane vote only while EXEC is the launch mask. A pixel shader that needs derivatives starts with `s_wqm_b64 exec, exec`, and LLVM branches on uniform conditions inside that region in the same form: `v_cmp_* sN, ` / `s_and_b64 vcc, exec, s[N:N+1]` / `s_cbranch_vccnz` (or the compare straight into VCC). **That is exact too, for a compare of immediates and scalars**: it is the same in every lane, so its mask is every lane of EXEC or none; EXEC is the whole quads of the launch mask, a quad is four consecutive lanes and never straddles the two 32-lane halves, and a half that runs has a launch lane, so EXEC has a lane in every half that runs and each half votes as the wave does. Both sides of the branch may then have code and scalars of their own (if/else, a uniform loop back edge), as under the launch mask. `tools/wave64_halves.py` carries it as a dataflow fact (`q`: EXEC is the whole quads of the launch mask), set by `s_wqm_b64 exec, exec` while EXEC is the launch mask and dropped by every other write to EXEC; `uniform_cmp` and the `s_and_b64 .., exec, ..` of a uniform mask accept it next to the launch mask. **What stays tier C, and why**: a VGPR source, even one SHADER-10 calls uniform (it was written under the launch mask, and the helper lanes EXEC now includes never got it, so they compare what they held; a VGPR written inside the region is refused as well, because the analysis does not tell the two apart); the whole quads of a narrowed EXEC, and any narrowing after the `s_wqm_b64` (a half can be empty); whole quads saved and put back later, or made in a register and copied to EXEC (only the write by `s_wqm_b64 exec, exec` is modelled); and a compare on a path where a scalar was read out of a uniform VGPR from a lane the launch mask may not have written, by `v_readlane_b32` at any time or by `v_readfirstlane_b32` while EXEC was not the launch mask (`qr`, kept for the rest of the path: SHADER-10 treats such a scalar as uniform, this rule does not build on that). **Corpus** (1.0.2.1, all 26,503, `wave64_halves.analyse` on every wave64 VS/PS/GS, with SHADER-W64-SDST-PAIR on `main` `3ed8e50b7` as the baseline, because the listings name the compare's destination by one register and without that rule the vote is hidden behind `tainted-branch`): **452 pixel shaders go from tier C to A**, no shader moves the other way and no vertex or geometry shader moves: A 5,267 to 5,719, B 397, C 7,741 to 7,289 (PS 3,545/34/7,395 to 3,997/34/6,943). Reasons: `unsafe-vote-branch` 7,362 to 6,861, `tainted-exec` 5,829 to 5,793, `stale-scalar` 3,287 to 3,254, the others unchanged; 802 shaders still have `unsafe-vote-branch` as their only reason. CPU-checked by `tests/semantic/test_wave64_halves_wqm_uvote.py`: the accepted forms in both printed forms of the destination, ten near misses that stay tier C, and a vertex and a pixel shader run on the wave interpreter as one wave of 64 lanes and as two of 32, equal and equal to the derived words with s4 = 9 and s4 = 1 (every lane covered there: the interpreters do not model a helper lane in a quad swap, so partial coverage rests on the argument above). GPU-checked by `ps_w64_a_wqm_uniform_vote` (`w64_graphics.py`: an if/else on a compare into VCC, the LLVM form through an SGPR pair and a loop closed by the vote, all under `s_wqm_b64 exec, exec`, EXEC put back before the export), which gives the words its header derives on an NVIDIA GeForce RTX 4070 Ti (Linux, driver 620.70.06, 32 only). That device has one subgroup size, so the 64-lane image was not drawn there and the full-screen draw has no partly covered quad; the run confirms the translated SPIR-V against the ISA reference, not native RDNA2 behaviour. | diff --git a/make_game.py b/make_game.py index 3eb089945..077e263e7 100644 --- a/make_game.py +++ b/make_game.py @@ -1775,7 +1775,7 @@ def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"), ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), - ("--compact-spirv", "compact_spirv")) + ("--compact-spirv", "compact_spirv"), ("--int64-atomics", "int64_atomics")) def fallback_flags(a) -> tuple[str, ...]: @@ -3039,6 +3039,10 @@ def main() -> int: help="keep s0..s31 in 128 push-constant bytes and move heap/code base to a set-1 uniform " "block; on by itself when the runtime's GPU reports maxPushConstantsSize below what " "the shaders need (144, or 152 with --mesh-compute)") + ap.add_argument("--int64-atomics", action="store_true", + help="emit 64-bit OpAtomicExchange (OpCapability Int64Atomics, requires " + "shaderBufferInt64Atomics) for buffer_atomic_swap_x2 / global_atomic_swap_x2 " + "instead of two 32-bit dword exchanges (ds_wrxchg_rtn_b64 is unchanged)") ap.add_argument("--no-tui", action="store_true", help="plain console logs (default when stdout is not a TTY); skip the LEONIDA setup screen " "and per-stage log view") diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 0d76ae44a..739dbc52e 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -191,6 +191,9 @@ struct VulkanDeviceInfo { // arena and have console VAs (docs section 3.3), and GetGPUVirtualAddress returns those addresses; ray tracing // needs it too. Without it, GetGPUVirtualAddress returns 0 and pipelines cannot be created. bool buffer_device_address = false; + // Vulkan 1.2 shaderBufferInt64Atomics is enabled on `device`: translated shaders built with + // `rdna2spirv.py --int64-atomics` (OpCapability Int64Atomics on *_atomic_swap_x2) can create compute/graphics PSOs. + bool shader_buffer_int64_atomics = false; // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. bool ray_tracing = false; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 12494d201..67c245187 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -16085,6 +16085,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable12.separateDepthStencilLayouts = VK_TRUE; info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE; enable12.bufferDeviceAddress = info.buffer_device_address ? VK_TRUE : VK_FALSE; + info.shader_buffer_int64_atomics = chosen12.shaderBufferInt64Atomics == VK_TRUE; + enable12.shaderBufferInt64Atomics = info.shader_buffer_int64_atomics ? VK_TRUE : VK_FALSE; info.storage_buffer_8bit = chosen12.storageBuffer8BitAccess == VK_TRUE; enable12.storageBuffer8BitAccess = info.storage_buffer_8bit; // Where the GPU has them: what the bindless set 0 needs (VulkanDeviceInfo::bindless), and the sampler features diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 9df462d3f..d1300e1c3 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -7121,6 +7121,7 @@ int main() { EXPECT(on.shaderResourceMinLod == have.features.shaderResourceMinLod); EXPECT(made->shader_output_layer == (have12.shaderOutputLayer == VK_TRUE)); EXPECT(made->shader_output_viewport_index == (have12.shaderOutputViewportIndex == VK_TRUE)); + EXPECT(made->shader_buffer_int64_atomics == (have12.shaderBufferInt64Atomics == VK_TRUE)); // The pixel-shader extensions (barycentrics, the POPS interlock, maintenance8's texel offsets): each is // enabled exactly when the GPU offers the extension and its feature. A structure is chained into the // query only when its extension is offered. diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 03a7ecd22..1081dd5cf 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -31,6 +31,7 @@ import json import os import re +import shutil import struct import subprocess import sys @@ -198,7 +199,26 @@ def translate_tests(work, names): # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): cmd.append("--pc-tail-ubo") - return subprocess.run(cmd).returncode + int64_on = (os.environ.get("LEONIDA_INT64_ATOMICS") or "").strip().lower() in ("1", "true", "yes", "on") + if int64_on: + cmd.append("--int64-atomics") + rc = subprocess.run(cmd).returncode + if rc or int64_on or "cs_atomic_swap_x2_int64" not in names: + return rc + # cs_atomic_swap_x2_int64 specifically exercises --int64-atomics even when LEONIDA_INT64_ATOMICS is unset globally. + atomic_disasm = work / "disasm_int64" + atomic_out = work / "spirv_int64" + atomic_disasm.mkdir() + shutil.copy2(disasm / "cs_atomic_swap_x2_int64.s", atomic_disasm / "cs_atomic_swap_x2_int64.s") + rc = subprocess.run(cmd[:3] + [atomic_disasm, "--out", atomic_out, *cmd[6:], "--int64-atomics"]).returncode + if rc: + return rc + shutil.copy2(atomic_out / "cs_atomic_swap_x2_int64.spv", spirv / "cs_atomic_swap_x2_int64.spv") + main_idx = json.loads((spirv / "index.json").read_text(encoding="utf-8")) + sub_idx = json.loads((atomic_out / "index.json").read_text(encoding="utf-8")) + main_idx["cs_atomic_swap_x2_int64"] = sub_idx["cs_atomic_swap_x2_int64"] + (spirv / "index.json").write_text(json.dumps(main_idx, indent=2) + "\n", encoding="utf-8", newline="\n") + return 0 def main(): diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index f0ddf2f31..059a65a78 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -344,7 +344,9 @@ def not_found_message(build, missing): GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 0x0000009E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE]), # global/buffer atomics, 8/16-bit global stores and d16 loads with CPU-only checks until now - ("cs_global_mem_ext", "40", [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234])] + ("cs_global_mem_ext", "40", [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234]), + # 64-bit OpAtomicExchange multi-thread tearing regression (built with --int64-atomics; exits 77 if unsupported) + ("cs_atomic_swap_x2_int64", "40", [0, 0, 256, 256, 1, 1, 0xDEAD0001, 0x9ABCDEF0])] # cs_heap_init.asm: vk_compute_test's VKC_HEAP_INIT copies this file (zeros, then four words at 0x100) to the start # of the heap; the shader copies the four words to 0, and out[4..7] are the file's zeros, not the 0xEE fill. HEAP_INIT_WORDS = [0x1BADB002, 0xCAFEF00D, 0x80000001, 0x0000FFFF] diff --git a/runtime/test/shaders/cs_atomic_swap_x2_int64.asm b/runtime/test/shaders/cs_atomic_swap_x2_int64.asm new file mode 100644 index 000000000..9bbbd11fb --- /dev/null +++ b/runtime/test/shaders/cs_atomic_swap_x2_int64.asm @@ -0,0 +1,172 @@ +; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm +; GPU multi-thread test for --int64-atomics (64-bit OpAtomicExchange / Int64Atomics on buffer_atomic_swap_x2 and +; global_atomic_swap_x2; ds_wrxchg_rtn_b64 is unchanged). Built with --int64-atomics by run_gpu_tests.py and +; build.py (and globally with LEONIDA_INT64_ATOMICS=1); exits 77 if the Vulkan device lacks shaderBufferInt64Atomics. +; 40 groups make a 0x2800-byte heap; only group 0 runs the atomic swaps across all 64 threads (2 wave32 waves) over +; 4 rounds (256 buffer + 256 global swaps), verifying every returned pair has matching (lo ^ hi) tag+id parity +; (0 tears on atomic 64-bit exchange; two 32-bit dword exchanges tear when concurrent waves interleave). +; Finally group 0 thread 0 checks known return + readback values: +; Run: vk_compute_test cs_atomic_swap_x2_int64.spv 40 dump -> +; 0x0 0x0 0x100 0x100 0x1 0x1 0xdead0001 0x9abcdef0 +v_or_b32_e32 v1, s4, v0 +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32 v2, 0x2000 +v_mov_b32 v10, 0xaa000000 +v_mov_b32 v11, 0xbb000000 +buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen +s_mov_b32 s20, 0x2000 +s_mov_b32 s21, 0 +v_mov_b32 v30, 0 +v_mov_b32 v4, 0xcc000000 +v_mov_b32 v5, 0xee000000 +global_atomic_swap_x2 v30, v[4:5], s[20:21] offset:16 +v_mov_b32 v9, 0 +v_mov_b32 v18, 0x2020 +buffer_atomic_and v9, v18, s[0:3], 0 offen +v_mov_b32 v19, 0x2024 +buffer_atomic_and v9, v19, s[0:3], 0 offen +v_mov_b32 v22, 0x2028 +buffer_atomic_and v9, v22, s[0:3], 0 offen +v_mov_b32 v23, 0x202c +buffer_atomic_and v9, v23, s[0:3], 0 offen +s_waitcnt vmcnt(0) +s_mov_b32 exec_lo, -1 +s_barrier +v_mov_b32 v1, s4 +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32 v2, 0x2000 +s_mov_b32 s20, 0x2000 +s_mov_b32 s21, 0 +v_mov_b32 v30, 0 +v_mov_b32 v18, 0x2020 +v_mov_b32 v19, 0x2024 +v_mov_b32 v22, 0x2028 +v_mov_b32 v23, 0x202c +v_mov_b32 v9, 1 +v_add_nc_u32_e32 v3, 1, v0 +v_or_b32_e32 v10, 0xaa000000, v3 +v_or_b32_e32 v11, 0xbb000000, v3 +buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v10, v11 +v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v18, s[0:3], 0 offen +buffer_atomic_add v9, v22, s[0:3], 0 offen +v_or_b32_e32 v4, 0xcc000000, v3 +v_or_b32_e32 v5, 0xee000000, v3 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v6, v7 +v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v19, s[0:3], 0 offen +buffer_atomic_add v9, v23, s[0:3], 0 offen +v_add_nc_u32_e32 v3, 64, v3 +v_or_b32_e32 v10, 0xaa000000, v3 +v_or_b32_e32 v11, 0xbb000000, v3 +buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v10, v11 +v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v18, s[0:3], 0 offen +buffer_atomic_add v9, v22, s[0:3], 0 offen +v_or_b32_e32 v4, 0xcc000000, v3 +v_or_b32_e32 v5, 0xee000000, v3 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v6, v7 +v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v19, s[0:3], 0 offen +buffer_atomic_add v9, v23, s[0:3], 0 offen +v_add_nc_u32_e32 v3, 64, v3 +v_or_b32_e32 v10, 0xaa000000, v3 +v_or_b32_e32 v11, 0xbb000000, v3 +buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v10, v11 +v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v18, s[0:3], 0 offen +buffer_atomic_add v9, v22, s[0:3], 0 offen +v_or_b32_e32 v4, 0xcc000000, v3 +v_or_b32_e32 v5, 0xee000000, v3 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v6, v7 +v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v19, s[0:3], 0 offen +buffer_atomic_add v9, v23, s[0:3], 0 offen +v_add_nc_u32_e32 v3, 64, v3 +v_or_b32_e32 v10, 0xaa000000, v3 +v_or_b32_e32 v11, 0xbb000000, v3 +buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v10, v11 +v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v18, s[0:3], 0 offen +buffer_atomic_add v9, v22, s[0:3], 0 offen +v_or_b32_e32 v4, 0xcc000000, v3 +v_or_b32_e32 v5, 0xee000000, v3 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v6, v7 +v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 +v_cndmask_b32_e32 v8, 0, v9, vcc_lo +buffer_atomic_add v8, v19, s[0:3], 0 offen +buffer_atomic_add v9, v23, s[0:3], 0 offen +s_waitcnt vmcnt(0) +s_mov_b32 exec_lo, -1 +s_barrier +v_or_b32_e32 v1, s4, v0 +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32 v10, 0 +buffer_atomic_add v10, v18, s[0:3], 0 offen glc +v_mov_b32 v11, 0 +buffer_atomic_add v11, v19, s[0:3], 0 offen glc +v_mov_b32 v12, 0 +buffer_atomic_add v12, v22, s[0:3], 0 offen glc +v_mov_b32 v13, 0 +buffer_atomic_add v13, v23, s[0:3], 0 offen glc +v_mov_b32 v14, 0xdead0001 +v_mov_b32 v15, 0xcafe0002 +buffer_atomic_swap_x2 v[14:15], v2, s[0:3], 0 offen glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v14, v15 +v_cmp_eq_u32_e32 vcc_lo, 0x11000000, v8 +v_cndmask_b32_e32 v14, 0, v9, vcc_lo +v_mov_b32 v16, 0x11223344 +v_mov_b32 v17, 0x55667788 +buffer_atomic_swap_x2 v[16:17], v2, s[0:3], 0 offen glc +v_mov_b32 v4, 0x12345678 +v_mov_b32 v5, 0x9abcdef0 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v8, v6, v7 +v_cmp_eq_u32_e32 vcc_lo, 0x22000000, v8 +v_cndmask_b32_e32 v15, 0, v9, vcc_lo +v_mov_b32 v4, 0 +v_mov_b32 v5, 0 +global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc +s_waitcnt vmcnt(0) +v_mov_b32 v20, 0 +buffer_store_dword v10, v20, s[0:3], 0 offen +v_mov_b32 v20, 4 +buffer_store_dword v11, v20, s[0:3], 0 offen +v_mov_b32 v20, 8 +buffer_store_dword v12, v20, s[0:3], 0 offen +v_mov_b32 v20, 12 +buffer_store_dword v13, v20, s[0:3], 0 offen +v_mov_b32 v20, 16 +buffer_store_dword v14, v20, s[0:3], 0 offen +v_mov_b32 v20, 20 +buffer_store_dword v15, v20, s[0:3], 0 offen +v_mov_b32 v20, 24 +buffer_store_dword v16, v20, s[0:3], 0 offen +v_mov_b32 v20, 28 +buffer_store_dword v7, v20, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 8ba62104d..9d31b7ecf 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -397,6 +397,9 @@ def pc_tail_ubo() -> bool: # block at set 1), for devices whose maxPushConstantsSize is 128. The test programs read the same variable # (runtime/test/vk_pc_tail.h) and bind the block; same accepted values as LEONIDA_W64_EMULATE. return (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on") +def int64_atomics() -> bool: + # LEONIDA_INT64_ATOMICS=1: translate all tests with --int64-atomics (64-bit OpAtomicExchange on *_atomic_swap_x2). + return (os.environ.get("LEONIDA_INT64_ATOMICS") or "").strip().lower() in ("1", "true", "yes", "on") def wavemask_check(vk_compute: str, spv: str, env: dict | None, emulated: bool) -> tuple[bool | None, str]: """cs_wavemask, as in check.py: (passed, detail), passed None for a skip. The native build needs a 64-wide subgroup and skips where the device has none; with LEONIDA_W64_EMULATE=1 it was translated with @@ -946,6 +949,8 @@ def run_suite(a, work: str) -> int: cmd.append("--mesh-compute") if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 cmd.append("--pc-tail-ubo") + if int64_atomics(): # 64-bit OpAtomicExchange on *_atomic_swap_x2 (OpCapability Int64Atomics) + cmd.append("--int64-atomics") if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) cmd += ["--fma", os.environ["LEONIDA_FMA"]] rc, out = run_cmd(cmd, gpu=False) @@ -953,6 +958,32 @@ def run_suite(a, work: str) -> int: print(out) if rc != 0: return 1 + if not int64_atomics() and any(os.path.basename(p) == "cs_atomic_swap_x2_int64.s" for p in disasm_files): + # Always translate the multi-thread tearing fixture with --int64-atomics so CI exercises 64-bit OpAtomicExchange + # without mutating the 32-bit default path tested by cs_global_mem_ext. + with tempfile.TemporaryDirectory(prefix="disasm_i64-", dir=work) as i64_disasm, \ + tempfile.TemporaryDirectory(prefix="spirv_i64-", dir=work) as i64_spirv: + shutil.copyfile(os.path.join(disasm_dir, "cs_atomic_swap_x2_int64.s"), + os.path.join(i64_disasm, "cs_atomic_swap_x2_int64.s")) + i64_cmd = cmd[:4] + [i64_disasm, "--out", i64_spirv] + cmd[7:] + ["--int64-atomics"] + rc64, out64 = run_cmd(i64_cmd, gpu=False) + if rc64 != 0: + print("=== rdna2spirv.py (--int64-atomics) ===", file=sys.stderr) + print(out64, file=sys.stderr) + return 1 + shutil.copyfile(os.path.join(i64_spirv, "cs_atomic_swap_x2_int64.spv"), + os.path.join(spirv_dir, "cs_atomic_swap_x2_int64.spv")) + main_idx_p = os.path.join(spirv_dir, "index.json") + sub_idx_p = os.path.join(i64_spirv, "index.json") + if os.path.isfile(main_idx_p) and os.path.isfile(sub_idx_p): + with open(main_idx_p, encoding="utf-8") as f: + main_idx = json.load(f) + with open(sub_idx_p, encoding="utf-8") as f: + sub_idx = json.load(f) + main_idx["cs_atomic_swap_x2_int64"] = sub_idx["cs_atomic_swap_x2_int64"] + with open(main_idx_p, "w", encoding="utf-8", newline="\n") as f: + json.dump(main_idx, f, indent=2) + f.write("\n") if bary_fallback(): import bary_fallback_gs for gs in bary_fallback_gs.build_for_index(spirv_dir): @@ -1104,14 +1135,16 @@ def run_suite(a, work: str) -> int: # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) results.append((name, not problem, problem or "80/80 dumped words exact")) - elif name in ("cs_global_neg_offset", "cs_global_mem_ext"): + elif name in ("cs_global_neg_offset", "cs_global_mem_ext", "cs_atomic_swap_x2_int64"): # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement. # cs_global_mem_ext.asm: global/buffer atomics, 8/16-bit global stores and d16 loads in the same heap. + # cs_atomic_swap_x2_int64.asm: multi-thread *_atomic_swap_x2 tearing test (--int64-atomics). rc, msg = run_cmd([vk_compute, spv, "40", "dump"], env=cs_env) want = {"cs_global_neg_offset": [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 0x9E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE], - "cs_global_mem_ext": [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234]}[name] + "cs_global_mem_ext": [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234], + "cs_atomic_swap_x2_int64": [0, 0, 256, 256, 1, 1, 0xDEAD0001, 0x9ABCDEF0]}[name] ok, detail = judge_cs_dump(rc, msg, want, wave64=False, partial=False, emulated=False, hexwords=True) results.append((name, ok, detail)) elif name == "cs_heap_init": diff --git a/tests/semantic/fixtures/disasm/cs_atomic_swap_x2_int64.s b/tests/semantic/fixtures/disasm/cs_atomic_swap_x2_int64.s new file mode 100644 index 000000000..fde276fd5 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_atomic_swap_x2_int64.s @@ -0,0 +1,163 @@ +; cs_atomic_swap_x2_int64 test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_atomic_swap_x2_int64.asm + v_or_b32_e32 v1, s4, v0 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32 v2, 0x2000 + v_mov_b32 v10, 0xaa000000 + v_mov_b32 v11, 0xbb000000 + buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen + s_mov_b32 s20, 0x2000 + s_mov_b32 s21, 0 + v_mov_b32 v30, 0 + v_mov_b32 v4, 0xcc000000 + v_mov_b32 v5, 0xee000000 + global_atomic_swap_x2 v30, v[4:5], s[20:21] offset:16 + v_mov_b32 v9, 0 + v_mov_b32 v18, 0x2020 + buffer_atomic_and v9, v18, s[0:3], 0 offen + v_mov_b32 v19, 0x2024 + buffer_atomic_and v9, v19, s[0:3], 0 offen + v_mov_b32 v22, 0x2028 + buffer_atomic_and v9, v22, s[0:3], 0 offen + v_mov_b32 v23, 0x202c + buffer_atomic_and v9, v23, s[0:3], 0 offen + s_waitcnt vmcnt(0) + s_mov_b32 exec_lo, -1 + s_barrier + v_mov_b32 v1, s4 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32 v2, 0x2000 + s_mov_b32 s20, 0x2000 + s_mov_b32 s21, 0 + v_mov_b32 v30, 0 + v_mov_b32 v18, 0x2020 + v_mov_b32 v19, 0x2024 + v_mov_b32 v22, 0x2028 + v_mov_b32 v23, 0x202c + v_mov_b32 v9, 1 + v_add_nc_u32_e32 v3, 1, v0 + v_or_b32_e32 v10, 0xaa000000, v3 + v_or_b32_e32 v11, 0xbb000000, v3 + buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v10, v11 + v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v18, s[0:3], 0 offen + buffer_atomic_add v9, v22, s[0:3], 0 offen + v_or_b32_e32 v4, 0xcc000000, v3 + v_or_b32_e32 v5, 0xee000000, v3 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v6, v7 + v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v19, s[0:3], 0 offen + buffer_atomic_add v9, v23, s[0:3], 0 offen + v_add_nc_u32_e32 v3, 64, v3 + v_or_b32_e32 v10, 0xaa000000, v3 + v_or_b32_e32 v11, 0xbb000000, v3 + buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v10, v11 + v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v18, s[0:3], 0 offen + buffer_atomic_add v9, v22, s[0:3], 0 offen + v_or_b32_e32 v4, 0xcc000000, v3 + v_or_b32_e32 v5, 0xee000000, v3 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v6, v7 + v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v19, s[0:3], 0 offen + buffer_atomic_add v9, v23, s[0:3], 0 offen + v_add_nc_u32_e32 v3, 64, v3 + v_or_b32_e32 v10, 0xaa000000, v3 + v_or_b32_e32 v11, 0xbb000000, v3 + buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v10, v11 + v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v18, s[0:3], 0 offen + buffer_atomic_add v9, v22, s[0:3], 0 offen + v_or_b32_e32 v4, 0xcc000000, v3 + v_or_b32_e32 v5, 0xee000000, v3 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v6, v7 + v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v19, s[0:3], 0 offen + buffer_atomic_add v9, v23, s[0:3], 0 offen + v_add_nc_u32_e32 v3, 64, v3 + v_or_b32_e32 v10, 0xaa000000, v3 + v_or_b32_e32 v11, 0xbb000000, v3 + buffer_atomic_swap_x2 v[10:11], v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v10, v11 + v_cmp_ne_u32_e32 vcc_lo, 0x11000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v18, s[0:3], 0 offen + buffer_atomic_add v9, v22, s[0:3], 0 offen + v_or_b32_e32 v4, 0xcc000000, v3 + v_or_b32_e32 v5, 0xee000000, v3 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v6, v7 + v_cmp_ne_u32_e32 vcc_lo, 0x22000000, v8 + v_cndmask_b32_e32 v8, 0, v9, vcc_lo + buffer_atomic_add v8, v19, s[0:3], 0 offen + buffer_atomic_add v9, v23, s[0:3], 0 offen + s_waitcnt vmcnt(0) + s_mov_b32 exec_lo, -1 + s_barrier + v_or_b32_e32 v1, s4, v0 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32 v10, 0 + buffer_atomic_add v10, v18, s[0:3], 0 offen glc + v_mov_b32 v11, 0 + buffer_atomic_add v11, v19, s[0:3], 0 offen glc + v_mov_b32 v12, 0 + buffer_atomic_add v12, v22, s[0:3], 0 offen glc + v_mov_b32 v13, 0 + buffer_atomic_add v13, v23, s[0:3], 0 offen glc + v_mov_b32 v14, 0xdead0001 + v_mov_b32 v15, 0xcafe0002 + buffer_atomic_swap_x2 v[14:15], v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v14, v15 + v_cmp_eq_u32_e32 vcc_lo, 0x11000000, v8 + v_cndmask_b32_e32 v14, 0, v9, vcc_lo + v_mov_b32 v16, 0x11223344 + v_mov_b32 v17, 0x55667788 + buffer_atomic_swap_x2 v[16:17], v2, s[0:3], 0 offen glc + v_mov_b32 v4, 0x12345678 + v_mov_b32 v5, 0x9abcdef0 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_xor_b32_e32 v8, v6, v7 + v_cmp_eq_u32_e32 vcc_lo, 0x22000000, v8 + v_cndmask_b32_e32 v15, 0, v9, vcc_lo + v_mov_b32 v4, 0 + v_mov_b32 v5, 0 + global_atomic_swap_x2 v[6:7], v30, v[4:5], s[20:21] offset:16 glc + s_waitcnt vmcnt(0) + v_mov_b32 v20, 0 + buffer_store_dword v10, v20, s[0:3], 0 offen + v_mov_b32 v20, 4 + buffer_store_dword v11, v20, s[0:3], 0 offen + v_mov_b32 v20, 8 + buffer_store_dword v12, v20, s[0:3], 0 offen + v_mov_b32 v20, 12 + buffer_store_dword v13, v20, s[0:3], 0 offen + v_mov_b32 v20, 16 + buffer_store_dword v14, v20, s[0:3], 0 offen + v_mov_b32 v20, 20 + buffer_store_dword v15, v20, s[0:3], 0 offen + v_mov_b32 v20, 24 + buffer_store_dword v16, v20, s[0:3], 0 offen + v_mov_b32 v20, 28 + buffer_store_dword v7, v20, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/test_atomic_swap_x2_int64.py b/tests/semantic/test_atomic_swap_x2_int64.py new file mode 100644 index 000000000..979829790 --- /dev/null +++ b/tests/semantic/test_atomic_swap_x2_int64.py @@ -0,0 +1,173 @@ +"""Tests for --int64-atomics (64-bit OpAtomicExchange for *_atomic_swap_x2).""" + +import contextlib +import os +import pathlib +import re +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +if HERE not in sys.path: + sys.path.insert(0, HERE) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "tools")) +sys.path.insert(0, ROOT) +import make_game # noqa: E402 +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +import support # noqa: E402 + +FSSM = bytearray(0x148) +struct.pack_into("<4I", FSSM, 0x138, 0x8088, 64, 1, 1) # 4 user SGPRs, workgroup id in s4, 64x1x1 +FSSM = bytes(FSSM) +VSHARP = [0, 0, 0x2800, 0x31016FAC] +EXPECTED_FIXTURE = [0, 0, 256, 256, 1, 1, 0xDEAD0001, 0x9ABCDEF0] + + +@contextlib.contextmanager +def _int64_atomics_enabled(enabled: bool): + prev = rdna2spirv.INT64_ATOMICS + rdna2spirv.INT64_ATOMICS = enabled + try: + yield + finally: + rdna2spirv.INT64_ATOMICS = prev + + +def _translate_cs(body: list[str], *, int64_atomics: bool): + with tempfile.TemporaryDirectory() as tmp: + os.makedirs(os.path.join(tmp, "fssm")) + os.makedirs(os.path.join(tmp, "disasm")) + with open(os.path.join(tmp, "fssm", "cs_test.fssm"), "wb") as f: + f.write(FSSM) + src = os.path.join(tmp, "disasm", "cs_test.s") + with open(src, "w", encoding="utf-8") as f: + f.write("; cs_test\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") + with _int64_atomics_enabled(int64_atomics), warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(src) + + +class AtomicSwapX2Int64Tests(unittest.TestCase): + def test_buffer_atomic_swap_x2_uses_int64_atomic_when_enabled(self): + body = [ + "s_mov_b32 s4, 0", + "s_mov_b32 s5, 0", + "s_mov_b32 s6, 64", + "s_mov_b32 s7, 0x31016fac", + "v_mov_b32 v0, 0x11223344", + "v_mov_b32 v1, 0x55667788", + "v_mov_b32 v2, 8", + "buffer_atomic_swap_x2 v[0:1], v2, s[4:7], 0 offen glc", + ] + spv_on = _translate_cs(body, int64_atomics=True) + self.assertIn("OpCapability Int64Atomics", spv_on) + self.assertIn("%_ptr_PSB_ulong = OpTypePointer PhysicalStorageBuffer %ulong", spv_on) + self.assertIn("= OpAtomicExchange %ulong", spv_on) + + spv_off = _translate_cs(body, int64_atomics=False) + self.assertNotIn("Int64Atomics", spv_off) + self.assertNotIn("OpAtomicExchange %ulong", spv_off) + + def test_global_atomic_swap_x2_uses_int64_atomic_when_enabled(self): + body = [ + "v_mov_b32 v0, 0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0xdeadbeef", + "v_mov_b32 v3, 0xcafebabe", + "global_atomic_swap_x2 v[4:5], v[0:1], v[2:3], off glc", + ] + spv_on = _translate_cs(body, int64_atomics=True) + self.assertIn("OpCapability Int64Atomics", spv_on) + self.assertIn("= OpAtomicExchange %ulong", spv_on) + + def test_bitwise_x2_keeps_32bit_form_even_when_int64_atomics_enabled(self): + body = [ + "s_mov_b32 s4, 0", + "s_mov_b32 s5, 0", + "s_mov_b32 s6, 64", + "s_mov_b32 s7, 0x31016fac", + "v_mov_b32 v0, 0xff", + "v_mov_b32 v1, 0xff", + "v_mov_b32 v2, 0", + "buffer_atomic_and_x2 v[0:1], v2, s[4:7], 0 offen glc", + ] + spv_on = _translate_cs(body, int64_atomics=True) + self.assertNotIn("Int64Atomics", spv_on) + self.assertNotIn("OpAtomicExchange %ulong", spv_on) + + def test_cli_flag_end_to_end(self): + with tempfile.TemporaryDirectory() as tmp: + in_dir = os.path.join(tmp, "in") + os.makedirs(os.path.join(in_dir, "fssm")) + os.makedirs(os.path.join(in_dir, "disasm")) + out_dir = os.path.join(tmp, "out") + with open(os.path.join(in_dir, "fssm", "cs_cli.fssm"), "wb") as f: + f.write(FSSM) + with open(os.path.join(in_dir, "disasm", "cs_cli.s"), "w", encoding="utf-8") as f: + f.write("; cs_cli\n\t" + "\n\t".join([ + "s_mov_b32 s4, 0", + "s_mov_b32 s5, 0", + "s_mov_b32 s6, 64", + "s_mov_b32 s7, 0x31016fac", + "v_mov_b32 v0, 1", + "v_mov_b32 v1, 2", + "v_mov_b32 v2, 8", + "buffer_atomic_swap_x2 v[0:1], v2, s[4:7], 0 offen glc", + "s_endpgm", + ]) + "\n") + translator = pathlib.Path(__file__).resolve().parents[2] / "tools" / "rdna2spirv.py" + res = subprocess.run( + [sys.executable, "-I", str(translator), os.path.join(in_dir, "disasm"), + "--out", out_dir, "--int64-atomics"], + capture_output=True, text=True, check=False, + ) + if res.returncode != 0: + self.assertTrue( + "FileNotFoundError" in res.stderr or "not found" in res.stderr, + res.stderr, + ) + spv_path = next(pathlib.Path(out_dir).rglob("*.spvasm")) + spv_text = spv_path.read_text(encoding="utf-8") + self.assertIn("OpCapability Int64Atomics", spv_text) + self.assertIn("= OpAtomicExchange %ulong", spv_text) + + def test_gpu_fixture_matches_runners_and_translates_both_modes(self): + with _int64_atomics_enabled(False): + spv_default = support.translate_fixture("cs_atomic_swap_x2_int64", fssm=FSSM) + mem = {} + si.run_workgroup(spv_default, 64, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), + "%sg_lane": i}, + push_constants=VSHARP + [0] * 32, memory=mem) + for k, want in enumerate(EXPECTED_FIXTURE): + with self.subTest(word=k): + self.assertEqual(mem.get(4 * k), want) + + with _int64_atomics_enabled(True): + spv_int64 = support.translate_fixture("cs_atomic_swap_x2_int64", fssm=FSSM) + self.assertIn("OpCapability Int64Atomics", spv_int64) + self.assertEqual(spv_int64.count("= OpAtomicExchange %ulong"), 14) + + for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): + with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: + text = f.read() + m = re.search(r'"cs_atomic_swap_x2_int64"[,:]\s*(?:"40",\s*)?\[([^\]]*)\]', text, re.S) + with self.subTest(file="/".join(rel)): + self.assertIsNotNone(m) + self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED_FIXTURE) + if rel[0] == "scripts": + self.assertIn('"--int64-atomics"', text) + + def test_make_game_forwards_int64_atomics_flag(self): + self.assertIn(("--int64-atomics", "int64_atomics"), make_game.FALLBACK_FLAGS) + ns = make_game.argparse.Namespace(int64_atomics=True) + self.assertIn("--int64-atomics", make_game.fallback_flags(ns)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 936de535a..2b8f51fc0 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -105,6 +105,7 @@ # the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS # can use there. F16_HALVES = False +INT64_ATOMICS = False F16_HALF_TOP = 29 OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) @@ -341,6 +342,8 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): # The --fma option this module is translated under, for the index: a caller that changes the option before # shader_meta (translation and indexing in separate steps) must not relabel it. self.fma_mode = "exact" if FMA_EXACT else "khr" if FMA_KHR else "glsl" + self.uses_int64_atomics = False # a 64-bit OpAtomicExchange was emitted: capability Int64Atomics + self.int64_atomics = INT64_ATOMICS # --int64-atomics: use 64-bit OpAtomicExchange for *_atomic_swap_x2 self.uses_clock = set() self.uses_bvh = False self.lconsts = {} # 64-bit constants: value -> id @@ -3048,8 +3051,25 @@ def global_atomic_float(self, op, kind, a, mods): if vdst is not None: self.dst(vdst, old) + def _emit_atomic_swap_x2(self, host_addr, vals): + """Emit a single 64-bit OpAtomicExchange on a PhysicalStorageBuffer pointer and return [lo, hi].""" + self.uses_int64_atomics = True + p64, lo64, hi64, hi_sh, val64, r64 = (self.tmp() for _ in range(6)) + r_lo, r_hi64, r_hi = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{p64} = OpConvertUToPtr %_ptr_PSB_ulong {host_addr}") + self.emit(f"{lo64} = OpUConvert %ulong {vals[0]}") + self.emit(f"{hi64} = OpUConvert %ulong {vals[1]}") + self.emit(f"{hi_sh} = OpShiftLeftLogical %ulong {hi64} %c64_32") + self.emit(f"{val64} = OpBitwiseOr %ulong {lo64} {hi_sh}") + self.emit(f"{r64} = OpAtomicExchange %ulong {p64} {self.cu(1)} {self.cu(0)} {val64}") + self.emit(f"{r_lo} = OpUConvert %uint {r64}") + self.emit(f"{r_hi64} = OpShiftRightLogical %ulong {r64} %c64_32") + self.emit(f"{r_hi} = OpUConvert %uint {r_hi64}") + return [r_lo, r_hi] + 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.""" + """global_atomic_{and,or,xor,swap}_x2 (see global_atomic): one 32-bit atomic per dword by default, or + 64-bit OpAtomicExchange on %ulong (OpCapability Int64Atomics) for swap_x2 when --int64-atomics is enabled.""" if any(m in mods for m in ("slc", "dlc", "lds")): raise Unsupported(op + " form") rtn = "glc" in mods @@ -3070,14 +3090,17 @@ 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) + if self.int64_atomics and kind == "swap": + res = self._emit_atomic_swap_x2(self.host_addr(full), vals) + else: + 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.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] @@ -3191,13 +3214,12 @@ def buffer_atomic_float(self, op, kind, a, mods): 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).""" + (two dwords, low first); with glc the old 64 bits are returned in vdata. By default each dword uses its own + 32-bit atomic (safe for bitwise ops, while concurrent swaps can tear across dwords); with --int64-atomics, + swap_x2 emits 64-bit OpAtomicExchange on %ulong (OpCapability Int64Atomics, requires shaderBufferInt64Atomics) + so swaps cannot tear. 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).""" vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 2: raise Unsupported(op + " data") @@ -3212,14 +3234,17 @@ 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) + if self.int64_atomics and kind == "swap": + res = self._emit_atomic_swap_x2(self.host_addr(addr), vals) + else: + 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.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] @@ -15795,6 +15820,8 @@ def assemble(gen): caps.append("Float64") if gen.uses_fma_khr: caps.append("FMAKHR") + if gen.uses_int64_atomics: + caps.append("Int64Atomics") if gen.uses_clock: caps.append("ShaderClockKHR") if gen.uses_dynamic_sampled_index: @@ -15959,6 +15986,8 @@ def assemble(gen): types += ["%ulong = OpTypeInt 64 0", "%c64_32 = OpConstant %ulong 32", "%long = OpTypeInt 64 1", "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] + if gen.uses_int64_atomics: + types.append("%_ptr_PSB_ulong = OpTypePointer PhysicalStorageBuffer %ulong") dec.append("OpDecorate %rt_uint ArrayStride 4") types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(gen.lconsts.items())] if tex: @@ -19025,6 +19054,7 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): "ClipDistance": "shaderClipDistance", "CullDistance": "shaderCullDistance", "ShaderLayer": "shaderOutputLayer", "ShaderViewportIndex": "shaderOutputViewportIndex", "DrawParameters": "shaderDrawParameters", + "Int64Atomics": "shaderBufferInt64Atomics", } # FMAKHR: shaderFmaFloat32 / shaderFmaFloat64 (VK_KHR_shader_fma) by the width used, below m = {"stage": g.stage, "wave64": bool(g.wave64), "control_flow": getattr(g, "control_flow", "straight line"), # How fused multiply-adds were emitted. --fma khr is already implied by the FMAKHR capability, @@ -19494,6 +19524,9 @@ def main(): help="16-bit interpolation without PerVertexKHR inputs, for devices that can't compile them " "(MoltenVK): VS and mesh params also export their f16 halves decoded to f32, which the PS " "reads as ordinary interpolated inputs (metadata: f16_halves)") + ap.add_argument("--int64-atomics", action="store_true", + help="use 64-bit OpAtomicExchange for global_atomic_swap_x2 / buffer_atomic_swap_x2 " + "(needs shaderBufferInt64Atomics, capability Int64Atomics; prevents 32-bit tearing)") ap.add_argument("--max-shared-memory", type=int, default=MAX_SHARED_BYTES, metavar="BYTES", help="cap on a compute shader's workgroup memory, its LDS plus what --wave64-emulate adds " "(default %(default)s, the 64 KiB hard cap): over it the LDS array shrinks to the program's " @@ -19536,7 +19569,7 @@ def main(): DESCRIPTOR_HASH = a.descriptor_hash LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth - global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV + global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, INT64_ATOMICS, OPT_SPIRV global PC_TAIL_UBO PC_TAIL_UBO = a.pc_tail_ubo global FMA_EXACT @@ -19552,6 +19585,7 @@ def main(): TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback MESH_COMPUTE = a.mesh_compute F16_HALVES = a.f16_interp_fallback + INT64_ATOMICS = a.int64_atomics OPT_SPIRV = a.opt if a.merge: try: