From 5668f16b490a182452521fca3ccfc29e682eca2b Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Tue, 24 Nov 2026 09:18:49 -0500 Subject: [PATCH 1/2] wave64 emulate: a cross-lane read of a missing lane in a partial wave gives 0 Restores old upstream PR 7450, ported onto main. With --wave64-emulate, every read of another lane's exchange slot (ds_swizzle, ds_bpermute, ds_permute, readlane, ...) now selects 0 when the source lane does not exist in a partial last wave (Gen.x_lane_word), instead of relying on the prologue's zeroed slot. RADV (Mesa 26.3.1) turned the store, barrier and load of an exchange behind a branch into masked_swizzle_amd with fetch_inactive, so in a 40-thread group lanes 32-39 of a SWAP 8 swizzle read the missing lanes' registers. Full waves emit the same module as before. scripts/run_gpu_tests.py now runs the partial-wave fixtures emulated at subgroup 32, as check.py's partial_wave_test does. It left the subgroup size to the driver, and RADV picks 64 for compute, where the new fixture passed even without the fix. GPU test cs_w64x_partial_swizzle (words measured on gfx1036 through tools/hw_oracle), semantic test test_w64x_partial_swizzle with a hand-written fixture, and a contract-table row in docs/design.md. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 1 + runtime/test/shaders/check.py | 3 +- .../test/shaders/cs_w64x_partial_swizzle.asm | 78 +++++++++++++++++++ scripts/run_gpu_tests.py | 15 ++-- .../fixtures/disasm/cs_w64x_partial_swizzle.s | 59 ++++++++++++++ .../fixtures/w64x_partial_swizzle.asm | 20 +++++ tests/semantic/test_w64x_partial_swizzle.py | 77 ++++++++++++++++++ tools/rdna2spirv.py | 31 ++++++-- 8 files changed, 272 insertions(+), 12 deletions(-) create mode 100644 runtime/test/shaders/cs_w64x_partial_swizzle.asm create mode 100644 tests/semantic/fixtures/disasm/cs_w64x_partial_swizzle.s create mode 100644 tests/semantic/fixtures/w64x_partial_swizzle.asm create mode 100644 tests/semantic/test_w64x_partial_swizzle.py diff --git a/docs/design.md b/docs/design.md index 3f2d522517..93f209c147 100644 --- a/docs/design.md +++ b/docs/design.md @@ -402,6 +402,7 @@ How the generated SPIR-V expects the runtime to work: | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | +| Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index fe0d98bcee..2a045c2ee7 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -440,7 +440,8 @@ def shift64_test(tools, spirv, env=None): ("cs_w64x_saveexec_b64", [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171])] # A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), - ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])] + ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0]), + ("cs_w64x_partial_swizzle", [508, 523, 0, 0, 528, 0, 531, 0])] PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036) "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), diff --git a/runtime/test/shaders/cs_w64x_partial_swizzle.asm b/runtime/test/shaders/cs_w64x_partial_swizzle.asm new file mode 100644 index 0000000000..44ac9061d4 --- /dev/null +++ b/runtime/test/shaders/cs_w64x_partial_swizzle.asm @@ -0,0 +1,78 @@ +; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm +; Partial wave64, ds_swizzle_b32 / ds_bpermute_b32 from a lane that doesn't exist: a 40x1x1 group is one wave with +; lanes 0-39 running and 40-63 missing. A source lane that doesn't exist reads 0 (RDNA2 ISA, ds_swizzle/ds_bpermute of +; a lane that isn't running; on gfx1036 through tools/hw_oracle, 40 threads, native wave64: lanes 32-39 of SWAP 8 and +; of BROADCAST 16,15 read 0). The exchange sits after a vote and an s_cbranch_execz, as in the crosslane_fuzz +; programs that found it (seed 48315): with --wave64-emulate, RADV (Mesa 26.3.1) turned the store, barrier and load of +; the exchange slot into a subgroup swizzle that fetched the missing lane's register, so lanes 32-39 read garbage +; that changed between runs although the slot was zeroed. +; v1 = lane, v2 = 500 + lane, s8 = s_bcnt1 of EXEC (40, an exchange before the branch). +; v3 = ds_swizzle SWAP 8 of v2 (source lane ^ 8): lane 0 -> 8 -> 508, lane 31 -> 23 -> 523, lane 33 -> 41 -> 0, +; lane 39 -> 47 -> 0. +; v4 = ds_bpermute with addr = (lane ^ 8) * 4 (each half its own 32 lanes): lane 20 -> 28 -> 528, lane 33 -> 41 -> 0. +; v5 = ds_swizzle BROADCAST 16,15 (lane 15 of each group of 16): lane 20 -> 31 -> 531, lane 35 -> 47 -> 0. +; Stores: out[0] lane 0 v3, out[1] lane 31 v3, out[2] lane 33 v3, out[3] lane 39 v3, out[4] lane 20 v4, +; out[5] lane 33 v4, out[6] lane 20 v5, out[7] lane 35 v5. +; As for cs_w64x_partial, 40 threads can't have full subgroups: check.py asks for subgroup size 64 (32 when emulated). +; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64x_partial_swizzle.spv 1 dump +; -> out[0..7] = 508 523 0 0 528 0 531 0 +; mattr: +wavefrontsize64,-wavefrontsize32 +; group: 40,1,1 +v_mbcnt_lo_u32_b32 v1, -1, 0 +v_mbcnt_hi_u32_b32 v1, -1, v1 +v_add_nc_u32_e32 v2, 500, v1 +v_mov_b32_e32 v3, 99 +v_mov_b32_e32 v4, 99 +v_mov_b32_e32 v5, 99 +s_mov_b64 s[6:7], exec +s_bcnt1_i32_b64 s8, exec +v_cmp_gt_u32_e64 s[4:5], 48, v1 +s_and_saveexec_b64 s[10:11], s[4:5] +s_cbranch_execz 9 +ds_swizzle_b32 v3, v2 offset:swizzle(SWAP,8) +ds_swizzle_b32 v5, v2 offset:swizzle(BROADCAST,16,15) +v_xor_b32_e32 v6, 8, v1 +v_lshlrev_b32_e32 v6, 2, v6 +ds_bpermute_b32 v4, v6, v2 +s_waitcnt lgkmcnt(0) +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32_e32 v20, v3 +v_mov_b32_e32 v21, 0 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 31, v1 +v_mov_b32_e32 v20, v3 +v_mov_b32_e32 v21, 4 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 33, v1 +v_mov_b32_e32 v20, v3 +v_mov_b32_e32 v21, 8 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 39, v1 +v_mov_b32_e32 v20, v3 +v_mov_b32_e32 v21, 12 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 20, v1 +v_mov_b32_e32 v20, v4 +v_mov_b32_e32 v21, 16 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 33, v1 +v_mov_b32_e32 v20, v4 +v_mov_b32_e32 v21, 20 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 20, v1 +v_mov_b32_e32 v20, v5 +v_mov_b32_e32 v21, 24 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_mov_b64 exec, s[6:7] +v_cmpx_eq_u32_e32 35, v1 +v_mov_b32_e32 v20, v5 +v_mov_b32_e32 v21, 28 +buffer_store_dword v20, v21, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 80b380d9e3..479c5b64c5 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1168,7 +1168,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", "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_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", + "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_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): cs_dump_wants = { @@ -1252,6 +1252,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave + "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], @@ -1286,10 +1287,12 @@ def run_suite(a, work: str) -> int: # as check.py does, where the device has none # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were # translated with --wave64-emulate and run on any subgroup size. - # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for - # size 64 without them. + # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full + # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the + # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there + # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. emulated = w64_emulated() - partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") + partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", @@ -1299,8 +1302,8 @@ def run_suite(a, work: str) -> int: "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec", "cs_w32_exec_computed") and not emulated and not partial - if partial and not emulated: - cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") + 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) cs_env = dict(os.environ, **WAVE32_LANE_ENV) rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) diff --git a/tests/semantic/fixtures/disasm/cs_w64x_partial_swizzle.s b/tests/semantic/fixtures/disasm/cs_w64x_partial_swizzle.s new file mode 100644 index 0000000000..51e79edb20 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_partial_swizzle.s @@ -0,0 +1,59 @@ +; cs_w64x_partial_swizzle test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_partial_swizzle.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 500, v1 + v_mov_b32_e32 v3, 99 + v_mov_b32_e32 v4, 99 + v_mov_b32_e32 v5, 99 + s_mov_b64 s[6:7], exec + s_bcnt1_i32_b64 s8, exec + v_cmp_gt_u32_e64 s[4:5], 48, v1 + s_and_saveexec_b64 s[10:11], s[4:5] + s_cbranch_execz 9 + ds_swizzle_b32 v3, v2 offset:swizzle(SWAP,8) + ds_swizzle_b32 v5, v2 offset:swizzle(BROADCAST,16,15) + v_xor_b32_e32 v6, 8, v1 + v_lshlrev_b32_e32 v6, 2, v6 + ds_bpermute_b32 v4, v6, v2 + s_waitcnt lgkmcnt(0) + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v3 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 31, v1 + v_mov_b32_e32 v20, v3 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v3 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, v3 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 20, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 20, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 35, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/w64x_partial_swizzle.asm b/tests/semantic/fixtures/w64x_partial_swizzle.asm new file mode 100644 index 0000000000..897fb5617e --- /dev/null +++ b/tests/semantic/fixtures/w64x_partial_swizzle.asm @@ -0,0 +1,20 @@ +; Wave64 cross-lane reads from lanes that don't exist in a partial last wave (straight-line; the GPU test +; runtime/test/shaders/cs_w64x_partial_swizzle.asm has the same three reads behind a vote and an EXECZ branch). +; v1 = wave lane, v2 = 500 + lane. Every lane stores v3, v4, v5 at 12 * thread: +; v3 = ds_swizzle SWAP 8 (source lane ^ 8), v4 = ds_bpermute with addr (lane ^ 8) * 4, +; v5 = ds_swizzle BROADCAST 16,15 (lane 15 of each group of 16). +; A source lane that doesn't exist reads 0 (measured on gfx1036 through tools/hw_oracle, 40 threads, wave64). +v_mbcnt_lo_u32_b32 v1, -1, 0 +v_mbcnt_hi_u32_b32 v1, -1, v1 +v_add_nc_u32_e32 v2, 500, v1 +ds_swizzle_b32 v3, v2 offset:swizzle(SWAP,8) +ds_swizzle_b32 v5, v2 offset:swizzle(BROADCAST,16,15) +v_xor_b32_e32 v6, 8, v1 +v_lshlrev_b32_e32 v6, 2, v6 +ds_bpermute_b32 v4, v6, v2 +s_waitcnt lgkmcnt(0) +v_mul_u32_u24_e32 v22, 12, v0 +buffer_store_dword v3, v22, s[0:3], 0 offen +buffer_store_dword v4, v22, s[0:3], 0 offen offset:4 +buffer_store_dword v5, v22, s[0:3], 0 offen offset:8 +s_endpgm diff --git a/tests/semantic/test_w64x_partial_swizzle.py b/tests/semantic/test_w64x_partial_swizzle.py new file mode 100644 index 0000000000..963ec21a12 --- /dev/null +++ b/tests/semantic/test_w64x_partial_swizzle.py @@ -0,0 +1,77 @@ +"""--wave64-emulate: a cross-lane read from a lane that doesn't exist in a partial last wave gives 0. + +The exchange slots of the missing lanes are zeroed in the prologue, but the read must not depend on that: RADV +(Mesa 26.3.1, gfx1036 and RX 7900 XTX) turned the store, barrier and load of an emulated ds_swizzle into a subgroup +swizzle that fetched the missing lane's register, so lanes 32-39 of a 40-thread group read garbage (crosslane_fuzz +seed 48315, 7 programs; runtime/test/shaders/cs_w64x_partial_swizzle.asm). The translator now selects 0 by the +source lane's place in the workgroup. Here the prologue's zero stores are replaced by a poison word before the +workgroup interpreter runs the module, so a read that still took the slot shows the poison. + +Fixture: fixtures/w64x_partial_swizzle.asm (hand-written; expected words from its header, the RDNA2 ISA rule for a +source lane that isn't running, and the gfx1036 hardware oracle). +""" +import re +import struct +import sys +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from support import rdna2spirv, translate_lines # noqa: E402 +from test_wave64_emulate_opt import VSHARP, run_emulated_workgroup # noqa: E402 + +POISON = 0xDEADBEEF +FIXTURE = Path(__file__).with_name("fixtures") / "w64x_partial_swizzle.asm" + + +def translate(threads, emulate=True): + lines = [ln for ln in FIXTURE.read_text(encoding="ascii").splitlines() if ln and not ln.startswith(";")] + fssm = bytearray(0x148) # header word 0xD4 = 0: wave64 + struct.pack_into("<4I", fssm, 0x138, 0x8, threads, 1, 1) # four user SGPRs (the output V#) + with patch.object(rdna2spirv, "WAVE64_EMULATE", emulate): + return translate_lines(f"cs_w64x_partial_swizzle_{threads}", lines, fssm=bytes(fssm)) + + +def poison_missing_slots(spv): + """The prologue's zero stores to the missing lanes' slots store POISON instead.""" + spv, n = re.subn(r"(OpStore %x_yp\d+_\d+ )%\w+", rf"\1%x_poison", spv) + head = re.search(r"^%uint = OpTypeInt 32 0\n", spv, re.MULTILINE) + return spv[:head.end()] + f"%x_poison = OpConstant %uint {POISON}\n" + spv[head.end():], n + + +def expected(threads): + words = {} + for t in range(threads): + lane, base = t % 64, t - t % 64 + + def read(src): + return 500 + src if base + src < threads else 0 + words[t] = (read(lane ^ 8), read(lane ^ 8), read((lane & ~15) | 15)) + return words + + +class PartialWaveSwizzle(unittest.TestCase): + def check(self, threads): + spv, stores = poison_missing_slots(translate(threads)) + self.assertGreater(stores, 0, "the prologue zeroes the missing lanes' slots") + mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28) + for t, want in expected(threads).items(): + got = tuple(mem.get(12 * t + 4 * k, 0) for k in range(3)) + self.assertEqual(got, want, f"thread {t} of {threads}") + + def test_one_partial_wave(self): + self.check(40) # lanes 32-39 read lanes 40-47 (SWAP 8, bpermute) and 47 (BROADCAST 16,15) + + def test_partial_second_wave(self): + self.check(104) # wave 1 has lanes 0-39; wave 0 is full and reads its own lanes + + def test_full_waves_unchanged(self): + # No select is added where every lane exists: the module is the one the plain slot read gives. + with patch.object(rdna2spirv.Gen, "x_lane_word", lambda self, idx, lane: self.x_word(idx)): + plain = translate(64) + self.assertEqual(translate(64), plain) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae8..f239a12829 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -5522,6 +5522,27 @@ def x_word(self, idx): self.emit(f"{v} = OpLoad %uint {p}") return v + def x_lane_word(self, idx, lane): + """The data slot `idx` of lane `lane` (0-63) of this wave, read in an exchange. A lane of a partial last wave + that doesn't exist reads as 0 (as a source that isn't running does for ds_swizzle / ds_bpermute on the + hardware): the value is selected by the lane's place in the workgroup, not left to the zeroed slot, because + RADV (Mesa 26.3.1) turns a store, barrier and load of another lane's slot into a subgroup swizzle that + fetches the missing lane's register instead. Full waves read the slot as before.""" + v = self.x_word(idx) + size = (self.cs or self.ms)["size"] + threads = size[0] * size[1] * size[2] + if threads >= self.x_lanes: + return v + if self.x_lanes == 64: + at = lane + else: + at = self.tmp() + self.emit(f"{at} = OpIAdd %uint %x_wbase {lane}") + ok, r = self.tmp(), self.tmp() + self.emit(f"{ok} = OpULessThan %bool {at} {self.cu(threads)}") + self.emit(f"{r} = OpSelect %uint {ok} {v} {self.cu(0)}") + return r + def x_mask_slot(self, it): """Index of the wave's first mask word in the slot of round `it`.""" s, a, b, c = (self.tmp() for _ in range(4)) @@ -5667,11 +5688,11 @@ def read(lane): if w == 1: j = self.tmp() self.emit(f"{j} = OpIAdd %uint {data_base} {lane}") - return self.x_word(j) + return self.x_lane_word(j, lane) i, j = self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {data_base} %x_wbase") self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) + return self.x_lane_word(j, lane) return read, None if data is None and bits is not None and bits[0] is not None and bits[1] is None: fn = self._ensure_x_pre_fn("vote") @@ -5716,11 +5737,11 @@ def read(lane): if w == 1: j = self.tmp() self.emit(f"{j} = OpIAdd %uint {base} {lane}") - return self.x_word(j) + return self.x_lane_word(j, lane) i, j = self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) + return self.x_lane_word(j, lane) return read, res it = self.tmp() self.emit(f"{it} = OpLoad %uint %x_it") @@ -5758,7 +5779,7 @@ def read(lane): self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") j = self.tmp() self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) + return self.x_lane_word(j, lane) return read, res def x_memory_order(self, op): From 485e38fb696d4f442f5e026b5dac3ae73c69b8ae Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 14:38:56 -0500 Subject: [PATCH 2/2] test_w64x_partial_swizzle: poison the prologue's OpAtomicStore zeroes main now resets the missing lanes' exchange slots with OpAtomicStore (19e42d6de) instead of OpStore, so the test's poison substitution matched nothing and both partial-wave cases failed on their own guard. Match the atomic store's value operand instead. Without x_lane_word the 40-thread case still fails, so the test keeps covering the fix. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_w64x_partial_swizzle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/semantic/test_w64x_partial_swizzle.py b/tests/semantic/test_w64x_partial_swizzle.py index 963ec21a12..d2bbe9fa87 100644 --- a/tests/semantic/test_w64x_partial_swizzle.py +++ b/tests/semantic/test_w64x_partial_swizzle.py @@ -35,7 +35,7 @@ def translate(threads, emulate=True): def poison_missing_slots(spv): """The prologue's zero stores to the missing lanes' slots store POISON instead.""" - spv, n = re.subn(r"(OpStore %x_yp\d+_\d+ )%\w+", rf"\1%x_poison", spv) + spv, n = re.subn(r"(OpAtomicStore %x_yp\d+_\d+ %\w+ %\w+ )%\w+", rf"\1%x_poison", spv) head = re.search(r"^%uint = OpTypeInt 32 0\n", spv, re.MULTILINE) return spv[:head.end()] + f"%x_poison = OpConstant %uint {POISON}\n" + spv[head.end():], n