From e72218ed2a4116737cd4bfebbfddb79558c077ce Mon Sep 17 00:00:00 2001 From: SweatierKey <53280918+SweatierKey@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:51:49 +0100 Subject: [PATCH] wave64_emulate_opt: flow-sensitive must-be-zero proof in _exec_writes_stay_inactive --- docs/design.md | 1 + tests/semantic/test_wave64_emulate_opt.py | 52 +++++++ tests/test_wave64_emulate_opt_cfg.py | 92 ++++++++++++ tools/wave64_emulate_opt.py | 168 +++++++++++++++++++++- 4 files changed, 307 insertions(+), 6 deletions(-) diff --git a/docs/design.md b/docs/design.md index 3f2d522517..4717fe8bca 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: flow-sensitive EXEC-inactive check in folded EXECZ regions | Inside a candidate lane-local `s_cbranch_execz`/`execnz` region, `_exec_writes_stay_inactive` in `tools/wave64_emulate_opt.py` runs a forward must-be-zero dataflow over 64-bit SGPR pairs `s[0..126]` and `vcc` (tracking `s_*_saveexec_b64`, `s_andn1/andn2_wrexec_b64`, `v_cmp_*`, `s_and/andn2/or/xor/mov/cselect/cmov_b64`, and killing every overlapping pair on partial 32-bit or non-preserving writes, with a post-convergence verification pass over cycles). Previously the check was flow-insensitive per register pair, so reusing a scratch pair with `s_or_b64` / `s_xor_b64 ..., -1` right before `s_and_saveexec_b64 s[r:r+1], s[r:r+1]` falsely rejected the outer EXECZ fold and forced a wave vote + workgroup barrier. Confirmed on the CPU by `tests/test_wave64_emulate_opt_cfg.py` (`FlowSensitiveExecInactiveTest`: 7 positive and negative soundness cases) and `tests/semantic/test_wave64_emulate_opt.py` (`test_flow_sensitive_reused_scratch_saveexec_folds_without_barriers`, 64 and 128 threads, 0 wave votes, passes `spirv-val`), and GPU-verified on NVIDIA GeForce RTX 5070 Ti (driver 616.92, Windows 11) across 30 emulated wave64 compute fixtures plus the nested scratch-saveexec pattern. | | 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_opt.py b/tests/semantic/test_wave64_emulate_opt.py index da6400036c..692ae69733 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -1753,6 +1753,58 @@ def test_bounded_opcode_caches_and_superblock_dirty_transfer(self): self.assertEqual(plan["dirty_in"][3], frozenset({("mem", "r")})) self.assertEqual(plan["dirty_in"][4], frozenset({("mem", "r")})) + def test_flow_sensitive_reused_scratch_saveexec_folds_without_barriers(self): + """Nested EXECZ region reusing s[40:41] via s_or/s_xor -1 before s_and_saveexec_b64 folds with 0 barriers.""" + # Outer EXECZ keeps lanes with (lane & 1) == 0 active. + # Inside, s[40:41] is first computed with s_or_b64 + s_xor_b64 -1 (non-zero for inactive lanes), + # then overwritten with old EXEC by s_and_saveexec_b64 s[40:41], s[40:41], followed by an inner + # EXECZ branch that modifies v2 and restores EXEC via s_mov_b64 exec, s[40:41]. + insns = [ + ("v_mov_b32_e32 v1, 100", 4), # outer result + ("v_mov_b32_e32 v2, 200", 4), # inner result + ("v_and_b32_e32 v3, 1, v0", 4), + ("v_and_b32_e32 v4, 2, v0", 4), + ("v_and_b32_e32 v5, 4, v0", 4), + ("v_cmp_eq_u32_e64 s[4:5], 0, v4", 8), # bit 1 == 0 + ("v_cmp_eq_u32_e64 s[6:7], 0, v5", 8), # bit 2 == 0 + ("v_cmp_eq_u32_e64 s[8:9], 0, v3", 8), # bit 0 == 0 (outer guard) + ("s_and_saveexec_b64 s[10:11], s[8:9]", 4), + ("s_cbranch_execz 9", 4), # skip to restore (9 dwords) + # --- folded outer region (9 dwords) --- + ("v_add_nc_u32_e32 v1, 10, v1", 4), # 1 dw: active if bit0==0 -> 110 + ("s_or_b64 s[40:41], s[4:5], s[6:7]", 4), # 1 dw: bit1==0 || bit2==0 + ("s_xor_b64 s[40:41], s[40:41], -1", 4), # 1 dw: bit1!=0 && bit2!=0 (non-zero on inactive!) + ("s_and_saveexec_b64 s[40:41], s[40:41]", 4), # 1 dw: overwrites s[40:41] with old EXEC (0 on inactive) + ("s_cbranch_execz 1", 4), # 1 dw: skip 1 dw inner body + ("v_add_nc_u32_e32 v2, 33, v2", 4), # 1 dw: active if bit0==0 && bit1!=0 && bit2!=0 -> 233 + ("s_mov_b64 exec, s[40:41]", 4), # 1 dw: restore outer EXEC from s[40:41] + ("v_add_nc_u32_e32 v1, 5, v1", 4), # 1 dw: active if bit0==0 -> 115 + ("s_nop 0", 4), # 1 dw + # --- outer join --- + ("s_or_b64 exec, exec, s[10:11]", 4), + ("v_add_nc_u32_e32 v3, v1, v2", 4), + ("v_lshlrev_b32_e32 v6, 2, v0", 4), + ("buffer_store_dword v3, v6, s[0:3], 0 offen", 8), + ("s_endpgm", 4), + ] + for wg in ((64, 1, 1), (128, 1, 1)): + spv, gen = _translate_encoded("cs_flow_sens_saveexec", insns, wg, emulate=True) + self.assertEqual(_switch_case_count(gen), 1, + f"expected entire nested scratch-saveexec region to fold to 1 superblock (wg={wg})") + self.assertEqual(spv.count("OpAtomicOr"), 0, + f"expected 0 wave votes when scratch saveexec region folds (wg={wg})") + self.assertNotIn("OpGroupNonUniform", spv) + mem, _ = run_emulated_workgroup(spv, wg, push_constants=VSHARP + [0] * 28) + for lane in range(wg[0]): + v1 = 100 + v2 = 200 + if (lane & 1) == 0: + v1 += 10 + if (lane & 2) != 0 and (lane & 4) != 0: + v2 += 33 + v1 += 5 + self.assertEqual(mem[lane * 4], v1 + v2, f"wg={wg} lane={lane}") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_wave64_emulate_opt_cfg.py b/tests/test_wave64_emulate_opt_cfg.py index 62131e3742..b976dc11ea 100644 --- a/tests/test_wave64_emulate_opt_cfg.py +++ b/tests/test_wave64_emulate_opt_cfg.py @@ -277,5 +277,97 @@ def test_loop_shape_is_kept_and_a_guard_needs_proof_in_front_of_it(self): self.assertEqual(out, [("guard", 2, [("block", 1)])]) +class FlowSensitiveExecInactiveTest(unittest.TestCase): + """Flow-sensitive must-be-zero proof in `_exec_writes_stay_inactive`.""" + + def _run_check(self, blocks, succ, region=None, run=0, run_live_in=0): + active_blocks = [w._active_insns(b) for b in blocks] + blk_info = [w._classify_block_body(b, {}, set(), set()) for b in active_blocks] + if region is None: + region = frozenset(range(len(blocks))) + return w._exec_writes_stay_inactive( + region, blk_info, run_live_in, run=run, succ=succ, active_blocks=active_blocks + ) + + def test_scratch_pair_clobbered_before_saveexec_then_restored_is_safe(self): + # s[40:41] first receives a non-zero mask via s_xor_b64 -1, then is overwritten + # by s_and_saveexec_b64 (old EXEC == 0 for inactive lanes) before restoring EXEC. + imm = lambda v: {"k": "imm", "v": v} + vgpr = lambda r: {"k": "vgpr", "r": r, "n": 1} + blocks = blocks_of( + [ + ins("s_or_b64", sgpr(40, 2), sgpr(4, 2), sgpr(6, 2)), + ins("s_xor_b64", sgpr(40, 2), sgpr(40, 2), imm(-1)), + ins("s_and_saveexec_b64", sgpr(40, 2), sgpr(40, 2)), + ins("s_cbranch_execz", imm(1)), + ], + [ins("v_add_nc_u32", vgpr(0), vgpr(0), imm(1))], + [ins("s_mov_b64", special("exec"), sgpr(40, 2))], + ) + self.assertTrue(self._run_check(blocks, succ=[[2, 1], [2], []])) + + def test_vcmp_and_cselect_zero_masks_preserve_inactive_lanes(self): + imm = lambda v: {"k": "imm", "v": v} + vgpr = lambda r: {"k": "vgpr", "r": r, "n": 1} + blocks = blocks_of( + [ + ins("v_cmp_eq_u32_e64", sgpr(40, 2), vgpr(0), imm(0)), + ins("s_cselect_b64", sgpr(42, 2), sgpr(40, 2), imm(0)), + ins("s_or_b64", special("exec"), special("exec"), sgpr(42, 2)), + ], + ) + self.assertTrue(self._run_check(blocks, succ=[[]])) + + def test_unoverwritten_xor_mask_into_exec_is_rejected(self): + imm = lambda v: {"k": "imm", "v": v} + blocks = blocks_of( + [ + ins("s_xor_b64", sgpr(40, 2), sgpr(40, 2), imm(-1)), + ins("s_mov_b64", special("exec"), sgpr(40, 2)), + ], + ) + self.assertFalse(self._run_check(blocks, succ=[[]])) + + def test_diamond_merge_with_one_nonzero_branch_is_rejected(self): + imm = lambda v: {"k": "imm", "v": v} + blocks = blocks_of( + [ins("s_cbranch_scc1", imm(1))], + [ins("s_and_saveexec_b64", sgpr(40, 2), sgpr(4, 2))], # zero + [ins("s_mov_b64", sgpr(40, 2), imm(-1))], # non-zero + [ins("s_mov_b64", special("exec"), sgpr(40, 2))], + ) + self.assertFalse(self._run_check(blocks, succ=[[2, 1], [3], [3], []])) + + def test_loop_backedge_clobbering_saved_pair_is_rejected(self): + imm = lambda v: {"k": "imm", "v": v} + blocks = blocks_of( + [ins("s_and_saveexec_b64", sgpr(40, 2), sgpr(4, 2))], + [ins("s_mov_b64", special("exec"), sgpr(40, 2)), ins("s_cbranch_scc1", imm(1))], + [ins("s_mov_b64", sgpr(40, 2), imm(-1)), ins("s_branch", imm(-2))], + ) + self.assertFalse(self._run_check(blocks, succ=[[1], [2], [1]])) + + def test_partial_sgpr_overwrite_kills_overlapping_pair(self): + imm = lambda v: {"k": "imm", "v": v} + blocks = blocks_of( + [ + ins("s_and_saveexec_b64", sgpr(40, 2), sgpr(4, 2)), + ins("s_mov_b32", sgpr(41, 1), imm(1)), # clobbers high half of s[40:41] + ins("s_mov_b64", special("exec"), sgpr(40, 2)), + ], + ) + self.assertFalse(self._run_check(blocks, succ=[[]])) + + def test_vop3b_carry_out_does_not_mark_pair_zero(self): + vgpr = lambda r: {"k": "vgpr", "r": r, "n": 1} + blocks = blocks_of( + [ + ins("v_add_co_u32", vgpr(0), sgpr(40, 2), vgpr(1), vgpr(2)), + ins("s_mov_b64", special("exec"), sgpr(40, 2)), + ], + ) + self.assertFalse(self._run_check(blocks, succ=[[]])) + + if __name__ == "__main__": unittest.main() diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index c6e27e8e6f..5ead98a813 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py @@ -927,13 +927,116 @@ def _write_preserves_zero(op, a, zero_pairs, *, for_exec): return False -def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in): +_BIT_ZERO_VCC = 127 +_ALL_ZERO_BITS = (1 << 128) - 1 +_SGPR_PAIR_MASK = (1 << 127) - 1 + + +def _is_zero_bit(x, zmask): + if _is_exec_op_arg(x): + return True + if x.get("k") == "imm" and x.get("v", 1) == 0: + return True + if x.get("k") == "special" and x.get("t") == "vcc": + return bool(zmask & (1 << _BIT_ZERO_VCC)) + r = _sgpr_pair(x) + return r is not None and bool(zmask & (1 << r)) + + +def _exec_write_preserves_zero(op, a, zmask): + """True iff an EXEC-writing instruction keeps EXEC == 0 when entry EXEC == 0 and `zmask` holds.""" + if op.startswith("v_cmpx") or op in ( + "s_and_saveexec_b64", "s_and_saveexec_b32", + "s_andn1_saveexec_b64", "s_andn1_saveexec_b32", + "s_andn1_wrexec_b64", "s_andn1_wrexec_b32"): + return True + if op in ("s_andn2_saveexec_b64", "s_or_saveexec_b64", "s_xor_saveexec_b64", "s_andn2_wrexec_b64"): + return len(a) >= 2 and _is_zero_bit(a[1], zmask) + if not a or not _is_exec_op_arg(a[0]): + return False # partial exec_lo/exec_hi or unknown EXEC write + if op == "s_and_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) or _is_zero_bit(a[2], zmask) + if op == "s_andn2_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) + if op in ("s_or_b64", "s_xor_b64") and len(a) == 3: + return _is_zero_bit(a[1], zmask) and _is_zero_bit(a[2], zmask) + if op == "s_mov_b64" and len(a) == 2: + return _is_zero_bit(a[1], zmask) + if op == "s_cselect_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) and _is_zero_bit(a[2], zmask) + if op == "s_cmov_b64" and len(a) == 2: + return _is_zero_bit(a[1], zmask) + return False + + +def _mask64_write_preserves_zero(op, a, zmask): + """True iff a 64-bit mask write to `a[0]` (SGPR pair or VCC) produces 0 when EXEC == 0 and `zmask` holds.""" + if op.endswith("_saveexec_b64") or op == "s_andn1_wrexec_b64": + return True # saves old EXEC (or ~S0 & EXEC), both 0 when EXEC == 0 + if op == "s_andn2_wrexec_b64": + return len(a) >= 2 and _is_zero_bit(a[1], zmask) + if op.startswith("v_cmp") and not op.startswith("v_cmpx"): + return True # inactive lanes (EXEC == 0) always produce 0 in v_cmp_* + if op == "s_and_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) or _is_zero_bit(a[2], zmask) + if op == "s_andn2_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) + if op in ("s_or_b64", "s_xor_b64") and len(a) == 3: + return _is_zero_bit(a[1], zmask) and _is_zero_bit(a[2], zmask) + if op == "s_mov_b64" and len(a) == 2: + return _is_zero_bit(a[1], zmask) + if op == "s_cselect_b64" and len(a) == 3: + return _is_zero_bit(a[1], zmask) and _is_zero_bit(a[2], zmask) + if op == "s_cmov_b64" and len(a) == 2: + return _is_zero_bit(a[0], zmask) and _is_zero_bit(a[1], zmask) + return False + + +def _transfer_zero_ins(ins, zmask): + """Step forward must-be-zero state across one instruction; return `(exec_ok, new_zmask)`.""" + m = _OP_META_CACHE.get(ins["op"]) + if m is None: + m = _get_op_meta(ins["op"]) + if m[1]: # terminator + return True, zmask + op = m[0] + a = ins["args"] + flags = m[8] + writes_exec = bool(flags & _FLAG_WRITES_EXEC_OP) or ( + bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec") + ) + if writes_exec and not _exec_write_preserves_zero(op, a, zmask): + return False, zmask + + _, ins_mw, _ = _scalar_rw_with_meta(ins, m) + new_zmask = zmask + s_bits = ins_mw & _ALL_SGPRS + if s_bits: + # Pair r covers SGPRs r and r+1; kill every pair overlapping any written SGPR. + kill_pairs = (s_bits | (s_bits >> 1)) & _SGPR_PAIR_MASK + new_zmask &= ~kill_pairs + r = _sgpr_pair(a[0]) if a else None + if r is not None and s_bits == (3 << r) and _mask64_write_preserves_zero(op, a, zmask): + new_zmask |= 1 << r + if ins_mw & (1 << _BIT_VCC): + is_full_vcc = bool(a) and a[0].get("k") == "special" and a[0].get("t") == "vcc" + if is_full_vcc and _mask64_write_preserves_zero(op, a, zmask): + new_zmask |= 1 << _BIT_ZERO_VCC + else: + new_zmask &= ~(1 << _BIT_ZERO_VCC) + return True, new_zmask + + +def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in, *, run=None, succ=None, active_blocks=None): """Return True iff every EXEC write in `region_blocks` preserves `active == False` for inactive lanes. - Inductive proof over all execution steps in `region_blocks`: any SGPR pair `s[r:r+1]` not live-in at - the region entry (`run_live_in`) cannot be read before being written in the region. If every write to - `s[r:r+1]` and every write to `EXEC` produces 0 whenever `EXEC == 0` and all such pairs are 0, then - an inactive lane stays inactive across arbitrary nested / reused saveexec if-else diamonds. + When `run`, `succ` and `active_blocks` are supplied, runs a sound forward must-be-zero dataflow over + `region_blocks` tracking which 64-bit SGPR pairs `s[r:r+1]` (and `vcc`) are provably 0 for any lane with + entry `EXEC == 0`. This proves patterns where a scratch pair is computed with non-zero-preserving ops + (e.g. `s_or_b64` / `s_xor_b64 s[r:r+1], ..., -1`) and then overwritten with old `EXEC` by + `s_and_saveexec_b64 s[r:r+1], s[r:r+1]` before `s_mov_b64 exec, s[r:r+1]`, as well as `v_cmp_*` mask + writes (which always write 0 for inactive lanes). Falls back to the legacy flow-insensitive check when + called without CFG context. """ has_exec_write = False for u in region_blocks: @@ -942,6 +1045,58 @@ def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in): break if not has_exec_write: return True + + if run is not None and succ is not None and active_blocks is not None: + r_preds = {u: [] for u in region_blocks} + for u in region_blocks: + for s in succ[u]: + if s in region_blocks: + r_preds[s].append(u) + out_z = {} + work = collections.deque([run]) + in_work = {run} + while work: + u = work.popleft() + in_work.discard(u) + if u == run: + cur = 0 + else: + cur = _ALL_ZERO_BITS + seen_pred = False + for p in r_preds[u]: + if p in out_z: + cur &= out_z[p] + seen_pred = True + if not seen_pred: + cur = 0 + for ins in active_blocks[u]: + ok, cur = _transfer_zero_ins(ins, cur) + if not ok: + return False + if out_z.get(u) != cur: + out_z[u] = cur + for s in succ[u]: + if s in region_blocks and s not in in_work: + work.append(s) + in_work.add(s) + if len(out_z) != len(region_blocks): + return False + # Post-convergence verification pass over every block with its final meet state. + for u in region_blocks: + if u == run: + cur = 0 + else: + cur = _ALL_ZERO_BITS + for p in r_preds[u]: + cur &= out_z[p] + if not r_preds[u]: + cur = 0 + for ins in active_blocks[u]: + ok, cur = _transfer_zero_ins(ins, cur) + if not ok: + return False + return True + sgpr_writers = collections.defaultdict(list) for u in region_blocks: for item in blk_info[u][4]: @@ -1328,7 +1483,8 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr if region_may_w & scalar_live_in[skip]: continue # EXEC must stay inactive for any lane that skipped R. - if not _exec_writes_stay_inactive(region, blk_info, scalar_live_in[run]): + if not _exec_writes_stay_inactive(region, blk_info, scalar_live_in[run], + run=run, succ=succ, active_blocks=active_blocks): continue candidates.append((len(region), b, run, skip, frozenset(region), (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w)))