Shaders/opt: push Bitcast through Select/Phi and fold constant chains/masks #1398

Open
n-romanovich wants to merge 1 commit from upstream-pr/1398 into main
n-romanovich commented 2026-11-26 23:06:51 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by n-romanovich on 2026-11-26T23:06:51Z.


Related to #1383 (reducing the ~2.4x translated DXIL instruction ratio, where bitcast and select each make up ~12% of emitted instructions).

Problem

Because lower.rs stores vector/scalar registers and Op::Phi values as i32 and lowers predicated writes via i32 Op::Select, guarded float VALU ops, float loop Phis, v_cndmask_b32, and raw_dwords float loads systematically emit bitcast(f32 -> i32) -> select/phi(i32) -> bitcast(i32 -> f32) chains that opt.rs left unsimplified. Module::simplify and Module::key also missed associative constant folding across buffer/SMEM addressing (Add(Add(x, k1), k2)), redundant bitmask elimination (And(LShr(x, 27), 31)), boolean Select/Cmp(ZExt(i1)) peepholes, and commuted Cmp canonicalization.

Changes (crates/victory-shader/src/emit/bitcode/opt.rs)

  • Push Cast::Bitcast through Op::Select and Op::Phi:
    • In Module::simplify, rewrite Bitcast(Select(c, t, f)) to Select(c, t', f') when at least one arm strips a matching inverse Bitcast and the other converts via rebitcast (bit-exact for 32-bit ints/floats, preserving -0.0 and NaN payloads).
    • Add Module::retype_bitcast_phis (run inside Module::optimise under FOLD) to retype Op::Phi nodes whose non-self users are exclusively Bitcast to the same target type T when all incoming values convert to T, exposing the surrounding Bitcasts for elimination on the next merge pass.
  • Exact algebraic, known-bits, and boolean simplifications:
    • Add assoc_const_bin to fold associative constant chains across Add/Sub/And/Or/Xor/Mul and bounded Shl/LShr/AShr, plus Xor(x, x) -> 0 and Sub(x, x) -> 0.
    • Add possible_ones bitmask tracking to eliminate redundant And(x, m) masks (such as & 31 after LShr(_, 27) or ZExt).
    • Simplify Select(Xor(c, true), t, f) -> Select(c, f, t), Select(c, false, true) -> Xor(c, true), and Cmp(EQ/NE, ZExt(x: i1), 0/1).
    • Canonicalize operand order (b < a) with exact predicate flipping in Module::key for Op::Cmp (preserving IEEE/NaN semantics).

Verification

  • Added unit tests emit::bitcode::opt::tests::pushes_bitcast_through_select_and_phi and emit::bitcode::opt::tests::reassociates_constants_known_bits_and_boolean_peepholes.
  • cargo test --locked -p victory-shader --features host --lib: 235 passed; 0 failed; 4 ignored (including GPU diff_tests, valu_tests, wave64_tests, and every_pass_leaves_what_random_programs_store across 400 random programs).
  • cargo build --release --locked -p victory
<!-- greyfinch-sync:fxceless/victory-fork:issue:5518355412 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/1398). Originally posted by [n-romanovich](https://github.com/n-romanovich) on 2026-11-26T23:06:51Z. --- Related to #1383 (reducing the ~2.4x translated DXIL instruction ratio, where `bitcast` and `select` each make up ~12% of emitted instructions). ### Problem Because `lower.rs` stores vector/scalar registers and `Op::Phi` values as `i32` and lowers predicated writes via `i32` `Op::Select`, guarded float VALU ops, float loop `Phi`s, `v_cndmask_b32`, and `raw_dwords` float loads systematically emit `bitcast(f32 -> i32) -> select/phi(i32) -> bitcast(i32 -> f32)` chains that `opt.rs` left unsimplified. `Module::simplify` and `Module::key` also missed associative constant folding across buffer/SMEM addressing (`Add(Add(x, k1), k2)`), redundant bitmask elimination (`And(LShr(x, 27), 31)`), boolean `Select`/`Cmp(ZExt(i1))` peepholes, and commuted `Cmp` canonicalization. ### Changes (`crates/victory-shader/src/emit/bitcode/opt.rs`) - **Push `Cast::Bitcast` through `Op::Select` and `Op::Phi`:** - In `Module::simplify`, rewrite `Bitcast(Select(c, t, f))` to `Select(c, t', f')` when at least one arm strips a matching inverse `Bitcast` and the other converts via `rebitcast` (bit-exact for 32-bit ints/floats, preserving `-0.0` and NaN payloads). - Add `Module::retype_bitcast_phis` (run inside `Module::optimise` under `FOLD`) to retype `Op::Phi` nodes whose non-self users are exclusively `Bitcast` to the same target type `T` when all incoming values convert to `T`, exposing the surrounding `Bitcast`s for elimination on the next `merge` pass. - **Exact algebraic, known-bits, and boolean simplifications:** - Add `assoc_const_bin` to fold associative constant chains across `Add`/`Sub`/`And`/`Or`/`Xor`/`Mul` and bounded `Shl`/`LShr`/`AShr`, plus `Xor(x, x) -> 0` and `Sub(x, x) -> 0`. - Add `possible_ones` bitmask tracking to eliminate redundant `And(x, m)` masks (such as `& 31` after `LShr(_, 27)` or `ZExt`). - Simplify `Select(Xor(c, true), t, f) -> Select(c, f, t)`, `Select(c, false, true) -> Xor(c, true)`, and `Cmp(EQ/NE, ZExt(x: i1), 0/1)`. - Canonicalize operand order (`b < a`) with exact predicate flipping in `Module::key` for `Op::Cmp` (preserving IEEE/NaN semantics). ### Verification - Added unit tests `emit::bitcode::opt::tests::pushes_bitcast_through_select_and_phi` and `emit::bitcode::opt::tests::reassociates_constants_known_bits_and_boolean_peepholes`. - `cargo test --locked -p victory-shader --features host --lib`: `235 passed; 0 failed; 4 ignored` (including GPU `diff_tests`, `valu_tests`, `wave64_tests`, and `every_pass_leaves_what_random_programs_store` across 400 random programs). - `cargo build --release --locked -p victory`
Melow-code commented 2026-11-29 08:17:37 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by Melow-code on 2026-11-29T08:17:37Z.

Review: COMMENTED


Fuzzed the new folds on Linux, 5c36f59 merged onto main 368967f8 (no conflict): no objection.

I wrote a generator and an evaluator of my own for this, separate from random_program and run in your test module: chains of one to four constant operations (every integer operation, constant on either side, masks that match shift widths), float writes kept as bits behind up to two nested selects, joins of those in branches and loops, bits widened and compared with constants, selects of bits and repeated nots, 8-, 16- and 64-bit values, values combined with a register and undone.

  • 20,000 programs, 6 inputs each, under seven sets of passes (FOLD alone up to ALL): 7,710,402 stored values, the same bit for bit before and after, NaN payloads included. In the reached blocks the operands of every instruction and join still have the types they need, and no bitcast to its own type is left.
  • The fuzz sees this code. With one line broken it fails within the first 48 programs: (x + k1) - k2 with its operands swapped (seed 48), zext(bit) != 1 folded to the bit (seed 2), two ashr whose sum passes the width folded to 0 (seed 23), a join retyped although another instruction reads it as an integer (seed 37).
  • With all passes on, the programs go from 1,748,928 instructions and joins to 1,000,770; on main to 1,098,075. So 97,305 more go, and 810 joins became floats. These are synthetic programs; it says nothing about the title's ratio.
  • cargo test -p victory-formats -p victory-shader --lib: 42 and 209 passed, 0 failed (5 and 2 ignored).

Not run: Windows, the D3D12 validator, any card, the title's shaders. The fuzz evaluates one thread, so it cannot see a driver that treats a float select or phi of NaN bits or denormals differently from an integer one; a run of the semantics tests on a card would.

AI-assisted review (Claude Code).

<!-- greyfinch-sync:fxceless/victory-fork:review:6102051467 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/1398#pullrequestreview-6102051467). Originally posted by [Melow-code](https://github.com/Melow-code) on 2026-11-29T08:17:37Z. **Review:** COMMENTED --- Fuzzed the new folds on Linux, 5c36f59 merged onto main 368967f8 (no conflict): no objection. I wrote a generator and an evaluator of my own for this, separate from `random_program` and `run` in your test module: chains of one to four constant operations (every integer operation, constant on either side, masks that match shift widths), float writes kept as bits behind up to two nested selects, joins of those in branches and loops, bits widened and compared with constants, selects of bits and repeated nots, 8-, 16- and 64-bit values, values combined with a register and undone. - 20,000 programs, 6 inputs each, under seven sets of passes (`FOLD` alone up to `ALL`): 7,710,402 stored values, the same bit for bit before and after, NaN payloads included. In the reached blocks the operands of every instruction and join still have the types they need, and no bitcast to its own type is left. - The fuzz sees this code. With one line broken it fails within the first 48 programs: `(x + k1) - k2` with its operands swapped (seed 48), `zext(bit) != 1` folded to the bit (seed 2), two `ashr` whose sum passes the width folded to 0 (seed 23), a join retyped although another instruction reads it as an integer (seed 37). - With all passes on, the programs go from 1,748,928 instructions and joins to 1,000,770; on main to 1,098,075. So 97,305 more go, and 810 joins became floats. These are synthetic programs; it says nothing about the title's ratio. - `cargo test -p victory-formats -p victory-shader --lib`: 42 and 209 passed, 0 failed (5 and 2 ignored). Not run: Windows, the D3D12 validator, any card, the title's shaders. The fuzz evaluates one thread, so it cannot see a driver that treats a float `select` or `phi` of NaN bits or denormals differently from an integer one; a run of the semantics tests on a card would. AI-assisted review (Claude Code).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/1398:upstream-pr/1398'
git switch 'upstream-pr/1398'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/1398'
git switch 'upstream-pr/1398'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/1398'
git switch 'upstream-pr/1398'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/1398'
git switch 'main'
git merge --squash 'upstream-pr/1398'
git switch 'main'
git merge --ff-only 'upstream-pr/1398'
git switch 'main'
git merge 'upstream-pr/1398'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
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.

Reference
fxceless/victory-fork!1398
No description provided.