[PR #544] SPIRV-OPT-CFG-DSE-FOLDS: type-safe folding, constant branch/bitcast/select folds, liveness DSE, and mark-sweep DCE #592

Open
opened 2026-11-26 20:18:24 +01:00 by 4ld0 · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/ubiquitarianism/leonida/pull/544
Author: @xroneyaa
Created: 11/24/2026
Status: 🔄 Open

Base: main ← Head: fix/spirv-opt-cfg-dse-folds


📝 Commits (1)

  • 60668df spirv_opt: enforce type-safe folding, add constant branch/bitcast/select folds, liveness DSE, and mark-sweep DCE

📊 Changes

2 files changed (+731 additions, -152 deletions)

View changed files

📝 tests/test_spirv_opt.py (+238 -0)
📝 tools/spirv_opt.py (+493 -152)

📄 Description

Claimed in the coordination issue as: SPIRV-OPT-CFG-DSE-FOLDS

What and why

tools/spirv_opt.py had a few type-safety gaps in _fold_int_op and missed several common SPIR-V simplification opportunities left behind by translated RDNA2 shaders:

  1. Type-safe folding (_fold_int_op & id_type):
    • _fold_int_op returned raw operand IDs for algebraic identities (+ 0, * 1, & ~0, | 0, ^ 0, shifts by 0, x & x, x | x, OpBitFieldUExtract(..., 0, width)) and constant-folded comparisons without checking operand/result type equality. With mixed %int/%uint operands (e.g., OpIAdd %uint %ix %u0) or vector comparisons (OpIEqual %v4bool %v %v), this could substitute an %int result ID where %uint was expected or a scalar %bool constant into a %v4bool instruction.
    • _fold_int_op now checks id_type equality via same_ty(...), restricts boolean comparison folds to bool_type_id, maps absorbing zero/all-ones identities (* 0, & 0, | ~0, 0 << s, 0 >> s) strictly through int_const_by_val.get((res_ty, ...)), and folds OpBitFieldUExtract(..., width, 0) to zero.
    • optimize() also records types of OpSpecConstant*, OpUndef, and module-scope OpVariable, as well as OpDecorateId operand IDs so DCE never deletes an operand referenced by OpDecorateId.
  2. Additional peepholes & constant/select folds:
    • OpBitcast: eliminates identity casts (id_type[src] == dst_ty) and folds constant OpBitcast across matching-width 32/64-bit int and exact finite IEEE-754 float constants (distinguishing -0.0 from +0.0).
    • OpSelect & comparisons: simplifies chained same-condition selects (select(c, select(c, a, b), d) -> select(c, a, d)), folds select(c, false, true) to !c, and generalizes constant-outcome OpSelect comparisons (OpIEqual/OpINotEqual against any integer constant).
  3. Constant OpBranchConditional folding & unreachable block cleanup:
    • Folds structured selection headers branching on %true/%false (Case A when taken target is merge M, Case B when not-taken target is M and the taken block is single-predecessor, merge-free, ending in OpBranch M), removes dead incoming OpPhi pairs cleanly, and deletes unreachable blocks not referenced by surviving instructions.
  4. Cross-block backward slot-liveness DSE & mark-and-sweep pure DCE:
    • Replaces whole-function slot in loaded_slots DSE with iterative backward slot-liveness analysis across basic blocks on static_trackable slots (falling back if a block has an unrecognized terminator), eliminating cross-block overwritten stores while keeping loop-live stores intact.
    • Replaces single-pass use_count DCE with mark-and-sweep reachability from impure/decorated roots so dead self-referential OpPhi cycles and unused Function OpVariables are removed cleanly.

Tested

  • python -m unittest tests/test_spirv_opt.py -v -> 15/15 Passed (0.071 s), including new regression tests verifying mixed %int/%uint and %v4bool type safety, constant OpBitcast (with -0.0/+0.0), OpSelect comparisons, constant OpBranchConditional folding (spirv_mini_interp parity), cross-block DSE, dead OpPhi cycle DCE, and OpDecorateId operand preservation
  • Cross-check across all 52 tests/semantic/fixtures/disasm/ps_*.s fixtures:
    • spirv_asm.assemble(opt) -> 52/52 succeeded (0 errors)
    • spirv_mini_interp execution parity (raw vs opt) -> 51/51 executable PS fixtures matched bit-for-bit (0 mismatches; 1 fixture requires external descriptors)
    • Total lines across the 52 PS fixtures: 58343 -> 26510 (54.6% reduction)
  • python -I scripts/check_no_game_data.py tools/spirv_opt.py tests/test_spirv_opt.py -> exit 0

GPUs tested: n/a (CPU-only optimizer unit tests, spirv_asm, and spirv_mini_interp)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed (n/a — optimizer pass only, no new ISA translation rule).

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/ubiquitarianism/leonida/pull/544 **Author:** [@xroneyaa](https://github.com/xroneyaa) **Created:** 11/24/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/spirv-opt-cfg-dse-folds` --- ### 📝 Commits (1) - [`60668df`](https://github.com/ubiquitarianism/leonida/commit/60668dfbdfffdad4193a3e851a1935e2917f5d2d) spirv_opt: enforce type-safe folding, add constant branch/bitcast/select folds, liveness DSE, and mark-sweep DCE ### 📊 Changes **2 files changed** (+731 additions, -152 deletions) <details> <summary>View changed files</summary> 📝 `tests/test_spirv_opt.py` (+238 -0) 📝 `tools/spirv_opt.py` (+493 -152) </details> ### 📄 Description Claimed in the coordination issue as: SPIRV-OPT-CFG-DSE-FOLDS ### What and why `tools/spirv_opt.py` had a few type-safety gaps in `_fold_int_op` and missed several common SPIR-V simplification opportunities left behind by translated RDNA2 shaders: 1. **Type-safe folding (`_fold_int_op` & `id_type`)**: - `_fold_int_op` returned raw operand IDs for algebraic identities (`+ 0`, `* 1`, `& ~0`, `| 0`, `^ 0`, shifts by `0`, `x & x`, `x | x`, `OpBitFieldUExtract(..., 0, width)`) and constant-folded comparisons without checking operand/result type equality. With mixed `%int`/`%uint` operands (e.g., `OpIAdd %uint %ix %u0`) or vector comparisons (`OpIEqual %v4bool %v %v`), this could substitute an `%int` result ID where `%uint` was expected or a scalar `%bool` constant into a `%v4bool` instruction. - `_fold_int_op` now checks `id_type` equality via `same_ty(...)`, restricts boolean comparison folds to `bool_type_id`, maps absorbing zero/all-ones identities (`* 0`, `& 0`, `| ~0`, `0 << s`, `0 >> s`) strictly through `int_const_by_val.get((res_ty, ...))`, and folds `OpBitFieldUExtract(..., width, 0)` to zero. - `optimize()` also records types of `OpSpecConstant*`, `OpUndef`, and module-scope `OpVariable`, as well as `OpDecorateId` operand IDs so DCE never deletes an operand referenced by `OpDecorateId`. 2. **Additional peepholes & constant/select folds**: - `OpBitcast`: eliminates identity casts (`id_type[src] == dst_ty`) and folds constant `OpBitcast` across matching-width 32/64-bit int and exact finite IEEE-754 float constants (distinguishing `-0.0` from `+0.0`). - `OpSelect` & comparisons: simplifies chained same-condition selects (`select(c, select(c, a, b), d) -> select(c, a, d)`), folds `select(c, false, true)` to `!c`, and generalizes constant-outcome `OpSelect` comparisons (`OpIEqual`/`OpINotEqual` against any integer constant). 3. **Constant `OpBranchConditional` folding & unreachable block cleanup**: - Folds structured selection headers branching on `%true`/`%false` (`Case A` when taken target is merge `M`, `Case B` when not-taken target is `M` and the taken block is single-predecessor, merge-free, ending in `OpBranch M`), removes dead incoming `OpPhi` pairs cleanly, and deletes unreachable blocks not referenced by surviving instructions. 4. **Cross-block backward slot-liveness DSE & mark-and-sweep pure DCE**: - Replaces whole-function `slot in loaded_slots` DSE with iterative backward slot-liveness analysis across basic blocks on `static_trackable` slots (falling back if a block has an unrecognized terminator), eliminating cross-block overwritten stores while keeping loop-live stores intact. - Replaces single-pass `use_count` DCE with mark-and-sweep reachability from impure/decorated roots so dead self-referential `OpPhi` cycles and unused `Function` `OpVariable`s are removed cleanly. ### Tested - `python -m unittest tests/test_spirv_opt.py -v` -> 15/15 Passed (`0.071 s`), including new regression tests verifying mixed `%int`/`%uint` and `%v4bool` type safety, constant `OpBitcast` (with `-0.0`/`+0.0`), `OpSelect` comparisons, constant `OpBranchConditional` folding (`spirv_mini_interp` parity), cross-block DSE, dead `OpPhi` cycle DCE, and `OpDecorateId` operand preservation - Cross-check across all 52 `tests/semantic/fixtures/disasm/ps_*.s` fixtures: - `spirv_asm.assemble(opt)` -> 52/52 succeeded (0 errors) - `spirv_mini_interp` execution parity (`raw` vs `opt`) -> 51/51 executable PS fixtures matched bit-for-bit (0 mismatches; 1 fixture requires external descriptors) - Total lines across the 52 PS fixtures: `58343 -> 26510` (`54.6%` reduction) - `python -I scripts/check_no_game_data.py tools/spirv_opt.py tests/test_spirv_opt.py` -> exit 0 GPUs tested: n/a (CPU-only optimizer unit tests, `spirv_asm`, and `spirv_mini_interp`) AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed (n/a — optimizer pass only, no new ISA translation rule). --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
bug
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
starred/leonida#592
No description provided.