diff --git a/docs/design.md b/docs/design.md index eecb1cb844..1b9e513adf 100644 --- a/docs/design.md +++ b/docs/design.md @@ -414,7 +414,7 @@ How the generated SPIR-V expects the runtime to work: | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | | First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | -| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). In addition, `wave64_emulate_opt.py` excludes lane-mask `s_flbit_i32_b32`/`s_flbit_i32` and mixed mask+data `s_cmp_eq_u64`/`s_cmp_lg_u64` from folded/sync-free blocks and `Gen.x_memory_order` skips `ds_nop` (matching `_x_memory_order_access`), pinned by `tests/semantic/test_wave64_emulate_barriers.py` (CPU workgroup interpreter only, not GPU-checked). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | +| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler from the first early `s_endpgm`, or the first `s_barrier` under a guard or in a loop, to the end: waves on different paths may meet at different `s_barrier` sites, which only the rounds model; the NGG mesh epilogue, `s_cbranch_vccnz` over an `s_barrier`, is the common case). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` in the tail rounds, guarded `s_barrier` epilogue, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). In addition, `wave64_emulate_opt.py` excludes lane-mask `s_flbit_i32_b32`/`s_flbit_i32` and mixed mask+data `s_cmp_eq_u64`/`s_cmp_lg_u64` from folded/sync-free blocks and `Gen.x_memory_order` skips `ds_nop` (matching `_x_memory_order_access`), pinned by `tests/semantic/test_wave64_emulate_barriers.py` (CPU workgroup interpreter only, not GPU-checked). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py index c83dd5f534..2208ddd32d 100644 --- a/tests/semantic/test_loop_ballot_barrier.py +++ b/tests/semantic/test_loop_ballot_barrier.py @@ -1392,7 +1392,7 @@ def test_uniform_loop_barrier_wave64_emulate(self): """ prog = self._ring_shift_loop_cs(wave64=True, threads=128, iters=5) spv, gen = _translate_cs("cs_bar_loop_w64_emulate", prog, threads=128, lds_bytes=512, emulate=True) - self.assertEqual(gen.control_flow, "emulated wave64 rounds") + self.assertEqual(gen.control_flow, "emulated wave64 structured") # the loop is in the tail scheduler for rev in (False, True): with self.subTest(reverse_subgroups=rev): mem = run_compute_workgroup(spv, 128, 32, push_constants=VSHARP, reverse_subgroups=rev) @@ -1465,7 +1465,7 @@ def test_wave_divergent_barrier_loop_bar_rounds_and_emulate(self): spv_em, gen_em = _translate_cs( "cs_div_bar_em", self._wave_divergent_barrier_loop_cs(True), threads=128, lds_bytes=512, emulate=True ) - self.assertEqual(gen_em.control_flow, "emulated wave64 rounds") + self.assertEqual(gen_em.control_flow, "emulated wave64 structured") # the loop is in the tail scheduler mem_em = run_compute_workgroup(spv_em, 128, 32, push_constants=VSHARP) self.assertEqual([mem_em[4 * t] for t in range(128)], [2] * 64 + [4] * 64) diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 58b7c2c7e4..d3f551959d 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -1430,8 +1430,8 @@ def isa_v4_before_sbar(l): want = isa_v4_before_sbar(l) + isa_v4_before_sbar(l ^ 64) self.assertEqual(mem_new[1024 + l * 4], want, f"lane {l} rev={rev}") - def test_multiwave_divergent_sbarrier_falls_back_to_rounds(self): - # Wave 0 hits s_barrier in one arm while Wave 1 hits s_barrier in another -> MUST keep global rounds. + def test_multiwave_divergent_sbarrier_stays_in_tail_rounds(self): + # Wave 0 hits s_barrier in one arm while Wave 1 hits s_barrier in another -> both arms MUST keep the rounds. insns = [ ("s_mov_b64 exec, -1", 4), ("v_lshlrev_b32_e32 v2, 2, v0", 4), @@ -1449,11 +1449,49 @@ def test_multiwave_divergent_sbarrier_falls_back_to_rounds(self): ("s_endpgm", 4), ] spv, gen = _translate_encoded("cs_div_sbar_w64", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 rounds") - self.assertIsNone(gen.emulate_plan) - mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], lane + 64, f"lane {lane}") + self.assertEqual(gen.control_flow, "emulated wave64 structured") + plan = gen.emulate_plan + self.assertEqual(plan["inline_blocks"], {0}) + self.assertEqual(plan["tail_blocks"], {1, 2}) # both s_barrier arms + for rev in (False, True): + mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) + for lane in range(64): + self.assertEqual(mem[lane * 4], lane + 64, f"lane {lane}, reverse={rev}") + + def test_multiwave_guarded_sbarrier_epilogue_keeps_body_structured(self): + # The shape of an NGG mesh epilogue: a body with a wave vote, then a guarded s_barrier both waves skip or + # reach (s_cbranch_vccnz), then a top-level s_barrier. Only the part from the guard on stays in rounds. + def insns(vcc): + return [ + ("s_mov_b64 exec, -1", 4), + ("v_lshlrev_b32_e32 v2, 2, v0", 4), + ("v_add_nc_u32_e32 v5, 7, v0", 4), + ("v_readfirstlane_b32 s5, v0", 4), + ("v_add_nc_u32_e32 v5, s5, v5", 4), + ("ds_write_b32 v2, v5", 8), + (f"s_mov_b64 vcc, {vcc}", 4), + ("s_cbranch_vccnz 1", 4), + ("s_barrier", 4), + ("s_barrier", 4), + ("v_xor_b32_e32 v3, 64, v0", 4), + ("v_lshlrev_b32_e32 v3, 2, v3", 4), + ("ds_read_b32 v4, v3", 8), + ("buffer_store_dword v4, v2, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ] + for vcc in ("0", "-1"): + spv, gen = _translate_encoded("cs_sbar_epilogue_w64", insns(vcc), (128, 1, 1), emulate=True, + rsrc2=0x20088) + self.assertEqual(gen.control_flow, "emulated wave64 structured") + plan = gen.emulate_plan + self.assertEqual(plan["inline_blocks"], {0}) + self.assertEqual(plan["tail_blocks"], {1, 2}) + for rev in (False, True): + mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, + reverse_order=rev) + for lane in range(128): + other = lane ^ 64 + self.assertEqual(mem[lane * 4], other + 7 + (other & 64), f"lane {lane}, vcc={vcc}, rev={rev}") def test_monotone_dirty_transfer_no_phantom_clear_after_x_round(self): # Regression: an x_round (v_readlane_b32) clears g.x_dirty in codegen before a subsequent diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 1ff464fd15..f8a50e0eb8 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -1741,13 +1741,6 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb if any(sb_has_endpgm[u] for u in it_blocks): saw_endpgm = True - # Multi-wave soundness guard: any `s_barrier` inside a non-top-level guard/loop must stay in global x_scheduler - # so waves on different paths can meet at different s_barrier sites (cs_barrier_divergent). - for it in flat_top: - if it[0] != "block": - if any(sb_has_sbarrier[u] for u in _blocks_in_tree(it)): - return None - def check_sync_free(it): sub_blocks = _blocks_in_tree(it) has_loop = _tree_has_loop([it]) @@ -1793,7 +1786,10 @@ def check_sync_free(it): cur_dirty = sb_gen_dirty[b] if sb_clears_dirty[b] else (cur_dirty | sb_gen_dirty[b]) steps.append(("inline_block", b)) continue - if has_end: + # An `s_barrier` under a guard or in a loop: waves on different paths meet at different sites + # (cs_barrier_divergent), which only the round scheduler models. Every wave enters the tail in the same + # round, and what ran before it has no `s_barrier` that is not reached by the whole workgroup. + if has_end or (it[0] != "block" and any(sb_has_sbarrier[u] for u in it_blocks)): # Early s_endpgm inside a wave-divergent guard/loop (or non-final block): hand remaining tail to x_scheduler. rem = set() for rem_it in flat_top[idx_it:]: