From c4b709a14f641822de134e1d153bd180db50ce4c Mon Sep 17 00:00:00 2001 From: robot00f Date: Wed, 25 Nov 2026 18:10:16 -0300 Subject: [PATCH] shaders: coalesce and inline wave64 x_round exchanges (SHADER-W64-XROUND-BARRIERS) Coalesce redundant wave-wide Workgroup exchanges and remove helper-call / modulo overhead in `Gen.x_round` (`emulate_inline` in `tools/rdna2spirv.py`) for `--wave64-emulate` on 32-wide GPUs: 1. Inline division-free `Gen._x_round_inline`: emit inline `x_round` setup directly in `%main` without `%x_pre_*_fn` `OpFunctionCall`s, cycle `%x_it` through `0..5` (`lcm(2, 3) = 6`) with zero `OpUMod`s and omit dead scheduler-word reset `OpAtomicStore`s whenever `mini_blocks`/`tail_blocks` are empty, and narrow barrier semantics from `0x948` to `0x108` (`WorkgroupMemory`) whenever `"mem"` is clean in `x_dirty`. 2. Block-local `Any`-vote and first-lane caching (`x_vcache`, `x_flcache`, `x_vkeys`), preserved across `OpSelectionMerge` regions (`buffer_load`, `buffer_store`, `ds_*`) that do not write `%active`, `%vcc`, or `%sgpr`: share `Any` votes and first-active-lane indices across `scc_from_mask`, `branch_condition`, `wave_mask`, `v_readfirstlane_b32`, and DPP `fi:0` (deriving `Any` from `(lo | hi) != 0` with zero extra atomics, and issuing a bare `x_order_barrier` if memory became dirty before a cached voted branch). 3. Deferred SCC vote coalescing (`_pending_scc_vote` in `emulate_inline`): coalesce live-SCC mask votes into the next 1-bit vote (`s_cbranch_execz`/`vccz`), `data`-only `x_round` (`v_readlane_b32`, `ds_bpermute_b32`, `ds_swizzle_b32`), or `x_order_barrier` (`2 -> 1` barrier), or drop the deferred vote if `%scc` is overwritten unread. 4. Contiguous `v_readfirstlane_b32` batching (`Gen._emit_rfl_run`): once `first` is known, transfer up to 64 remaining values per wave from `wave_lane == first` across one `OpControlBarrier` (`8 -> 2` round barriers uncached, `8 -> 1` when `EXEC` is already cached). Add `tests/semantic/test_wave64_xround_barriers.py` and synthetic GPU shader `runtime/test/shaders/cs_w64x_xround_coalesce.asm`, and document the rules and GTX 1050 Ti measurements in `docs/design.md`. AI-assisted: yes (Antigravity, Gemini 4 Carbon) --- docs/design.md | 2 +- runtime/test/shaders/check.py | 4 +- .../test/shaders/cs_w64x_xround_coalesce.asm | 117 ++++ scripts/run_gpu_tests.py | 3 +- tests/semantic/test_wave64_emulate_opt.py | 11 +- tests/semantic/test_wave64_xround_barriers.py | 462 +++++++++++++ tools/rdna2spirv.py | 608 +++++++++++++----- 7 files changed, 1029 insertions(+), 178 deletions(-) create mode 100644 runtime/test/shaders/cs_w64x_xround_coalesce.asm create mode 100644 tests/semantic/test_wave64_xround_barriers.py diff --git a/docs/design.md b/docs/design.md index cc0126679b..31fc6ddd17 100644 --- a/docs/design.md +++ b/docs/design.md @@ -431,7 +431,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) 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). | +| 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). Inline structured exchanges (`Gen._x_round_inline`, SHADER-W64-XROUND-BARRIERS) further coalesce wave-wide rounds and remove NVVM inliner/division overhead: (a) inline `x_round` drops the outlined `%x_pre_*_fn` `OpFunctionCall`s, cycles `%x_it` through `0..5` (`lcm(2, 3) = 6`) with zero `OpUMod`s and omits dead scheduler-word reset atomics whenever `mini_blocks`/`tail_blocks` are empty, and narrows barrier semantics from `0x948` to `0x108` (`WorkgroupMemory`) whenever `"mem"` is clean in `x_dirty`; (b) block-local `x_vcache` and `x_flcache` (preserved across `OpSelectionMerge` regions such as `buffer_load`/`buffer_store`/`ds_*` that do not write `%active`/`%vcc`/`%sgpr`) share `Any` votes and first-active-lane indices across `scc_from_mask`, `branch_condition`, `wave_mask`, `v_readfirstlane_b32`, and DPP `fi:0` (deriving `Any` from `(lo \| hi) != 0` with zero extra atomics and issuing a bare `x_order_barrier` if memory became dirty before a cached branch); (c) deferred `_pending_scc_vote` coalesces live-SCC mask votes into the next 1-bit vote (`s_cbranch_execz`/`vccz`), `data`-only `x_round` (`v_readlane_b32`, `ds_bpermute_b32`, `ds_swizzle_b32`), or `x_order_barrier` (`2 -> 1` barrier); and (d) `Gen._emit_rfl_run` batches contiguous `v_readfirstlane_b32` runs so up to 64 remaining values per wave cross one single-writer `OpControlBarrier` (`8 -> 2` round barriers uncached, `8 -> 1` when `EXEC` is already cached). Pinned by `tests/semantic/test_wave64_xround_barriers.py` (40/64/128-thread forward/reverse CPU workgroup interpreter + `spirv-val`) and `runtime/test/shaders/cs_w64x_xround_coalesce.asm` (GPU-verified 3/3 on NVIDIA GeForce GTX 1050 Ti, driver 582.28, Vulkan 1.4.312, Windows 10 Pro 10.0.19045, alongside 24/24 `cs_w64x_*` / `cs_wavemask` / `cs_wave64_ballot` passes under `LEONIDA_W64_EMULATE=1`; cold `vkCreateComputePipelines` median of 3 runs via `vk_pipeline_check --jobs 1` with `__GL_SHADER_DISK_CACHE=0` drops `6.062 s -> 1.907 s` (`-68.5%`, barriers `641 -> 321`) at 80 probe/waterfall blocks, `17.433 s -> 5.296 s` (`-69.6%`, barriers `1,281 -> 641`) at 160 blocks, and `4.168 s -> 3.649 s` (`-12.5%`) / `12.224 s -> 11.479 s` (`-6.1%`) on pure 192-VGPR unfolded binary `if/else` trees at 156 / 324 barriers, where controlled barrier-stripping ablations show the remaining ~11 s baseline comes from `%pc`-guarded `OpSelectionMerge` Phi splitting rather than `OpControlBarrier`). (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/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 5abe2ab0a0..7267a6c7f7 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -784,7 +784,9 @@ def salu_ext_test(tools, spirv, env=None): # s_and/s_or_saveexec_b64 (VCC and SGPR-pair sources), s_andn2_saveexec/wrexec_b64 (SGPR pair): D, EXEC, SCC ("cs_w64x_saveexec_b64", [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171]), # SHADER-W64-SDST-PAIR: v_cmp_* / carry-out SGPR destinations printed as one register (no mattr line) - ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5])] + ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5]), + # SHADER-W64-XROUND-BARRIERS: Any-vote reuse, deferred SCC coalescing, batched v_readfirstlane_b32 + ("cs_w64x_xround_coalesce", [147, 308, 1832, 444, 625, 1335, 2379, 332])] # A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0]), diff --git a/runtime/test/shaders/cs_w64x_xround_coalesce.asm b/runtime/test/shaders/cs_w64x_xround_coalesce.asm new file mode 100644 index 0000000000..50ebb4f168 --- /dev/null +++ b/runtime/test/shaders/cs_w64x_xround_coalesce.asm @@ -0,0 +1,117 @@ +; Coalesced and cached wave-wide exchanges in --wave64-emulate (Gen.x_round): +; v1 = lane 0..63; v4 = 100 + lane, v5 = 200 + 3*lane, v6 = 500 + 5*lane, v7 = 900 + 7*lane. +; s[10:11] = lanes 36..51 (upper half only, lowest 36); s[14:15] = lanes 8..23 (low half only, lowest 8). +; 1) Live-SCC s_and_saveexec_b64 s[20:21], s[10:11] -> s_cbranch_execz (reuses cached Any vote) -> s_cselect_b32 s30, +; 11, 22 (SCC = 1 -> 11) + 4x contiguous v_readfirstlane_b32 from lane 36 (batched across one data round after +; finding first = 36): +; out[0] = s24 + s30 = 136 + 11 = 147, out[1] = s25 = 308, out[2] = s26 + s27 = 680 + 1152 = 1832. +; 2) Deferred SCC vote coalesced with s_cbranch_execz on distinct masks (opposite polarities): +; 2a) EXEC = s[10:11] (non-zero), s_and_b64 s[18:19], s[10:11], s[14:15] (0 -> SCC = 0), s_cbranch_execz not taken, +; s_cselect_b32 s31, 333, 444 -> out[3] = 444. +; 2b) EXEC = s[18:19] (0), s_or_b64 s[22:23], s[10:11], s[14:15] (non-zero -> SCC = 1), s_cbranch_execz taken over +; s32 = 666 (keeps 555), s_cselect_b32 s33, 70, 80 -> out[4] = 555 + 70 = 625. +; 3) Deferred SCC vote coalesced with cross-half v_readlane_b32 (lane 45 -> v5 = 335, SCC = 1 -> +1000): +; out[5] = 1335. +; 4) Cached EXEC mask from s_bcnt1_i32_b64 (lanes 41..63 -> 23, first = 41) reused by a 1-round 4x v_readfirstlane_b32 +; batch (141 + 323 + 705 + 1187), then EXEC rewritten to s[14:15] (first = 8 -> 108 + 224) to check invalidation: +; out[6] = 2379, out[7] = 332. +; Run: vk_compute_test cs_w64x_xround_coalesce.spv 1 dump --require-wave64 +; -> out[0..7] = 147 308 1832 444 625 1335 2379 332 +; mattr: +wavefrontsize64,-wavefrontsize32 +v_mbcnt_lo_u32_b32 v1, -1, 0 +v_mbcnt_hi_u32_b32 v1, -1, v1 +v_add_nc_u32_e32 v4, 100, v1 +v_mul_lo_u32 v5, 3, v1 +v_add_nc_u32_e32 v5, 200, v5 +v_mul_lo_u32 v6, 5, v1 +v_add_nc_u32_e32 v6, 500, v6 +v_mul_lo_u32 v7, 7, v1 +v_add_nc_u32_e32 v7, 900, v7 +v_cmp_ge_u32_e64 s[10:11], v1, 36 +v_cmp_lt_u32_e64 s[12:13], v1, 52 +s_and_b64 s[10:11], s[10:11], s[12:13] +v_cmp_ge_u32_e64 s[14:15], v1, 8 +v_cmp_lt_u32_e64 s[16:17], v1, 24 +s_and_b64 s[14:15], s[14:15], s[16:17] +; 1) Live-SCC saveexec + s_cbranch_execz + 4x batched v_readfirstlane_b32 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0 +s_mov_b32 s27, 0 +s_mov_b32 s30, 0 +s_and_saveexec_b64 s[20:21], s[10:11] +s_cbranch_execz 5 +s_cselect_b32 s30, 11, 22 +v_readfirstlane_b32 s24, v4 +v_readfirstlane_b32 s25, v5 +v_readfirstlane_b32 s26, v6 +v_readfirstlane_b32 s27, v7 +s_mov_b64 exec, -1 +s_add_i32 s24, s24, s30 +s_add_i32 s26, s26, s27 +; 2a) Deferred SCC = 0 coalesced with s_cbranch_execz (EXEC != 0) +s_mov_b64 exec, s[10:11] +s_mov_b32 s31, 99 +s_mov_b32 s43, 444 +s_and_b64 s[18:19], s[10:11], s[14:15] +s_cbranch_execz 2 +s_cselect_b32 s31, 333, s43 +; 2b) Deferred SCC = 1 coalesced with s_cbranch_execz (EXEC == 0) +s_mov_b64 exec, s[18:19] +s_mov_b32 s32, 555 +s_mov_b32 s43, 80 +s_or_b64 s[22:23], s[10:11], s[14:15] +s_cbranch_execz 2 +s_mov_b32 s32, 666 +s_cselect_b32 s33, 70, s43 +s_mov_b64 exec, -1 +s_add_i32 s32, s32, s33 +; 3) Deferred SCC = 1 coalesced with cross-half v_readlane_b32 (lane 45) +s_mov_b32 s43, 2000 +s_and_b64 s[22:23], s[10:11], s[10:11] +v_readlane_b32 s34, v5, 45 +s_cselect_b32 s35, 1000, s43 +s_add_i32 s34, s34, s35 +; 4) s_bcnt1 -> 1-round 4x v_readfirstlane_b32 batch, then EXEC rewrite invalidates first-lane cache +v_cmp_ge_u32_e64 s[28:29], v1, 41 +s_mov_b64 exec, s[28:29] +s_bcnt1_i32_b64 s36, exec +v_readfirstlane_b32 s37, v4 +v_readfirstlane_b32 s38, v5 +v_readfirstlane_b32 s39, v6 +v_readfirstlane_b32 s40, v7 +s_mov_b64 exec, s[14:15] +v_readfirstlane_b32 s41, v4 +v_readfirstlane_b32 s42, v5 +s_mov_b64 exec, -1 +s_add_i32 s36, s36, s37 +s_add_i32 s36, s36, s38 +s_add_i32 s36, s36, s39 +s_add_i32 s36, s36, s40 +s_add_i32 s41, s41, s42 +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32_e32 v20, s24 +v_mov_b32_e32 v21, 0 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s25 +v_mov_b32_e32 v21, 4 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s26 +v_mov_b32_e32 v21, 8 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s31 +v_mov_b32_e32 v21, 12 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s32 +v_mov_b32_e32 v21, 16 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s34 +v_mov_b32_e32 v21, 20 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s36 +v_mov_b32_e32 v21, 24 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, s41 +v_mov_b32_e32 v21, 28 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 81777000b5..8ae725c7d1 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1216,7 +1216,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", -"cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", + "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_w64x_xround_coalesce", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], @@ -1301,6 +1301,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_branch": [0, 0, 0, 0, 5, 5, 9, 9], "cs_w64x_mask_reuse": [8, 40, 8, 40, 2, 20, 10, 64], "cs_w64x_mask_reuse2": [10, 20, 8, 8, 5, 2, 132, 131], + "cs_w64x_xround_coalesce": [147, 308, 1832, 444, 625, 1335, 2379, 332], "cs_w64x_chain_barrier": [564, 563, 500, 627], "cs_w64x_ballot": [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109], "cs_w64x_wg128_branches": [121, 121, 343, 343, 14, 31, 19812, 22728], diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 995504234f..d404ec3535 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -1582,12 +1582,11 @@ def test_known_pc_guard_unwrap_and_x_pre_helper_functions(self): top_kinds = [(it[0], it[1]) for it in gen.emulate_plan["tree"]] # Blocks 0, 2, 4 are all direct top-level ("block", b) items; only blocks 1 and 3 are guarded! self.assertEqual(top_kinds, [("block", 0), ("guard", 1), ("block", 2), ("guard", 3), ("block", 4)]) - self.assertIn("%x_pre_vote_fn = OpFunction", spv) - self.assertIn("%x_pre_both_fn = OpFunction", spv) - self.assertIn("%x_pre_data_fn = OpFunction", spv) - self.assertGreaterEqual(spv.count("OpFunctionCall %uint %x_pre_vote_fn"), 2) - self.assertEqual(spv.count("OpFunctionCall %uint %x_pre_both_fn"), 1) - self.assertEqual(spv.count("OpFunctionCall %uint %x_pre_data_fn"), 1) + # Inline x_round emits direct division-free mod-6 exchanges with 0x108 WorkgroupMemory barriers (no %x_pre_*_fn calls). + self.assertNotIn("%x_pre_", spv) + self.assertEqual(spv.count("OpFunctionCall"), 0) + self.assertEqual(spv.count("OpUMod"), 0) + self.assertGreaterEqual(spv.count("OpControlBarrier %c2 %c2 %c108"), 4) # Verify binary SPIR-V assembly with tools/spirv_asm.py import spirv_asm binary = spirv_asm.assemble(spv, target_env="vulkan1.2") diff --git a/tests/semantic/test_wave64_xround_barriers.py b/tests/semantic/test_wave64_xround_barriers.py new file mode 100644 index 0000000000..17e9f68315 --- /dev/null +++ b/tests/semantic/test_wave64_xround_barriers.py @@ -0,0 +1,462 @@ +"""Unit and 40/64/128-lane workgroup execution tests for coalesced and inline `Gen.x_round` exchanges +under `--wave64-emulate` (SHADER-W64-XROUND-BARRIERS). + +Covers: + 1. Division-free inline `Gen._x_round_inline`: zero `%x_pre_*_fn` `OpFunctionCall`s, zero `OpUMod`s in + scheduler-free modules (`%x_it` cycles `0..5`), `OpUMod` retained when `mini_blocks`/`tail_blocks` exist, + `0x108` (`WorkgroupMemory`) barrier semantics when `"mem"` is clean vs `0x948` when `"mem"` is dirty, and + omitted dead scheduler-word atomics in scheduler-free multi-wave workgroups. + 2. Block-local `Any`-vote and first-lane caching (`x_vcache`, `x_mcache`, `x_flcache`), preserved across + mask-preserving `OpSelectionMerge` regions (`buffer_load`/`buffer_store`/`ds_*`): + - live-SCC `s_and_saveexec_b64` / `s_and_b64` + `s_cbranch_execz`/`vccz` share one `Any` vote (`1` round + barrier, `1` `OpAtomicOr`), emitting a bare `x_order_barrier` if memory became dirty in between; + - `s_bcnt1_i32_b64` / `v_readfirstlane_b32` + `s_cbranch_execz` derive `Any` from `(lo | hi) != 0` with zero + extra `OpAtomicOr`s; + - cache invalidation on EXEC / SGPR-pair / half-SGPR rewrite and across basic-block labels; + - 32-bit half-mask SGPR writes in wave64 never alias 64-bit full-wave `x_vcache` entries. + 3. Deferred SCC vote coalescing (`_pending_scc_vote` in `emulate_inline`): + - live-SCC mask op + `s_cbranch_execz` on distinct masks coalesces into one 2-word `x_round` (`2 -> 1` + round barrier) across all four `(SCC, EXEC != 0)` truth combinations and upper-half-only active lanes; + - live-SCC mask op + cross-half `v_readlane_b32` coalesces `data` and `bits` into one `x_round` (`2 -> 1` + round barrier); + - live-SCC mask op + memory-hazard `x_order_barrier` coalesces into one `0x948` barrier. + 4. Contiguous `v_readfirstlane_b32` batching (`Gen._emit_rfl_run` in `emulate_inline`): + - 8-register runs collapse `8 -> 2` (or `1` when EXEC's mask/first-lane is already cached) round barriers; + - exact across upper-half-only active lanes (`32..63`), `EXEC == 0` lane-0 fallback, partial 40-thread waves, + 128-thread 2-wave workgroups with distinct first active lanes per wave, and piggybacked pending SCC votes. + +Note: every `--wave64-emulate` module starts with 1 `x_prologue` `0x948` barrier after zeroing `%x_buf`, so total +`OpControlBarrier` count is `1 + `. + +Run from the repository root: python -I tests/semantic/test_wave64_xround_barriers.py +""" +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import support # noqa: E402 +import spirv_asm # noqa: E402 +from test_wave64_emulate_opt import ( # noqa: E402 + VSHARP, + _translate_encoded, + run_emulated_workgroup, +) + + +def _with_labels(items): + """Resolve `('label', name)` and `('branch', op, target)` into `(insn_text, nbytes)` pairs.""" + offsets = {} + byte_pos = 0 + for it in items: + if it[0] == "label": + offsets[it[1]] = byte_pos + elif it[0] == "branch": + byte_pos += 4 + else: + byte_pos += it[1] + out = [] + byte_pos = 0 + for it in items: + if it[0] == "label": + continue + if it[0] == "branch": + _, op, target = it + byte_pos += 4 + delta = offsets[target] - byte_pos + assert delta % 4 == 0, f"unaligned branch target {target}: {delta}" + out.append((f"{op} {delta // 4}", 4)) + else: + byte_pos += it[1] + out.append(it) + return out + + +def _with_structured_tail(items): + """Append a barrier-free 2-block scalar tail before `s_endpgm` so `len(eff_blocks) >= 2` and + `plan_structured_emulation` engages `inline_all` / `structured_hybrid` with 0 extra barriers.""" + assert items[-1] == ("s_endpgm", 4) + return _with_labels(list(items[:-1]) + [ + ("s_cmp_eq_u32 0, 1", 4), + ("branch", "s_cbranch_scc1", "_tail_end"), + ("s_nop 0", 4), + ("label", "_tail_end"), + ("s_endpgm", 4), + ]) + + +def _assemble_and_maybe_validate(spv): + binary = spirv_asm.assemble(spv, target_env="vulkan1.2") + val = shutil.which("spirv-val") + if val is not None: + with tempfile.NamedTemporaryFile(suffix=".spv", delete=False) as tf: + tf.write(binary) + spv_path = tf.name + try: + res = subprocess.run( + [val, "--target-env", "vulkan1.2", "--scalar-block-layout", spv_path], + capture_output=True, text=True, timeout=30, + ) + if res.returncode != 0: + raise AssertionError(f"spirv-val failed:\n{res.stderr}\n{res.stdout}") + finally: + try: + os.unlink(spv_path) + except OSError: + pass + return binary + + +def _run_both_orders(tc, spv, local_size, memory_init=None): + _assemble_and_maybe_validate(spv) + mem_fwd, bars_fwd = run_emulated_workgroup( + spv, local_size, push_constants=VSHARP + [0] * 28, + memory=dict(memory_init or {}), reverse_order=False, + ) + mem_rev, bars_rev = run_emulated_workgroup( + spv, local_size, push_constants=VSHARP + [0] * 28, + memory=dict(memory_init or {}), reverse_order=True, + ) + tc.assertEqual(mem_fwd, mem_rev) + tc.assertEqual(bars_fwd, bars_rev) + return mem_fwd, bars_fwd + + +class InlineXRoundTests(unittest.TestCase): + def test_inline_xround_eliminates_helper_calls_umod_and_dead_sched_atomics(self): + # 128-thread (2-wave) shader with uniform spine blocks + sync-free tail (no mini_scheduler / tail_scheduler): + # must emit 0 OpFunctionCall, 0 OpUMod, 0x108 barrier when mem is clean, 0x948 when mem is dirty, + # and only 2 reset OpAtomicStore per x_round (mask words only, omitting the 2 dead sched words). + insns = _with_structured_tail([ + ("s_mov_b64 exec, -1", 4), + ("v_add_nc_u32_e32 v4, 100, v0", 4), + ("v_readlane_b32 s10, v4, 45", 8), # clean mem -> 0x108 barrier + ("v_lshlrev_b32_e32 v8, 2, v0", 4), + ("buffer_load_dword v5, v8, s[0:3], 0 offen", 8), # dirties ("mem", "r") + ("v_add_nc_u32_e32 v5, s10, v5", 4), + ("v_readlane_b32 s11, v5, 50", 8), # dirty mem -> 0x948 barrier + ("v_add_nc_u32_e32 v6, s11, v4", 4), + ("v_add_nc_u32_e32 v9, 1024, v8", 4), + ("buffer_store_dword v6, v9, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv, gen = _translate_encoded("cs_inline_multiwave", insns, (128, 1, 1), emulate=True) + self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") + self.assertEqual(gen.emulate_plan["mini_blocks"], {}) + self.assertEqual(gen.emulate_plan["tail_blocks"], set()) + self.assertEqual(spv.count("OpFunctionCall"), 0) + self.assertEqual(spv.count("OpUMod"), 0) + self.assertEqual(spv.count("OpControlBarrier %c2 %c2 %c108"), 1) + # 1 prologue 0x948 + 1 dirty-mem x_round 0x948 = 2 + self.assertEqual(spv.count("OpControlBarrier %c2 %c2 %c948"), 2) + # 1 prologue zeroing store + 2 rounds * 2 mask-reset OpAtomicStores = 5 total (not 1 + 8 = 9 with dead sched resets). + self.assertEqual(spv.count("OpAtomicStore "), 1 + 4) + + init = {i * 4: i * 10 for i in range(128)} + mem, bars = _run_both_orders(self, spv, (128, 1, 1), init) + self.assertEqual(bars, 1 + 2) + for tid in range(128): + w_base = tid & ~63 + s10 = 100 + (w_base + 45) + s11 = s10 + init[(w_base + 50) * 4] + self.assertEqual(mem[1024 + tid * 4], s11 + 100 + tid, f"tid {tid}") + + def test_six_plus_inline_rounds_wrap_mod6_ring_cleanly(self): + # 8 sequential cross-half (s_bcnt1 + v_readlane_b32) pairs = 16 inline rounds cycling %x_it 0..5 -> 0..3. + items = [("v_mul_lo_u32 v4, 3, v0", 8), ("s_mov_b32 s20, 0", 4)] + for k in range(8): + src_lane = 33 + k + items.append((f"v_cmp_ge_u32_e64 s[10:11], v0, {src_lane}", 8)) + items.append(("s_bcnt1_i32_b64 s12, s[10:11]", 4)) + items.append((f"v_readlane_b32 s13, v4, {src_lane}", 8)) + items.append(("s_add_i32 s20, s20, s12", 4)) + items.append(("s_add_i32 s20, s20, s13", 4)) + items.extend([ + ("v_mov_b32_e32 v5, s20", 4), + ("v_mov_b32_e32 v6, 0", 4), + ("v_cmpx_eq_u32_e32 0, v0", 4), + ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv, gen = _translate_encoded("cs_mod6_wrap", _with_structured_tail(items), (64, 1, 1), emulate=True) + self.assertEqual(gen.emulate_plan["mode"], "inline_all") + self.assertEqual(spv.count("OpUMod"), 0) + mem, bars = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(bars, 1 + 16) + want = sum((64 - (33 + k)) + 3 * (33 + k) for k in range(8)) + self.assertEqual(mem[0], want) + + +class VoteAndMaskCacheTests(unittest.TestCase): + def test_live_scc_saveexec_and_cbranch_execz_share_single_vote(self): + # Live SCC from s_and_saveexec_b64 is read after s_cbranch_execz; only 1 round barrier + 1 OpAtomicOr! + insns = _with_labels([ + ("v_cmp_ge_u32_e64 s[10:11], v0, 44", 8), # upper-half lanes 44..63 only + ("s_mov_b32 s15, 7", 4), + ("s_and_saveexec_b64 s[12:13], s[10:11]", 4), + ("branch", "s_cbranch_execz", "skip"), + ("s_cselect_b32 s15, 91, 92", 4), + ("label", "skip"), + ("s_mov_b64 exec, -1", 4), + ("v_mov_b32_e32 v4, s15", 4), + ("v_mov_b32_e32 v5, 0", 4), + ("v_cmpx_eq_u32_e32 0, v0", 4), + ("buffer_store_dword v4, v5, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv, _ = _translate_encoded("cs_saveexec_reuse", insns, (64, 1, 1), emulate=True) + self.assertEqual(spv.count("OpAtomicOr"), 1) + self.assertEqual(spv.count("OpControlBarrier"), 1 + 1) + mem, bars = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(bars, 1 + 1) + self.assertEqual(mem[0], 91) + + def test_cached_branch_condition_survives_buffer_store_and_orders_dirty_memory(self): + # s_bcnt1_i32_b64 caches EXEC in x_mcache; buffer_store_dword emits an internal `if (%active)` selection + # without touching mask registers (so x_gen is restored!) and dirties ("mem", "w"); s_cbranch_execz + # derives Any from x_mcache with ZERO extra OpAtomicOrs and emits 1 bare 0x948 x_order_barrier! + insns = _with_labels([ + ("v_lshlrev_b32_e32 v5, 2, v0", 4), # per-lane byte offset while all 64 lanes are active + ("v_cmp_ge_u32_e64 s[10:11], v0, 32", 8), # lanes 32..63 active + ("s_mov_b64 exec, s[10:11]", 4), + ("s_bcnt1_i32_b64 s14, exec", 4), # caches EXEC in x_mcache (2 OpAtomicOrs, 0x108 barrier) + ("v_add_nc_u32_e32 v4, 500, v0", 4), + ("buffer_store_dword v4, v5, s[0:3], 0 offen", 8), # lanes 32..63 store to 128..252 + ("branch", "s_cbranch_execz", "done"), # cached Any -> 0 OpAtomicOrs, 1 bare 0x948 barrier! + ("s_mov_b64 exec, -1", 4), + ("v_sub_nc_u32_e32 v6, 63, v0", 4), + ("v_lshlrev_b32_e32 v6, 2, v6", 4), + ("buffer_load_dword v7, v6, s[0:3], 0 offen", 8), + ("v_add_nc_u32_e32 v7, s14, v7", 4), + ("v_add_nc_u32_e32 v8, 512, v5", 4), + ("buffer_store_dword v7, v8, s[0:3], 0 offen", 8), + ("label", "done"), + ("s_endpgm", 4), + ]) + spv, _ = _translate_encoded("cs_cached_branch_dirty_mem", insns, (64, 1, 1), emulate=True) + # 1 prologue + 1 (s_bcnt1 0x108) + 1 (s_cbranch_execz dirty-mem 0x948) + 1 (blk1 load->store WAR 0x948) = 4. + self.assertEqual(spv.count("OpAtomicOr"), 2) + self.assertEqual(spv.count("OpControlBarrier"), 1 + 3) + mem, bars = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(bars, 1 + 3) + self.assertEqual(mem[512 + 0], 595) + self.assertEqual(mem[512 + 15 * 4], 500 + 48 + 32) + + def test_half_mask_write_does_not_alias_full_wave_vote_cache(self): + insns = _with_labels([ + ("v_cmp_ge_u32_e64 s[10:11], v0, 40", 8), + ("s_and_b32 s10, s10, -1", 4), + ("s_cselect_b32 s14, 10, 20", 4), + ("s_mov_b64 vcc, s[10:11]", 4), + ("s_mov_b32 s15, 30", 4), + ("branch", "s_cbranch_vccz", "skip"), + ("s_mov_b32 s15, 40", 4), + ("label", "skip"), + ("s_add_i32 s14, s14, s15", 4), + ("v_mov_b32_e32 v4, s14", 4), + ("v_mov_b32_e32 v5, 0", 4), + ("v_cmpx_eq_u32_e32 0, v0", 4), + ("buffer_store_dword v4, v5, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv, _ = _translate_encoded("cs_half_mask_no_alias", insns, (64, 1, 1), emulate=True) + mem, _ = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(mem[0], 60) + + +class DeferredSccCoalesceTests(unittest.TestCase): + def test_deferred_scc_coalesces_with_cbranch_execz_all_four_truth_cases(self): + cases = [ + (70, 70, 0, 0), + (70, 48, 0, 1), + (48, 70, 1, 0), + (48, 52, 1, 1), + ] + for idx, (scc_thr, exec_thr, want_scc, want_exec_nz) in enumerate(cases): + with self.subTest(case=idx, want_scc=want_scc, want_exec_nz=want_exec_nz): + insns = _with_labels([ + (f"v_cmp_ge_u32_e64 s[10:11], v0, {scc_thr}", 8), + (f"v_cmp_ge_u32_e64 s[12:13], v0, {exec_thr}", 8), + ("s_mov_b64 exec, s[12:13]", 4), + ("s_mov_b32 s20, 100", 4), + ("s_and_b64 s[14:15], s[10:11], s[10:11]", 4), + ("branch", "s_cbranch_execz", "taken"), + ("s_mov_b32 s20, 200", 4), + ("label", "taken"), + ("s_cselect_b32 s21, 1, 0", 4), + ("s_mov_b64 exec, -1", 4), + ("s_add_i32 s20, s20, s21", 4), + ("v_mov_b32_e32 v4, s20", 4), + ("v_mov_b32_e32 v5, 0", 4), + ("v_cmpx_eq_u32_e32 0, v0", 4), + ("buffer_store_dword v4, v5, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv, _ = _translate_encoded(f"cs_coal_truth_{idx}", insns, (64, 1, 1), emulate=True) + self.assertEqual(spv.count("OpControlBarrier"), 1 + 1) + mem, bars = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(bars, 1 + 1) + self.assertEqual(mem[0], (200 if want_exec_nz else 100) + want_scc) + + def test_deferred_scc_coalesces_with_readlane_and_memory_order_barrier(self): + insns = _with_structured_tail([ + ("s_mov_b64 exec, -1", 4), + ("v_add_nc_u32_e32 v4, 300, v0", 4), + ("v_cmp_ge_u32_e64 s[10:11], v0, 50", 8), + ("s_and_b64 s[12:13], s[10:11], s[10:11]", 4), # deferred SCC = 1 + ("v_readlane_b32 s14, v4, 55", 8), # coalesces into 1st round barrier (0x108) + ("s_cselect_b32 s15, 10, 20", 4), # s15 = 10 + ("v_lshlrev_b32_e32 v5, 2, v0", 4), + ("buffer_store_dword v4, v5, s[0:3], 0 offen", 8), # dirties ("mem", "w") + ("v_cmp_ge_u32_e64 s[16:17], v0, 70", 8), + ("s_and_b64 s[18:19], s[16:17], s[16:17]", 4), # deferred SCC = 0 while mem is dirty + ("v_sub_nc_u32_e32 v6, 63, v0", 4), + ("v_lshlrev_b32_e32 v6, 2, v6", 4), + ("buffer_load_dword v7, v6, s[0:3], 0 offen", 8), # RAW hazard -> x_order_barrier coalesces SCC (0x948)! + ("s_cselect_b32 s16, 3, 7", 4), # SCC = 0 -> s16 = 7 + ("s_add_i32 s14, s14, s15", 4), + ("s_add_i32 s14, s14, s16", 4), + ("v_add_nc_u32_e32 v7, s14, v7", 4), + ("v_add_nc_u32_e32 v8, 512, v5", 4), + ("buffer_store_dword v7, v8, s[0:3], 0 offen", 8), # WAR hazard after load -> 1 more 0x948 barrier + ("s_endpgm", 4), + ]) + spv, _ = _translate_encoded("cs_coal_data_and_mem", insns, (64, 1, 1), emulate=True) + self.assertEqual(spv.count("OpControlBarrier %c2 %c2 %c108"), 1) + # 1 prologue + 1 coalesced (RAW + SCC) + 1 (load->store WAR) = 3 + self.assertEqual(spv.count("OpControlBarrier %c2 %c2 %c948"), 1 + 2) + mem, bars = _run_both_orders(self, spv, (64, 1, 1)) + self.assertEqual(bars, 1 + 3) + self.assertEqual(mem[512], 735) + + +class BatchedReadfirstlaneTests(unittest.TestCase): + def test_eight_readfirstlanes_batch_to_two_barriers_uncached_and_one_cached(self): + setup = [("v_mbcnt_lo_u32_b32 v1, -1, 0", 8), ("v_mbcnt_hi_u32_b32 v1, -1, v1", 8)] + for k in range(8): + setup.append((f"v_mul_lo_u32 v{4 + k}, {k + 2}, v1", 8)) + setup.append((f"v_add_nc_u32_e32 v{4 + k}, {100 * (k + 1)}, v{4 + k}", 4)) + + # 1) Uncached 8x RFL -> 2 round barriers total (down from 8)! + insns_uncached = _with_structured_tail(setup + [ + ("v_cmp_ge_u32_e64 s[10:11], v1, 39", 8), + ("s_mov_b64 exec, s[10:11]", 4), + ] + [(f"v_readfirstlane_b32 s{20 + k}, v{4 + k}", 4) for k in range(8)] + [ + ("s_mov_b64 exec, -1", 4), + ("s_mov_b32 s31, 0", 4), + ] + [(f"s_add_i32 s31, s31, s{20 + k}", 4) for k in range(8)] + [ + ("v_mov_b32_e32 v15, s31", 4), + ("v_mov_b32_e32 v16, 0", 4), + ("v_cmpx_eq_u32_e32 0, v1", 4), + ("buffer_store_dword v15, v16, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv_u, _ = _translate_encoded("cs_rfl8_uncached", insns_uncached, (64, 1, 1), emulate=True) + self.assertEqual(spv_u.count("OpControlBarrier"), 1 + 2) + mem_u, bars_u = _run_both_orders(self, spv_u, (64, 1, 1)) + self.assertEqual(bars_u, 1 + 2) + want_rfl = sum(100 * (k + 1) + (k + 2) * 39 for k in range(8)) + self.assertEqual(mem_u[0], want_rfl) + + # 2) Cached EXEC mask from s_bcnt1 + pending SCC vote piggybacking onto _emit_rfl_run's single barrier! + insns_cached = _with_structured_tail(setup + [ + ("v_cmp_ge_u32_e64 s[10:11], v1, 39", 8), + ("s_mov_b64 exec, s[10:11]", 4), + ("s_bcnt1_i32_b64 s18, exec", 4), # 1st round barrier (populates x_mcache[exec]) + ("v_cmp_ge_u32_e64 s[14:15], v1, 50", 8), + ("s_and_b64 s[16:17], s[14:15], s[14:15]", 4), # deferred SCC = 1 piggybacks onto _emit_rfl_run! + ] + [(f"v_readfirstlane_b32 s{20 + k}, v{4 + k}", 4) for k in range(8)] + [ + ("s_cselect_b32 s30, 77, 88", 4), + ("s_mov_b64 exec, -1", 4), + ("s_add_i32 s31, s18, s30", 4), + ] + [(f"s_add_i32 s31, s31, s{20 + k}", 4) for k in range(8)] + [ + ("v_mov_b32_e32 v15, s31", 4), + ("v_mov_b32_e32 v16, 0", 4), + ("v_cmpx_eq_u32_e32 0, v1", 4), + ("buffer_store_dword v15, v16, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv_c, _ = _translate_encoded("cs_rfl8_cached", insns_cached, (64, 1, 1), emulate=True) + # 1 prologue + 1 (s_bcnt1) + 1 (8x RFL + deferred SCC vote) = 3 barriers total (down from 11)! + self.assertEqual(spv_c.count("OpControlBarrier"), 1 + 2) + mem_c, bars_c = _run_both_orders(self, spv_c, (64, 1, 1)) + self.assertEqual(bars_c, 1 + 2) + self.assertEqual(mem_c[0], (64 - 39) + 77 + want_rfl) + + def test_batched_rfl_exec_zero_partial_wave_and_multiwave(self): + # 1) Partial 40-thread wave with active lanes 35..39 (first = 35) and EXEC = 0 fallback (reads lane 0). + insns_partial = _with_structured_tail([ + ("v_add_nc_u32_e32 v4, 400, v0", 4), + ("v_add_nc_u32_e32 v5, 800, v0", 4), + ("v_add_nc_u32_e32 v6, 900, v0", 4), + ("v_cmp_ge_u32_e64 s[10:11], v0, 35", 8), + ("s_mov_b64 exec, s[10:11]", 4), + ("v_readfirstlane_b32 s20, v4", 4), + ("v_readfirstlane_b32 s21, v5", 4), + ("v_readfirstlane_b32 s24, v6", 4), + ("v_cmp_ge_u32_e64 s[12:13], v0, 50", 8), + ("s_mov_b64 exec, s[12:13]", 4), + ("v_readfirstlane_b32 s22, v4", 4), + ("v_readfirstlane_b32 s23, v5", 4), + ("v_readfirstlane_b32 s25, v6", 4), + ("s_mov_b64 exec, -1", 4), + ("s_add_i32 s20, s20, s21", 4), + ("s_add_i32 s20, s20, s24", 4), + ("s_add_i32 s22, s22, s23", 4), + ("s_add_i32 s22, s22, s25", 4), + ("v_mov_b32_e32 v8, s20", 4), + ("v_mov_b32_e32 v9, 0", 4), + ("v_cmpx_eq_u32_e32 0, v0", 4), + ("buffer_store_dword v8, v9, s[0:3], 0 offen", 8), + ("v_mov_b32_e32 v8, s22", 4), + ("v_mov_b32_e32 v9, 4", 4), + ("buffer_store_dword v8, v9, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv_p, gen_p = _translate_encoded("cs_rfl_partial40", insns_partial, (40, 1, 1), emulate=True) + self.assertEqual(gen_p.emulate_plan["mode"], "inline_all") + # Each 3x RFL run takes 2 round barriers + 1 WAW barrier between the two stores -> 1 prologue + 5 = 6. + self.assertEqual(spv_p.count("OpControlBarrier"), 1 + 5) + mem_p, _ = _run_both_orders(self, spv_p, (40, 1, 1)) + self.assertEqual(mem_p[0], (400 + 35) + (800 + 35) + (900 + 35)) + self.assertEqual(mem_p[4], 400 + 800 + 900) + + # 2) 128-thread (2-wave) group where wave 0 has first active wave_lane = 42 (tid 42) and wave 1 has + # first active wave_lane = 7 (tid 71). + insns_mw = _with_structured_tail([ + ("v_add_nc_u32_e32 v4, 1000, v0", 4), + ("v_mul_lo_u32 v5, 5, v0", 8), + ("v_cmp_ge_u32_e64 s[10:11], v0, 42", 8), + ("v_cmp_ge_u32_e64 s[12:13], v0, 71", 8), + ("v_cmp_lt_u32_e64 s[14:15], v0, 64", 8), + ("s_and_b64 s[10:11], s[10:11], s[14:15]", 4), + ("s_or_b64 exec, s[10:11], s[12:13]", 4), + ("v_readfirstlane_b32 s20, v4", 4), + ("v_readfirstlane_b32 s21, v5", 4), + ("v_readfirstlane_b32 s22, v0", 4), + ("s_mov_b64 exec, -1", 4), + ("s_add_i32 s20, s20, s21", 4), + ("s_add_i32 s20, s20, s22", 4), + ("v_mov_b32_e32 v6, s20", 4), + ("v_lshlrev_b32_e32 v7, 2, v0", 4), + ("buffer_store_dword v6, v7, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ]) + spv_mw, gen_mw = _translate_encoded("cs_rfl_mw128", insns_mw, (128, 1, 1), emulate=True) + self.assertEqual(gen_mw.emulate_plan["mode"], "structured_hybrid") + self.assertEqual(spv_mw.count("OpControlBarrier"), 1 + 2) + mem_mw, _ = _run_both_orders(self, spv_mw, (128, 1, 1)) + for tid in range(64): + self.assertEqual(mem_mw[tid * 4], (1000 + 42) + 5 * 42 + 42) + for tid in range(64, 128): + self.assertEqual(mem_mw[tid * 4], (1000 + 71) + 5 * 71 + 71) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index a41db7eb75..cee93aee0f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -423,6 +423,9 @@ class Unsupported(Exception): class Gen: + _pending_scc_vote = None + _flushing_scc_vote = False + def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.stage = stage self.descriptor_hash = DESCRIPTOR_HASH @@ -546,7 +549,14 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.x_dirty = set() # emulate: (memory kind "lds"/"mem", "r"/"w") accessed since the last round self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity) self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok + self._x_gen_seq = 0 # emulate: monotonic counter allocating distinct x_gen ids + self._x_sel_stack = [] # emulate_inline: [merge_lbl, saved_x_gen, mask_reg_written] for open selections self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block + self.x_vcache = {} # emulate: wave_mask key -> %bool wave-wide Any vote already known in this block + self.x_flcache = {} # emulate: exec wave_mask key -> %uint first active lane (0..63) in this block + self.x_vkeys = {} # emulate: per-lane mask %uint SSA id -> list of wave_mask keys holding it + self._pending_scc_vote = None # emulate_inline: deferred (kind, bit_id, vkeys) for %scc before next read/vote + self._flushing_scc_vote = False self.lane_either = {} # id(instruction) -> SGPRs holding constant 0/-1 (EITHER) there self.cur_either = () self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves @@ -578,8 +588,6 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.guard_fn = None # --address-guard: lines of %guard_fn, once an access needs it self.guard_last = None # --address-guard: (guarded address, unguarded address) of the last host_addr self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths - self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup - self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes) self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok @@ -596,7 +604,31 @@ def cu(self, v): self.consts[v] = f"%c{v:x}" return self.consts[v] + def _bump_x_gen(self): + self._x_gen_seq += 1 + self.x_gen = self._x_gen_seq + + def _mark_x_sel_dirty(self): + for entry in self._x_sel_stack: + entry[2] = True + + def clear_x_caches(self): + self.flush_pending_scc_vote() + self.x_tok.clear() + self.x_mcache.clear() + self.x_vcache.clear() + self.x_flcache.clear() + self.x_vkeys.clear() + self._x_sel_stack.clear() + def emit(self, s): + if self._pending_scc_vote is not None and not self._flushing_scc_vote: + if s.startswith("OpStore %scc "): + self._pending_scc_vote = None + elif ("%scc" in s or s.endswith("= OpLabel") + or s.startswith(("OpSelectionMerge ", "OpLoopMerge ", "OpControlBarrier ", + "OpBranch", "OpSwitch ", "OpReturn", "OpStore %pc "))): + self.flush_pending_scc_vote() self.body.append(" " + s) if s.startswith("OpStore %active "): if self.exec_static_true: @@ -608,8 +640,21 @@ def emit(self, s): if s.startswith(("OpStore %vcc ", "OpStore %active ")): reg, val = s.split()[1:3] self.x_tok[reg] = val + self._mark_x_sel_dirty() + elif s.startswith(("OpStore %vcc_hi ", "OpLoopMerge ")): + self._mark_x_sel_dirty() + elif self.emulate_inline and s.startswith("OpSelectionMerge "): + self._x_sel_stack.append([s.split()[1], self.x_gen, False]) elif s.endswith("= OpLabel"): - self.x_gen += 1 + lbl = s.split()[0] + if self.emulate_inline and self._x_sel_stack and self._x_sel_stack[-1][0] == lbl: + _, saved_gen, dirty = self._x_sel_stack.pop() + if not dirty: + self.x_gen = saved_gen + else: + self._bump_x_gen() + else: + self._bump_x_gen() # ---- register access ---- def reg_ptr(self, kind, r): @@ -641,6 +686,7 @@ def store_reg(self, kind, r, val): if kind == "sgpr": self.sgpr_imm.pop(r, None) self.x_tok[("sgpr", r)] = val + self._mark_x_sel_dirty() if self.desc_cache: # every write to the %sgpr array comes through here (see desc_lookup_sgpr) self.desc_cache = {k: v for k, v in self.desc_cache.items() if not (k[0] <= r < k[0] + k[1])} p = self.reg_ptr(kind, r) @@ -1891,7 +1937,10 @@ def exec_bit(self, word): return bit def set_exec(self, mask_u): - self.emit(f"OpStore %active {self.tmp_bool_nz(mask_u)}") + b = self.tmp_bool_nz(mask_u) + self.emit(f"OpStore %active {b}") + if self.emulate: + self.x_vkeys.setdefault(mask_u, []).append(("exec", self.x_gen, b)) self.uses_active = True def vcc_half_keeps_mask(self): @@ -1983,6 +2032,14 @@ def lane_local(self, ins): and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes) + def _batchable_rfl(self, ins): + if not self.emulate_inline or base_op(ins["op"]) != "v_readfirstlane_b32" or ins["mods"]: + return False + a = ins["args"] + return (len(a) == 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 + and a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1 + and ("v", a[1]["r"]) not in self.lane_masks.get(id(ins), {})) + def insns(self, seq): """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN lane-local VALU instructions goes inside one `if (active)` and writes its VGPRs directly: the driver @@ -1993,6 +2050,14 @@ def insns(self, seq): local = [self.exec_changes and not self.emulate and self.lane_local(i) for i in seq] i = 0 while i < len(seq): + if self._batchable_rfl(seq[i]): + rfl_end = i + 1 + while rfl_end < len(seq) and self._batchable_rfl(seq[rfl_end]): + rfl_end += 1 + if rfl_end - i >= 2: + self._emit_rfl_run(seq[i:rfl_end]) + i = rfl_end + continue j = i while j < len(seq) and local[j]: j += 1 @@ -5929,41 +5994,53 @@ def x_mask_slot(self, it): def x_order_barrier(self): """Order pending memory/LDS accesses across both halves of an emulated wave64.""" if self.emulate_inline: - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") + if self._pending_scc_vote is not None and not self._flushing_scc_vote: + self.flush_pending_scc_vote() + if self.x_dirty: + sem = 0x108 if all(k == "lds" for k, _ in self.x_dirty) else 0x948 + self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(sem)}") + self.x_dirty = set() + return + sem = 0x108 if (self.x_dirty and all(k == "lds" for k, _ in self.x_dirty)) else 0x948 + self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(sem)}") self.x_dirty = set() else: self.x_split() - def _ensure_x_pre_fn(self, kind): - """Build (once per module) the barrier-free helper OpFunction for an inline wave64 x_round pre-barrier step. + def _x_has_schedulers(self): + return bool(self.emulate_plan and (self.emulate_plan["mini_blocks"] or self.emulate_plan["tail_blocks"])) + + def _x_inline_slots_and_reset(self, it): + """Compute `(s, n1)` for inline wave64 round `it` and reset round `(it + 1) % 3` in `%x_buf`. - Outlines the ~20-30 instructions of ring-buffer slot clearing (`sn = (it + 1) % 3`), mask/data slot indexing, - and pre-barrier %x_buf store/OpAtomicOr out of %main while keeping OpControlBarrier directly at the callsite - in %main. Returns the helper function's SPIR-V id (`%x_pre_vote_fn`, `%x_pre_mask_fn`, or `%x_pre_data_fn`). + When no round-loop scheduler (`mini_blocks` / `tail_blocks`) exists in the module, `%x_it` stays in + `0..5` (`lcm(2, 3) = 6`), preserving both `it & 1` parity and `it % 3` slot indexing with zero `OpUMod` + divisions and skipping unused scheduler-word atomic stores. """ - fn_name = f"%x_pre_{kind}_fn" - if kind in self.x_round_fns: - return fn_name w, mask, sched, sink = self.x_sizes() - tail_params = {"vote": ["val"], "data": ["val"], "mask": ["b0", "b1"], "both": ["val", "b0", "b1"]}[kind] - if w == 1: - p_names = ["it", "li"] + tail_params + has_sched = self._x_has_schedulers() + if not has_sched: + ge3, sub3, s, eq5, add1, n1 = (self.tmp() for _ in range(6)) + self.emit(f"{ge3} = OpUGreaterThanEqual %bool {it} {self.cu(3)}") + self.emit(f"{sub3} = OpISub %uint {it} {self.cu(3)}") + self.emit(f"{s} = OpSelect %uint {ge3} {sub3} {it}") + self.emit(f"{eq5} = OpIEqual %bool {it} {self.cu(5)}") + self.emit(f"{add1} = OpIAdd %uint {it} {self.cu(1)}") + self.emit(f"{n1} = OpSelect %uint {eq5} {self.cu(0)} {add1}") else: - p_names = ["it", "li", "lane", "wave"] + tail_params - arity = len(p_names) - fn_type = self.x_round_fn_types.setdefault(arity, f"%fn_x_pre{arity}") - params = {k: f"%xp_{kind}_{k}" for k in p_names} - p_it, p_li = params["it"], params["li"] - saved, self.body = self.body, [] - n1, sn = self.tmp(), self.tmp() - self.emit(f"{n1} = OpIAdd %uint {p_it} {self.cu(1)}") - self.emit(f"{sn} = OpUMod %uint {n1} {self.cu(3)}") + s, n1 = self.tmp(), self.tmp() + self.emit(f"{s} = OpUMod %uint {it} {self.cu(3)}") + self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") + s2, sp1, sn = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{s2} = OpIEqual %bool {s} {self.cu(2)}") + self.emit(f"{sp1} = OpIAdd %uint {s} {self.cu(1)}") + self.emit(f"{sn} = OpSelect %uint {s2} {self.cu(0)} {sp1}") if w == 1: m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(8)) self.emit(f"{m2} = OpIMul %uint {sn} {self.cu(2)}") self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") - self.emit(f"{ml} = OpIEqual %bool {p_li} {self.cu(0)}") + self.emit(f"{ml} = OpIEqual %bool %x_li {self.cu(0)}") self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") @@ -5971,70 +6048,248 @@ def _ensure_x_pre_fn(self, kind): self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") self.emit(f"OpAtomicStore {mp6} {self.cu(2)} {self.cu(0)} {self.cu(0)}") else: - p_lane, p_wave = params["lane"], params["wave"] m0, m1, m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(10)) self.emit(f"{m0} = OpIMul %uint {sn} {self.cu(w)}") - self.emit(f"{m1} = OpIAdd %uint {m0} {p_wave}") + self.emit(f"{m1} = OpIAdd %uint {m0} %x_wave") self.emit(f"{m2} = OpIMul %uint {m1} {self.cu(2)}") self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") - self.emit(f"{ml} = OpIEqual %bool {p_lane} {self.cu(0)}") + self.emit(f"{ml} = OpIEqual %bool %x_lane {self.cu(0)}") self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") self.emit(f"OpAtomicStore {mp5} {self.cu(2)} {self.cu(0)} {self.cu(0)}") self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") self.emit(f"OpAtomicStore {mp6} {self.cu(2)} {self.cu(0)} {self.cu(0)}") - q0, q1, q2, ql, q3, q4, qp3, qp4 = (self.tmp() for _ in range(8)) - self.emit(f"{q0} = OpIMul %uint {sn} {self.cu(2)}") - self.emit(f"{q1} = OpIAdd %uint {q0} {self.cu(sched)}") - self.emit(f"{q2} = OpIAdd %uint {q1} {self.cu(1)}") - self.emit(f"{ql} = OpIEqual %bool {p_li} {self.cu(0)}") - self.emit(f"{q3} = OpSelect %uint {ql} {q1} {self.cu(sink)}") - self.emit(f"{q4} = OpSelect %uint {ql} {q2} {self.cu(sink)}") - self.emit(f"{qp3} = OpAccessChain %_ptr_WG_uint_x %x_buf {q3}") - self.emit(f"OpAtomicStore {qp3} {self.cu(2)} {self.cu(0)} {self.cu(0)}") - self.emit(f"{qp4} = OpAccessChain %_ptr_WG_uint_x %x_buf {q4}") - self.emit(f"OpAtomicStore {qp4} {self.cu(2)} {self.cu(0)} {self.cu(0)}") - if kind in ("data", "both"): - par, data_base, i, p = (self.tmp() for _ in range(4)) - self.emit(f"{par} = OpBitwiseAnd %uint {p_it} {self.cu(1)}") + if has_sched: + q0, q1, q2, ql, q3, q4, qp3, qp4 = (self.tmp() for _ in range(8)) + self.emit(f"{q0} = OpIMul %uint {sn} {self.cu(2)}") + self.emit(f"{q1} = OpIAdd %uint {q0} {self.cu(sched)}") + self.emit(f"{q2} = OpIAdd %uint {q1} {self.cu(1)}") + self.emit(f"{ql} = OpIEqual %bool %x_li {self.cu(0)}") + self.emit(f"{q3} = OpSelect %uint {ql} {q1} {self.cu(sink)}") + self.emit(f"{q4} = OpSelect %uint {ql} {q2} {self.cu(sink)}") + self.emit(f"{qp3} = OpAccessChain %_ptr_WG_uint_x %x_buf {q3}") + self.emit(f"OpAtomicStore {qp3} {self.cu(2)} {self.cu(0)} {self.cu(0)}") + self.emit(f"{qp4} = OpAccessChain %_ptr_WG_uint_x %x_buf {q4}") + self.emit(f"OpAtomicStore {qp4} {self.cu(2)} {self.cu(0)} {self.cu(0)}") + return s, n1 + + def _x_round_inline(self, data=None, bits=None): + w, mask, _, _ = self.x_sizes() + it = self.tmp() + self.emit(f"{it} = OpLoad %uint %x_it") + s, n1 = self._x_inline_slots_and_reset(it) + data_base = None + if data is not None: + par, data_base, idx, ptr = (self.tmp() for _ in range(4)) + self.emit(f"{par} = OpBitwiseAnd %uint {it} {self.cu(1)}") self.emit(f"{data_base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") - self.emit(f"{i} = OpIAdd %uint {data_base} {p_li}") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") - self.emit(f"OpStore {p} {params['val']}") - ret_id = data_base - if kind in ("vote", "mask", "both"): + self.emit(f"{idx} = OpIAdd %uint {data_base} %x_li") + self.emit(f"{ptr} = OpAccessChain %_ptr_WG_uint_x %x_buf {idx}") + self.emit(f"OpStore {ptr} {data}") + rm = rm1 = None + if bits is not None: if w == 1: - s, c, rm = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") + c, rm = self.tmp(), self.tmp() self.emit(f"{c} = OpIMul %uint {s} {self.cu(2)}") self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") else: - s, a, b, c, rm = (self.tmp() for _ in range(5)) - self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") + a, b, c, rm = (self.tmp() for _ in range(4)) self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") - self.emit(f"{b} = OpIAdd %uint {a} {params['wave']}") + self.emit(f"{b} = OpIAdd %uint {a} %x_wave") self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") - p0, old0 = self.tmp(), self.tmp() - self.emit(f"{p0} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm}") - self.emit(f"{old0} = OpAtomicOr %uint {p0} {self.cu(2)} {self.cu(0)} {params['b0' if kind in ('mask', 'both') else 'val']}") - if kind in ("mask", "both"): + if bits[0] is not None: + p0, old0 = self.tmp(), self.tmp() + self.emit(f"{p0} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm}") + self.emit(f"{old0} = OpAtomicOr %uint {p0} {self.cu(2)} {self.cu(0)} {bits[0]}") + if bits[1] is not None: rm1, p1, old1 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{rm1} = OpIAdd %uint {rm} {self.cu(1)}") self.emit(f"{p1} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm1}") - self.emit(f"{old1} = OpAtomicOr %uint {p1} {self.cu(2)} {self.cu(0)} {params['b1']}") - ret_id = rm - lines, self.body = self.body, saved - self.x_round_fns[kind] = ( - [f"{fn_name} = OpFunction %uint None {fn_type}"] + - [f"{params[k]} = OpFunctionParameter %uint" for k in p_names] + - [f"{fn_name}_entry = OpLabel"] + - lines + - [f" OpReturnValue {ret_id}", "OpFunctionEnd"] - ) - return fn_name + self.emit(f"{old1} = OpAtomicOr %uint {p1} {self.cu(2)} {self.cu(0)} {bits[1]}") + sem = 0x948 if (("mem", "r") in self.x_dirty or ("mem", "w") in self.x_dirty) else 0x108 + self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(sem)}") + self.emit(f"OpStore %x_it {n1}") + self.x_dirty = set() + res = None + if bits is not None: + lo_v = self.x_word(rm) if bits[0] is not None else self.cu(0) + hi_v = self.x_word(rm1) if bits[1] is not None else None + res = (lo_v, hi_v) + if data is None: + return None, res + + def read(lane): + if w == 1: + j = self.tmp() + self.emit(f"{j} = OpIAdd %uint {data_base} {lane}") + return self.x_lane_word(j, lane) + i, j = self.tmp(), self.tmp() + self.emit(f"{i} = OpIAdd %uint {data_base} %x_wbase") + self.emit(f"{j} = OpIAdd %uint {i} {lane}") + return self.x_lane_word(j, lane) + return read, res + + def x_first_lane_from_words(self, lo, hi): + lz, hz, l, h, h32, fh, first = (self.tmp() for _ in range(7)) + self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") + self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") + self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") + self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") + self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") + self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") + self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") + return first + + def _emit_rfl_run(self, run): + """Emit a contiguous run of >= 2 `v_readfirstlane_b32` instructions in `emulate_inline` mode, + batching up to 64 values from `wave_lane == first` across one `OpControlBarrier` once `first` is known.""" + exec_key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) + first = self.x_flcache.get(exec_key) + if first is None and exec_key in self.x_mcache: + lo, hi = self.x_mcache[exec_key] + first = self.x_first_lane_from_words(lo, hi) + self.x_flcache[exec_key] = first + idx = 0 + if first is None: + self.insn(run[0]) + first = self.x_flcache[exec_key] + idx = 1 + rem = len(run) - idx + if rem == 1: + self.insn(run[idx]) + return + w, mask, _, _ = self.x_sizes() + while idx < len(run): + chunk = run[idx:idx + 64] + idx += len(chunk) + srcs = [self.load_reg("vgpr", ins["args"][1]["r"]) for ins in chunk] + pending = self._pending_scc_vote + self._pending_scc_vote = None + self._flushing_scc_vote = True + try: + it = self.tmp() + self.emit(f"{it} = OpLoad %uint %x_it") + s, n1 = self._x_inline_slots_and_reset(it) + par, data_base = self.tmp(), self.tmp() + self.emit(f"{par} = OpBitwiseAnd %uint {it} {self.cu(1)}") + self.emit(f"{data_base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") + w_base = data_base + if w > 1: + w_base = self.tmp() + self.emit(f"{w_base} = OpIAdd %uint {data_base} %x_wbase") + rm = None + if pending is not None: + p_kind, p_bit, p_vkeys = pending + if w == 1: + c, rm = self.tmp(), self.tmp() + self.emit(f"{c} = OpIMul %uint {s} {self.cu(2)}") + self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") + else: + a, b, c, rm = (self.tmp() for _ in range(4)) + self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") + self.emit(f"{b} = OpIAdd %uint {a} %x_wave") + self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") + self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") + p0, old0 = self.tmp(), self.tmp() + self.emit(f"{p0} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm}") + self.emit(f"{old0} = OpAtomicOr %uint {p0} {self.cu(2)} {self.cu(0)} {p_bit}") + is_src, lbl_do, lbl_end = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{is_src} = OpIEqual %bool {self.wave_lane()} {first}") + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {is_src} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + for k, sv in enumerate(srcs): + slot = w_base if k == 0 else self.tmp() + if k: + self.emit(f"{slot} = OpIAdd %uint {w_base} {self.cu(k)}") + ptr = self.tmp() + self.emit(f"{ptr} = OpAccessChain %_ptr_WG_uint_x %x_buf {slot}") + self.emit(f"OpStore {ptr} {sv}") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + sem = 0x948 if (("mem", "r") in self.x_dirty or ("mem", "w") in self.x_dirty) else 0x108 + self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(sem)}") + self.emit(f"OpStore %x_it {n1}") + self.x_dirty = set() + if pending is not None: + self._finish_scc_vote_word(p_kind, self.x_word(rm), p_vkeys) + finally: + self._flushing_scc_vote = False + # OpLabel inside the single-writer selection bumped x_gen, but no mask or register changed: + # restore exec_key's cached first-lane across chunks and for any trailing EXEC read in the block. + new_exec_key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) + self.x_flcache[new_exec_key] = first + if exec_key in self.x_mcache: + self.x_mcache[new_exec_key] = self.x_mcache[exec_key] + if exec_key in self.x_vcache: + self.x_vcache[new_exec_key] = self.x_vcache[exec_key] + exec_key = new_exec_key + for k, ins in enumerate(chunk): + self.cur_ins = ins + self.cur_masks = self.lane_masks.get(id(ins), {}) + slot = w_base if k == 0 else self.tmp() + if k: + self.emit(f"{slot} = OpIAdd %uint {w_base} {self.cu(k)}") + self.store_reg("sgpr", ins["args"][0]["r"], self.x_word(slot)) + + def record_any_vote(self, keys, any_id): + for k in keys: + if k is not None: + self.x_vcache[k] = any_id + + def x_cached_any(self, keys): + if (self._pending_scc_vote is not None and not self._flushing_scc_vote + and self._pending_scc_vote[0] == "Any" + and any(k in self._pending_scc_vote[2] for k in keys)): + self.flush_pending_scc_vote() + for k in keys: + if k in self.x_vcache: + return self.x_vcache[k] + for k in keys: + if k in self.x_mcache: + lo, hi = self.x_mcache[k] + if self.wave64 and hi is not None: + u, any_ = self.tmp(), self.tmp() + self.emit(f"{u} = OpBitwiseOr %uint {lo} {hi}") + self.emit(f"{any_} = OpINotEqual %bool {u} {self.cu(0)}") + else: + any_ = self.tmp() + self.emit(f"{any_} = OpINotEqual %bool {lo} {self.cu(0)}") + self.record_any_vote(keys, any_) + return any_ + return None + + def _finish_scc_vote_word(self, kind, word, vkeys): + b, z = self.tmp(), self.tmp() + self.emit(f"{b} = {'OpIEqual' if kind == 'All' else 'OpINotEqual'} %bool {word} {self.cu(0)}") + if kind == "Any" and vkeys: + self.record_any_vote(vkeys, b) + self.emit(f"{z} = OpSelect %uint {b} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + + def defer_scc_vote(self, kind, b, vkeys=()): + eff = b + if kind == "All": + eff = self.tmp() + self.emit(f"{eff} = OpLogicalNot %bool {b}") + bit = self.tmp() + self.emit(f"{bit} = OpSelect %uint {eff} {self.cu(1)} {self.cu(0)}") + self._pending_scc_vote = (kind, bit, tuple(vkeys)) + + def flush_pending_scc_vote(self): + if self._pending_scc_vote is None or self._flushing_scc_vote: + return + p_kind, p_bit, p_vkeys = self._pending_scc_vote + self._pending_scc_vote = None + self._flushing_scc_vote = True + try: + lo = self._x_round_inline(bits=(p_bit, None))[1][0] + self._finish_scc_vote_word(p_kind, lo, p_vkeys) + finally: + self._flushing_scc_vote = False def x_round(self, data=None, bits=None): """One exchange: this lane's uint `data` goes to its slot, `bits` (lo, hi; None = nothing) are ORed into @@ -6042,78 +6297,37 @@ def x_round(self, data=None, bits=None): and (lo, hi) is the OR over all 64 lanes. In round-loop mode both are valid in the next segment; in inline structured mode (`emulate_inline`) the barrier runs directly in place with zero x_split.""" if self.emulate_inline: - w, _, _, _ = self.x_sizes() - it, n1 = self.tmp(), self.tmp() - self.emit(f"{it} = OpLoad %uint %x_it") - if data is not None and bits is None: - fn = self._ensure_x_pre_fn("data") - args = f"{it} %x_li {data}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data}" - data_base = self.tmp() - self.emit(f"{data_base} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - - def read(lane): - if w == 1: - j = self.tmp() - self.emit(f"{j} = OpIAdd %uint {data_base} {lane}") - return self.x_lane_word(j, lane) - i, j = self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {data_base} %x_wbase") - self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_lane_word(j, lane) - return read, None - if data is None and bits is not None and bits[0] is not None and bits[1] is None: - fn = self._ensure_x_pre_fn("vote") - args = f"{it} %x_li {bits[0]}" if w == 1 else f"{it} %x_li %x_lane %x_wave {bits[0]}" - rm = self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - return None, (self.x_word(rm), None) - if data is None and bits is not None: - fn = self._ensure_x_pre_fn("mask") + if self._pending_scc_vote is not None and not self._flushing_scc_vote: + if data is not None and bits is None: + p_kind, p_bit, p_vkeys = self._pending_scc_vote + self._pending_scc_vote = None + self._flushing_scc_vote = True + try: + read, (lo, _) = self._x_round_inline(data=data, bits=(p_bit, None)) + self._finish_scc_vote_word(p_kind, lo, p_vkeys) + finally: + self._flushing_scc_vote = False + return read, None + if data is None and bits is not None and bits[0] is not None and bits[1] is None: + p_kind, p_bit, p_vkeys = self._pending_scc_vote + self._pending_scc_vote = None + self._flushing_scc_vote = True + try: + _, (lo, hi) = self._x_round_inline(data=None, bits=(p_bit, bits[0])) + self._finish_scc_vote_word(p_kind, lo, p_vkeys) + finally: + self._flushing_scc_vote = False + return None, (hi, None) + self.flush_pending_scc_vote() + if data is None and bits is not None and (bits[0] is None or bits[1] is not None): b0 = bits[0] if bits[0] is not None else self.cu(0) b1 = bits[1] if bits[1] is not None else self.cu(0) - args = f"{it} %x_li {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {b0} {b1}" - rm, hi_i = self.tmp(), self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") - return None, (self.x_word(rm), self.x_word(hi_i)) - fn = self._ensure_x_pre_fn("both") - b0 = bits[0] if bits[0] is not None else self.cu(0) - b1 = bits[1] if bits[1] is not None else self.cu(0) - args = f"{it} %x_li {data} {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data} {b0} {b1}" - rm, hi_i = self.tmp(), self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") - res = (self.x_word(rm), self.x_word(hi_i)) - - def read(lane): - par2, base = self.tmp(), self.tmp() - self.emit(f"{par2} = OpBitwiseAnd %uint {it} {self.cu(1)}") - self.emit(f"{base} = OpIMul %uint {par2} {self.cu(self.x_lanes)}") - if w == 1: - j = self.tmp() - self.emit(f"{j} = OpIAdd %uint {base} {lane}") - return self.x_lane_word(j, lane) - i, j = self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") - self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_lane_word(j, lane) - return read, res + return self._x_round_inline(data=None, bits=(b0, b1)) + if data is not None and bits is not None: + b0 = bits[0] if bits[0] is not None else self.cu(0) + b1 = bits[1] if bits[1] is not None else self.cu(0) + return self._x_round_inline(data=data, bits=(b0, b1)) + return self._x_round_inline(data=data, bits=bits) it = self.tmp() self.emit(f"{it} = OpLoad %uint %x_it") if data is not None: @@ -6402,9 +6616,26 @@ def scc_from_mask(self, v): could follow different s_cbranch_scc paths, which a hardware wave never does: it has one SCC.""" if not self.cur_scc_live: return + self.uses_vote = True + if self.emulate: + vkeys = self.x_vkeys.get(v, ()) + cached = self.x_cached_any(vkeys) + if cached is not None: + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {cached} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + return + if self.emulate_inline: + self.defer_scc_vote("Any", self.tmp_bool_nz(v), vkeys) + return + any_, z = self.tmp(), self.tmp() + self.g_vote(any_, "Any", self.tmp_bool_nz(v)) + self.record_any_vote(vkeys, any_) + self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + return any_, z = self.tmp(), self.tmp() self.g_vote(any_, "Any", self.tmp_bool_nz(v)) - self.uses_vote = True self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") @@ -6728,9 +6959,12 @@ def scc_any_half(self, v, half): self.emit(f"{inh} = {'OpUGreaterThanEqual' if half == 'hi' else 'OpULessThan'} %bool {lane} {self.cu(32)}") self.emit(f"{both} = OpLogicalAnd %bool {inh} {mine}") mine = both + self.uses_vote = True + if self.emulate_inline: + self.defer_scc_vote("Any", mine) + return any_ = self.tmp() self.g_vote(any_, "Any", mine) - self.uses_vote = True z = self.tmp() self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") @@ -6989,8 +7223,13 @@ def mask_dst(self, d, v): self.store_reg("sgpr", d["r"], v) if d.get("n") == 2: self.store_reg("sgpr", d["r"] + 1, v) + if self.emulate and (not self.wave64 or d.get("n") == 2): + toks = tuple(self.x_tok[("sgpr", d["r"] + i)] for i in range(d.get("n", 1))) + self.x_vkeys.setdefault(v, []).append(("v", self.x_gen, toks)) elif d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): self.emit(f"OpStore %vcc {v}") + if self.emulate and (not self.wave64 or d["t"] == "vcc"): + self.x_vkeys.setdefault(v, []).append(("v", self.x_gen, v)) elif d["k"] == "special" and d["t"] == "vcc_hi" and not self.wave64: self.emit(f"OpStore %vcc_hi {v}") else: @@ -7787,8 +8026,14 @@ def selectors(key, count, limit): shuffled = read(safe_g) src_ok = in_bounds if in_bounds is not None else "%true" else: - lo_bit, hi_bit = self.lane_bits(self.active_b()) - read, (lo_word, hi_word) = self.x_round(data=src_val, bits=(lo_bit, hi_bit)) + exec_key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) + if exec_key in self.x_mcache: + read, _ = self.x_round(data=src_val) + lo_word, hi_word = self.x_mcache[exec_key] + else: + lo_bit, hi_bit = self.lane_bits(self.active_b()) + read, (lo_word, hi_word) = self.x_round(data=src_val, bits=(lo_bit, hi_bit)) + self.x_mcache[exec_key] = (lo_word, hi_word) shuffled = read(safe_g) is_low = self.tmp() self.emit(f"{is_low} = OpULessThan %bool {safe_g} {self.cu(32)}") @@ -8164,18 +8409,24 @@ def _insn(self, ins): self.dst(a[0], r) return if self.emulate: - # The wave's active lanes as two mask words and every lane's value, in one round. - v, act = self.src_u(a[1]), self.active_b() - lo_in, hi_in = self.lane_bits(act) - read, (lo, hi) = self.x_round(data=v, bits=(lo_in, hi_in)) - lz, hz, l, h, h32, fh, first = (self.tmp() for _ in range(7)) - self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") - self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") - self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") - self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") - self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") - self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") - self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") + # The wave's active lanes as two mask words and every lane's value, in one round; when EXEC's + # mask or first active lane is already cached in this block, exchange only `data=v`. + v = self.src_u(a[1]) + exec_key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) + first = self.x_flcache.get(exec_key) + if first is not None: + read, _ = self.x_round(data=v) + elif exec_key in self.x_mcache: + read, _ = self.x_round(data=v) + lo, hi = self.x_mcache[exec_key] + first = self.x_first_lane_from_words(lo, hi) + self.x_flcache[exec_key] = first + else: + lo_in, hi_in = self.lane_bits(self.active_b()) + read, (lo, hi) = self.x_round(data=v, bits=(lo_in, hi_in)) + self.x_mcache[exec_key] = (lo, hi) + first = self.x_first_lane_from_words(lo, hi) + self.x_flcache[exec_key] = first self.dst(a[0], read(first)) return self.uses_subgroup = self.uses_ballot = self.uses_vote = True @@ -16206,7 +16457,7 @@ def assemble(gen): x_threads = (gen.cs or gen.ms)["size"] x_threads = x_threads[0] * x_threads[1] * x_threads[2] sx, sy, _ = (gen.cs or gen.ms)["size"] - for v in (0, 1, 2, 3, 6, 31, 63, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, + for v in (0, 1, 2, 3, 5, 6, 31, 63, 0x108, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, x_waves, sx, sx * sy, 0xFFFFFFC0): gen.cu(v) x_missing = gen.x_lanes - x_threads # lanes of a partial last wave that don't exist @@ -16582,8 +16833,6 @@ def assemble(gen): types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") if gen.fmt_enc_fn: types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) - for arity, fn_type in sorted(gen.x_round_fn_types.items()): - types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity)) # dedupe_types keeps the first uvec4 it meets: when the typed-image types follow, declare the ballot type after # them, so a shader that gains a ballot keeps the name %v4uint_st (SHADER-1016). st_types = bool(store_dims or gen.uses_int_fetch or gen.uses_d16_image) @@ -17006,8 +17255,6 @@ def assemble(gen): helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + (gen.guard_fn or []) for function in gen.tbuffer_norm_fns.values(): helpers.extend(function) - for function in gen.x_round_fns.values(): - helpers.extend(function) tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: @@ -18966,8 +19213,7 @@ def emit_folded_region(fd): g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() + g.clear_x_caches() act = g.active_b() lbl_do, lbl_end = g.tmp(), g.tmp() g.emit(f"OpSelectionMerge {lbl_end} None") @@ -19004,8 +19250,7 @@ def emit_folded_region(fd): g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() + g.clear_x_caches() uterm = None for ins in blocks[u]: op = base_op(ins["op"]) @@ -19080,8 +19325,7 @@ def emit_folded_region(fd): g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() + g.clear_x_caches() for n, blk in enumerate(blocks): if n in absorbed: @@ -19097,8 +19341,8 @@ def emit_folded_region(fd): g.block_label = f"%blk{n}" g.x_marks = [] g.x_dirty = set(plan["dirty_in"].get(n, ())) if g.emulate_inline else set() - g.x_tok, g.x_mcache = {}, {} # a register's value is only known from where this block wrote it - g.x_gen += 1 + g.clear_x_caches() # a register's value is only known from where this block wrote it + g._bump_x_gen() g.desc_cache.clear() g._active_ssa = None # a cached lookup is only good inside the block that made it g.sgpr_imm.clear() @@ -19121,8 +19365,7 @@ def emit_folded_region(fd): g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() + g.clear_x_caches() continue nxt_skip = folds[cur]["skip"] g.emit(f"OpStore %pc {g.cu(nxt_skip)}") @@ -19673,7 +19916,20 @@ def branch_condition(g, op): # invocation per lane, each lane holds only its own bit, so the condition is reduced across the subgroup # (= the wave). Deciding per lane would let lanes skip scalar instructions the wave executes, leaving their # SGPRs stale, and would break cross-lane ops and barriers inside the block. + vkey = None if op in ("s_cbranch_vccz", "s_cbranch_vccnz"): + if g.emulate_inline and (not g.wave64 or "vcc" in g.cur_masks): + vkey = ("v", g.x_gen, g.x_tok.get("%vcc", ("start", "vcc"))) + cached = g.x_cached_any((vkey,)) + if cached is not None: + if g.x_dirty: + g.x_order_barrier() + g.uses_vote = True + if op == "s_cbranch_vccnz": + return cached + b = g.tmp() + g.emit(f"{b} = OpLogicalNot %bool {cached}") + return b s = g.tmp() g.emit(f"{s} = OpLoad %uint %vcc") lane = g.tmp() @@ -19691,9 +19947,23 @@ def branch_condition(g, op): g.emit(f"{both} = OpLogicalOr %bool {lane} {hi_nz}") lane = both else: + if g.emulate_inline: + vkey = ("exec", g.x_gen, g.x_tok.get("%active", "start")) + cached = g.x_cached_any((vkey,)) + if cached is not None: + if g.x_dirty: + g.x_order_barrier() + g.uses_vote = True + if op == "s_cbranch_execnz": + return cached + b = g.tmp() + g.emit(f"{b} = OpLogicalNot %bool {cached}") + return b lane = g.active_b() any_ = g.tmp() g.g_vote(any_, "Any", lane) + if vkey is not None: + g.x_vcache[vkey] = any_ g.uses_vote = True if op in ("s_cbranch_vccnz", "s_cbranch_execnz"): return any_