diff --git a/docs/design.md b/docs/design.md index cc0126679b..d1679b032d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -403,6 +403,7 @@ How the generated SPIR-V expects the runtime to work: | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | +| Lane masks merged as data (`lane_masks.insert_data_merges`, `s_mask_to_data_b32`) | A register that is a lane mask at the end of a block, taken as data by every successor, where some successor may scan its lane bits before writing it (`s_ff0` / `s_ff1` / `s_bcnt0` / `s_bcnt1` / `s_flbit`, also through scalar copies and bitwise ops of it), gets a translator-only `s_mask_to_data_b32 sN, sN` before the block's branch. It stores the wave's mask word (`Gen.lane_mask_word`), the same number in every lane, as on hardware. This is the compiler's scalar loop over the set lanes of a ballot: the ballot enters the loop as a mask and the back edge writes a number. `wave64_emulate_opt` counts the instruction as a mask word reader, so it never lands inside a folded lane-local region, where the gather would run with only some lanes; under `--wave64-emulate` the gather is an exchange round and relies on its block being reached by the whole wave through scalar branches. A merge that is only read as a mask again (EXEC, an AND with it, a `v_cndmask` mask) needs no gather: `mask_src` takes bit L of a data register for lane L, and each lane's 0 / ~0 gives the same bit; other number reads of such a merge (an add, a compare) are left as before, since none is known in a shader. **Until 2026-11-28 each lane scanned its own 0 / ~0**: natively the wave64 subgroup split up at the ballot (`SubgroupDivergenceError` on the CPU interpreter), and under `--wave64-emulate` the loop body ran a wrong number of times per lane. Source: **synthetic repro** `tests/semantic/test_ballot_bit_loop.py` (a hand-written wave64 program in the compiler's shape: one bit loop over each half of a ballot, lanes 32-63 through the high half, each with a lane-local `s_cbranch_execz` region; native wave64, emulated structured and emulated with the round scheduler; on `main` all native runs diverge and the emulated runs give wrong counts, with the fix every lane matches the reference model) and the second case there (a mask/number merge read only by EXEC is exact with no gather, and none is inserted); placement, idempotence and the 64-bit high half pinned by `tests/test_lane_masks.py`; **game timing** by quartz-heron-58 (#2501): the library compute program with two such loops went from about 258 ms per dispatch (0.24 ms with a 64-pass cap) to 0.075 ms, 1.44 to about 2.2 frames/s, no device loss, and at the narrowed head the same 31 changed programs byte-identical to their prototype's, 2.30 frames/s; the full translator semantic suite (`scripts/run_semantic_tests.py tests/semantic`, 503 files, 6389 tests, 0 failed) and a dual-GPU `run_gpu_tests.py --filter cs_w64` run by timbot103 (24/24 on an RTX 5080 and on an AMD Radeon iGPU, `spirv-val` clean). Reach: 31 of 2,684 pipeline-library programs change under `--wave64-emulate`, none in the other shader folders. | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | diff --git a/tests/semantic/test_ballot_bit_loop.py b/tests/semantic/test_ballot_bit_loop.py new file mode 100644 index 0000000000..7fc5fbfec6 --- /dev/null +++ b/tests/semantic/test_ballot_bit_loop.py @@ -0,0 +1,180 @@ +"""A scalar loop over the lanes of a ballot, inside a wave64 loop that ends on a vote (SHADER-WAVE-LOOP-EXEC-VOTE). + +The compiler walks the lanes a ballot found with a scalar loop: `s_and_b64 s[26:27], vcc, exec`, then +`s_ff1_i32_b32` / `s_xor_b32` of s26 and `s_mov_b32 s26, sN` on the back edge, so s26 is a lane mask on the way in and +a number around the loop. The translator keeps a mask as each lane's own bit (0 or ~0) and data as one number, and at +the loop header took s26 as data without gathering the mask's bits: every lane found its own first bit and took its +own number of passes, where the wave takes one (lane_masks.insert_data_merges now gathers them on the way in). + +The program is hand-written in the shape of a library compute program that ran its outer loop to the loop guard +(#1608, SHADER-LIB-LOOP-AT-GUARD): an outer loop over the lanes' work items, 64 apart, that ends when +`v_cmpx_le` + `s_andn2_b64 saved, saved, exec` leaves no lane; inside it, one bit loop over each half of a ballot with a +lane-local `s_cbranch_execz` region. No game data. + + python -I tests/semantic/test_ballot_bit_loop.py +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402 + + +def program(count): + p = [ + f"s_movk_i32 s12, {count}", + "s_mov_b64 s[14:15], exec", + "s_add_u32 s16, s12, 63", # s16 = min(ceil(count / 64), 4) * 64: the passes, at most 4 + "s_lshr_b32 s16, s16, 6", + "s_min_u32 s16, s16, 4", + "s_lshl_b32 s16, s16, 6", + "v_mov_b32_e32 v1, v0", # the lane, kept + "v_mov_b32_e32 v2, 0", # passes of the outer loop + "v_mov_b32_e32 v3, 0", # passes of the bit loops' lane-local regions + "v_cmpx_gt_i32_e32 s16, v0", + "s_cbranch_execz done", + "s_mov_b64 s[18:19], exec", + "s_mov_b64 s[24:25], exec", # the lanes still looping + "s_branch body", + "head:", + "s_mov_b64 exec, s[24:25]", + "body:", + "v_add_nc_u32_e32 v2, 1, v2", + "v_cmpx_gt_u32_e32 s12, v0", # the lanes with an item this pass + "v_and_b32_e32 v4, 1, v0", + "v_cmp_eq_u32_e32 vcc, 0, v4", # ... whose item is even: the ballot + "s_and_b64 s[26:27], vcc, exec", + "s_mov_b64 exec, s[24:25]", + # Lanes 0-31 of the ballot, one pass per lane set; lanes below 16 count them. + "s_cmp_lg_i32 s26, 0", + "s_cbranch_scc0 after_lo", + "lo:", + "s_ff1_i32_b32 s32, s26", + "s_lshl_b32 s32, 1, s32", + "s_xor_b32 s35, s32, s26", + "v_cmp_gt_u32_e32 vcc, 16, v1", + "s_and_b64 exec, vcc, exec", + "s_cbranch_execz skip_lo", + "v_add_nc_u32_e32 v3, 1, v3", + "skip_lo:", + "s_mov_b64 exec, s[24:25]", + "s_cmp_eq_i32 s26, s32", + "s_cbranch_scc1 after_lo", + "s_mov_b32 s26, s35", + "s_branch lo", + "after_lo:", + # Lanes 32-63, the same through s27; lanes above 47 count them in the second byte. + "s_cmp_lg_i32 s27, 0", + "s_cbranch_scc0 after_hi", + "hi:", + "s_ff1_i32_b32 s32, s27", + "s_lshl_b32 s32, 1, s32", + "s_xor_b32 s35, s32, s27", + "v_cmp_lt_u32_e32 vcc, 47, v1", + "s_and_b64 exec, vcc, exec", + "s_cbranch_execz skip_hi", + "v_add_nc_u32_e32 v3, 0x100, v3", + "skip_hi:", + "s_mov_b64 exec, s[24:25]", + "s_cmp_eq_i32 s27, s32", + "s_cbranch_scc1 after_hi", + "s_mov_b32 s27, s35", + "s_branch hi", + "after_hi:", + # The next item 64 on; the loop ends when no lane has one left. + "v_add_nc_u32_e32 v0, 64, v0", + "v_cmpx_le_i32_e32 s16, v0", + "s_andn2_b64 s[24:25], s[24:25], exec", + "s_cbranch_scc1 head", + "s_mov_b64 exec, s[18:19]", + "done:", + "s_mov_b64 exec, s[14:15]", + "v_lshlrev_b32_e32 v6, 3, v1", + "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", + "buffer_store_dword v3, v6, s[0:3], 0 offen offset:4", + "s_endpgm", + ] + return p + + +def expected(count): + """(outer passes, bit-loop visits) per lane, as one wave64 runs it.""" + limit = min((count + 63) >> 6, 4) << 6 + item = {t: t for t in range(64)} + passes = {t: 0 for t in range(64)} + visits = {t: 0 for t in range(64)} + alive = [t for t in range(64) if item[t] < limit] + while alive: + for t in alive: + passes[t] += 1 + ballot = [t for t in alive if item[t] < count and item[t] % 2 == 0] + for _ in [t for t in ballot if t < 32]: + for t in alive: + visits[t] += 1 if t < 16 else 0 + for _ in [t for t in ballot if t >= 32]: + for t in alive: + visits[t] += 0x100 if t > 47 else 0 + for t in alive: + item[t] += 64 + alive = [t for t in alive if item[t] < limit] + return {t: (passes[t], visits[t]) for t in range(64)} + + +def mask_use_program(take_mask): + """A lane mask (even lanes) on one path and a number (lanes 0-15: 0xffff) on the other meet in s[6:7], which then + only goes into EXEC. Taken as data at the merge, each lane's 0 / ~0 on the mask path still gives its own bit + (bit L of a data register for lane L), so no gather is needed and none is inserted.""" + return [ + f"s_mov_b32 s40, {1 if take_mask else 0}", + "s_mov_b64 s[14:15], exec", + "v_mov_b32_e32 v2, 0", + "v_and_b32_e32 v4, 1, v0", + "v_cmp_eq_u32_e32 vcc, 0, v4", + "s_mov_b64 s[6:7], vcc", + "s_cmp_eq_u32 s40, 1", + "s_cbranch_scc1 join", + "s_mov_b32 s6, 0xffff", + "s_mov_b32 s7, 0", + "join:", + "s_and_b64 exec, s[6:7], exec", + "v_mov_b32_e32 v2, 1", + "s_mov_b64 exec, s[14:15]", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", + "s_endpgm", + ] + + +class BallotBitLoop(unittest.TestCase): + def test_a_merged_mask_used_as_a_mask_needs_no_gather(self): + for take_mask in (True, False): + want = {t: int(t % 2 == 0) if take_mask else int(t < 16) for t in range(64)} + for label, emulate, sg in (("native64", False, 64), ("emulate_sg32", True, 32)): + with self.subTest(take_mask=take_mask, mode=label): + spv, _ = _translate_cs(f"cs_merged_mask_{label}_{int(take_mask)}", mask_use_program(take_mask), + threads=64, emulate=emulate) + mem = run_compute_workgroup(spv, 64, sg, push_constants=VSHARP) + for t in range(64): + self.assertEqual(mem.get(4 * t, -1), want[t], f"{label} lane {t}") + + def test_every_lane_walks_the_wave_ballot(self): + configs = [ + ("native64", False, 64, True), + ("emulate_sg32", True, 32, True), + ("emulate_sg32_rounds", True, 32, False), + ] + for count in (100, 200, 7): + want = expected(count) + for label, emulate, sg, structured in configs: + with self.subTest(count=count, mode=label): + spv, _ = _translate_cs(f"cs_ballot_bit_loop_{label}_{count}", program(count), threads=64, + emulate=emulate, structured=structured) + mem = run_compute_workgroup(spv, 64, sg, push_constants=VSHARP) + for t in range(64): + got = (mem.get(8 * t, -1), mem.get(8 * t + 4, -1)) + self.assertEqual(got, want[t], f"{label} count {count} lane {t}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_lane_masks.py b/tests/test_lane_masks.py index d83c1544fc..e5593b36e9 100644 --- a/tests/test_lane_masks.py +++ b/tests/test_lane_masks.py @@ -376,6 +376,81 @@ def test_wave32_vcc_hi_isolation(): assert out_w64 == {} +def test_mask_meets_data_at_a_merge(): + """insert_data_merges: a lane mask that a merge takes as data gets the wave's bits on the way there (the scalar + loop over a ballot's lanes: s_and_b64 s[26:27], vcc, exec, then s_ff1 / s_xor of s26 and s_mov_b32 s26 on the + back edge). Only where every successor takes it as data and one may still read it.""" + branches = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_endpgm"} + + def bit_loop(): + return [ + [ins("v_cmp_eq_u32_e32", sp("vcc"), imm(0), v(4)), ins("s_and_b64", s(26, 2), sp("vcc"), sp("exec")), + ins("s_cmp_lg_i32", s(26), imm(0)), ins("s_cbranch_scc0")], # 0 + [ins("s_ff1_i32_b32", s(32), s(26)), ins("s_lshl_b32", s(32), imm(1), s(32)), # 1: loop header + ins("s_xor_b32", s(35), s(32), s(26)), ins("s_cmp_eq_i32", s(26), s(32)), ins("s_cbranch_scc1")], + [ins("s_mov_b32", s(26), s(35)), ins("s_branch")], # 2: back edge + [ins("s_endpgm")], # 3 + ], [[3, 1], [3, 2], [1], []] + + blocks, succ = bit_loop() + # Before: s26 is a mask where block 0 ends and data at the loop header (a number on the back edge). + assert masks_at_last(blocks, succ, 0) >= {26} + assert 26 not in L.analyse(blocks, succ)[0][id(blocks[1][0])] + assert L.insert_data_merges(blocks, succ, branches) == 1 + marker = blocks[0][-2] + assert marker["op"] == L.TO_DATA and marker["args"][0] == s(26) == marker["args"][1] + assert L.base_op(blocks[0][-1]["op"]) == "s_cbranch_scc0" # before the branch + # The marker itself still sees the mask (it gathers it) and leaves data behind it. + assert 26 in L.analyse(blocks, succ)[0][id(marker)] + assert 26 not in L.analyse(blocks, succ)[0][id(blocks[0][-1])] + # s27 is a mask at the merge too, but nothing reads it again: no gather for it. Running again adds nothing. + assert all(i["args"][0]["r"] != 27 for blk in blocks for i in blk if i["op"] == L.TO_DATA) + assert L.insert_data_merges(blocks, succ, branches) == 0 + + # A merge that is only read as a mask again (written back to EXEC, ANDed with it, a v_cndmask mask) needs no + # gather: this lane's 0 / ~0 already gives bit L there. + def diamond(use): + # 0 branches to a block that writes a mask to s[6:7] and one that writes data; both go on to `use`. + return [[ins("s_cbranch_scc0")], + [ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_branch")], + [ins("s_mov_b64", s(6, 2), s(20, 2))], + [use, ins("s_endpgm")]], [[2, 1], [3], [3], []] + + for use in (ins("s_mov_b64", sp("exec"), s(6, 2)), ins("s_and_b64", s(8, 2), s(6, 2), sp("exec")), + ins("v_cndmask_b32_e64", v(1), imm(0), imm(1), s(6, 2))): + blocks, succ = diamond(use) + assert L.insert_data_merges(blocks, succ, branches) == 0, use["op"] + # ... while a scan of its lane bits does, for the register it scans, also through a copy of it. + for use in ([ins("s_bcnt1_i32_b32", s(8), s(6))], + [ins("s_not_b32", s(9), s(6)), ins("s_ff1_i32_b32", s(8), s(9))]): + blocks, succ = diamond(use[0]) + blocks[3][1:1] = use[1:] + assert L.insert_data_merges(blocks, succ, branches) == 1 + assert [i["args"][0]["r"] for i in blocks[1] if i["op"] == L.TO_DATA] == [6] + assert L.base_op(blocks[1][-1]["op"]) == "s_branch" + assert L.insert_data_merges(blocks, succ, branches) == 0 # idempotent: the marker leaves data + # A 64-bit scan of the whole ballot (s_bcnt1_i32_b64 / s_ff1_i32_b64 of s[6:7]) gathers both halves, so lanes + # 32-63 come from s7. + for scan in ("s_bcnt1_i32_b64", "s_ff1_i32_b64"): + blocks, succ = diamond(ins(scan, s(8), s(6, 2))) + assert L.insert_data_merges(blocks, succ, branches) == 2, scan + assert [i["args"][0]["r"] for i in blocks[1] if i["op"] == L.TO_DATA] == [6, 7], scan + assert L.insert_data_merges(blocks, succ, branches) == 0, scan + # Other number reads are left as they were (the gather is kept to the bit scans the compiler's lane loops use). + blocks, succ = diamond(ins("s_add_u32", s(8), s(6), imm(1))) + assert L.insert_data_merges(blocks, succ, branches) == 0 + + # A successor that still reads the register as a mask keeps this lane's bit: nothing is inserted. + blocks = [[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_cbranch_scc0")], + [ins("s_mov_b64", sp("exec"), s(6, 2)), ins("s_endpgm")]] + assert L.insert_data_merges(blocks, [[1], []], branches) == 0 + # A mask on both paths to a merge is no data merge. + blocks = [[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_cbranch_scc0")], + [ins("s_and_b64", s(6, 2), s(6, 2), sp("vcc"))], + [ins("s_bcnt1_i32_b64", s(8), s(6, 2)), ins("s_endpgm")]] + assert L.insert_data_merges(blocks, [[2, 1], [2], []], branches) == 0 + + if __name__ == "__main__": test_straight_line() test_joins() @@ -387,4 +462,5 @@ def test_wave32_vcc_hi_isolation(): test_writelane_sdwa_dpp_swaps_stores_and_div_scale() test_v_and_or_xnor_bfi_track_vector_masks() test_wave32_vcc_hi_isolation() + test_mask_meets_data_at_a_merge() print("ok") diff --git a/tools/lane_masks.py b/tools/lane_masks.py index 07dddd6703..08f0e83b53 100644 --- a/tools/lane_masks.py +++ b/tools/lane_masks.py @@ -159,6 +159,9 @@ def step(state, ins, wave64=True): op, a = base_op(ins["op"]), ins["args"] if not a or op.startswith(NO_DESTINATION): return + if op == TO_DATA: # the wave's bits of a mask: data, the same in every lane + put(state, a[0], None, wave64) + return if ins.get("vcc_data_pair"): # Gen materializes both scalar words (including a source mask's lane bits). put(state, a[0], None, wave64) @@ -288,6 +291,208 @@ def parked(blocks, masks): return sorted(found) +TO_DATA = "s_mask_to_data_b32" # the translator's own: sD = the real bits of the lane-mask word in sD + + +def _fixpoint(blocks, succ, wave64): + """Each block's state on entry (None where it is not reached), as analyse() works it out.""" + entry = [None] * len(blocks) + if blocks: + entry[0] = {} + work = [0] if blocks else [] + while work: + n = work.pop() + state = dict(entry[n]) + for ins in blocks[n]: + step(state, ins, wave64) + for s in succ[n]: + merged = dict(state) if entry[s] is None else _merge(entry[s], state) + if merged != entry[s]: + entry[s] = merged + work.append(s) + return entry + + +def _merge(a, b): + """A mask on both paths, or a mask on one and 0 / -1 on the other; anything else is data (left out).""" + merged = {} + for r in a.keys() & b.keys(): + a_k, b_k = a[r], b[r] + if a_k == b_k: + merged[r] = a_k + elif a_k == EITHER: + merged[r] = b_k + elif b_k == EITHER: + merged[r] = a_k + else: + merged[r] = MASK + return merged + + +ALL = "all" # an instruction that may read any SGPR (s_movrels / s_movrelsd: the register comes from M0) + + +def _sgprs(x): + if x.get("k") == "sgpr": + return set(range(x["r"], x["r"] + x.get("n", 1))) + if x.get("k") == "slist": + return {r for r in x["r"] if isinstance(r, int)} + return set() + + +def _reads_writes(ins): + """The SGPR numbers `ins` reads and the ones it surely writes (a destination it may leave alone is read too).""" + op, a = base_op(ins["op"]), ins["args"] + if op.startswith(("s_movrels", "s_movreld", "s_swappc", "s_setpc", "s_call", "s_cbranch_g_fork")): + return ALL, set() + if not a: + return set(), set() + if op.startswith(NO_DESTINATION): + reads = set() + for x in a: + if x is not None: + reads |= _sgprs(x) + return reads, set() + reads = set() + for x in a[1:]: + if x is not None: + reads |= _sgprs(x) + # A SOPK read-modify-write, a 16-bit or SDWA/DPP partial write, or a VOP3b carry-out pair: the first operand is + # taken as read too, which only ever keeps a register live. (A compare writes its whole mask in any encoding.) + if op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32") or op.startswith("s_cmov") or "_co_" in op or \ + (ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) and not op.startswith("v_cmp")): + reads |= _sgprs(a[0]) + return reads, set() + return reads, _sgprs(a[0]) + + +def _is_mask_operand(x, masks): + if x is None: + return False + if x.get("k") == "special": + return x.get("t", "").startswith(("exec", "vcc")) + return x.get("k") == "sgpr" and any(x["r"] + i in masks for i in range(x.get("n", 1))) + + +# The scalar ops that read a register as a whole word of lane bits: the first or last set bit, or how many there are. +WORD_SCANS = ("s_ff0_i32_b", "s_ff1_i32_b", "s_bcnt0_i32_b", "s_bcnt1_i32_b", "s_flbit_i32") + + +def _numeric_reads(ins, masks): + """(reads, through) for insert_data_merges: the SGPR numbers `ins` scans as a whole word of lane bits + (WORD_SCANS), which a register taken as data must hold the wave's bits for. `through`: a scalar copy or + bitwise op of data, whose sources count only where its result is scanned in turn (`s_xor_b32 s35, s32, s26` + then `s_mov_b32 s26, s35`). Other reads are left out. As a mask (EXEC, a bitwise op with a mask, v_cndmask) + this lane's 0 / ~0 is exact: the translator takes bit L of a data register there (rdna2spirv's mask_src). + `masks`: the registers holding a mask before `ins` (analyse()).""" + reads, _ = _reads_writes(ins) + if reads is ALL: + return ALL, False + op, a = base_op(ins["op"]), ins["args"] + if not a: + return set(), False + if op.startswith(WORD_SCANS): + return reads, False + if op.startswith(("s_mov_b", "s_not_b") + BITWISE) and a[0].get("k") == "sgpr" and not any(_is_mask_operand(x, masks) for x in a[1:]): + return reads, True + return set(), False + + +def _numeric_live_in(blocks, succ, masks_before): + """The SGPR numbers each block may read as a number before writing them (ALL for every one), following scalar + copies and bitwise ops of data to where their results are read (_numeric_reads).""" + info = [[(_reads_writes(ins)[1], *_numeric_reads(ins, masks_before.get(id(ins), {}))) for ins in blk] + for blk in blocks] + + def through(n, live): + for w, reads, via in reversed(info[n]): + if reads is ALL: + return ALL + needed = not via or bool(w & live) + live = live - w + if needed: + live = live | reads + return live + + live = [set() for _ in blocks] + changed = True + while changed: + changed = False + for n in range(len(blocks) - 1, -1, -1): + if live[n] is ALL: + continue + out = set() + for s in succ[n]: + if live[s] is ALL: + out = ALL + break + out |= live[s] + new = ALL if out is ALL else through(n, out) + if new != live[n]: + live[n] = new + changed = True + return live + + +def insert_data_merges(blocks, succ, branches, wave64=True): + """In place: where an SGPR holds a lane mask at the end of a block but is data where a successor begins (a + mask on one path to it, a number on another), insert a TO_DATA instruction for it before the block's branch. + + The two kinds of value are kept differently: a mask as this lane's bit (all ones or zero), data as the same + number in every lane. Where they meet the register is taken as data, which the path that wrote the mask does + not hold. The compiler makes such a merge when it walks the lanes of a ballot with a scalar loop: + `s_and_b64 s[26:27], vcc, exec`, then s_ff1_i32_b32 / s_xor_b32 of s26 and `s_mov_b32 s26, sN` on the back + edge. The loop's s26 was this lane's 0 / ~0 on the first pass, so each lane found its own first bit and took + its own number of passes, where the wave takes one. TO_DATA gathers the wave's real bits into the register + (rdna2spirv's lane_mask_word), so the loop sees on every path what the hardware has. + + A register is converted only when every successor takes it as data (one that still reads it as a mask keeps + this lane's bit) and some successor may scan its lane bits before writing it (s_ff0 / s_ff1 / s_bcnt0 / + s_bcnt1 / s_flbit, also through scalar copies of it: _numeric_reads). The gather is a cross-lane step (a + barrier round under --wave64-emulate), and most such merges are only ever read as masks again (written back to + EXEC, ANDed with it), where this lane's 0 / ~0 is already exact: the translator takes bit L of a data register + for lane L there (rdna2spirv's mask_src). Other number reads of such a merge (an add, a compare) would need the + gather too; none is known in a shader, and they are left as they were to keep the change to the lane loops. + TO_DATA itself writes data (step), so a second run finds nothing left to insert. + + Under --wave64-emulate the gather is an exchange round that both halves of the wave must join, so it relies on + its block being reached by the whole wave, through scalar (wave-uniform) branches, as the compiler's lane loops + are; wave64_emulate_opt keeps it out of lane-local regions (_MASK_WORD_READERS). + `branches`: the opcodes that end a block. Returns how many instructions were inserted.""" + inserted = 0 + before, _ = analyse(blocks, succ, wave64=wave64) + live = _numeric_live_in(blocks, succ, before) + for _ in range(len(blocks) + 1): # each round only takes masks away, so this ends + entry = _fixpoint(blocks, succ, wave64) + added = 0 + for n, blk in enumerate(blocks): + if entry[n] is None or not succ[n]: + continue + state = dict(entry[n]) + for ins in blk: + step(state, ins, wave64) + regs = [] + for r, k in sorted((r, k) for r, k in state.items() if isinstance(r, int) and k in MASK_KINDS): + if all(entry[s] is not None and r not in entry[s] for s in succ[n]) and \ + any(live[s] is ALL or r in live[s] for s in succ[n]): + regs.append(r) + if not regs: + continue + last = blk[-1] if blk else None + at = len(blk) - 1 if last is not None and (base_op(last["op"]) in branches) else len(blk) + pc = last.get("pc", 0) if last is not None else 0 + for r in regs: + reg = {"k": "sgpr", "r": r, "n": 1} + blk.insert(at, {"op": TO_DATA, "args": [dict(reg), dict(reg)], "mods": [], "pc": pc, "enc": "", + "synthetic": True}) + at += 1 + added += 1 + inserted += added + if not added: + break + return inserted + + def analyse(blocks, succ, *, include_either=False, wave64=True): entry = [None] * len(blocks) # None: not reached yet if blocks: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index a41db7eb75..18f8d6d1a8 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -7556,6 +7556,13 @@ def insn(self, ins): self.x_memory_order(base_op(ins["op"])) self.cur_either = self.lane_either.get(id(ins), ()) try: + if ins["op"] == lane_masks.TO_DATA: + # A lane mask that a merge further on takes as data (lane_masks.insert_data_merges): the + # register gets the wave's real bits, the same number in every lane. + src = ins["args"][1] + val = self.lane_mask_word(src) if self.holds_lane_mask(src) else self.src_u(src) + self.dst(ins["args"][0], val) + return None if ins["op"].endswith("_dpp"): bop = base_op(ins["op"]) if bop in SOPC_CMP32_OPS or bop in SOPC_CMP64_OPS or bop in SOPC_BITCMP_OPS: @@ -18938,6 +18945,8 @@ def target(ins): succ = [list(dict.fromkeys(e)) for e in raw_edges] g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) + # A lane mask that meets data at a merge is turned into the wave's bits on the way there (lane_masks.py). + lane_masks.insert_data_merges(blocks, succ, BRANCHES | {"s_endpgm"}, wave64=g.wave64) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index f8a50e0eb8..90ccca6ee8 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -83,6 +83,7 @@ "s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64", "s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64", "s_flbit_i32_b32", "s_flbit_i32_b64", "s_flbit_i32", + "s_mask_to_data_b32", # lane_masks.TO_DATA: the mask's bits where a merge takes the register as data }) # Mask ops that emit a cross-lane vote in --wave64-emulate when SCC is live.