diff --git a/docs/design.md b/docs/design.md index daeb4eb425..4fde75f7d2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -417,6 +417,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: 32-bit lane-mask opposite-half and live-SCC barrier guards | Under `--wave64-emulate`, three 32-bit mask paths in `tools/rdna2spirv.py` emit cross-half `wave_mask` or `g_vote` exchanges (`x_round`/`x_split`): (1) opposite-half `_mask_b32_src` on `s_mov_b32`, `s_cselect_b32`, `s_not_b32`, and `MASK_SOP2_B32` (independent of SCC liveness), (2) live-SCC `scc_logic` votes on `_SOP2_B32_LOGIC`, and (3) opposite-half `wave_mask` on `s_*_saveexec_b32`/`s_*_wrexec_b32` (high-half source or `exec_hi`/`vcc_hi` destination, independent of SCC liveness). `tools/wave64_emulate_opt.py` (`_mask_chk_may_barrier`, shared by `_classify_block_body`, `find_local_exec_folds`, and `_insn_may_barrier_with_meta`) excludes all three from lane-local folded regions and multi-wave `inline_sync_free` guards while still allowing same-half dead-SCC 32-bit mask ops to fold; `_is_uniform_scc_safe` also checks `vcc_lo`/`vcc_hi` mask writes. Confirmed on the CPU by `tests/semantic/test_wave64_emulate_barriers.py` (`B32MaskBarrierTests`, 64- and 128-thread workgroup interpreter with uniform barrier checks and `spirv_asm.assemble`; all 9 folded cases crash on `main` before the change with `AssertionError: wave64 emulation: x_split inside a folded lane-local region`). **Not GPU-verified.** | | 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/tests/semantic/test_wave64_emulate_barriers.py b/tests/semantic/test_wave64_emulate_barriers.py index 7e8ba488f8..51772d2380 100644 --- a/tests/semantic/test_wave64_emulate_barriers.py +++ b/tests/semantic/test_wave64_emulate_barriers.py @@ -594,5 +594,200 @@ def test_ds_nop_stays_sync_free_in_multiwave_guard(self): self.assertEqual(mem[512 + l * 4], 900 + l, f"v5 w1 l={l} rev={rev}") +class B32MaskBarrierTests(unittest.TestCase): + def _insn(self, op, args): + return {"op": op, "args": args, "mods": [], "enc": None, "pc": 0} + + def test_unit_b32_opposite_half_and_live_scc_prediction(self): + vcc_lo = {"k": "special", "t": "vcc_lo"} + vcc_hi = {"k": "special", "t": "vcc_hi"} + exec_lo = {"k": "special", "t": "exec_lo"} + exec_hi = {"k": "special", "t": "exec_hi"} + s6 = {"k": "sgpr", "r": 6, "n": 1} + s7 = {"k": "sgpr", "r": 7, "n": 1} + s10 = {"k": "sgpr", "r": 10, "n": 1} + s12 = {"k": "sgpr", "r": 12, "n": 1} + lm_vcc = {"vcc": "mask", 6: "mask_lo", 7: "mask_hi"} + + cases = [ + # s_mov_b32: opposite-half mask destination emits wave_mask even with dead SCC + ("s_mov_b32", [vcc_lo, vcc_hi], lm_vcc, False, True), + ("s_mov_b32", [vcc_lo, s7], lm_vcc, False, True), + ("s_mov_b32", [exec_lo, vcc_hi], lm_vcc, False, True), + ("s_mov_b32", [vcc_hi, exec_lo], {}, False, True), + ("s_mov_b32", [vcc_lo, vcc_lo], lm_vcc, False, False), + ("s_mov_b32", [vcc_lo, s6], lm_vcc, False, False), + ("s_mov_b32", [vcc_lo, s10], {}, False, False), + # s_cselect_b32: opposite-half mask source emits wave_mask even with dead SCC + ("s_cselect_b32", [vcc_lo, vcc_hi, s10], lm_vcc, False, True), + ("s_cselect_b32", [vcc_lo, s10, s7], lm_vcc, False, True), + ("s_cselect_b32", [vcc_lo, vcc_lo, s10], lm_vcc, False, False), + # _SOP2_B32_LOGIC: opposite-half emits wave_mask regardless of SCC; live SCC votes on mask ops + ("s_and_b32", [vcc_lo, vcc_hi, s10], lm_vcc, False, True), + ("s_and_b32", [vcc_lo, s7, s10], lm_vcc, False, True), + ("s_not_b32", [vcc_lo, vcc_hi], lm_vcc, False, True), + ("s_not_b32", [vcc_lo, vcc_lo], lm_vcc, False, False), + ("s_not_b32", [vcc_lo, vcc_lo], lm_vcc, True, True), + ("s_and_b32", [vcc_lo, vcc_lo, s10], lm_vcc, False, False), + ("s_and_b32", [vcc_lo, vcc_lo, s10], lm_vcc, True, True), + ("s_and_b32", [s12, vcc_lo, s10], lm_vcc, False, False), + ("s_and_b32", [s12, vcc_lo, s10], lm_vcc, True, True), + ("s_or_b32", [s12, s10, s10], {}, True, False), + # saveexec_b32 / wrexec_b32: high-half source or high-half special dst emits wave_mask even when SCC is dead + ("s_and_saveexec_b32", [s10, vcc_hi], lm_vcc, False, True), + ("s_and_saveexec_b32", [s10, s7], lm_vcc, False, True), + ("s_and_saveexec_b32", [vcc_hi, s6], lm_vcc, False, True), + ("s_and_saveexec_b32", [exec_hi, s6], lm_vcc, False, True), + ("s_andn1_wrexec_b32", [s10, vcc_hi], lm_vcc, False, True), + ("s_andn1_wrexec_b32", [vcc_hi, s6], lm_vcc, False, True), + ("s_and_saveexec_b32", [s10, s6], lm_vcc, False, False), + ("s_and_saveexec_b32", [s10, s6], lm_vcc, True, True), + ] + for op, args, lm, scc_live_flag, want in cases: + ins = self._insn(op, args) + lm_map = {id(ins): lm} + scc_live = {id(ins)} if scc_live_flag else set() + self.assertEqual( + wave64_emulate_opt._insn_may_barrier(ins, lm_map, scc_live), + want, + f"_insn_may_barrier {op} {args} scc_live={scc_live_flag}", + ) + clean = wave64_emulate_opt._classify_block_body([ins], lm_map, scc_live, frozenset())[0] + self.assertEqual(clean, not want, f"_classify_block_body {op} {args} scc_live={scc_live_flag}") + + def test_opposite_half_and_live_scc_b32_inside_execz_regions(self): + # Every one of these triggers wave_mask or scc_logic vote under --wave64-emulate and previously tripped + # `AssertionError: wave64 emulation: x_split inside a folded lane-local region`. + cases = [ + ("s_mov_b32_vcc_opp", [ + ("v_cmp_ge_u32_e64 vcc, v0, 36", 8), + ("s_mov_b32 vcc_lo, vcc_hi", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ], lambda l: (20 if (l + 32) >= 36 else 10) if l < 16 else (20 if l >= 36 else 0)), + ("s_and_b32_vcc_opp_dead_scc", [ + ("v_cmp_ge_u32_e64 vcc, v0, 38", 8), + ("s_and_b32 vcc_lo, vcc_hi, -1", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ], lambda l: (20 if (l + 32) >= 38 else 10) if l < 16 else ((20 if l >= 38 else 10) if l >= 36 else 0)), + ("s_not_b32_vcc_opp_dead_scc", [ + ("v_cmp_ge_u32_e64 vcc, v0, 38", 8), + ("s_not_b32 vcc_lo, vcc_hi", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ], lambda l: (20 if not ((l + 32) >= 38) else 10) if l < 16 else ((20 if l >= 38 else 10) if l >= 36 else 0)), + ("s_cselect_b32_vcc_opp", [ + ("s_cmp_eq_u32 1, 1", 4), + ("v_cmp_ge_u32_e64 vcc, v0, 37", 8), + ("s_cselect_b32 vcc_lo, vcc_hi, 0", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ], lambda l: (20 if (l + 32) >= 37 else 10) if l < 16 else ((20 if l >= 37 else 10) if l >= 36 else 0)), + ("s_and_b32_vcc_same_live_scc", [ + ("v_cmp_eq_u32_e64 vcc, v0, 5", 8), + ("s_and_b32 vcc_lo, vcc_lo, -1", 4), + ("s_cselect_b32 s14, 77, 88", 4), + ("v_mov_b32_e32 v4, s14", 4), + ], lambda l: 77 if (l < 16 or l >= 36) else 0), + ("s_and_b32_sgpr_live_scc", [ + ("v_cmp_eq_u32_e64 vcc, v0, 5", 8), + ("s_and_b32 s15, vcc_lo, -1", 4), + ("s_cselect_b32 s14, 91, 92", 4), + ("v_mov_b32_e32 v4, s14", 4), + ], lambda l: 91 if (l < 16 or l >= 36) else 0), + ("s_and_saveexec_b32_hi_src", [ + ("v_cmp_ge_u32_e64 vcc, v0, 36", 8), + ("s_and_saveexec_b32 s14, vcc_hi", 4), + ("v_mov_b32_e32 v4, 33", 4), + ], lambda l: 33 if ((l < 16 and (l + 32) >= 36) or l >= 36) else 0), + ("s_andn1_wrexec_b32_hi_src", [ + ("v_cmp_ge_u32_e64 vcc, v0, 36", 8), + ("s_andn1_wrexec_b32 s14, vcc_hi", 4), + ("v_mov_b32_e32 v4, 44", 4), + ], lambda l: 44 if ((l < 16 and not ((l + 32) >= 36)) or l >= 36) else 0), + ("s_and_saveexec_b32_vcc_hi_dst", [ + ("v_cmp_lt_u32_e64 s[6:7], v0, 8", 8), + ("s_and_saveexec_b32 vcc_hi, s6", 4), + ("v_mov_b32_e32 v4, 55", 4), + ], lambda l: 55 if (l < 8 or l >= 36) else 0), + ] + for name, body, expect in cases: + with self.subTest(case=name): + skip_words = sum(nb for _, nb in body) // 4 + # Lanes 0..15 and 36..63 active so vcc_hi has non-zero bits while vcc_lo observes them. + insns = [ + ("v_mov_b32_e32 v4, 0", 4), + ("v_cmp_lt_u32_e64 s[4:5], v0, 16", 8), + ("v_cmp_ge_u32_e64 s[8:9], v0, 36", 8), + ("s_or_b64 s[4:5], s[4:5], s[8:9]", 4), + ("s_and_saveexec_b64 s[2:3], s[4:5]", 4), + (f"s_cbranch_execz {skip_words}", 4), + ] + body + [ + ("s_mov_b64 exec, s[2:3]", 4), + ("v_lshlrev_b32_e32 v10, 2, v0", 4), + ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ] + spv, _ = _translate_encoded("cs_" + name, insns, (64, 1, 1), emulate=True) + self.assertEqual(spirv_asm.assemble(spv, target_env="vulkan1.2")[:4], b"\x03\x02\x23\x07") + self.assertGreaterEqual(_pre_vote_or_atomic_count(spv), 1) + for rev in (False, True): + mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) + for lane in range(64): + self.assertEqual(mem[lane * 4], expect(lane), f"{name} lane {lane} rev={rev}") + + def test_same_half_b32_dead_scc_still_folds(self): + # Negative control: same-half s_and_b32 with dead SCC does not emit wave_mask/vote and still folds. + insns = [ + ("v_mov_b32_e32 v4, 0", 4), + ("v_cmp_lt_u32_e64 s[4:5], v0, 16", 8), + ("s_and_saveexec_b64 s[2:3], s[4:5]", 4), + ("s_cbranch_execz 5", 4), + ("v_cmp_lt_u32_e64 vcc, v0, 8", 8), + ("s_and_b32 vcc_lo, vcc_lo, -1", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ("s_mov_b64 exec, s[2:3]", 4), + ("v_lshlrev_b32_e32 v10, 2, v0", 4), + ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ] + spv, gen = _translate_encoded("cs_same_half_dead_scc", insns, (64, 1, 1), emulate=True) + self.assertEqual(_pre_vote_or_atomic_count(spv), 0) + self.assertEqual(sum(1 for b in gen.blocks if b is not None), 1) + mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) + for lane in range(64): + want = 20 if lane < 8 else (10 if lane < 16 else 0) + self.assertEqual(mem[lane * 4], want, f"lane {lane}") + + def test_opposite_half_b32_multiwave_divergent_guard(self): + # 128 threads: Wave 0 enters s_cbranch_scc0 guard containing `s_mov_b32 vcc_lo, vcc_hi` (dead SCC); + # Wave 1 skips it. The guard MUST NOT be placed in sync_free_blocks (would deadlock at OpControlBarrier). + insns = [ + ("s_mov_b64 exec, -1", 4), + ("v_mov_b32_e32 v4, 10", 4), + ("v_and_b32_e32 v1, 63, v0", 4), + ("v_cmp_ge_u32_e64 vcc, v1, 40", 8), + ("v_readfirstlane_b32 s19, v0", 4), + ("s_cmp_lt_u32 s19, 64", 4), + ("s_cbranch_scc0 3", 4), + ("s_mov_b32 vcc_lo, vcc_hi", 4), + ("v_cndmask_b32_e64 v4, 10, 20, vcc", 8), + ("v_lshlrev_b32_e32 v10, 2, v0", 4), + ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ] + spv, gen = _translate_encoded("cs_b32_opp_mw", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) + self.assertEqual(gen.control_flow, "emulated wave64 structured") + self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") + self.assertEqual(len(gen.emulate_plan["sync_free_blocks"]), 0) + self.assertGreaterEqual(len(gen.emulate_plan["mini_blocks"]), 1) + self.assertEqual(spirv_asm.assemble(spv, target_env="vulkan1.2")[:4], b"\x03\x02\x23\x07") + for rev in (False, True): + mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) + for l in range(64): + local = l & 63 + want = 20 if ((local < 32 and local + 32 >= 40) or local >= 40) else 10 + self.assertEqual(mem[l * 4], want, f"w0 l={l} rev={rev}") + for l in range(64, 128): + self.assertEqual(mem[l * 4], 10, f"w1 l={l} rev={rev}") + + if __name__ == "__main__": unittest.main() diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index d6e1ad7d5b..623bfe475b 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -186,6 +186,9 @@ _MASK_CHK_MBCNT = 2 _MASK_CHK_SCMP = 3 _MASK_CHK_SCC_VOTE = 4 +_MASK_CHK_B32_MOV = 5 +_MASK_CHK_B32_LOGIC = 6 +_MASK_CHK_B32_CSELECT = 7 # 4-bit dirty-state bitmask: bit0=("mem","r"), bit1=("mem","w"), bit2=("lds","r"), bit3=("lds","w") _DIRTY_MEM_R = 1 @@ -331,6 +334,12 @@ def _get_op_meta(raw_op): mask_chk = _MASK_CHK_SCMP elif op in _MASK_SCC_VOTE_OPS: mask_chk = _MASK_CHK_SCC_VOTE + elif op == "s_mov_b32": + mask_chk = _MASK_CHK_B32_MOV + elif op in _SOP2_B32_LOGIC: + mask_chk = _MASK_CHK_B32_LOGIC + elif op == "s_cselect_b32": + mask_chk = _MASK_CHK_B32_CSELECT else: mask_chk = _MASK_CHK_NONE @@ -833,6 +842,103 @@ def _is_mask_op(ins, x, lm_map): return _has_vcc_or_exec(x) +def _mask_half(x, lm_map): + """Matches Gen.mask_half (wave64) in tools/rdna2spirv.py: return 'lo', 'hi', or None.""" + k = x.get("k") + if k == "special": + t = x.get("t", "") + if t in ("exec_lo", "vcc_lo"): + return "lo" + if t in ("exec_hi", "vcc_hi"): + return "hi" + return None + if k == "sgpr" and x.get("n", 1) == 1: + mk = lm_map.get(x["r"]) + if mk == _lane_masks.MASK_LO: + return "lo" + if mk == _lane_masks.MASK_HI: + return "hi" + return None + + +def _mask_b32_dst_half(d, srcs, ins, lm_map): + """Matches Gen._mask_b32_dst_half (wave64) in tools/rdna2spirv.py: return (to_mask_dst, half).""" + if d.get("k") != "special": + return False, None + t = d.get("t", "") + if t in ("exec_lo", "exec_hi"): + return True, "hi" if t == "exec_hi" else "lo" + if t in ("vcc_lo", "vcc_hi") and ("vcc" in lm_map or any(_holds_lane_mask(ins, s, lm_map) for s in srcs)): + return True, "hi" if t == "vcc_hi" else "lo" + return False, None + + +def _mask_chk_may_barrier(ins, meta, lane_masks, scc_live): + """True iff `ins` (with non-zero `meta[11]`) may emit wave_mask / wave_equal / g_vote under --wave64-emulate.""" + mask_chk = meta[11] + a = ins["args"] + if mask_chk == _MASK_CHK_SCC_VOTE: + op = meta[0] + if op.endswith("_b32") and op in _ALL_SAVEEXEC_WREXEC: + # In wave64, s_*_saveexec_b32 / s_*_wrexec_b32 operate on EXEC_LO and collect an opposite-half + # wave_mask when the source is in the high half or the saved destination is exec_hi/vcc_hi, + # independent of SCC liveness (rdna2spirv.py). + if a and a[0].get("k") == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): + return True + if len(a) >= 2: + lm = lane_masks.get(id(ins), {}) + if _holds_lane_mask(ins, a[1], lm) and _mask_half(a[1], lm) == "hi": + return True + if not scc_live or id(ins) not in scc_live: + return False + if (meta[8] & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])): + return True + lm = lane_masks.get(id(ins), {}) + return any(_is_mask_op(ins, x, lm) for x in a[1:]) + if mask_chk == _MASK_CHK_B32_MOV: + if len(a) < 2: + return False + lm = lane_masks.get(id(ins), {}) + to_mask_dst, dst_half = _mask_b32_dst_half(a[0], a[1:2], ins, lm) + return (to_mask_dst and dst_half is not None + and _holds_lane_mask(ins, a[1], lm) and _mask_half(a[1], lm) not in (None, dst_half)) + if mask_chk == _MASK_CHK_B32_CSELECT: + if len(a) < 3: + return False + lm = lane_masks.get(id(ins), {}) + srcs = a[1:3] + to_mask_dst, dst_half = _mask_b32_dst_half(a[0], srcs, ins, lm) + return (to_mask_dst and dst_half is not None and all(_lane_masks._maskable_b32(s) for s in srcs) + and any(_holds_lane_mask(ins, s, lm) and _mask_half(s, lm) not in (None, dst_half) for s in srcs)) + if mask_chk == _MASK_CHK_B32_LOGIC: + if len(a) < 2: + return False + lm = lane_masks.get(id(ins), {}) + srcs = a[1:2] if meta[0] == "s_not_b32" else a[1:3] + to_mask_dst, dst_half = _mask_b32_dst_half(a[0], srcs, ins, lm) + if (to_mask_dst and dst_half is not None and all(_lane_masks._maskable_b32(s) for s in srcs) + and any(_holds_lane_mask(ins, s, lm) and _mask_half(s, lm) not in (None, dst_half) for s in srcs)): + return True + if scc_live and id(ins) in scc_live: + if to_mask_dst: + return True + mask_srcs = [s for s in srcs if _holds_lane_mask(ins, s, lm)] + if mask_srcs: + halves = {_mask_half(s, lm) for s in mask_srcs} - {None} + if len(halves) <= 1: + return True + return False + if mask_chk == _MASK_CHK_WORD_READER: + return len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})) + if mask_chk == _MASK_CHK_MBCNT: + return len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})) + # _MASK_CHK_SCMP + lm = lane_masks.get(id(ins), {}) + return any(_holds_lane_mask(ins, x, lm) or + (meta[0] in ("s_cmp_eq_u64", "s_cmp_lg_u64") and _has_any_lane_mask_word(x, lm)) + for x in a) + + def _is_exec_op_arg(x): return x.get("k") == "special" and x.get("t", "") == "exec" @@ -923,29 +1029,10 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes): if sacc[1]: mem_w = True - # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). + # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`/`scc_logic`). a = ins["args"] - mask_chk = m[11] - if mask_chk: - if mask_chk == _MASK_CHK_SCC_VOTE: - if has_scc_live and id(ins) in scc_live: - if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])): - return False, _EMPTY_MEM_STATS, 0, (), () - lm = lane_masks.get(id(ins), {}) - if any(_is_mask_op(ins, x, lm) for x in a[1:]): - return False, _EMPTY_MEM_STATS, 0, (), () - elif mask_chk == _MASK_CHK_WORD_READER: - if len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})): - return False, _EMPTY_MEM_STATS, 0, (), () - elif mask_chk == _MASK_CHK_MBCNT: - if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})): - return False, _EMPTY_MEM_STATS, 0, (), () - else: # _MASK_CHK_SCMP - lm = lane_masks.get(id(ins), {}) - if any(_holds_lane_mask(ins, x, lm) or - (m[0] in ("s_cmp_eq_u64", "s_cmp_lg_u64") and _has_any_lane_mask_word(x, lm)) - for x in a): - return False, _EMPTY_MEM_STATS, 0, (), () + if m[11] and _mask_chk_may_barrier(ins, m, lane_masks, scc_live if has_scc_live else None): + return False, _EMPTY_MEM_STATS, 0, (), () # 3. Track scalar writes and EXEC writes. _, ins_mw, _ = _scalar_rw_with_meta(ins, m) @@ -1292,32 +1379,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr mem_w = True a = ins["args"] - mask_chk = m[11] - if mask_chk: - if mask_chk == _MASK_CHK_SCC_VOTE: - if has_scc_live and id(ins) in scc_live: - if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])): - clean = False - continue - lm = lane_masks.get(id(ins), {}) - if any(_is_mask_op(ins, x, lm) for x in a[1:]): - clean = False - continue - elif mask_chk == _MASK_CHK_WORD_READER: - if len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})): - clean = False - continue - elif mask_chk == _MASK_CHK_MBCNT: - if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})): - clean = False - continue - else: # _MASK_CHK_SCMP - lm = lane_masks.get(id(ins), {}) - if any(_holds_lane_mask(ins, x, lm) or - (m[0] in ("s_cmp_eq_u64", "s_cmp_lg_u64") and _has_any_lane_mask_word(x, lm)) - for x in a): - clean = False - continue + if m[11] and _mask_chk_may_barrier(ins, m, lane_masks, scc_live if has_scc_live else None): + clean = False + continue may_w |= ins_mw s_bits = ins_mw & _ALL_SGPRS @@ -1521,8 +1585,8 @@ def _is_uniform_scc_safe(active_blocks, lane_masks, scc_live): continue a = ins["args"] lm = lane_masks.get(ins_id, {}) - writes_exec = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec") - if writes_exec or any(_holds_lane_mask(ins, x, lm) for x in a[1:]): + to_mask_dst, _ = _mask_b32_dst_half(a[0], a[1:], ins, lm) if a else (False, None) + if to_mask_dst or any(_holds_lane_mask(ins, x, lm) for x in a[1:]): return False return True @@ -1533,25 +1597,9 @@ def _insn_may_barrier_with_meta(ins, meta, lane_masks, scc_live): flags = meta[8] if flags & _FLAG_ALWAYS_BARRIER or _vcc_pair_collects_mask(ins, lane_masks): return True - mask_chk = meta[11] - if not mask_chk: + if not meta[11]: return False - a = ins["args"] - if mask_chk == _MASK_CHK_SCC_VOTE: - if not scc_live or id(ins) not in scc_live: - return False - if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])): - return True - lm = lane_masks.get(id(ins), {}) - return any(_is_mask_op(ins, x, lm) for x in a[1:]) - if mask_chk == _MASK_CHK_WORD_READER: - return len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})) - if mask_chk == _MASK_CHK_MBCNT: - return len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})) - lm = lane_masks.get(id(ins), {}) - return any(_holds_lane_mask(ins, x, lm) or - (meta[0] in ("s_cmp_eq_u64", "s_cmp_lg_u64") and _has_any_lane_mask_word(x, lm)) - for x in a) + return _mask_chk_may_barrier(ins, meta, lane_masks, scc_live) def _insn_may_barrier(ins, lane_masks, scc_live):