From 63f668391bbc5ee0c1cc78915d1d72fa6f4991c5 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:42:02 +0200 Subject: [PATCH 1/5] translator: a VALU data read of a lane-mask operand yields the wave's mask word MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — v_mov_b32 of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — materialized each lane's own 0 / ~0 bit. Hardware holds the whole wave's mask word there (tools/crosslane_fuzz.py's op_maskdata model: the uniform word written to the active lanes), so every lane gets the word, the same in each. - src_u materializes the wave mask word (lane_mask_word) for SGPR and EXEC/VCC operands when the instruction's VGPR destination makes the read a data read (mask_read_is_data); SGPR/EXEC/VCC destinations keep this lane's bit, which mask_src readers rely on. Mask-holding VGPRs already store the word, so their reads are plain loads. - mask_src extracts this lane's bit back out of a mask-holding VGPR (_vgpr_mask_lane_bit), half-aware in wave64 via mask_half. - mask_data_src keeps instructions that materialize the word out of EXEC-gated active runs (a subgroup op can't sit inside if (active)). - v_readfirstlane_b32 of a mask VGPR broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated v_mov_b32 — as the word itself into a VGPR destination (VGPR writes are never mask-tracked), or this lane's bit for a mask-tracked SGPR/special one; fixes cs_wavemask lanes 48-63. Found by tools/crosslane_fuzz.py (#293). docs/design.md's whole-wave mask contract updated. Co-Authored-By: Devin --- docs/design.md | 2 +- .../test_lane_masks_vector_bitwise.py | 62 +++++++++- tests/semantic/test_salu64_bitwise_data.py | 6 +- tests/semantic/test_salu_movrels_lane_mask.py | 4 +- tests/semantic/test_scselect_b64_data.py | 4 +- tools/rdna2spirv.py | 110 ++++++++++++++++-- 6 files changed, 168 insertions(+), 20 deletions(-) diff --git a/docs/design.md b/docs/design.md index 8e185c5d65..15f37795e3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -400,7 +400,7 @@ How the generated SPIR-V expects the runtime to work: | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 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`). | +| 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). | | 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_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py index d4adde9a57..579cf7bb81 100644 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ b/tests/semantic/test_lane_masks_vector_bitwise.py @@ -144,6 +144,32 @@ def _bitwise_mask_lines(wave_size): return lines +def _readfirstlane_vgpr_dst_lines(wave_size): + """v_readfirstlane_b32 into a VGPR of a mask-holding VGPR, stored back as data. The + destination is plain data — VGPR writes are never mask-tracked — so every lane must get + the broadcast wave mask word, not this lane's 0 / ~0 bit (the mask word here is the low + word in wave64, which is all v2 holds).""" + is64 = wave_size == 64 + r = { + "exec": "exec" if is64 else "exec_lo", + "mov": "s_mov_b64" if is64 else "s_mov_b32", + "s6": "s[6:7]" if is64 else "s6", + "s8": "s[8:9]" if is64 else "s8", + "s10": "s[10:11]" if is64 else "s10", + } + return [ + f"{r['mov']} {r['exec']}, -1", + "v_and_b32 v1, 1, v0", + f"v_cmp_eq_u32_e64 {r['s6']}, v1, 0", # even lanes + f"v_cmp_lt_u32_e64 {r['s8']}, v0, 10", # lanes < 10 + f"v_cmp_lt_u32_e64 {r['s10']}, v0, 20", # lanes < 20 + "v_and_or_b32 v2, s6, s8, s10", # mask VGPR: (even & <10) | <20 + "v_readfirstlane_b32 v3, v2", # VGPR dst: the broadcast mask word + "v_mul_lo_u32 v14, v0, 36", + "buffer_store_dword v3, v14, s[0:3], 0 offen", + ] + + def _vgpr_stores(spv): """Return mapping `vgpr_idx -> [rhs_expression, ...]` for constant-index `%vgpr` OpStores.""" const_uint = {} @@ -190,11 +216,16 @@ def test_vector_bitwise_masks_under_partial_exec(self): cnt_andor = sum(want_andor) cnt_xnor = sum(want_xnor) cnt_bfi = sum(want_bfi) + # The mask VGPRs hold the whole wave's mask word (a VALU read of a mask operand is a data + # read), stored in every lane by the mask writes; the low word covers lanes 0-31. + word_andor = sum(1 << i for i in range(32) if want_andor[i]) + word_xnor = sum(1 << i for i in range(32) if want_xnor[i]) + word_bfi = sum(1 << i for i in range(32) if want_bfi[i]) for lane in range(self.wave_size): base = lane * 36 - self.assertEqual(mem[base], 0xFFFFFFFF if want_andor[lane] else 0, f"lane {lane} raw and_or") - self.assertEqual(mem[base + 4], 0xFFFFFFFF if want_xnor[lane] else 0, f"lane {lane} raw xnor") - self.assertEqual(mem[base + 8], 0xFFFFFFFF if want_bfi[lane] else 0, f"lane {lane} raw bfi") + self.assertEqual(mem[base], word_andor, f"lane {lane} raw and_or") + self.assertEqual(mem[base + 4], word_xnor, f"lane {lane} raw xnor") + self.assertEqual(mem[base + 8], word_bfi, f"lane {lane} raw bfi") self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, f"lane {lane} cndmask and_or") self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, f"lane {lane} cndmask xnor") self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, f"lane {lane} cndmask bfi") @@ -202,6 +233,17 @@ def test_vector_bitwise_masks_under_partial_exec(self): self.assertEqual(mem[base + 28], cnt_xnor, f"lane {lane} bcnt xnor") self.assertEqual(mem[base + 32], cnt_bfi, f"lane {lane} bcnt bfi") + def test_readfirstlane_mask_vgpr_dst_gets_wave_word(self): + mem = _run_cs( + f"cs_rfl_vgpr_w{self.wave_size}", + _readfirstlane_vgpr_dst_lines(self.wave_size), + wave_size=self.wave_size, + ) + # (even & lane < 10) | lane < 20 -> lanes 0..19 of the low word, the same in every lane. + want = sum(1 << i for i in range(32) if ((i & 1) == 0 and i < 10) or i < 20) + for lane in range(self.wave_size): + self.assertEqual(mem[lane * 36], want, f"lane {lane} readfirstlane dst") + class TestVectorBitwiseMasksWave32(_VectorBitwiseMixin, unittest.TestCase): wave_size = 32 @@ -223,7 +265,9 @@ def test_vector_bitwise_masks_emulate_spirv_structure(self): ) self.assertTrue(gen.wave64 and gen.emulate) self.assertEqual(len(gen.mask_writes), 6) - self.assertNotIn("FindILsb", spv) + # Emulation exchanges through %x_buf instead of subgroup ops; FindILsb (GLSL extinst) is fine — + # the readfirstlane of a mask VGPR now takes the exchange path like any other readfirstlane. + self.assertNotIn("OpGroupNonUniform", spv) self.assertIn("OpControlBarrier", spv) self.assertIn("OpStore %x_it", spv) stores = _vgpr_stores(spv) @@ -234,6 +278,16 @@ def test_vector_bitwise_masks_emulate_spirv_structure(self): for vreg in (4, 7): # v_bfi_b32 -> final OpBitwiseOr self.assertTrue(stores[vreg][-1].startswith("OpBitwiseOr %uint "), stores[vreg][-1]) + def test_readfirstlane_vgpr_dst_emulate_structure(self): + spv, gen = _translate_cs( + "cs_rfl_vgpr_w64_emu", + _readfirstlane_vgpr_dst_lines(64), + wave_size=64, + emulate=True, + ) + self.assertTrue(gen.wave64 and gen.emulate) + self.assertNotIn("OpGroupNonUniform", spv) + class TestVectorBitwiseDataControl(unittest.TestCase): def test_non_mask_data_stays_exec_gated_wave32(self): diff --git a/tests/semantic/test_salu64_bitwise_data.py b/tests/semantic/test_salu64_bitwise_data.py index c8e3f18388..76ca1c8d32 100644 --- a/tests/semantic/test_salu64_bitwise_data.py +++ b/tests/semantic/test_salu64_bitwise_data.py @@ -558,9 +558,11 @@ def test_wave32_all_six_ops_and_scc_vote(self): "v_mov_b32 v3, 0", ] outs, _ = run_ps_wave(lines, wave=32) + # v2 = v_mov_b32 of the mask result s[6:7]: a data read gives the whole wave's mask + # word, the same in every lane, not this lane's 0 / ~0 bit. + want_word = sum(1 << l for l in range(32) if pred(l)) for lane in range(32): - want_bit = MASK32 if pred(lane) else 0 - self.assertEqual(outs[lane], (want_cnt, want_scc, want_bit, 0), f"lane={lane}") + self.assertEqual(outs[lane], (want_cnt, want_scc, want_word, 0), f"lane={lane}") # Empty mask intersection -> SCC=0 across all lanes, and null dst on lane-mask path sets SCC. lines = [ diff --git a/tests/semantic/test_salu_movrels_lane_mask.py b/tests/semantic/test_salu_movrels_lane_mask.py index 15a7916092..71b2136515 100644 --- a/tests/semantic/test_salu_movrels_lane_mask.py +++ b/tests/semantic/test_salu_movrels_lane_mask.py @@ -80,7 +80,9 @@ def test_finding_reproducer(self): with self.subTest(lane=lane): self.assertEqual((d, bits), (5, 2)) self.assertEqual(ctl_bits, 2) - self.assertEqual(ctl_d, 0xFFFFFFFF if lane in (0, 2) else 0) # a copy stays a mask + # The copy stays a mask (ctl_bits), but the VALU read of it is a data read: every lane gets + # the whole wave's mask word 5, not its own 0 / ~0 bit. + self.assertEqual(ctl_d, 5) def test_index_from_m0_hits_mask_and_data_neighbours(self): # s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9. diff --git a/tests/semantic/test_scselect_b64_data.py b/tests/semantic/test_scselect_b64_data.py index 2dd7032b3a..85a631e289 100644 --- a/tests/semantic/test_scselect_b64_data.py +++ b/tests/semantic/test_scselect_b64_data.py @@ -380,10 +380,12 @@ def test_wave32_vcc_exec_and_sgpr_masks(self): ] outs, _ = run_ps_wave(lines, wave=32) want_cnt = 10 if scc else 16 + # v3 = v_mov_b32 of mask SGPR s4: a data read gives the whole wave's mask word, + # the same in every lane, not this lane's 0 / ~0 bit. + want_s4 = sum(1 << l for l in range(32) if ((l < 10) if scc else (l >= 16))) for lane in range(32): in_mask = (lane < 10) if scc else (lane >= 16) want_v1 = 0x55 if (scc == 0 or in_mask) else 0xAA - want_s4 = MASK32 if in_mask else 0 self.assertEqual(outs[lane], (want_cnt, want_v1, scc, want_s4), f"lane={lane}") def test_wave64_vcc_exec_and_sgpr_masks(self): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index bf51eabc61..9b713d0394 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -510,7 +510,18 @@ def imm_val(self, a): def src_u(self, a): k = a["k"] - if k in ("vgpr", "sgpr"): + if ((k == "sgpr" and a.get("n", 1) == 1) or + (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \ + and self.holds_lane_mask(a) and self.mask_read_is_data(): + # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's + # mask word (the same in every lane), as the SOP ops that read a mask as a number already do + # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each + # lane its own bit where hardware gives the mask itself (found by tools/crosslane_fuzz.py). + # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this + # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too — + # mask_src extracts this lane's bit back out when a mask consumer reads one. + v = self.lane_mask_word(a) + elif k in ("vgpr", "sgpr"): if a.get("n", 1) != 1: raise Unsupported("64-bit operand") v = self.load_reg(k, a["r"]) @@ -550,6 +561,26 @@ def src_u(self, a): v = self.sdwa_src(v, a) return self.modify(v, a) + def mask_read_is_data(self): + """Whether the instruction being translated (self.cur_ins) consumes a lane mask as plain data. + A VGPR destination means the mask operand is read as a 32-bit value — the whole wave's mask word, + which is what hardware holds and what the VGPR then stores (a mask that stays in a VGPR keeps the + word too; mask_src extracts this lane's bit back out for mask consumers). Anything else — an SGPR, + EXEC or VCC destination — keeps this lane's 0 / ~0 bit, which mask_src readers rely on.""" + ins = self.cur_ins + if ins is None: + return False + a = ins["args"] + if not a or a[0]["k"] != "vgpr": + return False + if base_op(ins["op"]) == "v_writelane_b32": + # A mask parked in one lane of a VGPR comes back through v_readlane as this lane's bit: the + # parked SGPR slot keeps the per-lane value. + slot = lane_masks.lane_slot(a[0], a[2]) + if slot and slot[1:] in self.parked: + return False + return True + def src_u_sign_mods(self, a): """A 32-bit source with its VOP3 abs/neg applied as sign-bit moves on the raw bits (abs clears bit 31, neg flips it), for an op that only moves bits: SPIR-V FAbs/OpFNegate may quiet a signalling NaN or flush a @@ -1738,13 +1769,37 @@ def lane_local(self, ins): """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as - data is this lane's bit (only s_bcnt1, s_ff1 and v_mbcnt gather the whole wave's); a mask on its way + data gathers the whole wave's mask word (mask_data_src keeps such instructions out of + the run, since the subgroup op can't sit inside `if (active)`); a mask on its way through a VGPR (mask_writes) is written in every lane, so it stays out.""" op = base_op(ins["op"]) a = ins["args"] return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op 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) + and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes + and not self.mask_data_src(ins)) + + def mask_data_src(self, ins): + """Whether ins reads a lane mask as data through src_u (a mask-holding SGPR, or EXEC/VCC), which + materializes the whole wave's mask word with a subgroup op. That can't happen inside an active run + (RUN_FORBIDDEN bars OpGroup there, and inactive lanes wouldn't vote), so lane_local keeps the + instruction out; dst()'s per-write EXEC select gates the VGPR write instead. A mask-holding VGPR is + not listed: it already stores the wave's mask word, so reading it is a plain register load. The mask + state is the one lane_masks.py precomputed for this instruction (self.lane_masks), since lane_local + runs before the instruction is translated.""" + masks = self.lane_masks.get(id(ins)) + if not masks: + return False + for x in ins["args"][1:]: + if x["k"] == "sgpr" and x.get("n", 1) == 1 and x["r"] in masks: + return True + if x["k"] == "special": + t = x.get("t", "") + if t in ("exec_lo", "exec_hi") or \ + (t in ("vcc", "vcc_lo") and "vcc" in masks) or \ + (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks): + return True + return False def insns(self, seq): """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN @@ -6208,6 +6263,12 @@ def mask_half(self, a): return "lo" if k == lane_masks.MASK_HI: return "hi" + if a["k"] == "vgpr" and a.get("n", 1) == 1: + k = self.cur_masks.get(("v", a["r"])) + if k == lane_masks.MASK_LO: + return "lo" + if k == lane_masks.MASK_HI: + return "hi" return None def lane_mask_word(self, a): @@ -6489,6 +6550,23 @@ def _scalar_word_lane_bit(self, word, lane=None): self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r + def _vgpr_mask_lane_bit(self, word, a): + """This lane's 0 / ~0 bit of the lane-mask word `word` held by mask VGPR operand `a`: its own position + of the word — and only when the lane is in the half the register covers (a MASK_LO/MASK_HI word means + nothing to the other half).""" + half = self.mask_half(a) + if half is None: + return self._scalar_word_lane_bit(word) + lane = self.wave_lane() + in_half = self.tmp() + self.emit(f"{in_half} = OpULessThan %bool {lane} {self.cu(32)}" + if half == "lo" else + f"{in_half} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") + bit = self._scalar_word_lane_bit(word, lane) + r = self.tmp() + self.emit(f"{r} = OpSelect %uint {in_half} {bit} {self.cu(0)}") + return r + def mask_src(self, a, wide=True): """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or @@ -6519,6 +6597,8 @@ def mask_src(self, a, wide=True): return self._scalar_word_lane_bit(word, lane) if a["k"] == "special" and a["t"] == "null": return self.cu(0) + if a["k"] == "vgpr" and a.get("n", 1) == 1 and ("v", a["r"]) in self.cur_masks: + return self._vgpr_mask_lane_bit(self.load_reg("vgpr", a["r"]), a) if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: v = self.tmp() self.emit(f"{v} = OpLoad %uint %vcc_hi") @@ -7806,11 +7886,15 @@ def _insn(self, ins): # lane took its own value. That is the same thing only when all lanes hold the value, and after a # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group # of lanes), they loaded from wherever their stale register pointed. - if a[1]["k"] == "vgpr" and ("v", a[1]["r"]) in self.cur_masks: - # A lane mask that went through the vector unit (three SGPRs ORed with v_or3_b32, say). The - # hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit. - self.dst(a[0], self.src_u(a[1])) - return + # A VGPR that holds a lane mask keeps the whole wave's mask word, but only in the lanes a write + # reached: an EXEC-gated v_mov_b32 leaves the other lanes' old word behind (SHADER-21 part 2), so + # this lane's own copy can be a stale half's word. Hardware reads the first active lane's copy — + # the broadcast below. A VGPR destination is never mask-tracked (lane_masks.put ignores VGPR + # writes), so it gets the broadcast word itself, as hardware leaves it; a mask-tracked SGPR or + # special destination gets this lane's bit of that word (_vgpr_mask_lane_bit, half-aware in + # wave64), the per-lane value mask_src readers rely on. + mask_vgpr = (a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1 + and ("v", a[1]["r"]) in self.cur_masks) if self.wave32_fragment: self.uses_subgroup = self.uses_ballot = True v, act = self.src_u(a[1]), self.active_b() @@ -7821,7 +7905,8 @@ def _insn(self, ins): self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") self.g_shuffle(r, v, first) - self.dst(a[0], r) + res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) + self.dst(a[0], res) return if self.emulate: # The wave's active lanes as two mask words and every lane's value, in one round. @@ -7836,7 +7921,9 @@ def _insn(self, ins): 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}") - self.dst(a[0], read(first)) + w = read(first) + res = w if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(w, a[1]) + self.dst(a[0], res) return self.uses_subgroup = self.uses_ballot = self.uses_vote = True v, act = self.src_u(a[1]), self.active_b() @@ -7849,7 +7936,8 @@ def _insn(self, ins): self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") - self.dst(a[0], r) + res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) + self.dst(a[0], res) elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", "image_sample_c_lz_o", "image_sample_c_o", "image_sample_c_b_o", "image_sample_cl_o", "image_sample_b_cl_o", "image_sample_c_cl_o", "image_sample_c_b_cl_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", From 77f23d0588d0ac6bd729325c027900dbe658279d Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:22:09 +0200 Subject: [PATCH 2/5] translator: gate mask-word gathers on EXEC coverage; scalar mask number reads Review fixes for the mask-as-data change: - The wave-mask gather is a group op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote: NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on and produced the EXEC value instead of the frozen mask word (cs_mask_vgpr_exec). mask_word_read_ok now gathers only when a CFG must-analysis (mark_exec_state) proves every lane that can hold a set bit of the mask is EXEC-active at the read: each EXEC half is tracked as clean, a constant mask, or an unknown narrowing (s_mov/s_cselect resolve constants, saved-EXEC aliases and unchanged EXEC, so the common restore idioms still gather), and mask_exec_sigs records every EXEC state seen while each mask register held a mask. Unproven reads keep this lane's 0 / ~0 bit, the pre-change answer. - Scalar number ops read a lane mask operand as data too (MASK_NUMBER_READERS, #1043's NUMBER_READERS): s_add_u32 s20, s10, K after v_cmp wrote s10 yields the wave's mask word, while mask moves and mask logic ops keep this lane's bit for the saveexec idioms. - wave64_emulate_opt treats ins["mask_words"] (a mask read that will gather) as a cross-lane exchange for the lane-local fold planner and barrier scheduler, covering the scalar readers as well. - test_slot67_operand_forms' expectedFailure comes off: the packed vcc_hi word now reaches the data read. Co-Authored-By: Devin --- docs/design.md | 2 +- .../test_lane_masks_vector_bitwise.py | 154 ++++- tests/semantic/test_slot67_operand_forms.py | 4 +- tools/rdna2spirv.py | 563 +++++++++++++++++- tools/wave64_emulate_opt.py | 8 +- 5 files changed, 692 insertions(+), 39 deletions(-) diff --git a/docs/design.md b/docs/design.md index 15f37795e3..327a4fda22 100644 --- a/docs/design.md +++ b/docs/design.md @@ -400,7 +400,7 @@ How the generated SPIR-V expects the runtime to work: | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). | +| 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | | 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_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py index 579cf7bb81..53e6f78252 100644 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ b/tests/semantic/test_lane_masks_vector_bitwise.py @@ -213,25 +213,27 @@ def test_vector_bitwise_masks_under_partial_exec(self): want_andor = [((i & 1 == 0) and i < 10) or (i & 2 == 0) for i in range(self.wave_size)] want_xnor = [(i & 1 == 0) == (i < 10) for i in range(self.wave_size)] want_bfi = [(i < 10) if (i & 1 == 0) else (i & 2 == 0) for i in range(self.wave_size)] - cnt_andor = sum(want_andor) - cnt_xnor = sum(want_xnor) - cnt_bfi = sum(want_bfi) - # The mask VGPRs hold the whole wave's mask word (a VALU read of a mask operand is a data - # read), stored in every lane by the mask writes; the low word covers lanes 0-31. - word_andor = sum(1 << i for i in range(32) if want_andor[i]) - word_xnor = sum(1 << i for i in range(32) if want_xnor[i]) - word_bfi = sum(1 << i for i in range(32) if want_bfi[i]) for lane in range(self.wave_size): base = lane * 36 - self.assertEqual(mem[base], word_andor, f"lane {lane} raw and_or") - self.assertEqual(mem[base + 4], word_xnor, f"lane {lane} raw xnor") - self.assertEqual(mem[base + 8], word_bfi, f"lane {lane} raw bfi") - self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, f"lane {lane} cndmask and_or") - self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, f"lane {lane} cndmask xnor") - self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, f"lane {lane} cndmask bfi") - self.assertEqual(mem[base + 24], cnt_andor, f"lane {lane} bcnt and_or") - self.assertEqual(mem[base + 28], cnt_xnor, f"lane {lane} bcnt xnor") - self.assertEqual(mem[base + 32], cnt_bfi, f"lane {lane} bcnt bfi") + # The mask reads run while EXEC is narrowed to lanes < 10, so the wave-mask gather is + # suppressed (mask_word_read_ok: a group op can't be relied on to see lanes EXEC has + # off — MoltenVK, #1397 review). Each lane's mask operand read keeps its own 0 / ~0 + # bit and the bitwise ops still update every lane, so each lane stores its own bit of + # the composed mask: ~0 where the lane is in it, 0 elsewhere. + self.assertEqual(mem[base], 0xFFFFFFFF if want_andor[lane] else 0, + f"lane {lane} raw and_or") + self.assertEqual(mem[base + 4], 0xFFFFFFFF if want_xnor[lane] else 0, + f"lane {lane} raw xnor") + self.assertEqual(mem[base + 8], 0xFFFFFFFF if want_bfi[lane] else 0, + f"lane {lane} raw bfi") + # readfirstlane broadcasts lane 0's result — ~0 in each case — so every lane takes the + # mask-set arm and bcnt counts the whole wave's bits. + self.assertEqual(mem[base + 12], 20, f"lane {lane} cndmask and_or") + self.assertEqual(mem[base + 16], 40, f"lane {lane} cndmask xnor") + self.assertEqual(mem[base + 20], 60, f"lane {lane} cndmask bfi") + self.assertEqual(mem[base + 24], self.wave_size, f"lane {lane} bcnt and_or") + self.assertEqual(mem[base + 28], self.wave_size, f"lane {lane} bcnt xnor") + self.assertEqual(mem[base + 32], self.wave_size, f"lane {lane} bcnt bfi") def test_readfirstlane_mask_vgpr_dst_gets_wave_word(self): mem = _run_cs( @@ -323,5 +325,123 @@ def test_non_mask_data_stays_exec_gated_wave32(self): self.assertEqual(mem[base + 8], SENTINEL, f"inactive lane {lane} bfi") +class TestScalarMaskNumberReads(unittest.TestCase): + """A scalar ALU op that reads a lane mask as a number gets the wave's mask word, not this + lane's 0 / ~0 bit (MASK_NUMBER_READERS, ported from #1043's NUMBER_READERS). Mask moves and + mask logic ops keep the bit so the saveexec/restore and mask-copy idioms still work.""" + + def _run(self, lines, wave_size=32, emulate=False): + prologue = ["s_mov_b64 exec, -1"] if wave_size == 64 else [] + body = prologue + lines + [ + "v_lshlrev_b32_e32 v9, 2, v0", + "buffer_store_dword v4, v9, s[0:3], 0 offen", + "s_endpgm", + ] + mem = _run_cs("cs_scalar_masknum", body, wave_size=wave_size, emulate=emulate) + return {mem[4 * lane] for lane in range(wave_size) if 4 * lane in mem} + + def test_scalar_add_reads_mask_word(self): + # wave32: mask of lanes < 10 -> word 0x3FF. wave64: mask of lanes < 43 -> the s10 operand + # is the low half, all 32 low lanes set -> 0xFFFFFFFF. The scalar op is uniform: every + # lane's v4 is the same word + 0x1234. + for wave, lanes, dst, word in ((32, 10, "s10", 0x3FF), (64, 43, "s[10:11]", 0xFFFFFFFF)): + with self.subTest(wave=wave): + got = self._run( + [f"v_cmp_gt_u32_e64 {dst}, {lanes}, v0", + "s_add_u32 s20, s10, 0x1234", + "v_mov_b32_e32 v4, s20"], wave_size=wave) + self.assertEqual(got, {(word + 0x1234) & 0xFFFFFFFF}) + + def test_scalar_readers_table(self): + # A representative slice of MASK_NUMBER_READERS on wave32: mask of lanes < 10 -> 0x3FF. + setup = ["v_cmp_gt_u32_e64 s10, 10, v0"] + cases = { + "s_add_u32 s20, s10, 0x1234": (0x3FF + 0x1234) & 0xFFFFFFFF, + "s_sub_u32 s20, s10, 0x1234": (0x3FF - 0x1234) & 0xFFFFFFFF, + "s_mul_i32 s20, s10, 0x1234": (0x3FF * 0x1234) & 0xFFFFFFFF, + "s_lshl_b32 s20, s10, 3": (0x3FF << 3) & 0xFFFFFFFF, + "s_lshr_b32 s20, s10, 3": 0x3FF >> 3, + "s_brev_b32 s20, s10": int(f"{0x3FF:032b}"[::-1], 2), + "s_min_u32 s20, s10, 0x1234": min(0x3FF, 0x1234), + "s_max_u32 s20, s10, 0x1234": max(0x3FF, 0x1234), + } + for op, want in cases.items(): + with self.subTest(op=op): + got = self._run(setup + [op, "v_mov_b32_e32 v4, s20"]) + self.assertEqual(got, {want}) + + def test_mask_copy_keeps_bit_then_scalar_reads_word(self): + # s_mov_b32 is not a number reader: the copy stays a mask (per-lane bit), and the scalar + # add on the copy still gathers the word because lane_masks tracks s11 as a mask. + got = self._run(["v_cmp_gt_u32_e64 s10, 10, v0", "s_mov_b32 s11, s10", + "s_add_u32 s20, s11, 1", "v_mov_b32_e32 v4, s20"]) + self.assertEqual(got, {0x400}) + + def test_exec_as_data_gathers_exec_word(self): + # exec_lo narrowed to lanes < 10 by saveexec: the EXEC operand's own word still gathers — + # lanes off in EXEC contribute 0 either way, so every driver agrees. + got = self._run(["v_cmp_gt_u32_e64 s10, 10, v0", + "s_and_saveexec_b32 s12, s10", + "s_add_u32 s20, exec_lo, 1", + "s_mov_b32 exec_lo, s12", + "v_mov_b32_e32 v4, s20"]) + self.assertEqual(got, {0x3FF + 1}) + + +class TestMaskDataReadExecGate(unittest.TestCase): + """A lane-mask data read gathers the wave's mask word with a group op only while every lane the + word covers is EXEC-active: drivers differ on whether lanes EXEC has off still vote (MoltenVK's + group ops saw only the lanes a narrowed EXEC left on, #1397 review). Otherwise the read keeps + this lane's 0 / ~0 — the pre-#1397 answer — and an EXEC operand's own word still gathers, since + lanes off in EXEC contribute 0 either way.""" + + def _lines(self, tail): + return [ + "v_and_b32 v1, 1, v0", + "v_cmp_eq_u32_e64 vcc_lo, v1, 1", # VCC = odd lanes, 0xAAAAAAAA + f"v_mov_b32_e32 v2, {SENTINEL:#x}", # sentinel: lanes EXEC leaves off keep it + "s_mov_b32 exec_lo, 0x55555555", # EXEC = even lanes + ] + tail + [ + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_endpgm", + ] + + def test_vcc_read_under_narrowed_exec_keeps_lane_bit(self): + lines = self._lines(["v_mov_b32_e32 v2, vcc_lo"]) + spv, _ = _translate_cs("cs_maskdata_narrowed", lines, wave_size=32, emulate=False) + self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_narrowed_run", lines, wave_size=32, emulate=False) + for lane in range(32): + # EXEC-active even lanes store their own VCC bit (0: VCC is the odd lanes); odd lanes + # are off in EXEC — the store doesn't run — which is the per-lane answer, not the + # 0xAAAAAAAA word a gather would have produced. + if lane & 1: + self.assertNotIn(lane * 4, mem, f"lane {lane}") + else: + self.assertEqual(mem[lane * 4], 0, f"lane {lane}") + + def test_vcc_read_after_exec_restore_gathers(self): + lines = self._lines(["s_mov_b32 exec_lo, -1", "v_mov_b32_e32 v2, vcc_lo"]) + spv, _ = _translate_cs("cs_maskdata_restored", lines, wave_size=32, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_restored_run", lines, wave_size=32, emulate=False) + want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, every lane + for lane in range(32): + self.assertEqual(mem[lane * 4], want, f"lane {lane}") + + def test_exec_read_under_narrowed_exec_still_gathers(self): + lines = self._lines(["v_mov_b32_e32 v2, exec_lo"]) + spv, _ = _translate_cs("cs_execdata_narrowed", lines, wave_size=32, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_execdata_narrowed_run", lines, wave_size=32, emulate=False) + for lane in range(32): + # EXEC's word is 0x55555555; only the even lanes EXEC leaves on store it. + if lane & 1: + self.assertNotIn(lane * 4, mem, f"lane {lane}") + else: + self.assertEqual(mem[lane * 4], 0x55555555, f"lane {lane}") + + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_slot67_operand_forms.py b/tests/semantic/test_slot67_operand_forms.py index e54188c714..af99780589 100644 --- a/tests/semantic/test_slot67_operand_forms.py +++ b/tests/semantic/test_slot67_operand_forms.py @@ -20,9 +20,7 @@ def test_wave64_bitreplicate_exec_reenables_lanes_and_keeps_scc(self): # The merge into main kept main's wave32 VCC_HI model (47494e725: VCC_HI that holds a compare result is a # per-lane mask), not this branch's packed-word form (1f001c739). On hardware `s_mov_b32 s8, vcc_hi` copies the - # packed 32-bit word (0x80000004 here); main's translator gives each lane its own mask value instead, so this - # case fails there. Kept as the expectation the translator should meet. - @unittest.expectedFailure + # packed 32-bit word (0x80000004 here); the mask-as-data read gives each lane that word, so this passes. def test_wave32_compare_high_word_preserves_low_and_clears_inactive_bits(self): lines = [ "v_cmp_lt_u32_e64 vcc_lo, v0, 6", diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 9b713d0394..31dae32e17 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -256,6 +256,23 @@ def user_data_dword(stage, sgpr): }) SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) +# Ops that read a lane-mask operand as a plain number even though the destination is not a VGPR +# (the scalar ALU set; the v_* entries already qualify through their VGPR destinations). Ported from +# PR #1043's lane_masks.NUMBER_READERS so scalar readers (s_add_u32 s20, s10, K after v_cmp wrote s10) +# see the wave's mask word, not this lane's 0 / ~0 bit. Mask-preserving ops (s_mov_b32, the MASK_SOP2 +# logic ops, saveexec/wrexec) are deliberately absent: a mask moving or combining as a mask keeps the +# per-lane bit mask_src readers rely on. _sdwa / _dpp / _dpp8 forms are excluded at the check site. +MASK_NUMBER_READERS = frozenset(( + "s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32", "s_mul_i32", + "s_mul_hi_u32", "s_mul_hi_i32", "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_bfe_u32", "s_bfe_i32", + "s_min_u32", "s_min_i32", "s_max_u32", "s_max_i32", "s_brev_b32", + "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_lshlrev_b32", "v_lshrrev_b32", + "v_ashrrev_i32", "v_mul_lo_u32", "v_mul_hi_u32", "v_min_u32", "v_max_u32", "v_min_i32", + "v_max_i32", "v_bfe_u32", "v_bfe_i32", "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", + "v_bcnt_u32_b32", +)) + # Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). # VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or # other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). @@ -350,6 +367,10 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) + self.exec_state_at = {} # id(instruction) -> ((lo clean, lo tag), (hi clean, hi tag)) + self.mask_exec_sigs = {} # mask register -> [(blk, pos, EXEC sig)] while it held a mask + self.ins_pos = {} # id(instruction) -> (block, position) + self.exec_reach = [] # block -> bitmask of blocks reachable in >= 1 step self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative) self.cur_masks = {} self.vcc_scalar_pointer = False @@ -512,7 +533,8 @@ def src_u(self, a): k = a["k"] if ((k == "sgpr" and a.get("n", 1) == 1) or (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \ - and self.holds_lane_mask(a) and self.mask_read_is_data(): + and self.holds_lane_mask(a) and self.mask_read_is_data() \ + and self.mask_word_read_ok(a, self.cur_ins): # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's # mask word (the same in every lane), as the SOP ops that read a mask as a number already do # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each @@ -520,6 +542,10 @@ def src_u(self, a): # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too — # mask_src extracts this lane's bit back out when a mask consumer reads one. + # mask_word_read_ok keeps the gather for the cases every driver answers the same: lanes + # EXEC has off may not vote in a group op (MoltenVK's did not, #1397 review), so a VCC or + # mask-SGPR word is only gathered while its lanes are all EXEC-active; an EXEC operand's + # word is the current EXEC itself and gathers correctly either way. v = self.lane_mask_word(a) elif k in ("vgpr", "sgpr"): if a.get("n", 1) != 1: @@ -561,17 +587,24 @@ def src_u(self, a): v = self.sdwa_src(v, a) return self.modify(v, a) - def mask_read_is_data(self): - """Whether the instruction being translated (self.cur_ins) consumes a lane mask as plain data. + def mask_read_is_data(self, ins=None): + """Whether the instruction being translated (self.cur_ins, or `ins`) consumes a lane mask as plain data. A VGPR destination means the mask operand is read as a 32-bit value — the whole wave's mask word, which is what hardware holds and what the VGPR then stores (a mask that stays in a VGPR keeps the word too; mask_src extracts this lane's bit back out for mask consumers). Anything else — an SGPR, EXEC or VCC destination — keeps this lane's 0 / ~0 bit, which mask_src readers rely on.""" - ins = self.cur_ins + ins = self.cur_ins if ins is None else ins if ins is None: return False a = ins["args"] - if not a or a[0]["k"] != "vgpr": + if not a: + return False + if base_op(ins["op"]) in MASK_NUMBER_READERS and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")): + # A scalar (or plain vector) number op reads the mask operand as data even with an SGPR + # destination: s_add_u32 s20, s10, K wants the wave's mask word in s20 (#1043's + # NUMBER_READERS). Mask moves and mask logic ops are not listed, so they keep the bit. + return True + if a[0]["k"] != "vgpr": return False if base_op(ins["op"]) == "v_writelane_b32": # A mask parked in one lane of a VGPR comes back through v_readlane as this lane's bit: the @@ -1787,19 +1820,504 @@ def mask_data_src(self, ins): not listed: it already stores the wave's mask word, so reading it is a plain register load. The mask state is the one lane_masks.py precomputed for this instruction (self.lane_masks), since lane_local runs before the instruction is translated.""" - masks = self.lane_masks.get(id(ins)) - if not masks: + masks = self.lane_masks.get(id(ins)) or {} + return any(self._mask_data_operand(x, masks, ins) for x in ins["args"][1:]) + + def _mask_data_operand(self, x, masks, ins): + """Whether src_u will materialize operand `x`'s lane mask as the wave's mask word for `ins` + (a subgroup op or, under --wave64-emulate, an exchange round): `masks` is the lane_masks state + for ins — self.lane_masks[id(ins)], the same dict self.cur_masks holds while translating.""" + if x["k"] == "sgpr": + if x.get("n", 1) != 1 or x["r"] not in masks: + return False + elif x["k"] == "special": + t = x.get("t", "") + if not (t in ("exec_lo", "exec_hi") or + (t in ("vcc", "vcc_lo") and "vcc" in masks) or + (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks)): + return False + else: return False - for x in ins["args"][1:]: - if x["k"] == "sgpr" and x.get("n", 1) == 1 and x["r"] in masks: - return True - if x["k"] == "special": - t = x.get("t", "") - if t in ("exec_lo", "exec_hi") or \ - (t in ("vcc", "vcc_lo") and "vcc" in masks) or \ - (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks): - return True - return False + return self.mask_read_is_data(ins) and self.mask_word_read_ok(x, ins, masks) + + def mask_operand_halves(self, a, masks=None): + """The EXEC halves ('lo' = lanes 0-31, 'hi' = lanes 32-63) that must be all-ones for a wave_mask + gather of operand `a` to see every lane the operand's word covers; empty for an EXEC operand — + its word IS the current EXEC, so lanes off in it contribute 0 whether they vote or not — and + None when `a` is not a lane-mask operand at all. `masks` is the lane_masks state for an SGPR + operand's half (self.cur_masks while translating, the per-instruction state while planning).""" + if self.emulate: + return frozenset() # the exchange round sees every lane whatever EXEC says + if a["k"] == "special": + t = a.get("t", "") + if t.startswith("exec"): + return frozenset() + if t in ("exec_hi", "vcc_hi"): + return frozenset(("hi",)) if self.wave64 else frozenset(("lo",)) + return frozenset(("lo",)) # vcc / vcc_lo: the b32 data read yields the low word + if a["k"] == "sgpr" and a.get("n", 1) == 1: + state = self.cur_masks if masks is None else masks + if self.wave64 and state.get(a["r"]) == lane_masks.MASK_HI: + return frozenset(("hi",)) + return frozenset(("lo",)) + return None + + def mask_word_read_ok(self, a, ins, masks=None): + """Whether a data read of lane-mask operand `a` in `ins` may gather the wave's mask word. + The gather is a group op over the lanes EXEC leaves active: drivers differ on whether lanes + EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, + MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on and produced the EXEC + value instead of the frozen mask word (#1397 review, cs_mask_vgpr_exec). A gather is exact + whenever every lane that can hold a set bit of the mask is EXEC-active, so the read is + allowed while EXEC's needed half is provably all-ones, and otherwise only when the mask was + a mask exclusively under this same EXEC narrowing (mask_exec_sigs: every EXEC state seen + while the register held a mask is this one, so no lane outside it can hold a bit). Where + neither holds, src_u keeps this lane's 0 / ~0, the pre-#1397 answer. An EXEC operand needs + no such guarantee (its off lanes contribute 0 either way) and --wave64-emulate exchanges + through workgroup memory, which every lane runs.""" + halves = self.mask_operand_halves(a, masks) + if halves is None: + return False + if not halves: + return True + st = self.exec_state_at.get(id(ins)) + if st is None: + return self.exec_static_true + key = self._mask_sig_key(a) + sigs = self.mask_exec_sigs.get(key) + if not sigs: + return False + pos = self.ins_pos.get(id(ins)) + bi, pi = pos if pos is not None else (0, 0) + reach_bi = 1 << bi + self_loop = bool(self.exec_reach[bi] & reach_bi) + for h in halves: + i = 0 if h == "lo" else 1 + rstate = st[i] + if rstate[0] == "c": + continue + for bj, pj, sig in sigs: + # Only signatures whose instruction can reach this read constrain the value: + # same block needs an earlier position (or a loop back-edge), another block must + # reach this one in the CFG. + if bj == bi: + if not (pj < pi or self_loop): + continue + elif not (self.exec_reach[bj] & reach_bi): + continue + if not self._exec_covers(sig[i], rstate): + return False + return True + + @staticmethod + def _exec_covers(w, r): + """Whether every lane EXEC-active under half-state `w` is also active under `r` — the + condition for a mask written under `w` to have all its set bits visible to a group op + running under `r`. Half-states: ("c",) all lanes, ("k", v) the constant mask v, ("n", tag) + an unknown narrowing identified by the instruction that made it (None never matches).""" + if w[0] == "n" and w[1] is None: + return False # an unknown narrowing never provably covers anything + if w == r: + return True + if w[0] == "c": + return r[0] == "c" + if w[0] == "k": + return r[0] == "k" and (w[1] & ~r[1] & 0xFFFFFFFF) == 0 + return r[0] == "n" and r[1] is not None and w[1] == r[1] + + def _mask_sig_key(self, a): + """The lane_masks state key a mask operand's writes are recorded under (mask_exec_sigs).""" + if a["k"] == "sgpr": + return a["r"] + t = a.get("t", "") + if t in ("vcc", "vcc_lo") or (t == "vcc_hi" and self.wave64): + return "vcc" + if t == "vcc_hi": + return "vcc_hi" + return None + + @staticmethod + def _ex_const(v): + """A constant EXEC half-state: all-ones folds to clean.""" + v &= 0xFFFFFFFF + return ("c",) if v == 0xFFFFFFFF else ("k", v) + + # Scalar ops that provably leave SCC alone (branches and stores read or ignore it; s_mov and + # the non-ALU scalar ops never write it). Anything else starting with "s_" may write SCC and + # resets the tracked value — losing precision is safe, keeping a stale one is not. + _SCC_KEEPS = frozenset(( + "s_mov_b32", "s_mov_b64", "s_movrelsd_2_b32", "s_movreld_b32", "s_movreld_b64", + "s_nop", "s_endpgm", "s_waitcnt", "s_barrier", "s_sleep", "s_branch", "s_cbranch", + "s_cbranch_execz", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", + "s_cbranch_vccnz", "s_set", "s_setpc_b64", "s_getpc_b64", + "s_get_waveid_in_workgroup", "s_sendmsg", "s_dcache_inv", "s_dcache_wb", + "s_dcache_inv_vol", "s_icache_inv", "s_trap", "s_rfe", "s_memtime", + "s_memrealtime", + )) + _SCC_KEEP_PREFIXES = ("s_store", "s_buffer_store", "s_wait", "s_branch", "s_cbranch", + "s_sendmsg", "s_dcache", "s_icache", "s_getpc", "s_setpc") + + def _const_of(self, a, sconst, ex): + """The constant 32-bit value of a scalar operand, or None. EXEC halves resolve through + the tracked EXEC state so `s_cmp s, exec_lo`-style compares can fold too.""" + if a["k"] == "imm": + return a.get("v", 0) & 0xFFFFFFFF + if a["k"] == "sgpr": + return sconst.get(a["r"]) if a.get("n", 1) == 1 else None + if a["k"] == "special": + t = a.get("t", "") + h = ex[0] if t == "exec_lo" else ex[1] if t == "exec_hi" else None + if h is not None: + return 0xFFFFFFFF if h[0] == "c" else h[1] if h[0] == "k" else None + if t == "null": + return 0 + return None + + def _cmp_scc(self, op, ins, sconst, ex): + """Fold a compare's SCC when both sources are constant; None when they are not (or the + predicate/width is outside the implemented set — safe under-approximation).""" + if op.startswith("s_bitcmp"): + return None + name = op + for p in ("s_cmpk_", "s_cmp_"): + if name.startswith(p): + name = name[len(p):] + break + else: + return None + a = ins["args"] + if len(a) < 2: + return None + x = self._const_of(a[-2], sconst, ex) + y = self._const_of(a[-1], sconst, ex) + if x is None or y is None: + return None + for sep in ("_u32", "_i32", "_u64", "_i64"): + if name.endswith(sep): + pred, ty = name[: -len(sep)], sep + break + else: + return None + if ty != "_u32" and ty != "_i32": + return None + sx = x - 0x100000000 if ty == "_i32" and x & 0x80000000 else x + sy = y - 0x100000000 if ty == "_i32" and y & 0x80000000 else y + if pred == "eq": + r = sx == sy + elif pred == "ne" or pred == "lg": + r = sx != sy + elif pred == "lt": + r = sx < sy + elif pred == "le": + r = sx <= sy + elif pred == "gt": + r = sx > sy + elif pred == "ge": + r = sx >= sy + else: + return None + return int(r) + + def _scc_step(self, scc, ins, sconst, ex): + op = base_op(ins["op"]) + if not op.startswith("s_"): + return scc + if "cmp" in op or "bitcmp" in op: + return self._cmp_scc(op, ins, sconst, ex) + if op in self._SCC_KEEPS or op.startswith(self._SCC_KEEP_PREFIXES): + return scc + return None + + def _mov_sgpr_vals(self, src, regs, ex, alias, sconst): + """Values a scalar s_mov writes into dst regs: int = constant, ("al", halves) = the + register now aliases an EXEC half-state (a saved EXEC), None = unknown.""" + out = [] + if src is None: + return [None] * len(regs) + if src["k"] == "imm": + v = src.get("v", 0) + if len(regs) == 2: + return [v & 0xFFFFFFFF, (v >> 32) & 0xFFFFFFFF] + return [v & 0xFFFFFFFF] + if src["k"] == "sgpr": + n = src.get("n", 1) + for i, d in enumerate(regs): + s = src["r"] + i if n == 2 else src["r"] + if s in sconst: + out.append(sconst[s]) + elif s in alias: + out.append(("al", alias[s])) + else: + out.append(None) + return out + if src["k"] == "special": + t = src.get("t", "") + vals = [] + for i in range(len(regs)): + h = ex[0] if (t == "exec_lo" or (t == "exec" and i == 0)) else \ + ex[1] if (t == "exec_hi" or (t == "exec" and i == 1)) else None + if h is None: + vals.append(None) + elif h[0] == "c": + vals.append(0xFFFFFFFF) + elif h[0] == "k": + vals.append(h[1]) + else: + vals.append(None) + return vals + return [None] * len(regs) + + def _exec_src_ex(self, src, h, ex, alias, sconst, ins, wide): + """EXEC half-state a scalar source gives EXEC half `h` when moved in.""" + i = 0 if h == "lo" else 1 + if src["k"] == "imm": + v = src.get("v", 0) + if wide: + v = (v >> (32 * i)) & 0xFFFFFFFF + return self._ex_const(v & 0xFFFFFFFF) + if src["k"] == "sgpr": + n = src.get("n", 1) + r = src["r"] + i if wide and n == 2 else src["r"] + if r in sconst: + return self._ex_const(sconst[r]) + al = alias.get(r) + if al is not None and al[i] is not None: + return al[i] + return ("n", id(ins)) + if src["k"] == "special": + t = src.get("t", "") + if t == "exec_lo": + return ex[0] + if t == "exec_hi": + return ex[1] + if t == "exec": + return ex[i] + return ("n", id(ins)) + + def _exec_write(self, ex, ins, alias, sconst, scc): + """EXEC pair after an EXEC-writing instruction. s_mov resolves its source — a constant + gives a constant half-state, a register that aliases a saved EXEC restores that state, + anything else starts a fresh unknown narrowing. s_cselect with a known SCC resolves to + its chosen source the same way (the `exec, -1, exec` restore idiom). Every other EXEC + write narrows (or changes) EXEC in a way we cannot name, so the affected halves get + this instruction's tag.""" + op, a = base_op(ins["op"]), ins["args"] + lo, hi = ex + + def halves_of(t): + if t == "exec_hi": + return ("hi",) + if t == "exec_lo": + return ("lo",) + return ("lo", "hi") if self.wave64 else ("lo",) + + dsts = [] + if a and a[0]["k"] == "special" and a[0].get("t", "").startswith("exec"): + dsts.append(a[0]) + if op in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "special" \ + and a[1].get("t", "").startswith("exec"): + dsts.append(a[1]) + if op in ("s_mov_b32", "s_mov_b64") and dsts and len(a) >= 2: + src = a[1] + wide = op.endswith("b64") + elif op in ("s_cselect_b32", "s_cselect_b64") and dsts and len(a) >= 3 \ + and scc is not None: + src = a[1] if scc else a[2] # D = SCC ? src0 : src1 + wide = op.endswith("b64") + else: + src = None + if src is not None: + for d in dsts: + for h in halves_of(d["t"]): + v = self._exec_src_ex(src, h, ex, alias, sconst, ins, wide) + if h == "lo": + lo = v + else: + hi = v + return lo, hi + if dsts: + affected = set(h for d in dsts for h in halves_of(d["t"])) + elif self.wave64 and op.endswith("_b32"): + affected = {"lo"} # the _b32 saveexec/wrexec forms touch EXEC_LO only + else: + affected = {"lo", "hi"} if self.wave64 else {"lo"} + tag = ("n", id(ins)) + return (tag if "lo" in affected else lo, + tag if "hi" in affected else hi) + + def _exec_step(self, st, ins): + """One instruction's effect on the analysis state (ex, alias, sconst, scc): + ex = (lo, hi) EXEC half-states, ("c",) clean / ("k", v) constant / ("n", tag) unknown + narrowing; alias = {sgpr: (loEX|None, hiEX|None)} registers holding a saved EXEC value; + sconst = {sgpr: constant}; scc = 0/1/None.""" + ex, alias, sconst, scc = st + op, a = base_op(ins["op"]), ins["args"] + alias = dict(alias) + sconst = dict(sconst) + pre_ex = ex + + # Scalar destination bookkeeping: constants and saved-EXEC aliases, invalidated by any + # other write to the register. + if op in ("s_mov_b32", "s_mov_b64") and a and a[0]["k"] == "sgpr" and len(a) >= 2: + d = a[0] + regs = list(range(d["r"], d["r"] + d.get("n", 1))) + vals = self._mov_sgpr_vals(a[1], regs, ex, alias, sconst) + for r, v in zip(regs, vals): + if v is None: + sconst.pop(r, None) + alias.pop(r, None) + elif isinstance(v, tuple): + alias[r] = v[1] + sconst.pop(r, None) + else: + sconst[r] = v + alias.pop(r, None) + else: + dsts = [] + if a and a[0]["k"] == "sgpr": + dsts.append(a[0]) + if op in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "sgpr": + dsts.append(a[1]) + for d in dsts: + for r in range(d["r"], d["r"] + d.get("n", 1)): + sconst.pop(r, None) + alias.pop(r, None) + + # saveexec/wrexec write their destination the EXEC value from *before* this instruction. + if ("saveexec" in op or "wrexec" in op) and a and a[0]["k"] == "sgpr": + d = a[0] + pair = (pre_ex[0], None) if self.wave64 and op.endswith("_b32") else pre_ex + for i, r in enumerate(range(d["r"], d["r"] + d.get("n", 1))): + alias[r] = (pair[0], None) if i == 0 else (None, pair[1]) + sconst.pop(r, None) + + if writes_exec(ins): + ex = self._exec_write(ex, ins, alias, sconst, scc) + scc = self._scc_step(scc, ins, sconst, ex) + return ex, alias, sconst, scc + + @staticmethod + def _ex_merge(x, y): + """Meet of two EXEC half-states: equal states merge to themselves; an identical + narrowing tag on both sides survives; anything else is an unknown narrowing.""" + if x == y: + return x + if x[0] == "n" and y[0] == "n" and x[1] is not None and x[1] == y[1]: + return x + return ("n", None) + + def _state_merge(self, a, b): + """Meet of two analysis states at a control-flow join: EXEC halves meet pairwise, + register facts survive only where both sides agree, SCC survives only when equal.""" + ex = (self._ex_merge(a[0][0], b[0][0]), self._ex_merge(a[0][1], b[0][1])) + alias = {r: v for r, v in a[1].items() if b[1].get(r) == v} + sconst = {r: v for r, v in a[2].items() if b[2].get(r) == v} + scc = a[3] if a[3] == b[3] else None + return ex, alias, sconst, scc + + def mark_exec_state(self, blocks, succ): + """self.exec_state_at[id(ins)] = (lo, hi) EXEC half-states just before ins, from a + must-analysis over the CFG — a block's entry state is the meet of its predecessors' + exits and _exec_step walks each block in order. mask_exec_sigs then records, for every + register lane_masks knows holds a mask, every EXEC state seen while it did: a mask's + set bits can only sit on lanes EXEC left active at its writes, so a gather is exact + only when every such signature's lanes are covered by the read's EXEC — see + mask_word_read_ok and _exec_covers.""" + n_blocks = len(blocks) + entry = [None] * n_blocks + out = [None] * n_blocks + clean = ("c",) + top = ((clean, clean), {}, {}, None) + entry[0] = top + work = [0] + queued = {0} + while work: + n = work.pop() + queued.discard(n) + st = entry[n] + for ins in blocks[n]: + st = self._exec_step(st, ins) + if out[n] == st: + continue + out[n] = st + for s in succ[n]: + if not (0 <= s < n_blocks): + continue + e = entry[s] + merged = st if e is None else self._state_merge(e, st) + if e is None or merged != e: + entry[s] = merged + if s not in queued: + work.append(s) + queued.add(s) + self.exec_state_at = {} + self.ins_pos = {} + for n, blk in enumerate(blocks): + st = entry[n] if entry[n] is not None else top + for p, ins in enumerate(blk): + self.exec_state_at[id(ins)] = st[0] + self.ins_pos[id(ins)] = (n, p) + st = self._exec_step(st, ins) + # exec_reach[b] = bitmask of blocks reachable from b in one or more steps; a set bit on b + # itself means b loops back to its top. + self.exec_reach = [0] * n_blocks + for b in range(n_blocks): + seen = 0 + stack = [s for s in succ[b] if 0 <= s < n_blocks] + while stack: + s = stack.pop() + if seen >> s & 1: + continue + seen |= 1 << s + stack.extend(t for t in succ[s] if 0 <= t < n_blocks) + self.exec_reach[b] = seen + # mask_exec_sigs[reg] = [(blk, pos, exec sig), ...]: every EXEC state seen at an + # instruction where lane_masks says the register holds a mask. A mask's set bits can only + # sit on lanes EXEC left active when they were written, so a gather under EXEC state T is + # exact only when every such signature that can reach the read agrees on T for the half + # the operand covers — see mask_word_read_ok. Signatures are recorded at the pre-state of + # each instruction; an instruction that itself writes EXEC (s_and_saveexec's saved mask, + # v_cmpx) produced its mask dst under the *pre-write* EXEC, so that state is added too. + self.mask_exec_sigs = {} + for n, blk in enumerate(blocks): + prev_exec_write = False + prev_sig = None + for p, ins in enumerate(blk): + sig = self.exec_state_at[id(ins)] + extra = prev_sig if prev_exec_write else None + prev_exec_write = writes_exec(ins) + prev_sig = sig + regs = self.lane_masks.get(id(ins)) + if not regs: + continue + for r in regs: + lst = self.mask_exec_sigs.setdefault(r, []) + if not lst or lst[-1][0] != n or lst[-1][2] != sig: + lst.append((n, p, sig)) + if extra is not None and (not lst or lst[-1][2] != extra): + lst.append((n, p, extra)) + # Block boundaries: a mask dst of a predecessor's last EXEC-writing instruction was + # produced under that instruction's pre-state EXEC; add it for the masks live at entry. + preds = [[] for _ in range(n_blocks)] + for b in range(n_blocks): + for s in succ[b]: + if 0 <= s < n_blocks: + preds[s].append(b) + for n, blk in enumerate(blocks): + if not blk: + continue + extras = [] + for p in preds[n]: + pblk = blocks[p] + if pblk and writes_exec(pblk[-1]): + extras.append(self.exec_state_at[id(pblk[-1])]) + if not extras: + continue + for r in self.lane_masks.get(id(blk[0]), {}): + lst = self.mask_exec_sigs.setdefault(r, []) + for e in extras: + if not lst or lst[-1][2] != e: + lst.append((n, 0, e)) def insns(self, seq): """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN @@ -6245,6 +6763,17 @@ def park_masks(self, blocks): self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} slots = lane_masks.parked(blocks[0], self.lane_masks) self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} + self.mark_exec_state(blocks[0], blocks[1]) + # Instructions whose lane-mask data read will gather the wave's mask word (src_u's + # lane_mask_word path, gated by mask_word_read_ok) are cross-lane exchanges for the + # wave64-emulation planner: it must not fold them into a lane-local region or schedule + # a barrier beside them (wave64_emulate_opt checks ins["mask_words"]). + for blk in blocks[0]: + for ins in blk: + words = tuple(i for i, x in enumerate(ins["args"]) + if i and self._mask_data_operand(x, self.lane_masks.get(id(ins), {}), ins)) + if words: + ins["mask_words"] = words def mask_half(self, a): """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 1ff464fd15..693bc5c7e7 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -923,6 +923,9 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes): if sacc[1]: mem_w = True + if ins.get("mask_words"): # a lane mask read as a number (rdna2spirv._mask_data_operand) + return False, _EMPTY_MEM_STATS, 0, (), () + # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). a = ins["args"] mask_chk = m[11] @@ -1229,6 +1232,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr if sacc[1]: mem_w = True + if ins.get("mask_words"): + clean = False + continue a = ins["args"] mask_chk = m[11] if mask_chk: @@ -1470,7 +1476,7 @@ def _insn_may_barrier_with_meta(ins, meta, lane_masks, scc_live): if meta[1]: return False flags = meta[8] - if flags & _FLAG_ALWAYS_BARRIER or _vcc_pair_collects_mask(ins, lane_masks): + if flags & _FLAG_ALWAYS_BARRIER or ins.get("mask_words") or _vcc_pair_collects_mask(ins, lane_masks): return True mask_chk = meta[11] if not mask_chk: From b83f9d29cac22070abcdd9c0e84dd0fffbe60a3b Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:55:28 +0200 Subject: [PATCH 3/5] translator: s_mov copies of EXEC keep the narrowing's tag through SGPR round-trips MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on the mask-word gather gate (#1397): `s_mov_b32 s4, exec_lo` under an unknown EXEC narrowing recorded nothing for s4, so the later `s_mov_b32 exec_lo, s4` restore minted a fresh ("n", id) tag in _exec_src_ex. mask_exec_sigs coverage then failed and the read kept this lane's 0 / ~0 bit, while the equivalent literal `s_mov_b32 exec_lo, -1` resolved to a constant half-state and gathered — register and literal restores of the same runtime value disagreed. _mov_sgpr_vals now returns an ("al", halves) alias for an EXEC source whose half-state is an unknown narrowing, the same scheme saveexec uses: exec_lo gives (state, None), exec_hi (None, state), exec gives each half in its own register for b64 moves. _exec_src_ex already resolves those aliases, so the restore reproduces the original tag and the gather stays exact; untracked SGPR sources still mint a fresh narrowing and stay conservative. Tests: two semantic cases (wave32 and wave64) assert the register round-trip gathers OpGroupNonUniformBitwiseOr identically to the literal -1 restore; cs_exec_copy.asm (+ fixture, check.py/run_gpu_tests.py dump entries) stores the mask word, exec_lo's own word and the literal-restore word side by side on real hardware — PASS on RTX 4070 and Radeon (64-wide), wave64 exec filters 9/9 on AMD. Co-Authored-By: Devin --- docs/design.md | 2 +- runtime/test/shaders/check.py | 10 ++-- runtime/test/shaders/cs_exec_copy.asm | 40 +++++++++++++++ scripts/run_gpu_tests.py | 10 ++-- tests/semantic/fixtures/disasm/cs_exec_copy.s | 26 ++++++++++ .../test_lane_masks_vector_bitwise.py | 50 +++++++++++++++++++ tools/rdna2spirv.py | 14 ++++-- 7 files changed, 142 insertions(+), 10 deletions(-) create mode 100644 runtime/test/shaders/cs_exec_copy.asm create mode 100644 tests/semantic/fixtures/disasm/cs_exec_copy.s diff --git a/docs/design.md b/docs/design.md index 327a4fda22..afdf87950b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -400,7 +400,7 @@ How the generated SPIR-V expects the runtime to work: | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | +| 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations or an `s_mov` copy of `exec`/`exec_lo`/`exec_hi`, which carries the narrowing's tag so an `s_mov_b32 exec_lo, sD` restore keeps it), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | | 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/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 39a3179a46..e230b7b537 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -110,7 +110,7 @@ def not_found_message(build, missing): "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "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_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", - "cs_w32_exec_computed") + "cs_w32_exec_computed", "cs_exec_copy") # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is # narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with # 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may @@ -118,7 +118,7 @@ def not_found_message(build, missing): WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "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_permlane_fi", - "cs_w32_exec_computed") + "cs_w32_exec_computed", "cs_exec_copy") CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), @@ -210,7 +210,11 @@ def not_found_message(build, missing): ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]), # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR) ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF])] + 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF]), + # EXEC restored through an SGPR copy keeps the narrowing's identity: the mask word still + # gathers (cs_exec_copy.asm header); out[1] is exec_lo's own word, 0xFFFFFFFF + ("cs_exec_copy", [0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 0, + 0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 1])] # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. # The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. # Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. diff --git a/runtime/test/shaders/cs_exec_copy.asm b/runtime/test/shaders/cs_exec_copy.asm new file mode 100644 index 0000000000..8fb72dfa60 --- /dev/null +++ b/runtime/test/shaders/cs_exec_copy.asm @@ -0,0 +1,40 @@ +; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm +; EXEC restored through an SGPR copy keeps the narrowing's identity (mask-regs EXEC tracking, #1397 review): +; s7 = 0xffffffff comes from v_readfirstlane_b32, so the translator can't fold it; s_mov_b32 exec_lo, s7 is an +; EXEC write the analysis can only name as an unknown narrowing. s8 = the odd-lane mask is written under it, +; s4 = exec_lo / exec_lo = s4 round-trips EXEC through an SGPR unchanged, and the mask-word read must still +; gather — lanes return the wave's mask word, not this lane's 0 / ~0 bit, exactly as s_mov_b32 exec_lo, -1 gives. +; Before the fix the copy lost the narrowing's tag, the restore minted a fresh one, mask_exec_sigs coverage +; failed and every lane stored its own bit (0 or ~0) instead of 0xAAAAAAAA. +; Per lane (stride 16 bytes): out[0] = s8's mask word after the SGPR round-trip (0xAAAAAAAA), +; out[1] = exec_lo's word (0xFFFFFFFF: EXEC really is all-ones), out[2] = the same mask word after the +; literal -1 restore, out[3] = the lane id. +; Lane 0 stores words 0..3, lane 1 words 4..7 (checked by the dump's first eight words). +; group: 32,1,1 +; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_exec_copy.spv 1 dump -> out[0..7] = aaaaaaaa ffffffff aaaaaaaa 0 aaaaaaaa ffffffff aaaaaaaa 1 +; mattr: +wavefrontsize32,-wavefrontsize64 +v_mov_b32_e32 v7, -1 +v_readfirstlane_b32 s7, v7 +s_mov_b32 exec_lo, s7 +v_and_b32 v1, 1, v0 +v_cmp_ne_u32_e64 s8, v1, 0 +s_mov_b32 s4, exec_lo +s_mov_b32 exec_lo, s4 +v_mov_b32_e32 v2, s8 +v_mov_b32_e32 v4, exec_lo +s_mov_b32 exec_lo, -1 +v_mov_b32_e32 v5, s8 +v_lshlrev_b32_e32 v3, 4, v0 +v_mov_b32_e32 v20, v2 +v_mov_b32_e32 v21, v3 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, v4 +v_add_nc_u32_e32 v21, 4, v3 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, v5 +v_add_nc_u32_e32 v21, 8, v3 +buffer_store_dword v20, v21, s[0:3], 0 offen +v_mov_b32_e32 v20, v0 +v_add_nc_u32_e32 v21, 12, v3 +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 f87290ec65..7da853713a 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1212,8 +1212,8 @@ 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_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): + "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_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed", "cs_exec_copy"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone @@ -1331,6 +1331,10 @@ def run_suite(a, work: str) -> int: # inactive lanes keep the old VGPR (cs_mask_vgpr_exec.asm) "cs_mask_vgpr_exec": [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF], + # EXEC round-tripped through an SGPR copy keeps its narrowing's identity: the mask + # word gathers as the literal -1 restore does (cs_exec_copy.asm header) + "cs_exec_copy": [0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 0, + 0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 1], } want = cs_dump_wants[name] # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / @@ -1353,7 +1357,7 @@ def run_suite(a, work: str) -> int: "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", - "cs_w32_exec_computed") and not emulated and not partial + "cs_w32_exec_computed", "cs_exec_copy") and not emulated and not partial if partial: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) diff --git a/tests/semantic/fixtures/disasm/cs_exec_copy.s b/tests/semantic/fixtures/disasm/cs_exec_copy.s new file mode 100644 index 0000000000..d5b885661f --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_exec_copy.s @@ -0,0 +1,26 @@ +; cs_exec_copy test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_exec_copy.asm + v_mov_b32_e32 v7, -1 + v_readfirstlane_b32 s7, v7 + s_mov_b32 exec_lo, s7 + v_and_b32 v1, 1, v0 + v_cmp_ne_u32_e64 s8, v1, 0 + s_mov_b32 s4, exec_lo + s_mov_b32 exec_lo, s4 + v_mov_b32_e32 v2, s8 + v_mov_b32_e32 v4, exec_lo + s_mov_b32 exec_lo, -1 + v_mov_b32_e32 v5, s8 + v_lshlrev_b32_e32 v3, 4, v0 + v_mov_b32_e32 v20, v2 + v_mov_b32_e32 v21, v3 + buffer_store_dword v20, v21, s[0:3], 0 offen + v_mov_b32_e32 v20, v4 + v_add_nc_u32_e32 v21, 4, v3 + buffer_store_dword v20, v21, s[0:3], 0 offen + v_mov_b32_e32 v20, v5 + v_add_nc_u32_e32 v21, 8, v3 + buffer_store_dword v20, v21, s[0:3], 0 offen + v_mov_b32_e32 v20, v0 + v_add_nc_u32_e32 v21, 12, v3 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/test_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py index 53e6f78252..5988957156 100644 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ b/tests/semantic/test_lane_masks_vector_bitwise.py @@ -442,6 +442,56 @@ def test_exec_read_under_narrowed_exec_still_gathers(self): else: self.assertEqual(mem[lane * 4], 0x55555555, f"lane {lane}") + def test_exec_copy_roundtrip_keeps_mask_gather(self): + # `s_mov_b32 s4, exec_lo` copies EXEC under an unknown narrowing and `s_mov_b32 exec_lo, s4` + # restores the same value — EXEC is unchanged, so a mask written under that narrowing must + # still gather. The copy has to carry the narrowing's tag into `alias`: without it the + # restore minted a fresh tag in _exec_src_ex, mask_exec_sigs coverage failed and the read + # kept this lane's 0 / ~0 bit where `s_mov_b32 exec_lo, -1` gathered the word (#1397 review). + lines = [ + "v_mov_b32_e32 v7, -1", + "v_readfirstlane_b32 s7, v7", # s7 = 0xffffffff, not a tracked constant + "s_mov_b32 exec_lo, s7", # EXEC = unknown narrowing, runtime all-ones + "v_and_b32 v1, 1, v0", + "v_cmp_ne_u32_e64 s10, v1, 0", # odd-lane mask written under that EXEC + "s_mov_b32 s4, exec_lo", + "s_mov_b32 exec_lo, s4", + "v_mov_b32_e32 v2, s10", + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_endpgm", + ] + spv, _ = _translate_cs("cs_maskdata_exec_copy", lines, wave_size=32, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_exec_copy_run", lines, wave_size=32, emulate=False) + want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, every lane + for lane in range(32): + self.assertEqual(mem[lane * 4], want, f"lane {lane}") + + def test_exec_copy_roundtrip_keeps_mask_gather_wave64(self): + # Same round-trip on the exec_lo half of a wave64 EXEC: the VCC mask's low word must still + # gather while exec_hi stays clean. + lines = [ + "s_mov_b64 exec, -1", # wave64 marker (and a clean EXEC to start) + "v_mov_b32_e32 v7, -1", + "v_readfirstlane_b32 s7, v7", + "s_mov_b32 exec_lo, s7", # exec_lo = unknown narrowing, runtime all-ones + "v_and_b32 v1, 1, v0", + "v_cmp_ne_u32_e64 vcc, v1, 0", + "s_mov_b32 s4, exec_lo", + "s_mov_b32 exec_lo, s4", + "v_mov_b32_e32 v2, vcc_lo", + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_endpgm", + ] + spv, _ = _translate_cs("cs_maskdata_exec_copy_w64", lines, wave_size=64, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_exec_copy_w64_run", lines, wave_size=64, emulate=False) + want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, the vcc_lo word + for lane in range(64): + self.assertEqual(mem[lane * 4], want, f"lane {lane}") + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 31dae32e17..86dcd9a9c9 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -2054,8 +2054,12 @@ def _mov_sgpr_vals(self, src, regs, ex, alias, sconst): t = src.get("t", "") vals = [] for i in range(len(regs)): - h = ex[0] if (t == "exec_lo" or (t == "exec" and i == 0)) else \ - ex[1] if (t == "exec_hi" or (t == "exec" and i == 1)) else None + if t == "exec_lo" or (t == "exec" and i == 0): + h, hi = ex[0], False + elif t == "exec_hi" or (t == "exec" and i == 1): + h, hi = ex[1], True + else: + h, hi = None, False if h is None: vals.append(None) elif h[0] == "c": @@ -2063,7 +2067,11 @@ def _mov_sgpr_vals(self, src, regs, ex, alias, sconst): elif h[0] == "k": vals.append(h[1]) else: - vals.append(None) + # An EXEC copy under an unknown narrowing holds that narrowing's value: alias + # the half-state (as saveexec does) so `s_mov_b32 exec_lo, sD` restores the + # same tag and mask_exec_sigs coverage still holds — a plain None would mint a + # fresh tag in _exec_src_ex and suppress gathers that are exact (#1397 review). + vals.append(("al", (None, h) if hi else (h, None))) return vals return [None] * len(regs) From ec8b9619078867af5c8647c4e8937228a0d048c4 Mon Sep 17 00:00:00 2001 From: hugo <63666848+hugo0024@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:39:03 +0800 Subject: [PATCH 4/5] rdna2spirv: the wave mask gather is stored before it is read, so every lane runs it (SHADER-WAVEMASK-EAGER) A register holds this lane's bit of a lane mask; v_mbcnt, s_bcnt1 and s_ff1 gather the other lanes' bits with a subgroup operation (Gen.wave_mask). v_mbcnt writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary: v6 = active ? popcount(simd_or(mine ? bit : 0) & below) + acc : v6; A lane that is off never ran the gather, so its bit was missing from every other lane's count. Gen.wave_mask now stores the gather to a variable of its own with Gen.eager, as SHADER-529 did for DPP's ballot and shuffle. On an Apple M5 (MoltenVK 1.4.2), tools/crosslane_fuzz.py with wave 32, native and no maskdata goes from 92 of 100 programs matching to 100 of 100, and from 193 to 200 of 200 with DPP at seed 7. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: SWE-2.1 Max --- docs/design.md | 2 +- tests/semantic/README.md | 3 + tests/semantic/test_wave_mask_eager.py | 140 +++++++++++++++++++++++++ tools/rdna2spirv.py | 8 +- 4 files changed, 150 insertions(+), 3 deletions(-) create mode 100644 tests/semantic/test_wave_mask_eager.py diff --git a/docs/design.md b/docs/design.md index afdf87950b..7d72b2b912 100644 --- a/docs/design.md +++ b/docs/design.md @@ -400,7 +400,7 @@ How the generated SPIR-V expects the runtime to work: | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations or an `s_mov` copy of `exec`/`exec_lo`/`exec_hi`, which carries the narrowing's tag so an `s_mov_b32 exec_lo, sD` restore keeps it), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | +| 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations or an `s_mov` copy of `exec`/`exec_lo`/`exec_hi`, which carries the narrowing's tag so an `s_mov_b32 exec_lo, sD` restore keeps it), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | | 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/README.md b/tests/semantic/README.md index 5360ab2443..01452e9945 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -182,6 +182,9 @@ instruction family per file; the list below describes some of them, not every fi (MoltenVK) would inline it into a short-circuiting `&&`/`||` or a ternary's arm, for 11 DPP16/DPP8 forms with and without a lane off in EXEC, using a model of SPIRV-Cross's single-use forwarding (its own tests cover the model). It also runs the same programs in `spirv_wave_interp.py` against a plain-Python DPP reference. +- `test_wave_mask_eager.py` (SHADER-WAVEMASK-EAGER) does the same for the whole-wave mask gather: `v_mbcnt`, + `s_bcnt1` and `s_ff1` of a compare mask, of VCC and of EXEC, read while EXEC is narrowed, leave no subgroup op in + a ternary's arm, in a compute, a vertex and a pixel shader, and `v_mbcnt` counts the lanes that are off. Limits: single lane (or lanes in lockstep, one instruction per lane per round, that exchange values only through `OpGroupNonUniformShuffle`, `Ballot`, `Any`, `All` and `BitwiseOr` Reduce), control flow followed one branch at a time (the fragment-exit discard test, the compute diff --git a/tests/semantic/test_wave_mask_eager.py b/tests/semantic/test_wave_mask_eager.py new file mode 100644 index 0000000000..5ef7936927 --- /dev/null +++ b/tests/semantic/test_wave_mask_eager.py @@ -0,0 +1,140 @@ +"""The whole-wave mask gather runs in every lane, also after SPIRV-Cross inlines expressions (SHADER-WAVEMASK-EAGER). + +A register holds only this lane's bit of a lane mask. The instructions that read a mask as a whole (v_mbcnt, s_bcnt1, +s_ff1, ...) gather the other lanes' bits with a subgroup operation (Gen.wave_mask). v_mbcnt writes a VGPR, so its +result is an OpSelect on the lane's EXEC, and SPIRV-Cross (MoltenVK) inlines a result that is used once into the +expression that uses it. The gather ended up in the taken arm of a ternary, + + v6 = active ? popcount(simd_or(mine ? bit : 0) & below) + acc : v6; + +where a lane that is off in EXEC never runs it, so its mask bit is missing from what every other lane counts. +tools/crosslane_fuzz.py found it on an Apple M5 (MoltenVK 1.4.2): 4 of 100 wave32 programs of the default seed +mismatched, each a v_mbcnt of a compare mask read after EXEC was narrowed. Gen.wave_mask now stores the gather to a +Function variable (Gen.eager, as SHADER-529 did for DPP's ballot and shuffle), and a store is a statement every lane +runs. + +The check is test_dpp_eager_subgroup.py's model of SPIRV-Cross's single-use forwarding. The values are checked too, +in tests/semantic/spirv_wave_interp.py; it runs every lane at every instruction, so it shows that the stored gather +still counts the right lanes, not what Metal did. + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import support # noqa: E402 (puts tools/ on the path) +import spirv_wave_interp as wi # noqa: E402 +from test_dpp_eager_subgroup import conditional_subgroup_ops # noqa: E402 + +READERS = ("v_mbcnt", "s_bcnt1", "s_ff1") +MASKS = ("s16", "vcc_lo", "exec_lo") +FLOOR, LIMIT = 8, 20 # EXEC is narrowed to the lanes above FLOOR; the compare mask is the lanes below LIMIT + + +def body(reader, mask): + """v0 = the lane. `mask` gets the lanes below LIMIT (exec_lo is read as it is), EXEC is narrowed to the lanes + above FLOOR, and `reader` reads the mask there: the lanes at or below FLOOR are off, and every one of them below + LIMIT has its bit set in the mask. v6 = 100 + the result in the lanes still on, and stays 100 in the others.""" + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v6, 100", "v_mov_b32 v7, 100", "s_mov_b32 s10, exec_lo"] + if mask != "exec_lo": + lines.append(f"v_cmp_gt_u32_e64 {mask}, {LIMIT}, v0") + lines.append(f"v_cmpx_lt_u32_e32 {FLOOR}, v0") + if reader == "v_mbcnt": + lines.append(f"v_mbcnt_lo_u32_b32 v6, {mask}, v7") + else: + lines += [f"{reader}_i32_b32 s5, {mask}", "v_add_nc_u32 v6, s5, v7"] + return lines + ["s_mov_b32 exec_lo, s10"] + + +def vertex(reader, mask): + return support.translate_lines("vs_wave_mask_eager", body(reader, mask) + [ + "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"]) + + +def pixel(reader, mask): + return support.translate_lines("ps_wave_mask_eager", body(reader, mask) + [ + "exp mrt0 v6, v6, v6, v6 done vm", "s_endpgm"]) + + +def compute(reader, mask, threads=32): + header = bytearray(0x148) + struct.pack_into("<4I", header, 0x138, 0x8088, threads, 1, 1) + return support.translate_lines("cs_wave_mask_eager", body(reader, mask) + [ + "v_lshlrev_b32_e32 v22, 2, v0", "buffer_store_dword v6, v22, s[0:3], 0 offen", "s_endpgm"], fssm=bytes(header)) + + +def reference(reader, mask, wave=32): + """v6 per lane after body(reader, mask), from the ISA: a mask is one bit per lane, whatever EXEC is when it is + read; v_mbcnt_lo counts its bits below the lane, s_bcnt1 all of them, s_ff1 gives the lowest.""" + on = [lane > FLOOR for lane in range(wave)] + bits = on if mask == "exec_lo" else [lane < LIMIT for lane in range(wave)] + out = [] + for lane in range(wave): + if not on[lane]: + out.append(100) + elif reader == "v_mbcnt": + out.append(100 + sum(bits[:lane])) + elif reader == "s_bcnt1": + out.append(100 + sum(bits)) + else: + out.append(100 + bits.index(True)) + return out + + +class WaveMaskGatherRunsInEveryLane(unittest.TestCase): + def test_no_gather_is_conditional(self): + for stage, make in (("vertex", vertex), ("compute", compute), ("pixel", pixel)): + for reader in READERS: + for mask in MASKS: + with self.subTest(stage=stage, reader=reader, mask=mask): + spv = make(reader, mask) + gather = "OpGroupNonUniformBallot" if stage == "pixel" else "OpGroupNonUniformBitwiseOr" + self.assertIn(gather, spv) + self.assertEqual(conditional_subgroup_ops(spv), []) + + def test_the_gather_is_stored_before_v_mbcnt_selects_on_exec(self): + # The shape itself, for the case the fuzzer hit: both halves of the gathered mask go to a variable. + spv = compute("v_mbcnt", "s16") + gathers = [ln.split()[0] for ln in spv.splitlines() if "OpGroupNonUniformBitwiseOr" in ln] + self.assertEqual(len(gathers), 2, spv) + for g in gathers: + uses = [ln.split() for ln in spv.splitlines() if g in ln.split()[1:]] + self.assertEqual([u[0] for u in uses], ["OpStore"], f"{g} is used by {uses}") + + def test_the_model_finds_the_old_shape(self): + # What Gen.wave_mask gave v_mbcnt before: the gather's one use chain ends in an arm of the select on EXEC. + old = ("%lo = OpGroupNonUniformBitwiseOr %uint %c3 Reduce %lo_in\n" + "%below = OpBitwiseAnd %uint %lo %m1\n" + "%cnt = OpBitCount %uint %below\n" + "%r = OpIAdd %uint %cnt %acc\n" + "%active = OpLoad %bool %active_var\n" + "%sel = OpSelect %uint %active %r %old\n" + "OpStore %reg_v6 %sel\n") + self.assertEqual([(r, op) for r, op, _ in conditional_subgroup_ops(old)], + [("%lo", "OpGroupNonUniformBitwiseOr")]) + + def test_values(self): + for reader in READERS: + for mask in MASKS: + with self.subTest(reader=reader, mask=mask): + res = wi.run_wave(vertex(reader, mask), wave=32, + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + got = [o["%out_param0"][0] for o in res["outputs"]] + self.assertEqual(got, reference(reader, mask)) + + def test_reference_counts_the_lanes_that_are_off(self): + # Lane 12 is on; lanes 0..8 are off and all in the compare mask, so v_mbcnt counts 12, not the 3 that are on. + self.assertEqual(reference("v_mbcnt", "s16")[12], 112) + self.assertEqual(reference("v_mbcnt", "exec_lo")[12], 103) # EXEC itself: only lanes 9, 10, 11 + self.assertEqual(reference("s_bcnt1", "vcc_lo")[31], 100 + LIMIT) + self.assertEqual(reference("s_ff1", "exec_lo")[9], 100 + FLOOR + 1) + self.assertEqual(reference("s_ff1", "s16")[FLOOR], 100) # off: keeps its 100 + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 86dcd9a9c9..aa08b6b106 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -6899,12 +6899,16 @@ def wave_mask(self, a): if key is not None: self.x_mcache[key] = res return res + # The gather is stored to a variable of its own (eager, SHADER-529): a reader that writes a VGPR, v_mbcnt, is + # an OpSelect on the lane's EXEC, and SPIRV-Cross (MoltenVK) inlines a single-use gather into that ternary's + # taken arm. A lane that is off then never runs the subgroup op, and its bit is missing from the mask the + # other lanes count (SHADER-WAVEMASK-EAGER; Apple M5, MoltenVK 1.4.2, tools/crosslane_fuzz.py). if self.wave32_fragment: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {mine}") word = self.wave32_ballot_word(ballot) self.uses_ballot = True - return word, self.cu(0) + return self.eager("%uint", word), self.cu(0) self.uses_wave_bits = True lane = self.wave_lane() low, sh, bit, b, lo_in, hi_in, lo, hi = (self.tmp() for _ in range(8)) @@ -6916,7 +6920,7 @@ def wave_mask(self, a): self.emit(f"{hi_in} = OpSelect %uint {low} {self.cu(0)} {b}") self.emit(f"{lo} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {lo_in}") self.emit(f"{hi} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {hi_in}") - return lo, hi + return self.eager("%uint", lo), self.eager("%uint", hi) def quad_any(self, v): """This lane's value after whole-quad mode: all ones if any of the 4 lanes of its quad (4n .. 4n+3 of the From e3e119a46fd791bb41e80ef3837893baa2ef35d8 Mon Sep 17 00:00:00 2001 From: whoalin1 <207920491+whoalin1@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:57:58 +0200 Subject: [PATCH 5/5] translator: lane-mask data reads gather the wave word under narrowed EXEC A lane mask in an SGPR, EXEC or VCC is one wave-wide word on hardware. The EXEC-coverage gate added earlier in this pull request could not prove the independent-SGPR restore idioms crosslane_fuzz uses, so it fell back to this lane's 0 / ~0 bit for exactly the programs the read is meant to fix. It also encoded the wrong control-flow model: EXEC narrowing is a per-lane value here, not a SPIR-V edge. Mask-data readers are already kept out of lane-local `if (active)` runs, and the eager wave-mask store keeps lowering from moving the subgroup gather into an EXEC-selected arm, so lanes EXEC has off still contribute their mask bits. Remove the gate and the CFG EXEC provenance analysis it needed, gather the mask word for every lane-mask data read, and cover narrowed SGPR and VCC reads, an independent all-ones SGPR EXEC restore, and the composed vector-bitwise mask words. The vector-bitwise expectations now check the uniform mask words and the resulting per-lane cndmask bits and popcounts rather than the old fallback artifact. Co-Authored-By: SWE-2.1 Max --- docs/design.md | 2 +- .../test_lane_masks_vector_bitwise.py | 103 ++-- tools/rdna2spirv.py | 506 +----------------- 3 files changed, 80 insertions(+), 531 deletions(-) diff --git a/docs/design.md b/docs/design.md index 7d72b2b912..afbf365ffb 100644 --- a/docs/design.md +++ b/docs/design.md @@ -400,7 +400,7 @@ How the generated SPIR-V expects the runtime to work: | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). 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`). The mask-word gather is a subgroup op over the lanes EXEC leaves active, and drivers differ on whether lanes EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on (`cs_mask_vgpr_exec` on MoltenVK). So the gather is emitted only when a CFG must-analysis (`Gen.mark_exec_state`) proves every lane that can hold a set bit of the mask is EXEC-active at the read: the read's EXEC half-state must cover every EXEC state seen while the register held a mask (`mask_exec_sigs`, matched per half — clean, constant, or the same narrowing instruction). EXEC writes are tracked by value where provable — `s_mov`/`s_cselect` of an all-ones constant, an SGPR aliasing a saved EXEC (`s_*_saveexec` destinations or an `s_mov` copy of `exec`/`exec_lo`/`exec_hi`, which carries the narrowing's tag so an `s_mov_b32 exec_lo, sD` restore keeps it), or unchanged EXEC — so the common restore idioms still gather; anything unproven narrows conservatively and the read falls back to this lane's 0 / ~0 bit. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | +| 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. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). 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`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | | 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_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py index 5988957156..f61813e5cd 100644 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ b/tests/semantic/test_lane_masks_vector_bitwise.py @@ -215,25 +215,28 @@ def test_vector_bitwise_masks_under_partial_exec(self): want_bfi = [(i < 10) if (i & 1 == 0) else (i & 2 == 0) for i in range(self.wave_size)] for lane in range(self.wave_size): base = lane * 36 - # The mask reads run while EXEC is narrowed to lanes < 10, so the wave-mask gather is - # suppressed (mask_word_read_ok: a group op can't be relied on to see lanes EXEC has - # off — MoltenVK, #1397 review). Each lane's mask operand read keeps its own 0 / ~0 - # bit and the bitwise ops still update every lane, so each lane stores its own bit of - # the composed mask: ~0 where the lane is in it, 0 elsewhere. - self.assertEqual(mem[base], 0xFFFFFFFF if want_andor[lane] else 0, - f"lane {lane} raw and_or") - self.assertEqual(mem[base + 4], 0xFFFFFFFF if want_xnor[lane] else 0, - f"lane {lane} raw xnor") - self.assertEqual(mem[base + 8], 0xFFFFFFFF if want_bfi[lane] else 0, - f"lane {lane} raw bfi") - # readfirstlane broadcasts lane 0's result — ~0 in each case — so every lane takes the - # mask-set arm and bcnt counts the whole wave's bits. - self.assertEqual(mem[base + 12], 20, f"lane {lane} cndmask and_or") - self.assertEqual(mem[base + 16], 40, f"lane {lane} cndmask xnor") - self.assertEqual(mem[base + 20], 60, f"lane {lane} cndmask bfi") - self.assertEqual(mem[base + 24], self.wave_size, f"lane {lane} bcnt and_or") - self.assertEqual(mem[base + 28], self.wave_size, f"lane {lane} bcnt xnor") - self.assertEqual(mem[base + 32], self.wave_size, f"lane {lane} bcnt bfi") + # The mask reads run while EXEC is narrowed to lanes < 10. Hardware SGPRs hold the + # whole wave's mask word, and the eager gather sees the lanes EXEC has off too, so the + # bitwise VALU op composes the 32-bit mask words themselves. The VGPR result is that + # wave-uniform word in every lane (for the low-half SGPRs in wave64 as well). + andor_word = sum((1 << i) for i, b in enumerate(want_andor[:32]) if b) + xnor_word = sum((1 << i) for i, b in enumerate(want_xnor[:32]) if b) + bfi_word = sum((1 << i) for i, b in enumerate(want_bfi[:32]) if b) + self.assertEqual(mem[base], andor_word, f"lane {lane} raw and_or") + self.assertEqual(mem[base + 4], xnor_word, f"lane {lane} raw xnor") + self.assertEqual(mem[base + 8], bfi_word, f"lane {lane} raw bfi") + # readfirstlane broadcasts lane 0's copy of the composed wave mask word. Mask consumers + # extract each lane's own bit again: cndmask follows that lane's membership, and bcnt + # counts the set bits of the composed masks (low plus high halves in wave64). + self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, + f"lane {lane} cndmask and_or") + self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, + f"lane {lane} cndmask xnor") + self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, + f"lane {lane} cndmask bfi") + self.assertEqual(mem[base + 24], sum(want_andor), f"lane {lane} bcnt and_or") + self.assertEqual(mem[base + 28], sum(want_xnor), f"lane {lane} bcnt xnor") + self.assertEqual(mem[base + 32], sum(want_bfi), f"lane {lane} bcnt bfi") def test_readfirstlane_mask_vgpr_dst_gets_wave_word(self): mem = _run_cs( @@ -389,11 +392,11 @@ def test_exec_as_data_gathers_exec_word(self): class TestMaskDataReadExecGate(unittest.TestCase): - """A lane-mask data read gathers the wave's mask word with a group op only while every lane the - word covers is EXEC-active: drivers differ on whether lanes EXEC has off still vote (MoltenVK's - group ops saw only the lanes a narrowed EXEC left on, #1397 review). Otherwise the read keeps - this lane's 0 / ~0 — the pre-#1397 answer — and an EXEC operand's own word still gathers, since - lanes off in EXEC contribute 0 either way.""" + """A lane-mask data read gathers the wave's mask word even while EXEC is narrowed. EXEC is a + per-lane value in the translator's model, not SPIR-V control flow; the mask-data reader is kept + out of lane-local `if (active)` runs and wave_mask's eager store keeps drivers from moving the + subgroup gather into an EXEC-selected arm. Thus lanes EXEC has off still contribute the bits they + hold, as hardware's wave-wide mask register does.""" def _lines(self, tail): return [ @@ -407,19 +410,59 @@ def _lines(self, tail): "s_endpgm", ] - def test_vcc_read_under_narrowed_exec_keeps_lane_bit(self): + def test_vcc_read_under_narrowed_exec_gathers_mask_word(self): lines = self._lines(["v_mov_b32_e32 v2, vcc_lo"]) spv, _ = _translate_cs("cs_maskdata_narrowed", lines, wave_size=32, emulate=False) - self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) mem = _run_cs("cs_maskdata_narrowed_run", lines, wave_size=32, emulate=False) for lane in range(32): - # EXEC-active even lanes store their own VCC bit (0: VCC is the odd lanes); odd lanes - # are off in EXEC — the store doesn't run — which is the per-lane answer, not the - # 0xAAAAAAAA word a gather would have produced. + # EXEC-active even lanes store the whole odd-lane VCC word; odd lanes are off in EXEC, + # so the store doesn't run for them. if lane & 1: self.assertNotIn(lane * 4, mem, f"lane {lane}") else: - self.assertEqual(mem[lane * 4], 0, f"lane {lane}") + self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") + + def test_sgpr_read_under_narrowed_exec_gathers_mask_word(self): + # Gefik23's crosslane_fuzz family: a compare-written SGPR mask read after EXEC narrows. + lines = [ + "v_and_b32 v1, 1, v0", + "v_cmp_eq_u32_e64 s10, v1, 1", # s10 = odd lanes, 0xAAAAAAAA + f"v_mov_b32_e32 v2, {SENTINEL:#x}", + "s_mov_b32 exec_lo, 0x55555555", # EXEC = even lanes + "v_mov_b32_e32 v2, s10", + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_endpgm", + ] + spv, _ = _translate_cs("cs_maskdata_sgpr_narrowed", lines, wave_size=32, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_sgpr_narrowed_run", lines, wave_size=32, emulate=False) + for lane in range(32): + if lane & 1: + self.assertNotIn(lane * 4, mem, f"lane {lane}") + else: + self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") + + def test_sgpr_read_after_independent_full_exec_restore_gathers(self): + # ecox982745's independent-SGPR restore: s7 is runtime-all-ones but is not an EXEC alias. + # The mask word is still the wave-wide value; no EXEC provenance proof is needed. + lines = [ + "v_mov_b32_e32 v7, -1", + "v_readfirstlane_b32 s7, v7", + "v_and_b32 v1, 1, v0", + "v_cmp_ne_u32_e64 s10, v1, 0", # odd lanes + "s_mov_b32 exec_lo, s7", + "v_mov_b32_e32 v2, s10", + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_store_dword v2, v3, s[0:3], 0 offen", + "s_endpgm", + ] + spv, _ = _translate_cs("cs_maskdata_independent_exec", lines, wave_size=32, emulate=False) + self.assertIn("OpGroupNonUniformBitwiseOr", spv) + mem = _run_cs("cs_maskdata_independent_exec_run", lines, wave_size=32, emulate=False) + for lane in range(32): + self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") def test_vcc_read_after_exec_restore_gathers(self): lines = self._lines(["s_mov_b32 exec_lo, -1", "v_mov_b32_e32 v2, vcc_lo"]) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index aa08b6b106..5574c6f97e 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -367,10 +367,6 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) - self.exec_state_at = {} # id(instruction) -> ((lo clean, lo tag), (hi clean, hi tag)) - self.mask_exec_sigs = {} # mask register -> [(blk, pos, EXEC sig)] while it held a mask - self.ins_pos = {} # id(instruction) -> (block, position) - self.exec_reach = [] # block -> bitmask of blocks reachable in >= 1 step self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative) self.cur_masks = {} self.vcc_scalar_pointer = False @@ -533,8 +529,7 @@ def src_u(self, a): k = a["k"] if ((k == "sgpr" and a.get("n", 1) == 1) or (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \ - and self.holds_lane_mask(a) and self.mask_read_is_data() \ - and self.mask_word_read_ok(a, self.cur_ins): + and self.holds_lane_mask(a) and self.mask_read_is_data(): # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's # mask word (the same in every lane), as the SOP ops that read a mask as a number already do # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each @@ -542,10 +537,9 @@ def src_u(self, a): # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too — # mask_src extracts this lane's bit back out when a mask consumer reads one. - # mask_word_read_ok keeps the gather for the cases every driver answers the same: lanes - # EXEC has off may not vote in a group op (MoltenVK's did not, #1397 review), so a VCC or - # mask-SGPR word is only gathered while its lanes are all EXEC-active; an EXEC operand's - # word is the current EXEC itself and gathers correctly either way. + # The gather itself is eager (wave_mask): EXEC narrowing is a per-lane value in this + # model, not SPIR-V control flow, and mask-data readers are kept out of lane-local + # `if (active)` runs, so lanes off in EXEC still contribute their mask bits. v = self.lane_mask_word(a) elif k in ("vgpr", "sgpr"): if a.get("n", 1) != 1: @@ -1838,494 +1832,7 @@ def _mask_data_operand(self, x, masks, ins): return False else: return False - return self.mask_read_is_data(ins) and self.mask_word_read_ok(x, ins, masks) - - def mask_operand_halves(self, a, masks=None): - """The EXEC halves ('lo' = lanes 0-31, 'hi' = lanes 32-63) that must be all-ones for a wave_mask - gather of operand `a` to see every lane the operand's word covers; empty for an EXEC operand — - its word IS the current EXEC, so lanes off in it contribute 0 whether they vote or not — and - None when `a` is not a lane-mask operand at all. `masks` is the lane_masks state for an SGPR - operand's half (self.cur_masks while translating, the per-instruction state while planning).""" - if self.emulate: - return frozenset() # the exchange round sees every lane whatever EXEC says - if a["k"] == "special": - t = a.get("t", "") - if t.startswith("exec"): - return frozenset() - if t in ("exec_hi", "vcc_hi"): - return frozenset(("hi",)) if self.wave64 else frozenset(("lo",)) - return frozenset(("lo",)) # vcc / vcc_lo: the b32 data read yields the low word - if a["k"] == "sgpr" and a.get("n", 1) == 1: - state = self.cur_masks if masks is None else masks - if self.wave64 and state.get(a["r"]) == lane_masks.MASK_HI: - return frozenset(("hi",)) - return frozenset(("lo",)) - return None - - def mask_word_read_ok(self, a, ins, masks=None): - """Whether a data read of lane-mask operand `a` in `ins` may gather the wave's mask word. - The gather is a group op over the lanes EXEC leaves active: drivers differ on whether lanes - EXEC has off still vote — NVIDIA, AMD and KosmicKrisp return the whole subgroup's bits, - MoltenVK's ballot/reduce saw only the lanes a narrowed EXEC left on and produced the EXEC - value instead of the frozen mask word (#1397 review, cs_mask_vgpr_exec). A gather is exact - whenever every lane that can hold a set bit of the mask is EXEC-active, so the read is - allowed while EXEC's needed half is provably all-ones, and otherwise only when the mask was - a mask exclusively under this same EXEC narrowing (mask_exec_sigs: every EXEC state seen - while the register held a mask is this one, so no lane outside it can hold a bit). Where - neither holds, src_u keeps this lane's 0 / ~0, the pre-#1397 answer. An EXEC operand needs - no such guarantee (its off lanes contribute 0 either way) and --wave64-emulate exchanges - through workgroup memory, which every lane runs.""" - halves = self.mask_operand_halves(a, masks) - if halves is None: - return False - if not halves: - return True - st = self.exec_state_at.get(id(ins)) - if st is None: - return self.exec_static_true - key = self._mask_sig_key(a) - sigs = self.mask_exec_sigs.get(key) - if not sigs: - return False - pos = self.ins_pos.get(id(ins)) - bi, pi = pos if pos is not None else (0, 0) - reach_bi = 1 << bi - self_loop = bool(self.exec_reach[bi] & reach_bi) - for h in halves: - i = 0 if h == "lo" else 1 - rstate = st[i] - if rstate[0] == "c": - continue - for bj, pj, sig in sigs: - # Only signatures whose instruction can reach this read constrain the value: - # same block needs an earlier position (or a loop back-edge), another block must - # reach this one in the CFG. - if bj == bi: - if not (pj < pi or self_loop): - continue - elif not (self.exec_reach[bj] & reach_bi): - continue - if not self._exec_covers(sig[i], rstate): - return False - return True - - @staticmethod - def _exec_covers(w, r): - """Whether every lane EXEC-active under half-state `w` is also active under `r` — the - condition for a mask written under `w` to have all its set bits visible to a group op - running under `r`. Half-states: ("c",) all lanes, ("k", v) the constant mask v, ("n", tag) - an unknown narrowing identified by the instruction that made it (None never matches).""" - if w[0] == "n" and w[1] is None: - return False # an unknown narrowing never provably covers anything - if w == r: - return True - if w[0] == "c": - return r[0] == "c" - if w[0] == "k": - return r[0] == "k" and (w[1] & ~r[1] & 0xFFFFFFFF) == 0 - return r[0] == "n" and r[1] is not None and w[1] == r[1] - - def _mask_sig_key(self, a): - """The lane_masks state key a mask operand's writes are recorded under (mask_exec_sigs).""" - if a["k"] == "sgpr": - return a["r"] - t = a.get("t", "") - if t in ("vcc", "vcc_lo") or (t == "vcc_hi" and self.wave64): - return "vcc" - if t == "vcc_hi": - return "vcc_hi" - return None - - @staticmethod - def _ex_const(v): - """A constant EXEC half-state: all-ones folds to clean.""" - v &= 0xFFFFFFFF - return ("c",) if v == 0xFFFFFFFF else ("k", v) - - # Scalar ops that provably leave SCC alone (branches and stores read or ignore it; s_mov and - # the non-ALU scalar ops never write it). Anything else starting with "s_" may write SCC and - # resets the tracked value — losing precision is safe, keeping a stale one is not. - _SCC_KEEPS = frozenset(( - "s_mov_b32", "s_mov_b64", "s_movrelsd_2_b32", "s_movreld_b32", "s_movreld_b64", - "s_nop", "s_endpgm", "s_waitcnt", "s_barrier", "s_sleep", "s_branch", "s_cbranch", - "s_cbranch_execz", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", - "s_cbranch_vccnz", "s_set", "s_setpc_b64", "s_getpc_b64", - "s_get_waveid_in_workgroup", "s_sendmsg", "s_dcache_inv", "s_dcache_wb", - "s_dcache_inv_vol", "s_icache_inv", "s_trap", "s_rfe", "s_memtime", - "s_memrealtime", - )) - _SCC_KEEP_PREFIXES = ("s_store", "s_buffer_store", "s_wait", "s_branch", "s_cbranch", - "s_sendmsg", "s_dcache", "s_icache", "s_getpc", "s_setpc") - - def _const_of(self, a, sconst, ex): - """The constant 32-bit value of a scalar operand, or None. EXEC halves resolve through - the tracked EXEC state so `s_cmp s, exec_lo`-style compares can fold too.""" - if a["k"] == "imm": - return a.get("v", 0) & 0xFFFFFFFF - if a["k"] == "sgpr": - return sconst.get(a["r"]) if a.get("n", 1) == 1 else None - if a["k"] == "special": - t = a.get("t", "") - h = ex[0] if t == "exec_lo" else ex[1] if t == "exec_hi" else None - if h is not None: - return 0xFFFFFFFF if h[0] == "c" else h[1] if h[0] == "k" else None - if t == "null": - return 0 - return None - - def _cmp_scc(self, op, ins, sconst, ex): - """Fold a compare's SCC when both sources are constant; None when they are not (or the - predicate/width is outside the implemented set — safe under-approximation).""" - if op.startswith("s_bitcmp"): - return None - name = op - for p in ("s_cmpk_", "s_cmp_"): - if name.startswith(p): - name = name[len(p):] - break - else: - return None - a = ins["args"] - if len(a) < 2: - return None - x = self._const_of(a[-2], sconst, ex) - y = self._const_of(a[-1], sconst, ex) - if x is None or y is None: - return None - for sep in ("_u32", "_i32", "_u64", "_i64"): - if name.endswith(sep): - pred, ty = name[: -len(sep)], sep - break - else: - return None - if ty != "_u32" and ty != "_i32": - return None - sx = x - 0x100000000 if ty == "_i32" and x & 0x80000000 else x - sy = y - 0x100000000 if ty == "_i32" and y & 0x80000000 else y - if pred == "eq": - r = sx == sy - elif pred == "ne" or pred == "lg": - r = sx != sy - elif pred == "lt": - r = sx < sy - elif pred == "le": - r = sx <= sy - elif pred == "gt": - r = sx > sy - elif pred == "ge": - r = sx >= sy - else: - return None - return int(r) - - def _scc_step(self, scc, ins, sconst, ex): - op = base_op(ins["op"]) - if not op.startswith("s_"): - return scc - if "cmp" in op or "bitcmp" in op: - return self._cmp_scc(op, ins, sconst, ex) - if op in self._SCC_KEEPS or op.startswith(self._SCC_KEEP_PREFIXES): - return scc - return None - - def _mov_sgpr_vals(self, src, regs, ex, alias, sconst): - """Values a scalar s_mov writes into dst regs: int = constant, ("al", halves) = the - register now aliases an EXEC half-state (a saved EXEC), None = unknown.""" - out = [] - if src is None: - return [None] * len(regs) - if src["k"] == "imm": - v = src.get("v", 0) - if len(regs) == 2: - return [v & 0xFFFFFFFF, (v >> 32) & 0xFFFFFFFF] - return [v & 0xFFFFFFFF] - if src["k"] == "sgpr": - n = src.get("n", 1) - for i, d in enumerate(regs): - s = src["r"] + i if n == 2 else src["r"] - if s in sconst: - out.append(sconst[s]) - elif s in alias: - out.append(("al", alias[s])) - else: - out.append(None) - return out - if src["k"] == "special": - t = src.get("t", "") - vals = [] - for i in range(len(regs)): - if t == "exec_lo" or (t == "exec" and i == 0): - h, hi = ex[0], False - elif t == "exec_hi" or (t == "exec" and i == 1): - h, hi = ex[1], True - else: - h, hi = None, False - if h is None: - vals.append(None) - elif h[0] == "c": - vals.append(0xFFFFFFFF) - elif h[0] == "k": - vals.append(h[1]) - else: - # An EXEC copy under an unknown narrowing holds that narrowing's value: alias - # the half-state (as saveexec does) so `s_mov_b32 exec_lo, sD` restores the - # same tag and mask_exec_sigs coverage still holds — a plain None would mint a - # fresh tag in _exec_src_ex and suppress gathers that are exact (#1397 review). - vals.append(("al", (None, h) if hi else (h, None))) - return vals - return [None] * len(regs) - - def _exec_src_ex(self, src, h, ex, alias, sconst, ins, wide): - """EXEC half-state a scalar source gives EXEC half `h` when moved in.""" - i = 0 if h == "lo" else 1 - if src["k"] == "imm": - v = src.get("v", 0) - if wide: - v = (v >> (32 * i)) & 0xFFFFFFFF - return self._ex_const(v & 0xFFFFFFFF) - if src["k"] == "sgpr": - n = src.get("n", 1) - r = src["r"] + i if wide and n == 2 else src["r"] - if r in sconst: - return self._ex_const(sconst[r]) - al = alias.get(r) - if al is not None and al[i] is not None: - return al[i] - return ("n", id(ins)) - if src["k"] == "special": - t = src.get("t", "") - if t == "exec_lo": - return ex[0] - if t == "exec_hi": - return ex[1] - if t == "exec": - return ex[i] - return ("n", id(ins)) - - def _exec_write(self, ex, ins, alias, sconst, scc): - """EXEC pair after an EXEC-writing instruction. s_mov resolves its source — a constant - gives a constant half-state, a register that aliases a saved EXEC restores that state, - anything else starts a fresh unknown narrowing. s_cselect with a known SCC resolves to - its chosen source the same way (the `exec, -1, exec` restore idiom). Every other EXEC - write narrows (or changes) EXEC in a way we cannot name, so the affected halves get - this instruction's tag.""" - op, a = base_op(ins["op"]), ins["args"] - lo, hi = ex - - def halves_of(t): - if t == "exec_hi": - return ("hi",) - if t == "exec_lo": - return ("lo",) - return ("lo", "hi") if self.wave64 else ("lo",) - - dsts = [] - if a and a[0]["k"] == "special" and a[0].get("t", "").startswith("exec"): - dsts.append(a[0]) - if op in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "special" \ - and a[1].get("t", "").startswith("exec"): - dsts.append(a[1]) - if op in ("s_mov_b32", "s_mov_b64") and dsts and len(a) >= 2: - src = a[1] - wide = op.endswith("b64") - elif op in ("s_cselect_b32", "s_cselect_b64") and dsts and len(a) >= 3 \ - and scc is not None: - src = a[1] if scc else a[2] # D = SCC ? src0 : src1 - wide = op.endswith("b64") - else: - src = None - if src is not None: - for d in dsts: - for h in halves_of(d["t"]): - v = self._exec_src_ex(src, h, ex, alias, sconst, ins, wide) - if h == "lo": - lo = v - else: - hi = v - return lo, hi - if dsts: - affected = set(h for d in dsts for h in halves_of(d["t"])) - elif self.wave64 and op.endswith("_b32"): - affected = {"lo"} # the _b32 saveexec/wrexec forms touch EXEC_LO only - else: - affected = {"lo", "hi"} if self.wave64 else {"lo"} - tag = ("n", id(ins)) - return (tag if "lo" in affected else lo, - tag if "hi" in affected else hi) - - def _exec_step(self, st, ins): - """One instruction's effect on the analysis state (ex, alias, sconst, scc): - ex = (lo, hi) EXEC half-states, ("c",) clean / ("k", v) constant / ("n", tag) unknown - narrowing; alias = {sgpr: (loEX|None, hiEX|None)} registers holding a saved EXEC value; - sconst = {sgpr: constant}; scc = 0/1/None.""" - ex, alias, sconst, scc = st - op, a = base_op(ins["op"]), ins["args"] - alias = dict(alias) - sconst = dict(sconst) - pre_ex = ex - - # Scalar destination bookkeeping: constants and saved-EXEC aliases, invalidated by any - # other write to the register. - if op in ("s_mov_b32", "s_mov_b64") and a and a[0]["k"] == "sgpr" and len(a) >= 2: - d = a[0] - regs = list(range(d["r"], d["r"] + d.get("n", 1))) - vals = self._mov_sgpr_vals(a[1], regs, ex, alias, sconst) - for r, v in zip(regs, vals): - if v is None: - sconst.pop(r, None) - alias.pop(r, None) - elif isinstance(v, tuple): - alias[r] = v[1] - sconst.pop(r, None) - else: - sconst[r] = v - alias.pop(r, None) - else: - dsts = [] - if a and a[0]["k"] == "sgpr": - dsts.append(a[0]) - if op in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "sgpr": - dsts.append(a[1]) - for d in dsts: - for r in range(d["r"], d["r"] + d.get("n", 1)): - sconst.pop(r, None) - alias.pop(r, None) - - # saveexec/wrexec write their destination the EXEC value from *before* this instruction. - if ("saveexec" in op or "wrexec" in op) and a and a[0]["k"] == "sgpr": - d = a[0] - pair = (pre_ex[0], None) if self.wave64 and op.endswith("_b32") else pre_ex - for i, r in enumerate(range(d["r"], d["r"] + d.get("n", 1))): - alias[r] = (pair[0], None) if i == 0 else (None, pair[1]) - sconst.pop(r, None) - - if writes_exec(ins): - ex = self._exec_write(ex, ins, alias, sconst, scc) - scc = self._scc_step(scc, ins, sconst, ex) - return ex, alias, sconst, scc - - @staticmethod - def _ex_merge(x, y): - """Meet of two EXEC half-states: equal states merge to themselves; an identical - narrowing tag on both sides survives; anything else is an unknown narrowing.""" - if x == y: - return x - if x[0] == "n" and y[0] == "n" and x[1] is not None and x[1] == y[1]: - return x - return ("n", None) - - def _state_merge(self, a, b): - """Meet of two analysis states at a control-flow join: EXEC halves meet pairwise, - register facts survive only where both sides agree, SCC survives only when equal.""" - ex = (self._ex_merge(a[0][0], b[0][0]), self._ex_merge(a[0][1], b[0][1])) - alias = {r: v for r, v in a[1].items() if b[1].get(r) == v} - sconst = {r: v for r, v in a[2].items() if b[2].get(r) == v} - scc = a[3] if a[3] == b[3] else None - return ex, alias, sconst, scc - - def mark_exec_state(self, blocks, succ): - """self.exec_state_at[id(ins)] = (lo, hi) EXEC half-states just before ins, from a - must-analysis over the CFG — a block's entry state is the meet of its predecessors' - exits and _exec_step walks each block in order. mask_exec_sigs then records, for every - register lane_masks knows holds a mask, every EXEC state seen while it did: a mask's - set bits can only sit on lanes EXEC left active at its writes, so a gather is exact - only when every such signature's lanes are covered by the read's EXEC — see - mask_word_read_ok and _exec_covers.""" - n_blocks = len(blocks) - entry = [None] * n_blocks - out = [None] * n_blocks - clean = ("c",) - top = ((clean, clean), {}, {}, None) - entry[0] = top - work = [0] - queued = {0} - while work: - n = work.pop() - queued.discard(n) - st = entry[n] - for ins in blocks[n]: - st = self._exec_step(st, ins) - if out[n] == st: - continue - out[n] = st - for s in succ[n]: - if not (0 <= s < n_blocks): - continue - e = entry[s] - merged = st if e is None else self._state_merge(e, st) - if e is None or merged != e: - entry[s] = merged - if s not in queued: - work.append(s) - queued.add(s) - self.exec_state_at = {} - self.ins_pos = {} - for n, blk in enumerate(blocks): - st = entry[n] if entry[n] is not None else top - for p, ins in enumerate(blk): - self.exec_state_at[id(ins)] = st[0] - self.ins_pos[id(ins)] = (n, p) - st = self._exec_step(st, ins) - # exec_reach[b] = bitmask of blocks reachable from b in one or more steps; a set bit on b - # itself means b loops back to its top. - self.exec_reach = [0] * n_blocks - for b in range(n_blocks): - seen = 0 - stack = [s for s in succ[b] if 0 <= s < n_blocks] - while stack: - s = stack.pop() - if seen >> s & 1: - continue - seen |= 1 << s - stack.extend(t for t in succ[s] if 0 <= t < n_blocks) - self.exec_reach[b] = seen - # mask_exec_sigs[reg] = [(blk, pos, exec sig), ...]: every EXEC state seen at an - # instruction where lane_masks says the register holds a mask. A mask's set bits can only - # sit on lanes EXEC left active when they were written, so a gather under EXEC state T is - # exact only when every such signature that can reach the read agrees on T for the half - # the operand covers — see mask_word_read_ok. Signatures are recorded at the pre-state of - # each instruction; an instruction that itself writes EXEC (s_and_saveexec's saved mask, - # v_cmpx) produced its mask dst under the *pre-write* EXEC, so that state is added too. - self.mask_exec_sigs = {} - for n, blk in enumerate(blocks): - prev_exec_write = False - prev_sig = None - for p, ins in enumerate(blk): - sig = self.exec_state_at[id(ins)] - extra = prev_sig if prev_exec_write else None - prev_exec_write = writes_exec(ins) - prev_sig = sig - regs = self.lane_masks.get(id(ins)) - if not regs: - continue - for r in regs: - lst = self.mask_exec_sigs.setdefault(r, []) - if not lst or lst[-1][0] != n or lst[-1][2] != sig: - lst.append((n, p, sig)) - if extra is not None and (not lst or lst[-1][2] != extra): - lst.append((n, p, extra)) - # Block boundaries: a mask dst of a predecessor's last EXEC-writing instruction was - # produced under that instruction's pre-state EXEC; add it for the masks live at entry. - preds = [[] for _ in range(n_blocks)] - for b in range(n_blocks): - for s in succ[b]: - if 0 <= s < n_blocks: - preds[s].append(b) - for n, blk in enumerate(blocks): - if not blk: - continue - extras = [] - for p in preds[n]: - pblk = blocks[p] - if pblk and writes_exec(pblk[-1]): - extras.append(self.exec_state_at[id(pblk[-1])]) - if not extras: - continue - for r in self.lane_masks.get(id(blk[0]), {}): - lst = self.mask_exec_sigs.setdefault(r, []) - for e in extras: - if not lst or lst[-1][2] != e: - lst.append((n, 0, e)) + return self.mask_read_is_data(ins) def insns(self, seq): """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN @@ -6771,9 +6278,8 @@ def park_masks(self, blocks): self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} slots = lane_masks.parked(blocks[0], self.lane_masks) self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} - self.mark_exec_state(blocks[0], blocks[1]) # Instructions whose lane-mask data read will gather the wave's mask word (src_u's - # lane_mask_word path, gated by mask_word_read_ok) are cross-lane exchanges for the + # lane_mask_word path) are cross-lane exchanges for the # wave64-emulation planner: it must not fold them into a lane-local region or schedule # a barrier beside them (wave64_emulate_opt checks ins["mask_words"]). for blk in blocks[0]: