Shaders: reuse the predicate when reading a zero-extended SCC #1546

Open
github-bot wants to merge 2 commits from github-bot/gh-1546 into main AGit
Owner

@⁠Roroca-1 on GitHub · 2026-11-24 17:29 UTC · original
Roroca-1:dxil-opt-3-instcombine-cse → main · +53 −2 · 2 files · 2 commits · draft

Stacked on #1544. Only ce8c103 belongs here. Part of #1269.

Direct lowering writes the scalar condition code (SCC) by zero-extending an i1 predicate to i32. Reading SCC tests that word against zero. The comparison can return the original predicate.

What is in it

  • Fold this specific instruction pair in module.rs, cover the comparison and two counterexamples, and bump the direct translator cache version to 6. The merged #1426 supplies CSE.

Tested

  • Ryzen 7 7800X3D, Linux x86-64, Rust 1.98.1, Windows MSVC debug target via cargo-xwin. CPU-side tests under Wine on clean ce8c103.
  • TARGET_CFLAGS=/FIstring.h cargo xwin build --tests -p xcl --target x86_64-pc-windows-msvc succeeded.
  • wine xcl-67594ede252ac8b9.exe gpu::dxil::module::tests --nocapture ran 2 passed, 0 failed, 0 ignored, 0 skipped. Before the fold, the SCC test observed a new instruction instead of the original predicate and failed.
  • wine xcl-67594ede252ac8b9.exe gpu::dxil::bitreader_tests --test-threads=4 ran 3 passed, 0 failed, 0 ignored, 0 skipped.
  • For the earlier sibling-scope review, a temporary diamond test exercised the unchanged upstream optimizer. The join PHI kept each arm’s local value and the duplicate in one arm folded (1 passed, 0 failed, 0 ignored, 0 skipped).

Regression run
Pending paired clean main/head retail-title runs.

Not tested
Native Windows GPU workspace suite, DXIL validation, retail shaders and performance.

AI use
T3 Code (Codex, gpt-6.2-astra) narrowed the original T3 Code (Antigravity, gemini-pro-orchestrator-neon) optimizer proposal, wrote the current patch and tests, and ran the Wine checks.

**@⁠Roroca-1** on GitHub · 2026-11-24 17:29 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546) `Roroca-1:dxil-opt-3-instcombine-cse` → `main` · +53 −2 · 2 files · 2 commits · draft Stacked on #1544. Only `ce8c103` belongs here. Part of #1269. Direct lowering writes the scalar condition code (SCC) by zero-extending an i1 predicate to i32. Reading SCC tests that word against zero. The comparison can return the original predicate. **What is in it** - Fold this specific instruction pair in `module.rs`, cover the comparison and two counterexamples, and bump the direct translator cache version to 6. The merged #1426 supplies CSE. **Tested** - Ryzen 7 7800X3D, Linux x86-64, Rust 1.98.1, Windows MSVC debug target via cargo-xwin. CPU-side tests under Wine on clean `ce8c103`. - `TARGET_CFLAGS=/FIstring.h cargo xwin build --tests -p xcl --target x86_64-pc-windows-msvc` succeeded. - `wine xcl-67594ede252ac8b9.exe gpu::dxil::module::tests --nocapture` ran 2 passed, 0 failed, 0 ignored, 0 skipped. Before the fold, the SCC test observed a new instruction instead of the original predicate and failed. - `wine xcl-67594ede252ac8b9.exe gpu::dxil::bitreader_tests --test-threads=4` ran 3 passed, 0 failed, 0 ignored, 0 skipped. - For the earlier sibling-scope review, a temporary diamond test exercised the unchanged upstream optimizer. The join PHI kept each arm’s local value and the duplicate in one arm folded (1 passed, 0 failed, 0 ignored, 0 skipped). **Regression run** Pending paired clean main/head retail-title runs. **Not tested** Native Windows GPU workspace suite, DXIL validation, retail shaders and performance. **AI use** T3 Code (Codex, gpt-6.2-astra) narrowed the original T3 Code (Antigravity, gemini-pro-orchestrator-neon) optimizer proposal, wrote the current patch and tests, and ran the Wine checks.
An unreachable conversion survives in the instruction arena after optimization. Scan block instructions when inferring flags and invalidate cached containers.
The direct lowering stores SCC as an i32 zero extension and tests it against zero. Reuse the i1 instruction for this exact round trip and invalidate older cached containers.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:57:07 +00:00
Author
Owner

@⁠DavidM1911 on GitHub · 2026-11-24 19:19 UTC · original

Verification on RTX 3060 Ti (Windows 11): merge conflict with current main — needs a rebase before it can be tested.

**@⁠DavidM1911** on GitHub · 2026-11-24 19:19 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546#issuecomment-7141922062) Verification on RTX 3060 Ti (Windows 11): **merge conflict with current `main`** — needs a rebase before it can be tested.
Author
Owner

@⁠Toons29 on GitHub · 2026-11-25 03:33 UTC · original

Regression run of ce8c1039 on the retail title, for this PR's Regression run section. Both blocks are from scripts/smoke.ps1 as printed, not edited: main on 4178e888, this PR on its head commit with no uncommitted changes, same title and time.

xcl-smoke v1
commit: 4178e888c0b5be50a2887eda45cdb832763b68a4
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 14831 MB
xcl-smoke v1
commit: ce8c103945a6965450946d89c071e152dae5881b
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1632 (PresentX 1632)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14813 MB

Against the limits in CONTRIBUTING.md: 101 % of main's frames, 100 % of its peak commit, no crash, no device removal.

AMD Radeon RX 9070 (RDNA4, driver 32.0.32029.2010), Ryzen 7 7800X3D, 32 GB, Windows 11 build 26300, Rust 1.100.0, cargo build --release -p xcl, 60 s, XCL_NETWORK=0. This is a regression check only: it does not show whether the run reaches the code this PR changes.

AI use: Claude Code (Claude Opus 5.5) built both trees and ran scripts/smoke.ps1; I checked the blocks before posting.

**@⁠Toons29** on GitHub · 2026-11-25 03:33 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546#issuecomment-7152032907) Regression run of `ce8c1039` on the retail title, for this PR's **Regression run** section. Both blocks are from `scripts/smoke.ps1` as printed, not edited: `main` on `4178e888`, this PR on its head commit with no uncommitted changes, same title and time. ``` xcl-smoke v1 commit: 4178e888c0b5be50a2887eda45cdb832763b68a4 gpu: AMD Radeon RX 9070 title: game.exe seconds: 60 exit: 0x0 frames shown: 1618 (PresentX 1618) presents per 2 s (last 3): 61 60 60 device removals: 0 crashes: 0 peak commit: 14831 MB ``` ``` xcl-smoke v1 commit: ce8c103945a6965450946d89c071e152dae5881b gpu: AMD Radeon RX 9070 title: game.exe seconds: 60 exit: 0x0 frames shown: 1632 (PresentX 1632) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 14813 MB ``` Against the limits in CONTRIBUTING.md: 101 % of `main`'s frames, 100 % of its peak commit, no crash, no device removal. AMD Radeon RX 9070 (RDNA4, driver 32.0.32029.2010), Ryzen 7 7800X3D, 32 GB, Windows 11 build 26300, Rust 1.100.0, `cargo build --release -p xcl`, 60 s, `XCL_NETWORK=0`. This is a regression check only: it does not show whether the run reaches the code this PR changes. AI use: Claude Code (Claude Opus 5.5) built both trees and ran `scripts/smoke.ps1`; I checked the blocks before posting.
Author
Owner

@⁠DavidM1911 on GitHub · 2026-11-26 00:26 UTC · original

Re-verification on RTX 3060 Ti (Windows 11): still a merge conflict with current main on the new head — needs another rebase before it can be tested.

**@⁠DavidM1911** on GitHub · 2026-11-26 00:26 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546#issuecomment-7178764179) Re-verification on RTX 3060 Ti (Windows 11): still a **merge conflict with current `main`** on the new head — needs another rebase before it can be tested.
Author
Owner

@⁠gut0to on GitHub · 2026-11-24 17:32 UTC · original
On crates/xcl/src/gpu/dxil/opt.rs line 1795 (outdated):

@@ -0,0 +1,2770 @@
+//! Intra-function DXIL SSA IR optimization and module compaction pass suite.
+//!
+//! Runs after IR construction and before metadata/bitcode serialization:
+//! 1. Fixpoint loop over CFG simplification & RPO normalization, trivial/duplicate
+//!    PHI elimination, constant folding & algebraic/bitcast/select simplification,
+//!    dominator-scoped CSE (excluding implicit derivatives and non-pure intrinsics),
+//!    and iterative mark-and-sweep DCE.
+//! 2. Dense compaction of live instructions, constants, declarations, and globals.
+//! 3. Synchronization of [`Shader::features`] with the remaining live IR.
+//!
+//! All graph traversals use explicit stacks so large shaders cannot overflow.
+
+use std::collections::{BTreeSet, HashMap};
+
+use super::module::{BinOp, Block, CastOp, ConstDef, FnAttrs, MdDef, Module, Op, Pred, Ty, Value};
+use super::shader::{kind, Feature, Shader};
+
+const MAX_ROUNDS: usize = 8;
+
+/// Summary metrics of a DXIL [`Module`] (for diagnostics and optimization tests).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Stats {
+    pub blocks: usize,
+    pub insts: usize,
+    pub phis: usize,
+    pub consts: usize,
+    pub funcs: usize,
+    pub globals: usize,
+}
+
+/// Counts live blocks/instructions/PHIs and pooled constants/functions/globals.
+pub fn module_stats(m: &Module) -> Stats {
+    let mut insts = 0usize;
+    let mut phis = 0usize;
+    for b in &m.blocks {
+        insts += b.len();
+        for &id in b {
+            if matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                phis += 1;
+            }
+        }
+    }
+    Stats {
+        blocks: m.blocks.len(),
+        insts,
+        phis,
+        consts: m.consts.len(),
+        funcs: m.funcs.len(),
+        globals: m.globals.len(),
+    }
+}
+
+/// Optimizes `s.m`, compacts pooled module tables (updating `s.entry`), and
+/// synchronizes `s.features` against the remaining live IR.
+pub fn optimize(s: &mut Shader) {
+    if s.m.error().is_some() || s.m.blocks.is_empty() {
+        return;
+    }
+    optimize_core(&mut s.m);
+    compact_module(&mut s.m, Some(&mut s.entry));
+    sync_features(s);
+}
+
+/// Optimizes and compacts `m` without modifying wrapper shader metadata.
+pub fn optimize_module(m: &mut Module) {
+    if m.error().is_some() || m.blocks.is_empty() {
+        return;
+    }
+    optimize_core(m);
+    compact_module(m, None);
+}
+
+fn optimize_core(m: &mut Module) {
+    for _ in 0..MAX_ROUNDS {
+        let mut changed = false;
+        changed |= simplify_cfg(m);
+        changed |= simplify_phis(m);
+        changed |= simplify_insts(m);
+        changed |= cse(m);
+        changed |= dce(m);
+        if !changed {
+            break;
+        }
+    }
+    // Final normalization pass if the last DCE/CSE opened trivial CFG/PHI cleanup.
+    if simplify_cfg(m) {
+        let _ = simplify_phis(m);
+        let _ = dce(m);
+        let _ = simplify_cfg(m);
+    }
+}
+
+// ------------------------------------------------------------------ helpers
+
+fn mask_for(w: u32) -> u64 {
+    if w >= 64 {
+        u64::MAX
+    } else if w == 0 {
+        0
+    } else {
+        (1u64 << w) - 1
+    }
+}
+
+fn sext_i64(v: u64, w: u32) -> i64 {
+    if w >= 64 {
+        v as i64
+    } else if w == 0 {
+        0
+    } else {
+        ((v << (64 - w)) as i64) >> (64 - w)
+    }
+}
+
+fn const_int_u64(m: &Module, v: Value) -> Option<u64> {
+    match v {
+        Value::Const(c) => match &m.consts[c as usize] {
+            ConstDef::Int(t, x) => {
+                let w = m.int_width(*t)?;
+                Some((*x as u64) & mask_for(w))
+            }
+            ConstDef::Null(t) if m.int_width(*t).is_some() => Some(0),
+            _ => None,
+        },
+        _ => None,
+    }
+}
+
+fn scalar_bits(m: &Module, ty: Ty) -> Option<u32> {
+    if let Some(w) = m.int_width(ty) {
+        return Some(w);
+    }
+    if m.is_float(ty) {
+        return match m.alloc_size_layout(ty, true) {
+            2 => Some(16),
+            4 => Some(32),
+            8 => Some(64),
+            _ => None,
+        };
+    }
+    None
+}
+
+fn const_bitcast(m: &mut Module, v: Value, dst: Ty) -> Option<Value> {
+    if m.value_ty(v) == dst {
+        return Some(v);
+    }
+    let Value::Const(c) = v else { return None };
+    let dst_bits = scalar_bits(m, dst)?;
+    let def = m.consts[c as usize].clone();
+    match def {
+        ConstDef::Undef(t) => (scalar_bits(m, t) == Some(dst_bits)).then(|| m.undef(dst)),
+        ConstDef::Null(t) if scalar_bits(m, t) == Some(dst_bits) => {
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, 0))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, 0))
+            } else {
+                None
+            }
+        }
+        ConstDef::Int(t, x) => {
+            let w = m.int_width(t)?;
+            if w != dst_bits {
+                return None;
+            }
+            let raw = (x as u64) & mask_for(w);
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, raw))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, raw))
+            } else {
+                None
+            }
+        }
+        ConstDef::Float(t, bits) => {
+            let w = scalar_bits(m, t)?;
+            if w != dst_bits {
+                return None;
+            }
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, bits))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, bits))
+            } else {
+                None
+            }
+        }
+        _ => None,
+    }
+}
+
+fn is_undef(m: &Module, v: Value) -> bool {
+    matches!(v, Value::Const(c) if matches!(m.consts[c as usize], ConstDef::Undef(_)))
+}
+
+fn is_op_name(full: &str, base: &str) -> bool {
+    full == base || full.strip_prefix(base).is_some_and(|s| s.starts_with('.'))
+}
+
+fn resolve_val(mut v: Value, repl: &[Option<Value>]) -> Value {
+    let mut steps = 0usize;
+    while let Value::Inst(id) = v {
+        let Some(next) = repl.get(id as usize).copied().flatten() else { break };
+        if next == v || steps >= repl.len() {
+            break;
+        }
+        v = next;
+        steps += 1;
+    }
+    v
+}
+
+fn visit_op_values_mut(op: &mut Op, f: &mut dyn FnMut(&mut Value)) {
+    match op {
+        Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => {
+            f(a);
+            f(b);
+        }
+        Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(v),
+        Op::Store(p, v, _) => {
+            f(p);
+            f(v);
+        }
+        Op::Select(c, t, e) | Op::CmpXchg(c, t, e) => {
+            f(c);
+            f(t);
+            f(e);
+        }
+        Op::Call(_, args) => {
+            for a in args {
+                f(a);
+            }
+        }
+        Op::Phi(inc) => {
+            for (v, _) in inc {
+                f(v);
+            }
+        }
+        Op::Gep(p, idx) => {
+            f(p);
+            for i in idx {
+                f(i);
+            }
+        }
+        Op::Alloca(_, n, _) => f(n),
+        Op::CondBr(c, _, _) => f(c),
+        Op::Switch(v, _, cases) => {
+            f(v);
+            for (cv, _) in cases {
+                f(cv);
+            }
+        }
+        Op::Br(_) | Op::Ret | Op::Unreachable => {}
+    }
+}
+
+fn rewrite_op_values(op: &mut Op, repl: &[Option<Value>]) -> bool {
+    let mut changed = false;
+    visit_op_values_mut(op, &mut |v| {
+        let nv = resolve_val(*v, repl);
+        if nv != *v {
+            *v = nv;
+            changed = true;
+        }
+    });
+    changed
+}
+
+fn rewrite_md_values(m: &mut Module, repl: &[Option<Value>]) {
+    for md in &mut m.md {
+        if let MdDef::Val(_, v) = md {
+            *v = resolve_val(*v, repl);
+        }
+    }
+}
+
+fn for_each_op_value(op: &Op, mut f: impl FnMut(Value)) {
+    match op {
+        Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => {
+            f(*a);
+            f(*b);
+        }
+        Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(*v),
+        Op::Store(p, v, _) => {
+            f(*p);
+            f(*v);
+        }
+        Op::Select(c, t, x) | Op::CmpXchg(c, t, x) => {
+            f(*c);
+            f(*t);
+            f(*x);
+        }
+        Op::Call(_, args) => {
+            for &a in args {
+                f(a);
+            }
+        }
+        Op::Phi(inc) => {
+            for &(v, _) in inc {
+                f(v);
+            }
+        }
+        Op::Gep(p, idx) => {
+            f(*p);
+            for &i in idx {
+                f(i);
+            }
+        }
+        Op::Alloca(_, n, _) => f(*n),
+        Op::CondBr(c, _, _) => f(*c),
+        Op::Switch(v, _, cases) => {
+            f(*v);
+            for &(cv, _) in cases {
+                f(cv);
+            }
+        }
+        Op::Br(_) | Op::Ret | Op::Unreachable => {}
+    }
+}
+
+fn block_succs(m: &Module, b: usize) -> Vec<usize> {
+    let Some(&last) = m.blocks[b].last() else { return Vec::new() };
+    match &m.insts[last as usize].op {
+        Op::Br(t) => vec![t.0 as usize],
+        Op::CondBr(_, t, f) => vec![t.0 as usize, f.0 as usize],
+        Op::Switch(_, d, cases) => {
+            let mut s = Vec::with_capacity(1 + cases.len());
+            s.push(d.0 as usize);
+            for &(_, c) in cases {
+                s.push(c.0 as usize);
+            }
+            s
+        }
+        _ => Vec::new(),
+    }
+}
+
+fn invert_pred(p: Pred) -> Pred {
+    match p {
+        Pred::Eq => Pred::Ne,
+        Pred::Ne => Pred::Eq,
+        Pred::UGt => Pred::ULe,
+        Pred::UGe => Pred::ULt,
+        Pred::ULt => Pred::UGe,
+        Pred::ULe => Pred::UGt,
+        Pred::SGt => Pred::SLe,
+        Pred::SGe => Pred::SLt,
+        Pred::SLt => Pred::SGe,
+        Pred::SLe => Pred::SGt,
+        Pred::FFalse => Pred::FTrue,
+        Pred::FTrue => Pred::FFalse,
+        Pred::FOEq => Pred::FUNe,
+        Pred::FUNe => Pred::FOEq,
+        Pred::FOGt => Pred::FULe,
+        Pred::FULe => Pred::FOGt,
+        Pred::FOGe => Pred::FULt,
+        Pred::FULt => Pred::FOGe,
+        Pred::FOLt => Pred::FUGe,
+        Pred::FUGe => Pred::FOLt,
+        Pred::FOLe => Pred::FUGt,
+        Pred::FUGt => Pred::FOLe,
+        Pred::FONe => Pred::FUEq,
+        Pred::FUEq => Pred::FONe,
+        Pred::FOrd => Pred::FUno,
+        Pred::FUno => Pred::FOrd,
+    }
+}
+
+fn swap_pred(p: Pred) -> Pred {
+    match p {
+        Pred::UGt => Pred::ULt,
+        Pred::ULt => Pred::UGt,
+        Pred::UGe => Pred::ULe,
+        Pred::ULe => Pred::UGe,
+        Pred::SGt => Pred::SLt,
+        Pred::SLt => Pred::SGt,
+        Pred::SGe => Pred::SLe,
+        Pred::SLe => Pred::SGe,
+        Pred::FOGt => Pred::FOLt,
+        Pred::FOLt => Pred::FOGt,
+        Pred::FOGe => Pred::FOLe,
+        Pred::FOLe => Pred::FOGe,
+        Pred::FUGt => Pred::FULt,
+        Pred::FULt => Pred::FUGt,
+        Pred::FUGe => Pred::FULe,
+        Pred::FULe => Pred::FUGe,
+        other => other,
+    }
+}
+
+/// If `v` computes logical NOT (`xor i1 x, true`) returns `Some(x)`.
+fn match_not_i1(m: &Module, v: Value) -> Option<Value> {
+    let Value::Inst(id) = v else { return None };
+    if m.int_width(m.insts[id as usize].ty) != Some(1) {
+        return None;
+    }
+    if let Op::Bin(BinOp::Xor, a, b, _) = m.insts[id as usize].op {
+        if const_int_u64(m, b) == Some(1) {
+            return Some(a);
+        }
+        if const_int_u64(m, a) == Some(1) {
+            return Some(b);
+        }
+    }
+    None
+}
+
+// ------------------------------------------------------------ CFG simplify
+
+fn compute_rpo(m: &Module, alive: &[bool]) -> Vec<usize> {
+    let n = m.blocks.len();
+    if n == 0 || !alive[0] {
+        return Vec::new();
+    }
+    let succs: Vec<Vec<usize>> = (0..n)
+        .map(|b| if alive[b] { block_succs(m, b) } else { Vec::new() })
+        .collect();
+    let mut state = vec![0u8; n];
+    let mut postorder = Vec::with_capacity(n);
+    let mut stack = vec![(0usize, 0usize)];
+    state[0] = 1;
+    while let Some((b, idx)) = stack.last_mut() {
+        let b = *b;
+        let sb = &succs[b];
+        if *idx < sb.len() {
+            // Visit successors in reverse order so reversed postorder places the
+            // primary/true branch before the fallback/exit branch.
+            let next = sb[sb.len() - 1 - *idx];
+            *idx += 1;
+            if alive.get(next).copied().unwrap_or(false) && state[next] == 0 {
+                state[next] = 1;
+                stack.push((next, 0));
+            }
+        } else {
+            state[b] = 2;
+            postorder.push(b);
+            stack.pop();
+        }
+    }
+    postorder.reverse();
+    postorder
+}
+
+/// Keeps at most `keep` entries from `pred` in every `Op::Phi` of block `succ`.
+fn trim_phi_edges(m: &mut Module, succ: usize, pred: Block, keep: usize) -> bool {
+    let mut changed = false;
+    for k in 0..m.blocks[succ].len() {
+        let id = m.blocks[succ][k] as usize;
+        let Op::Phi(inc) = &mut m.insts[id].op else { break };
+        let have = inc.iter().filter(|&&(_, b)| b == pred).count();
+        if have > keep {
+            let mut left = keep;
+            inc.retain(|&(_, b)| {
+                if b == pred {
+                    if left > 0 {
+                        left -= 1;
+                        true
+                    } else {
+                        false
+                    }
+                } else {
+                    true
+                }
+            });
+            changed = true;
+        }
+    }
+    changed
+}
+
+fn replace_phi_pred_block(m: &mut Module, succ: usize, from: Block, to: Block) {
+    for k in 0..m.blocks[succ].len() {
+        let id = m.blocks[succ][k] as usize;
+        let Op::Phi(inc) = &mut m.insts[id].op else { break };
+        for (_, b) in inc.iter_mut() {
+            if *b == from {
+                *b = to;
+            }
+        }
+    }
+}
+
+fn block_has_phis(m: &Module, b: usize) -> bool {
+    m.blocks[b].first().is_some_and(|&id| matches!(m.insts[id as usize].op, Op::Phi(..)))
+}
+
+fn rewrite_term_target(term: &mut Op, from: Block, to: Block) -> usize {
+    let mut count = 0;
+    match term {
+        Op::Br(t) if *t == from => {
+            *t = to;
+            count += 1;
+        }
+        Op::CondBr(_, t, f) => {
+            if *t == from {
+                *t = to;
+                count += 1;
+            }
+            if *f == from {
+                *f = to;
+                count += 1;
+            }
+        }
+        Op::Switch(_, d, cases) => {
+            if *d == from {
+                *d = to;
+                count += 1;
+            }
+            for (_, t) in cases {
+                if *t == from {
+                    *t = to;
+                    count += 1;
+                }
+            }
+        }
+        _ => {}
+    }
+    count
+}
+
+/// Simplifies terminators, drops unreachable blocks, trims dead PHI edges,
+/// bypasses empty jump blocks, merges single-predecessor blocks, and lays out
+/// reachable blocks in RPO.
+pub(super) fn simplify_cfg(m: &mut Module) -> bool {
+    let n = m.blocks.len();
+    if n == 0 {
+        return false;
+    }
+    let mut changed = false;
+
+    // 1. Fold constant / redundant terminators.
+    for b in 0..n {
+        let Some(&term_id) = m.blocks[b].last() else { continue };
+        let op = m.insts[term_id as usize].op.clone();
+        match op {
+            Op::CondBr(c, t, f) => {
+                if let Some(cv) = const_int_u64(m, c) {
+                    let target = if cv & 1 != 0 { t } else { f };
+                    m.insts[term_id as usize].op = Op::Br(target);
+                    let pred = Block(b as u32);
+                    trim_phi_edges(m, target.0 as usize, pred, 1);
+                    let other = if target == t { f } else { t };
+                    if other != target {
+                        trim_phi_edges(m, other.0 as usize, pred, 0);
+                    }
+                    changed = true;
+                } else if t == f {
+                    m.insts[term_id as usize].op = Op::Br(t);
+                    trim_phi_edges(m, t.0 as usize, Block(b as u32), 1);
+                    changed = true;
+                } else if let Some(inner) = match_not_i1(m, c) {
+                    m.insts[term_id as usize].op = Op::CondBr(inner, f, t);
+                    changed = true;
+                }
+            }
+            Op::Switch(v, d, cases) => {
+                let mut old_targets = Vec::with_capacity(1 + cases.len());
+                old_targets.push(d);
+                for &(_, target) in &cases {
+                    if !old_targets.contains(&target) {
+                        old_targets.push(target);
+                    }
+                }
+                if let Some(cv) = const_int_u64(m, v) {
+                    let target = cases
+                        .iter()
+                        .find(|&&(k, _)| const_int_u64(m, k) == Some(cv))
+                        .map_or(d, |&(_, dst)| dst);
+                    m.insts[term_id as usize].op = Op::Br(target);
+                    let pred = Block(b as u32);
+                    for s in old_targets {
+                        trim_phi_edges(m, s.0 as usize, pred, usize::from(s == target));
+                    }
+                    changed = true;
+                } else {
+                    let mut seen_vals = Vec::with_capacity(cases.len());
+                    let filtered: Vec<(Value, Block)> = cases
+                        .iter()
+                        .copied()
+                        .filter(|&(cv, dst)| {
+                            if dst == d {
+                                return false;
+                            }
+                            if let Some(kv) = const_int_u64(m, cv) {
+                                if seen_vals.contains(&kv) {
+                                    return false;
+                                }
+                                seen_vals.push(kv);
+                            }
+                            true
+                        })
+                        .collect();
+                    if filtered.len() != cases.len() {
+                        let pred = Block(b as u32);
+                        if filtered.is_empty() {
+                            m.insts[term_id as usize].op = Op::Br(d);
+                            for s in old_targets {
+                                trim_phi_edges(m, s.0 as usize, pred, usize::from(s == d));
+                            }
+                        } else {
+                            m.insts[term_id as usize].op = Op::Switch(v, d, filtered.clone());
+                            for s in old_targets {
+                                let keep = usize::from(s == d) + filtered.iter().filter(|&&(_, x)| x == s).count();
+                                trim_phi_edges(m, s.0 as usize, pred, keep);
+                            }
+                        }
+                        changed = true;
+                    }
+                }
+            }
+            _ => {}
+        }
+    }
+
+    // 2. Reachability and incoming PHI edge reconciliation.
+    let mut alive = vec![true; n];
+    let rpo = compute_rpo(m, &alive);
+    let mut reach = vec![false; n];
+    for &b in &rpo {
+        reach[b] = true;
+    }
+    if rpo.len() < n {
+        alive = reach.clone();
+        changed = true;
+    }
+
+    let mut edge_counts: HashMap<(u32, u32), usize> = HashMap::new();
+    let mut preds: Vec<Vec<u32>> = vec![Vec::new(); n];
+    for &b in &rpo {
+        for succ in block_succs(m, b) {
+            if alive[succ] {
+                *edge_counts.entry((b as u32, succ as u32)).or_insert(0) += 1;
+                preds[succ].push(b as u32);
+            }
+        }
+    }
+
+    for &b in &rpo {
+        for k in 0..m.blocks[b].len() {
+            let id = m.blocks[b][k] as usize;
+            let Op::Phi(inc) = &mut m.insts[id].op else { break };
+            let mut rem: HashMap<u32, usize> = HashMap::new();
+            for &p in &preds[b] {
+                rem.insert(p, edge_counts[&(p, b as u32)]);
+            }
+            let orig_len = inc.len();
+            inc.retain(|&(_, pb)| {
+                if !alive.get(pb.0 as usize).copied().unwrap_or(false) {
+                    return false;
+                }
+                if let Some(cnt) = rem.get_mut(&pb.0) {
+                    if *cnt > 0 {
+                        *cnt -= 1;
+                        return true;
+                    }
+                }
+                false
+            });
+            if inc.len() != orig_len {
+                changed = true;
+            }
+        }
+    }
+
+    // 3. Bypass empty jump-only blocks (Br target with no other instructions).
+    for &b in &rpo {
+        if !alive[b] {
+            continue;
+        }
+        loop {
+            let succs = block_succs(m, b);
+            let mut bypassed = false;
+            for e in succs {
+                if e == 0 || e == b || !alive[e] || m.blocks[e].len() != 1 {
+                    continue;
+                }
+                let Op::Br(t) = m.insts[m.blocks[e][0] as usize].op else { continue };
+                let tu = t.0 as usize;
+                if tu == e {
+                    continue;
+                }
+                let no_phis = !block_has_phis(m, tu);
+                let single_pred_no_dup = preds[e].len() == 1
+                    && preds[e][0] == b as u32
+                    && !block_succs(m, b).contains(&tu);
+                if no_phis || single_pred_no_dup {
+                    let Some(&term_id) = m.blocks[b].last() else { break };
+                    let count = rewrite_term_target(&mut m.insts[term_id as usize].op, Block(e as u32), t);
+                    if count > 0 {
+                        if !no_phis {
+                            replace_phi_pred_block(m, tu, Block(e as u32), Block(b as u32));
+                        }
+                        let mut rem = count;
+                        preds[e].retain(|&p| {
+                            if rem > 0 && p == b as u32 {
+                                rem -= 1;
+                                false
+                            } else {
+                                true
+                            }
+                        });
+                        preds[tu].extend(std::iter::repeat_n(b as u32, count));
+                        if preds[e].is_empty() {
+                            alive[e] = false;
+                            if let Some(pos) = preds[tu].iter().position(|&p| p == e as u32) {
+                                preds[tu].swap_remove(pos);
+                            }
+                        }
+                        changed = true;
+                        bypassed = true;
+                        break;
+                    }
+                }
+            }
+            if !bypassed {
+                break;
+            }
+        }
+    }
+
+    // 4. Single-predecessor block merging (pred ends in `Br(succ)`, preds[succ] == [pred]).
+    let mut val_map: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut had_val_map = false;
+    for &pred in &rpo {
+        if !alive[pred] {
+            continue;
+        }
+        loop {
+            let Some(&last) = m.blocks[pred].last() else { break };
+            let Op::Br(succ_b) = m.insts[last as usize].op else { break };
+            let succ = succ_b.0 as usize;
+            if succ == 0 || succ == pred || !alive[succ] || preds[succ].len() != 1 {
+                break;
+            }
+            m.blocks[pred].pop();
+            let succ_insts = std::mem::take(&mut m.blocks[succ]);
+            for id in succ_insts {
+                let ty = m.insts[id as usize].ty;
+                if let Op::Phi(inc) = &m.insts[id as usize].op {
+                    let rep = inc
+                        .iter()
+                        .find(|&&(_, b)| b == Block(pred as u32))
+                        .map(|&(v, _)| resolve_val(v, &val_map))
+                        .unwrap_or_else(|| m.undef(ty));
+                    val_map[id as usize] = Some(rep);
+                    had_val_map = true;
+                } else {
+                    m.blocks[pred].push(id);
+                }
+            }
+            for s2 in block_succs(m, pred) {
+                replace_phi_pred_block(m, s2, Block(succ as u32), Block(pred as u32));
+                for p in &mut preds[s2] {
+                    if *p == succ as u32 {
+                        *p = pred as u32;
+                    }
+                }
+            }
+            preds[succ].clear();
+            alive[succ] = false;
+            changed = true;
+        }
+    }
+    if had_val_map {
+        for &b in &rpo {
+            if !alive[b] {
+                continue;
+            }
+            for &id in &m.blocks[b] {
+                rewrite_op_values(&mut m.insts[id as usize].op, &val_map);
+            }
+        }
+        rewrite_md_values(m, &val_map);
+    }
+
+    // 5. Dense RPO compaction & block index remapping.
+    let final_rpo = compute_rpo(m, &alive);
+    let already_ordered = final_rpo.len() == m.blocks.len() && final_rpo.iter().enumerate().all(|(i, &b)| i == b);
+    if !already_ordered {
+        let mut old_to_new: Vec<Option<Block>> = vec![None; m.blocks.len()];
+        let mut new_blocks = Vec::with_capacity(final_rpo.len());
+        for (new_idx, &old_idx) in final_rpo.iter().enumerate() {
+            old_to_new[old_idx] = Some(Block(new_idx as u32));
+            new_blocks.push(std::mem::take(&mut m.blocks[old_idx]));
+        }
+        m.blocks = new_blocks;
+        for b in &m.blocks {
+            for &id in b {
+                match &mut m.insts[id as usize].op {
+                    Op::Phi(inc) => {
+                        for (_, pb) in inc {
+                            *pb = old_to_new[pb.0 as usize].expect("live phi pred");
+                        }
+                    }
+                    Op::Br(t) => *t = old_to_new[t.0 as usize].expect("live br target"),
+                    Op::CondBr(_, t, f) => {
+                        *t = old_to_new[t.0 as usize].expect("live condbr true");
+                        *f = old_to_new[f.0 as usize].expect("live condbr false");
+                    }
+                    Op::Switch(_, d, cases) => {
+                        *d = old_to_new[d.0 as usize].expect("live switch default");
+                        for (_, t) in cases {
+                            *t = old_to_new[t.0 as usize].expect("live switch target");
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+        m.cur = Block(0);
+        changed = true;
+    }
+
+    changed
+}
+
+// ------------------------------------------------------------ PHI simplify
+
+fn intersect_idom(idom: &[Option<usize>], mut b1: usize, mut b2: usize) -> usize {
+    while b1 != b2 {
+        while b1 > b2 {
+            b1 = idom[b1].expect("rpo pred must have idom");
+        }
+        while b2 > b1 {
+            b2 = idom[b2].expect("rpo pred must have idom");
+        }
+    }
+    b1
+}
+
+/// Cooper-Harvey-Kennedy iterative immediate dominators over RPO indices `0..n`.
+fn compute_idom(m: &Module) -> Vec<Option<usize>> {
+    let n = m.blocks.len();
+    let mut idom: Vec<Option<usize>> = vec![None; n];
+    if n == 0 {
+        return idom;
+    }
+    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
+    for b in 0..n {
+        for s in block_succs(m, b) {
+            if s < n {
+                preds[s].push(b);
+            }
+        }
+    }
+    idom[0] = Some(0);
+    let mut dom_changed = true;
+    while dom_changed {
+        dom_changed = false;
+        for b in 1..n {
+            let Some(&first) = preds[b].iter().find(|&&p| idom[p].is_some()) else {
+                continue;
+            };
+            let mut new_idom = first;
+            for &p in &preds[b] {
+                if p != first && idom[p].is_some() {
+                    new_idom = intersect_idom(&idom, p, new_idom);
+                }
+            }
+            if idom[b] != Some(new_idom) {
+                idom[b] = Some(new_idom);
+                dom_changed = true;
+            }
+        }
+    }
+    idom
+}
+
+fn dominates(idom: &[Option<usize>], dom: usize, mut node: usize) -> bool {
+    while node > dom {
+        let Some(p) = idom[node] else { return false };
+        if p == node {
+            break;
+        }
+        node = p;
+    }
+    node == dom
+}
+
+/// Eliminates trivial PHIs (`phi [v, ...], [self, ...] -> v`) and deduplicates
+/// identical PHIs within the same block until reaching a fixed point.
+pub(super) fn simplify_phis(m: &mut Module) -> bool {
+    let idom = compute_idom(m);
+    let mut inst_block: Vec<Option<usize>> = vec![None; m.insts.len()];
+    for (bi, blk) in m.blocks.iter().enumerate() {
+        for &id in blk {
+            inst_block[id as usize] = Some(bi);
+        }
+    }
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut any_changed = false;
+
+    loop {
+        let mut round_changed = false;
+
+        for b in 0..m.blocks.len() {
+            let mut seen: HashMap<(Ty, Vec<(Option<Value>, u32)>), Value> = HashMap::new();
+            let old_insts = std::mem::take(&mut m.blocks[b]);
+            let mut keep = Vec::with_capacity(old_insts.len());
+            let mut in_phi_prefix = true;
+
+            for id in old_insts {
+                if !in_phi_prefix || !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    in_phi_prefix = false;
+                    if rewrite_op_values(&mut m.insts[id as usize].op, &repl) {
+                        round_changed = true;
+                    }
+                    keep.push(id);
+                    continue;
+                }
+                let phi_ty = m.insts[id as usize].ty;
+                let mut inc = match &mut m.insts[id as usize].op {
+                    Op::Phi(v) => std::mem::take(v),
+                    _ => unreachable!(),
+                };
+                for (v, _) in inc.iter_mut() {
+                    let nv = resolve_val(*v, &repl);
+                    if nv != *v {
+                        *v = nv;
+                        round_changed = true;
+                    }
+                }
+
+                let self_val = Value::Inst(id);
+
+                // Trivial PHI check: ignore self-references and undefs when looking for a unique value.
+                let mut unique: Option<Value> = None;
+                let mut non_trivial = false;
+                for &(v, _) in &inc {
+                    if v == self_val || is_undef(m, v) {
+                        continue;
+                    }
+                    match unique {
+                        None => unique = Some(v),
+                        Some(u) if u == v => {}
+                        Some(_) => {
+                            non_trivial = true;
+                            break;
+                        }
+                    }
+                }
+                if !non_trivial {
+                    let can_replace = match unique {
+                        Some(Value::Inst(ui)) => match inst_block.get(ui as usize).copied().flatten() {
+                            Some(db) if db != b => dominates(&idom, db, b),
+                            Some(_) => matches!(m.insts[ui as usize].op, Op::Phi(..)),
+                            None => false,
+                        },
+                        _ => true,
+                    };
+                    if can_replace {
+                        let rep = unique.unwrap_or_else(|| m.undef(phi_ty));
+                        repl[id as usize] = Some(rep);
+                        round_changed = true;
+                        continue;
+                    }
+                }
+
+                // Duplicate-PHI check within block `b` (normalizing self-ref to `None`).
+                let mut key_edges: Vec<(Option<Value>, u32)> = inc
+                    .iter()
+                    .map(|&(v, pb)| (if v == self_val { None } else { Some(v) }, pb.0))
+                    .collect();
+                key_edges.sort_unstable_by_key(|&(v, pb)| (pb, v));
+                let key = (phi_ty, key_edges);
+                if let Some(&prev) = seen.get(&key) {
+                    repl[id as usize] = Some(prev);
+                    round_changed = true;
+                    continue;
+                }
+                seen.insert(key, self_val);
+                m.insts[id as usize].op = Op::Phi(inc);
+                keep.push(id);
+            }
+            m.blocks[b] = keep;
+        }
+
+        if !round_changed {
+            break;
+        }
+        any_changed = true;
+        // Propagate replacements into PHIs whose producers came later in the same block or backedges.
+        for b in 0..m.blocks.len() {
+            for &id in &m.blocks[b] {
+                if !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    break;
+                }
+                rewrite_op_values(&mut m.insts[id as usize].op, &repl);
+            }
+        }
+    }
+
+    if any_changed {
+        rewrite_md_values(m, &repl);
+    }
+    any_changed
+}
+
+// --------------------------------------------------- InstCombine & Folding
+
+fn eval_int_binop(op: BinOp, w: u32, ua: u64, ub: u64) -> Option<u64> {
+    let mask = mask_for(w);
+    let ua = ua & mask;
+    let ub = ub & mask;
+    let r = match op {
+        BinOp::Add => ua.wrapping_add(ub),
+        BinOp::Sub => ua.wrapping_sub(ub),
+        BinOp::Mul => ua.wrapping_mul(ub),
+        BinOp::And => ua & ub,
+        BinOp::Or => ua | ub,
+        BinOp::Xor => ua ^ ub,
+        BinOp::UDiv => {
+            if ub == 0 {
+                return None;
+            }
+            ua / ub
+        }
+        BinOp::URem => {
+            if ub == 0 {
+                return None;
+            }
+            ua % ub
+        }
+        BinOp::SDiv => {
+            let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+            let smin = sext_i64(1u64 << (w - 1), w);
+            if sb == 0 || (sb == -1 && sa == smin) {
+                return None;
+            }
+            (sa / sb) as u64
+        }
+        BinOp::SRem => {
+            let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+            let smin = sext_i64(1u64 << (w - 1), w);
+            if sb == 0 || (sb == -1 && sa == smin) {
+                return None;
+            }
+            (sa % sb) as u64
+        }
+        BinOp::Shl => {
+            if ub >= w as u64 {
+                return None;
+            }
+            ua.wrapping_shl(ub as u32)
+        }
+        BinOp::LShr => {
+            if ub >= w as u64 {
+                return None;
+            }
+            ua >> (ub as u32)
+        }
+        BinOp::AShr => {
+            if ub >= w as u64 {
+                return None;
+            }
+            (sext_i64(ua, w) >> (ub as u32)) as u64
+        }
+    };
+    Some(r & mask)
+}
+
+fn eval_icmp(p: Pred, w: u32, ua: u64, ub: u64) -> Option<bool> {
+    let mask = mask_for(w);
+    let ua = ua & mask;
+    let ub = ub & mask;
+    let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+    Some(match p {
+        Pred::Eq => ua == ub,
+        Pred::Ne => ua != ub,
+        Pred::UGt => ua > ub,
+        Pred::UGe => ua >= ub,
+        Pred::ULt => ua < ub,
+        Pred::ULe => ua <= ub,
+        Pred::SGt => sa > sb,
+        Pred::SGe => sa >= sb,
+        Pred::SLt => sa < sb,
+        Pred::SLe => sa <= sb,
+        _ => return None,
+    })
+}
+
+fn make_not_op(m: &mut Module, x: Value) -> Op {
+    if let Value::Inst(xi) = x {
+        if let Op::Cmp(p, a, b) = m.insts[xi as usize].op {
+            return Op::Cmp(invert_pred(p), a, b);
+        }
+    }
+    let t = m.i1c(true);
+    Op::Bin(BinOp::Xor, x, t, 0)
+}
+
+fn unwrap_bitcast_src(m: &mut Module, v: Value, dst: Ty) -> Option<Value> {
+    if m.value_ty(v) == dst {
+        return Some(v);
+    }
+    if let Some(c) = const_bitcast(m, v, dst) {
+        return Some(c);
+    }
+    if let Value::Inst(id) = v {
+        if let Op::Cast(CastOp::BitCast, inner, _) = m.insts[id as usize].op {
+            if m.value_ty(inner) == dst {
+                return Some(inner);
+            }
+        }
+    }
+    None
+}
+
+fn simplify_int_bin(m: &mut Module, id: u32, ty: Ty, w: u32) -> Result<Value, Option<Op>> {
+    let Op::Bin(op, mut a, mut b, _flags) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    if matches!(op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor)
+        && const_int_u64(m, a).is_some()
+        && const_int_u64(m, b).is_none()
+    {
+        std::mem::swap(&mut a, &mut b);
+        return simplify_rewritten_bin(m, ty, w, op, a, b, true);
+    }
+    simplify_rewritten_bin(m, ty, w, op, a, b, false)
+}
+
+fn simplify_rewritten_bin(
+    m: &mut Module, ty: Ty, w: u32, op: BinOp, a: Value, b: Value, swapped: bool,
+) -> Result<Value, Option<Op>> {
+    let mask = mask_for(w);
+    let ca = const_int_u64(m, a);
+    let cb = const_int_u64(m, b);
+    if let (Some(ua), Some(ub)) = (ca, cb) {
+        if let Some(r) = eval_int_binop(op, w, ua, ub) {
+            return Ok(m.const_int(ty, r));
+        }
+    }
+
+    // Reassociate `(inner_op x, c1) outer_op c2` when `b = c2`.
+    if let (Value::Inst(ai), Some(c2)) = (a, cb) {
+        if let Op::Bin(op1, x, c1_val, _) = m.insts[ai as usize].op {
+            if let Some(c1) = const_int_u64(m, c1_val) {
+                let reassociated: Option<(BinOp, u64)> = match (op1, op) {
+                    (BinOp::Add, BinOp::Add) => Some((BinOp::Add, c1.wrapping_add(c2) & mask)),
+                    (BinOp::Sub, BinOp::Add) => Some((BinOp::Add, c2.wrapping_sub(c1) & mask)),
+                    (BinOp::Add, BinOp::Sub) => Some((BinOp::Add, c1.wrapping_sub(c2) & mask)),
+                    (BinOp::Sub, BinOp::Sub) => Some((BinOp::Add, 0u64.wrapping_sub(c1.wrapping_add(c2)) & mask)),
+                    (BinOp::Mul, BinOp::Mul) => Some((BinOp::Mul, c1.wrapping_mul(c2) & mask)),
+                    (BinOp::And, BinOp::And) => Some((BinOp::And, c1 & c2)),
+                    (BinOp::Or, BinOp::Or) => Some((BinOp::Or, c1 | c2)),
+                    (BinOp::Xor, BinOp::Xor) => Some((BinOp::Xor, c1 ^ c2)),
+                    (BinOp::Shl, BinOp::Shl)
+                    | (BinOp::LShr, BinOp::LShr)
+                    | (BinOp::AShr, BinOp::AShr)
+                        if (c1 as u128 + c2 as u128) < w as u128 =>
+                    {
+                        Some((op, c1 + c2))
+                    }
+                    _ => None,
+                };
+                if let Some((new_op, nc)) = reassociated {
+                    let nc_val = m.const_int(ty, nc);
+                    // Apply immediate identity check (e.g. `(x ^ c) ^ c -> x`).
+                    if let Ok(folded) = simplify_rewritten_bin(m, ty, w, new_op, x, nc_val, true) {
+                        return Ok(folded);
+                    }
+                    return Err(Some(Op::Bin(new_op, x, nc_val, 0)));
+                }
+            }
+        }
+    }
+
+    match op {
+        BinOp::Add => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b && w == 1 {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Sub => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b {
+                return Ok(m.const_int(ty, 0));
+            }
+            if ca == Some(0) && w == 1 {
+                return Ok(b);
+            }
+            if let Some(c) = cb {
+                let neg = (0u64.wrapping_sub(c)) & mask;
+                let neg_val = m.const_int(ty, neg);
+                return Err(Some(Op::Bin(BinOp::Add, a, neg_val, 0)));
+            }
+        }
+        BinOp::Mul => {
+            if cb == Some(0) {
+                return Ok(m.const_int(ty, 0));
+            }
+            if cb == Some(1) {
+                return Ok(a);
+            }
+            if a == b && w == 1 {
+                return Ok(a);
+            }
+        }
+        BinOp::UDiv | BinOp::SDiv => {
+            if cb == Some(1) {
+                return Ok(a);
+            }
+        }
+        BinOp::URem | BinOp::SRem => {
+            if cb == Some(1) {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Shl | BinOp::LShr | BinOp::AShr => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+        }
+        BinOp::And => {
+            if cb == Some(0) {
+                return Ok(m.const_int(ty, 0));
+            }
+            if cb == Some(mask) || a == b {
+                return Ok(a);
+            }
+            // `x & ~x == 0`
+            let is_comp = |lhs: Value, rhs: Value| -> bool {
+                let Value::Inst(ri) = rhs else { return false };
+                if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op {
+                    (x == lhs && const_int_u64(m, y) == Some(mask))
+                        || (y == lhs && const_int_u64(m, x) == Some(mask))
+                } else {
+                    false
+                }
+            };
+            if is_comp(a, b) || is_comp(b, a) {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Or => {
+            if cb == Some(0) || a == b {
+                return Ok(a);
+            }
+            if cb == Some(mask) {
+                return Ok(m.const_int(ty, mask));
+            }
+            let is_comp = |lhs: Value, rhs: Value| -> bool {
+                let Value::Inst(ri) = rhs else { return false };
+                if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op {
+                    (x == lhs && const_int_u64(m, y) == Some(mask))
+                        || (y == lhs && const_int_u64(m, x) == Some(mask))
+                } else {
+                    false
+                }
+            };
+            if is_comp(a, b) || is_comp(b, a) {
+                return Ok(m.const_int(ty, mask));
+            }
+        }
+        BinOp::Xor => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b {
+                return Ok(m.const_int(ty, 0));
+            }
+            // `(x ^ y) ^ y -> x`
+            if let Value::Inst(ai) = a {
+                if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[ai as usize].op {
+                    if v == b {
+                        return Ok(u);
+                    }
+                    if u == b {
+                        return Ok(v);
+                    }
+                }
+            }
+            if let Value::Inst(bi) = b {
+                if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[bi as usize].op {
+                    if v == a {
+                        return Ok(u);
+                    }
+                    if u == a {
+                        return Ok(v);
+                    }
+                }
+            }
+            // `xor(cmp(p, u, v), true) -> cmp(invert(p), u, v)`
+            if cb == Some(1) && w == 1 {
+                if let Value::Inst(ai) = a {
+                    if let Op::Cmp(p, u, v) = m.insts[ai as usize].op {
+                        return Err(Some(Op::Cmp(invert_pred(p), u, v)));
+                    }
+                }
+            }
+        }
+    }
+
+    if swapped {
+        Err(Some(Op::Bin(op, a, b, 0)))
+    } else {
+        Err(None)
+    }
+}
+
+fn simplify_cast(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Cast(op, v, dst) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    let src = m.value_ty(v);
+    if src == dst && matches!(op, CastOp::Trunc | CastOp::ZExt | CastOp::SExt | CastOp::FPTrunc | CastOp::FPExt | CastOp::BitCast) {
+        return Ok(v);
+    }
+
+    match op {
+        CastOp::Trunc | CastOp::ZExt => {
+            if let (Some(uv), Some(_)) = (const_int_u64(m, v), m.int_width(dst)) {
+                return Ok(m.const_int(dst, uv));
+            }
+        }
+        CastOp::SExt => {
+            if let (Some(uv), Some(sw), Some(_)) = (const_int_u64(m, v), m.int_width(src), m.int_width(dst)) {
+                let sv = sext_i64(uv, sw);
+                return Ok(m.const_int(dst, sv as u64));
+            }
+        }
+        CastOp::BitCast => {
+            if let Some(c) = const_bitcast(m, v, dst) {
+                return Ok(c);
+            }
+        }
+        _ => {}
+    }
+
+    if let Value::Inst(vi) = v {
+        match (op, m.insts[vi as usize].op.clone()) {
+            (CastOp::Trunc, Op::Cast(CastOp::Trunc, x, _)) => return Err(Some(Op::Cast(CastOp::Trunc, x, dst))),
+            (CastOp::ZExt, Op::Cast(CastOp::ZExt, x, _)) => return Err(Some(Op::Cast(CastOp::ZExt, x, dst))),
+            (CastOp::SExt, Op::Cast(CastOp::SExt, x, _)) => return Err(Some(Op::Cast(CastOp::SExt, x, dst))),
+            (CastOp::SExt, Op::Cast(CastOp::ZExt, x, _)) => {
+                if let (Some(wx), Some(wsrc)) = (m.int_width(m.value_ty(x)), m.int_width(src)) {
+                    if wx < wsrc {
+                        return Err(Some(Op::Cast(CastOp::ZExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::Trunc, Op::Cast(CastOp::ZExt, x, _)) => {
+                if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) {
+                    if wx == wd {
+                        return Ok(x);
+                    } else if wx > wd {
+                        return Err(Some(Op::Cast(CastOp::Trunc, x, dst)));
+                    } else {
+                        return Err(Some(Op::Cast(CastOp::ZExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::Trunc, Op::Cast(CastOp::SExt, x, _)) => {
+                if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) {
+                    if wx == wd {
+                        return Ok(x);
+                    } else if wx > wd {
+                        return Err(Some(Op::Cast(CastOp::Trunc, x, dst)));
+                    } else {
+                        return Err(Some(Op::Cast(CastOp::SExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::BitCast, Op::Cast(CastOp::BitCast, x, _)) => {
+                let xt = m.value_ty(x);
+                if xt == dst {
+                    return Ok(x);
+                }
+                if scalar_bits(m, xt).is_some() && scalar_bits(m, xt) == scalar_bits(m, dst) {
+                    return Err(Some(Op::Cast(CastOp::BitCast, x, dst)));
+                }
+            }
+            (CastOp::BitCast, Op::Select(c, a, b)) => {
+                if scalar_bits(m, src).is_some() && scalar_bits(m, src) == scalar_bits(m, dst) {
+                    if let (Some(ua), Some(ub)) = (unwrap_bitcast_src(m, a, dst), unwrap_bitcast_src(m, b, dst)) {
+                        if ua == ub {
+                            return Ok(ua);
+                        }
+                        return Err(Some(Op::Select(c, ua, ub)));
+                    }
+                }
+            }
+            _ => {}
+        }
+    }
+
+    Err(None)
+}
+
+fn simplify_cmp(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Cmp(mut p, mut a, mut b) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    let ty = m.value_ty(a);
+    let Some(w) = m.int_width(ty) else {
+        return Err(None);
+    };
+    let mut swapped = false;
+    if const_int_u64(m, a).is_some() && const_int_u64(m, b).is_none() {
+        std::mem::swap(&mut a, &mut b);
+        p = swap_pred(p);
+        swapped = true;
+    }
+
+    if let (Some(ua), Some(ub)) = (const_int_u64(m, a), const_int_u64(m, b)) {
+        if let Some(res) = eval_icmp(p, w, ua, ub) {
+            return Ok(m.i1c(res));
+        }
+    }
+    if a == b {
+        if let Some(res) = eval_icmp(p, w, 0, 0) {
+            return Ok(m.i1c(res));
+        }
+    }
+
+    let mask = mask_for(w);
+    if let Some(cb) = const_int_u64(m, b) {
+        if cb == 0 && p == Pred::ULt {
+            return Ok(m.i1c(false));
+        }
+        if cb == 0 && p == Pred::UGe {
+            return Ok(m.i1c(true));
+        }
+        if cb == mask && p == Pred::UGt {
+            return Ok(m.i1c(false));
+        }
+        if cb == mask && p == Pred::ULe {
+            return Ok(m.i1c(true));
+        }
+        if cb == 0 && p == Pred::ULe {
+            return Err(Some(Op::Cmp(Pred::Eq, a, b)));
+        }
+        if cb == 0 && p == Pred::UGt {
+            return Err(Some(Op::Cmp(Pred::Ne, a, b)));
+        }
+        if cb == mask && p == Pred::UGe {
+            return Err(Some(Op::Cmp(Pred::Eq, a, b)));
+        }
+        if cb == mask && p == Pred::ULt {
+            return Err(Some(Op::Cmp(Pred::Ne, a, b)));
+        }
+
+        if w == 1 {
+            return match (p, cb) {
+                (Pred::Eq, 1) | (Pred::Ne, 0) => Ok(a),
+                (Pred::Eq, 0) | (Pred::Ne, 1) => Err(Some(make_not_op(m, a))),
+                _ => {
+                    if swapped {
+                        Err(Some(Op::Cmp(p, a, b)))
+                    } else {
+                        Err(None)
+                    }
+                }
+            };
+        }
+
+        // Collapse `(zext i1 x) cmp k` and `(sext i1 x) cmp k` (`set_scc` / `scc_bit` idioms)
+        // and `select(c, const, const) cmp k`.
+        if let Value::Inst(ai) = a {
+            match m.insts[ai as usize].op {
+                Op::Cast(CastOp::ZExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => {
+                    if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, 1, cb)) {
+                        if f0 == f1 {
+                            return Ok(m.i1c(f0));
+                        }
+                        return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) };
+                    }
+                }
+                Op::Cast(CastOp::SExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => {
+                    if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, mask, cb)) {
+                        if f0 == f1 {
+                            return Ok(m.i1c(f0));
+                        }
+                        return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) };
+                    }
+                }
+                Op::Select(cond, tc, fc) => {
+                    if let (Some(ct), Some(cf)) = (const_int_u64(m, tc), const_int_u64(m, fc)) {
+                        if let (Some(bt), Some(bf)) = (eval_icmp(p, w, ct, cb), eval_icmp(p, w, cf, cb)) {
+                            if bt == bf {
+                                return Ok(m.i1c(bt));
+                            }
+                            return if bt { Ok(cond) } else { Err(Some(make_not_op(m, cond))) };
+                        }
+                    }
+                }
+                _ => {}
+            }
+        }
+    }
+
+    if swapped {
+        Err(Some(Op::Cmp(p, a, b)))
+    } else {
+        Err(None)
+    }
+}
+
+fn simplify_select(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Select(c, mut t, mut f) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    if let Some(cv) = const_int_u64(m, c) {
+        return Ok(if cv & 1 != 0 { t } else { f });
+    }
+    if t == f {
+        return Ok(t);
+    }
+    if let Some(inner) = match_not_i1(m, c) {
+        return Err(Some(Op::Select(inner, f, t)));
+    }
+
+    let ty = m.insts[id as usize].ty;
+    if m.int_width(ty) == Some(1) {
+        let ct = const_int_u64(m, t);
+        let cf = const_int_u64(m, f);
+        if ct == Some(1) && cf == Some(0) {
+            return Ok(c);
+        }
+        if ct == Some(0) && cf == Some(1) {
+            return Err(Some(make_not_op(m, c)));
+        }
+        if (t == c && cf == Some(0)) || (ct == Some(1) && f == c) {
+            return Ok(c);
+        }
+        if t == c && cf == Some(1) {
+            return Ok(m.i1c(true));
+        }
+        if ct == Some(0) && f == c {
+            return Ok(m.i1c(false));
+        }
+    }
+
+    // `select c, (select c, t1, _), f -> select c, t1, f` (and analogously in `f`).
+    let mut folded_arm = false;
+    if let Value::Inst(ti) = t {
+        if let Op::Select(c2, t2, _) = m.insts[ti as usize].op {
+            if c2 == c {
+                t = t2;
+                folded_arm = true;
+            }
+        }
+    }
+    if let Value::Inst(fi) = f {
+        if let Op::Select(c2, _, f2) = m.insts[fi as usize].op {
+            if c2 == c {
+                f = f2;
+                folded_arm = true;
+            }
+        }
+    }
+    if folded_arm {
+        if t == f {
+            return Ok(t);
+        }
+        return Err(Some(Op::Select(c, t, f)));
+    }
+
+    Err(None)
+}
+
+fn simplify_pure_dxop_call(m: &mut Module, id: u32) -> Option<Value> {
+    let Op::Call(f, args) = &m.insts[id as usize].op else { return None };
+    let name = &m.funcs[*f as usize].name;
+    let opc = args.first().and_then(|&v| const_int_u64(m, v))?;
+
+    if is_op_name(name, "dx.op.unaryBits") && args.len() == 2 {
+        let uv = const_int_u64(m, args[1])?;
+        let sw = m.int_width(m.value_ty(args[1]))?;
+        let mask = mask_for(sw);
+        let u = uv & mask;
+        let res = match opc {
+            31 => u.count_ones() as u64,
+            32 => {
+                if u == 0 {
+                    u32::MAX as u64
+                } else {
+                    u.trailing_zeros() as u64
+                }
+            }
+            33 => {
+                if u == 0 {
+                    u32::MAX as u64
+                } else {
+                    (u.leading_zeros() - (64 - sw)) as u64
+                }
+            }
+            34 => {
+                let sign = (u >> (sw - 1)) & 1 != 0;
+                let bits = if sign { (!u) & mask } else { u };
+                if bits == 0 {
+                    u32::MAX as u64
+                } else {
+                    (bits.leading_zeros() - (64 - sw)) as u64
+                }
+            }
+            _ => return None,
+        };
+        return Some(m.i32c(res as u32));
+    }
+
+    if is_op_name(name, "dx.op.unary") && opc == 30 && args.len() == 2 {
+        let ty = m.insts[id as usize].ty;
+        let sw = m.int_width(ty)?;
+        let uv = const_int_u64(m, args[1])?;
+        let rev = (uv & mask_for(sw)).reverse_bits() >> (64 - sw);
+        return Some(m.const_int(ty, rev));
+    }
+
+    if is_op_name(name, "dx.op.binary") && (37..=40).contains(&opc) && args.len() == 3 {
+        let (a, b) = (args[1], args[2]);
+        if a == b {
+            return Some(a);
+        }
+        let ty = m.insts[id as usize].ty;
+        let sw = m.int_width(ty)?;
+        let (ua, ub) = (const_int_u64(m, a)?, const_int_u64(m, b)?);
+        let r = match opc {
+            37 => (sext_i64(ua, sw).max(sext_i64(ub, sw))) as u64,
+            38 => (sext_i64(ua, sw).min(sext_i64(ub, sw))) as u64,
+            39 => ua.max(ub),
+            40 => ua.min(ub),
+            _ => unreachable!(),
+        };
+        return Some(m.const_int(ty, r));
+    }
+
+    None
+}
+
+/// RPO constant folding, cast simplification, integer identities/reassociation,
+/// comparison and select simplifications.
+pub(super) fn simplify_insts(m: &mut Module) -> bool {
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut changed = false;
+
+    for b in 0..m.blocks.len() {
+        let mut keep = Vec::with_capacity(m.blocks[b].len());
+        let old_insts = std::mem::take(&mut m.blocks[b]);
+        for id in old_insts {
+            if rewrite_op_values(&mut m.insts[id as usize].op, &repl) {
+                changed = true;
+            }
+            if matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                keep.push(id);
+                continue;
+            }
+            let ty = m.insts[id as usize].ty;
+            let simplified = match &m.insts[id as usize].op {
+                Op::Bin(..) => {
+                    if let Some(w) = m.int_width(ty) {
+                        simplify_int_bin(m, id, ty, w)
+                    } else {
+                        Err(None)
+                    }
+                }
+                Op::Cast(..) => simplify_cast(m, id),
+                Op::Cmp(..) => simplify_cmp(m, id),
+                Op::Select(..) => simplify_select(m, id),
+                Op::Call(..) => match simplify_pure_dxop_call(m, id) {
+                    Some(v) => Ok(v),
+                    None => Err(None),
+                },
+                _ => Err(None),
+            };
+            match simplified {
+                Ok(v) if v != Value::Inst(id) => {
+                    repl[id as usize] = Some(v);
+                    changed = true;
+                }
+                Err(Some(new_op)) => {
+                    m.insts[id as usize].op = new_op;
+                    changed = true;
+                    keep.push(id);
+                }
+                _ => keep.push(id),
+            }
+        }
+        m.blocks[b] = keep;
+    }
+
+    if changed {
+        for b in 0..m.blocks.len() {
+            for &id in &m.blocks[b] {
+                if !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    break;
+                }
+                rewrite_op_values(&mut m.insts[id as usize].op, &repl);
+            }
+        }
+        rewrite_md_values(m, &repl);
+    }
+
+    changed
+}
+
+// --------------------------------------------------------- Dominator CSE
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum CseKey {
+    Bin(u8, Value, Value, u64),
+    Cast(u8, Value, Ty),
+    Cmp(u8, Value, Value),
+    Select(Value, Value, Value),
+    Extract(Value, u32),
+    Gep(Value, Vec<Value>),
+    Call(u32, Vec<Value>),
+}
+
+fn cse_key(m: &Module, op: &Op) -> Option<CseKey> {
+    match op {
+        Op::Bin(bin_op, a, b, flags) => {
+            let (mut x, mut y) = (*a, *b);
+            if matches!(bin_op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) && x > y {
+                std::mem::swap(&mut x, &mut y);
+            }
+            Some(CseKey::Bin(*bin_op as u8, x, y, *flags))
+        }
+        Op::Cast(cop, v, ty) => Some(CseKey::Cast(*cop as u8, *v, *ty)),
+        Op::Cmp(p, a, b) => {
+            let (mut p, mut x, mut y) = (*p, *a, *b);
+            if x > y {
+                std::mem::swap(&mut x, &mut y);
+                p = swap_pred(p);
+            }
+            Some(CseKey::Cmp(p as u8, x, y))
+        }
+        Op::Select(c, t, f) => Some(CseKey::Select(*c, *t, *f)),
+        Op::Extract(a, idx) => Some(CseKey::Extract(*a, *idx)),
+        Op::Gep(p, idx) => Some(CseKey::Gep(*p, idx.clone())),
+        Op::Call(f, args) => {
+            let fd = &m.funcs[*f as usize];
+            if fd.attrs != FnAttrs::ReadNone {
+                return None;
+            }
+            // Implicit quad derivatives (`dx.op.unary` opcodes 83..=86) depend on
+            // CFG position even though declared `readnone`. Never CSE them.
+            if is_op_name(&fd.name, "dx.op.unary") {
+                let opc = args.first().and_then(|&v| const_int_u64(m, v));
+                if !matches!(opc, Some(0..=30)) {
+                    return None;
+                }
+            }
+            let mut norm_args = args.clone();
+            if is_op_name(&fd.name, "dx.op.binary")
+                && norm_args.len() == 3
+                && matches!(norm_args.first().and_then(|&v| const_int_u64(m, v)), Some(35..=40))
+                && norm_args[1] > norm_args[2]
+            {
+                norm_args.swap(1, 2);
+            }
+            Some(CseKey::Call(*f, norm_args))
+        }
+        _ => None,
+    }
+}
+
+/// Dominator-tree scoped CSE assuming blocks `0..n` are already in RPO.
+pub(super) fn cse(m: &mut Module) -> bool {
+    let n = m.blocks.len();
+    if n == 0 {
+        return false;
+    }
+
+    let idom = compute_idom(m);
+    let mut children: Vec<Vec<usize>> = vec![Vec::new(); n];
+    for b in 1..n {
+        if let Some(p) = idom[b] {
+            children[p].push(b);
+        }
+    }
+
+    enum DomFrame {
+        Enter(usize),
+        Exit(usize),
+    }
+
+    let mut table: HashMap<CseKey, Value> = HashMap::new();
+    let mut undo: Vec<CseKey> = Vec::new();
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut changed = false;
+    let mut stack = vec![DomFrame::Enter(0)];
+
+    while let Some(frame) = stack.pop() {
+        match frame {
+            DomFrame::Enter(b) => {
+                let mark = undo.len();
+                stack.push(DomFrame::Exit(mark));

Could each dominator child get its own CSE table scope? This Exit runs only after every child has been visited, so an expression inserted in one branch remains available in its sibling even though that definition does not dominate the sibling. CSE can then replace the sibling value with a non-dominating SSA value. Please restore the table to the parent mark between child subtrees. AI-assisted review: I traced the sibling-block traversal and table lifetime.

**@⁠gut0to** on GitHub · 2026-11-24 17:32 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546#discussion_r4684000349) On `crates/xcl/src/gpu/dxil/opt.rs` line 1795 (outdated): ```diff @@ -0,0 +1,2770 @@ +//! Intra-function DXIL SSA IR optimization and module compaction pass suite. +//! +//! Runs after IR construction and before metadata/bitcode serialization: +//! 1. Fixpoint loop over CFG simplification & RPO normalization, trivial/duplicate +//! PHI elimination, constant folding & algebraic/bitcast/select simplification, +//! dominator-scoped CSE (excluding implicit derivatives and non-pure intrinsics), +//! and iterative mark-and-sweep DCE. +//! 2. Dense compaction of live instructions, constants, declarations, and globals. +//! 3. Synchronization of [`Shader::features`] with the remaining live IR. +//! +//! All graph traversals use explicit stacks so large shaders cannot overflow. + +use std::collections::{BTreeSet, HashMap}; + +use super::module::{BinOp, Block, CastOp, ConstDef, FnAttrs, MdDef, Module, Op, Pred, Ty, Value}; +use super::shader::{kind, Feature, Shader}; + +const MAX_ROUNDS: usize = 8; + +/// Summary metrics of a DXIL [`Module`] (for diagnostics and optimization tests). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Stats { + pub blocks: usize, + pub insts: usize, + pub phis: usize, + pub consts: usize, + pub funcs: usize, + pub globals: usize, +} + +/// Counts live blocks/instructions/PHIs and pooled constants/functions/globals. +pub fn module_stats(m: &Module) -> Stats { + let mut insts = 0usize; + let mut phis = 0usize; + for b in &m.blocks { + insts += b.len(); + for &id in b { + if matches!(m.insts[id as usize].op, Op::Phi(..)) { + phis += 1; + } + } + } + Stats { + blocks: m.blocks.len(), + insts, + phis, + consts: m.consts.len(), + funcs: m.funcs.len(), + globals: m.globals.len(), + } +} + +/// Optimizes `s.m`, compacts pooled module tables (updating `s.entry`), and +/// synchronizes `s.features` against the remaining live IR. +pub fn optimize(s: &mut Shader) { + if s.m.error().is_some() || s.m.blocks.is_empty() { + return; + } + optimize_core(&mut s.m); + compact_module(&mut s.m, Some(&mut s.entry)); + sync_features(s); +} + +/// Optimizes and compacts `m` without modifying wrapper shader metadata. +pub fn optimize_module(m: &mut Module) { + if m.error().is_some() || m.blocks.is_empty() { + return; + } + optimize_core(m); + compact_module(m, None); +} + +fn optimize_core(m: &mut Module) { + for _ in 0..MAX_ROUNDS { + let mut changed = false; + changed |= simplify_cfg(m); + changed |= simplify_phis(m); + changed |= simplify_insts(m); + changed |= cse(m); + changed |= dce(m); + if !changed { + break; + } + } + // Final normalization pass if the last DCE/CSE opened trivial CFG/PHI cleanup. + if simplify_cfg(m) { + let _ = simplify_phis(m); + let _ = dce(m); + let _ = simplify_cfg(m); + } +} + +// ------------------------------------------------------------------ helpers + +fn mask_for(w: u32) -> u64 { + if w >= 64 { + u64::MAX + } else if w == 0 { + 0 + } else { + (1u64 << w) - 1 + } +} + +fn sext_i64(v: u64, w: u32) -> i64 { + if w >= 64 { + v as i64 + } else if w == 0 { + 0 + } else { + ((v << (64 - w)) as i64) >> (64 - w) + } +} + +fn const_int_u64(m: &Module, v: Value) -> Option<u64> { + match v { + Value::Const(c) => match &m.consts[c as usize] { + ConstDef::Int(t, x) => { + let w = m.int_width(*t)?; + Some((*x as u64) & mask_for(w)) + } + ConstDef::Null(t) if m.int_width(*t).is_some() => Some(0), + _ => None, + }, + _ => None, + } +} + +fn scalar_bits(m: &Module, ty: Ty) -> Option<u32> { + if let Some(w) = m.int_width(ty) { + return Some(w); + } + if m.is_float(ty) { + return match m.alloc_size_layout(ty, true) { + 2 => Some(16), + 4 => Some(32), + 8 => Some(64), + _ => None, + }; + } + None +} + +fn const_bitcast(m: &mut Module, v: Value, dst: Ty) -> Option<Value> { + if m.value_ty(v) == dst { + return Some(v); + } + let Value::Const(c) = v else { return None }; + let dst_bits = scalar_bits(m, dst)?; + let def = m.consts[c as usize].clone(); + match def { + ConstDef::Undef(t) => (scalar_bits(m, t) == Some(dst_bits)).then(|| m.undef(dst)), + ConstDef::Null(t) if scalar_bits(m, t) == Some(dst_bits) => { + if m.int_width(dst).is_some() { + Some(m.const_int(dst, 0)) + } else if m.is_float(dst) { + Some(m.const_float(dst, 0)) + } else { + None + } + } + ConstDef::Int(t, x) => { + let w = m.int_width(t)?; + if w != dst_bits { + return None; + } + let raw = (x as u64) & mask_for(w); + if m.int_width(dst).is_some() { + Some(m.const_int(dst, raw)) + } else if m.is_float(dst) { + Some(m.const_float(dst, raw)) + } else { + None + } + } + ConstDef::Float(t, bits) => { + let w = scalar_bits(m, t)?; + if w != dst_bits { + return None; + } + if m.int_width(dst).is_some() { + Some(m.const_int(dst, bits)) + } else if m.is_float(dst) { + Some(m.const_float(dst, bits)) + } else { + None + } + } + _ => None, + } +} + +fn is_undef(m: &Module, v: Value) -> bool { + matches!(v, Value::Const(c) if matches!(m.consts[c as usize], ConstDef::Undef(_))) +} + +fn is_op_name(full: &str, base: &str) -> bool { + full == base || full.strip_prefix(base).is_some_and(|s| s.starts_with('.')) +} + +fn resolve_val(mut v: Value, repl: &[Option<Value>]) -> Value { + let mut steps = 0usize; + while let Value::Inst(id) = v { + let Some(next) = repl.get(id as usize).copied().flatten() else { break }; + if next == v || steps >= repl.len() { + break; + } + v = next; + steps += 1; + } + v +} + +fn visit_op_values_mut(op: &mut Op, f: &mut dyn FnMut(&mut Value)) { + match op { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => { + f(a); + f(b); + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(v), + Op::Store(p, v, _) => { + f(p); + f(v); + } + Op::Select(c, t, e) | Op::CmpXchg(c, t, e) => { + f(c); + f(t); + f(e); + } + Op::Call(_, args) => { + for a in args { + f(a); + } + } + Op::Phi(inc) => { + for (v, _) in inc { + f(v); + } + } + Op::Gep(p, idx) => { + f(p); + for i in idx { + f(i); + } + } + Op::Alloca(_, n, _) => f(n), + Op::CondBr(c, _, _) => f(c), + Op::Switch(v, _, cases) => { + f(v); + for (cv, _) in cases { + f(cv); + } + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } +} + +fn rewrite_op_values(op: &mut Op, repl: &[Option<Value>]) -> bool { + let mut changed = false; + visit_op_values_mut(op, &mut |v| { + let nv = resolve_val(*v, repl); + if nv != *v { + *v = nv; + changed = true; + } + }); + changed +} + +fn rewrite_md_values(m: &mut Module, repl: &[Option<Value>]) { + for md in &mut m.md { + if let MdDef::Val(_, v) = md { + *v = resolve_val(*v, repl); + } + } +} + +fn for_each_op_value(op: &Op, mut f: impl FnMut(Value)) { + match op { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b); + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(*v), + Op::Store(p, v, _) => { + f(*p); + f(*v); + } + Op::Select(c, t, x) | Op::CmpXchg(c, t, x) => { + f(*c); + f(*t); + f(*x); + } + Op::Call(_, args) => { + for &a in args { + f(a); + } + } + Op::Phi(inc) => { + for &(v, _) in inc { + f(v); + } + } + Op::Gep(p, idx) => { + f(*p); + for &i in idx { + f(i); + } + } + Op::Alloca(_, n, _) => f(*n), + Op::CondBr(c, _, _) => f(*c), + Op::Switch(v, _, cases) => { + f(*v); + for &(cv, _) in cases { + f(cv); + } + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } +} + +fn block_succs(m: &Module, b: usize) -> Vec<usize> { + let Some(&last) = m.blocks[b].last() else { return Vec::new() }; + match &m.insts[last as usize].op { + Op::Br(t) => vec![t.0 as usize], + Op::CondBr(_, t, f) => vec![t.0 as usize, f.0 as usize], + Op::Switch(_, d, cases) => { + let mut s = Vec::with_capacity(1 + cases.len()); + s.push(d.0 as usize); + for &(_, c) in cases { + s.push(c.0 as usize); + } + s + } + _ => Vec::new(), + } +} + +fn invert_pred(p: Pred) -> Pred { + match p { + Pred::Eq => Pred::Ne, + Pred::Ne => Pred::Eq, + Pred::UGt => Pred::ULe, + Pred::UGe => Pred::ULt, + Pred::ULt => Pred::UGe, + Pred::ULe => Pred::UGt, + Pred::SGt => Pred::SLe, + Pred::SGe => Pred::SLt, + Pred::SLt => Pred::SGe, + Pred::SLe => Pred::SGt, + Pred::FFalse => Pred::FTrue, + Pred::FTrue => Pred::FFalse, + Pred::FOEq => Pred::FUNe, + Pred::FUNe => Pred::FOEq, + Pred::FOGt => Pred::FULe, + Pred::FULe => Pred::FOGt, + Pred::FOGe => Pred::FULt, + Pred::FULt => Pred::FOGe, + Pred::FOLt => Pred::FUGe, + Pred::FUGe => Pred::FOLt, + Pred::FOLe => Pred::FUGt, + Pred::FUGt => Pred::FOLe, + Pred::FONe => Pred::FUEq, + Pred::FUEq => Pred::FONe, + Pred::FOrd => Pred::FUno, + Pred::FUno => Pred::FOrd, + } +} + +fn swap_pred(p: Pred) -> Pred { + match p { + Pred::UGt => Pred::ULt, + Pred::ULt => Pred::UGt, + Pred::UGe => Pred::ULe, + Pred::ULe => Pred::UGe, + Pred::SGt => Pred::SLt, + Pred::SLt => Pred::SGt, + Pred::SGe => Pred::SLe, + Pred::SLe => Pred::SGe, + Pred::FOGt => Pred::FOLt, + Pred::FOLt => Pred::FOGt, + Pred::FOGe => Pred::FOLe, + Pred::FOLe => Pred::FOGe, + Pred::FUGt => Pred::FULt, + Pred::FULt => Pred::FUGt, + Pred::FUGe => Pred::FULe, + Pred::FULe => Pred::FUGe, + other => other, + } +} + +/// If `v` computes logical NOT (`xor i1 x, true`) returns `Some(x)`. +fn match_not_i1(m: &Module, v: Value) -> Option<Value> { + let Value::Inst(id) = v else { return None }; + if m.int_width(m.insts[id as usize].ty) != Some(1) { + return None; + } + if let Op::Bin(BinOp::Xor, a, b, _) = m.insts[id as usize].op { + if const_int_u64(m, b) == Some(1) { + return Some(a); + } + if const_int_u64(m, a) == Some(1) { + return Some(b); + } + } + None +} + +// ------------------------------------------------------------ CFG simplify + +fn compute_rpo(m: &Module, alive: &[bool]) -> Vec<usize> { + let n = m.blocks.len(); + if n == 0 || !alive[0] { + return Vec::new(); + } + let succs: Vec<Vec<usize>> = (0..n) + .map(|b| if alive[b] { block_succs(m, b) } else { Vec::new() }) + .collect(); + let mut state = vec![0u8; n]; + let mut postorder = Vec::with_capacity(n); + let mut stack = vec![(0usize, 0usize)]; + state[0] = 1; + while let Some((b, idx)) = stack.last_mut() { + let b = *b; + let sb = &succs[b]; + if *idx < sb.len() { + // Visit successors in reverse order so reversed postorder places the + // primary/true branch before the fallback/exit branch. + let next = sb[sb.len() - 1 - *idx]; + *idx += 1; + if alive.get(next).copied().unwrap_or(false) && state[next] == 0 { + state[next] = 1; + stack.push((next, 0)); + } + } else { + state[b] = 2; + postorder.push(b); + stack.pop(); + } + } + postorder.reverse(); + postorder +} + +/// Keeps at most `keep` entries from `pred` in every `Op::Phi` of block `succ`. +fn trim_phi_edges(m: &mut Module, succ: usize, pred: Block, keep: usize) -> bool { + let mut changed = false; + for k in 0..m.blocks[succ].len() { + let id = m.blocks[succ][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + let have = inc.iter().filter(|&&(_, b)| b == pred).count(); + if have > keep { + let mut left = keep; + inc.retain(|&(_, b)| { + if b == pred { + if left > 0 { + left -= 1; + true + } else { + false + } + } else { + true + } + }); + changed = true; + } + } + changed +} + +fn replace_phi_pred_block(m: &mut Module, succ: usize, from: Block, to: Block) { + for k in 0..m.blocks[succ].len() { + let id = m.blocks[succ][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + for (_, b) in inc.iter_mut() { + if *b == from { + *b = to; + } + } + } +} + +fn block_has_phis(m: &Module, b: usize) -> bool { + m.blocks[b].first().is_some_and(|&id| matches!(m.insts[id as usize].op, Op::Phi(..))) +} + +fn rewrite_term_target(term: &mut Op, from: Block, to: Block) -> usize { + let mut count = 0; + match term { + Op::Br(t) if *t == from => { + *t = to; + count += 1; + } + Op::CondBr(_, t, f) => { + if *t == from { + *t = to; + count += 1; + } + if *f == from { + *f = to; + count += 1; + } + } + Op::Switch(_, d, cases) => { + if *d == from { + *d = to; + count += 1; + } + for (_, t) in cases { + if *t == from { + *t = to; + count += 1; + } + } + } + _ => {} + } + count +} + +/// Simplifies terminators, drops unreachable blocks, trims dead PHI edges, +/// bypasses empty jump blocks, merges single-predecessor blocks, and lays out +/// reachable blocks in RPO. +pub(super) fn simplify_cfg(m: &mut Module) -> bool { + let n = m.blocks.len(); + if n == 0 { + return false; + } + let mut changed = false; + + // 1. Fold constant / redundant terminators. + for b in 0..n { + let Some(&term_id) = m.blocks[b].last() else { continue }; + let op = m.insts[term_id as usize].op.clone(); + match op { + Op::CondBr(c, t, f) => { + if let Some(cv) = const_int_u64(m, c) { + let target = if cv & 1 != 0 { t } else { f }; + m.insts[term_id as usize].op = Op::Br(target); + let pred = Block(b as u32); + trim_phi_edges(m, target.0 as usize, pred, 1); + let other = if target == t { f } else { t }; + if other != target { + trim_phi_edges(m, other.0 as usize, pred, 0); + } + changed = true; + } else if t == f { + m.insts[term_id as usize].op = Op::Br(t); + trim_phi_edges(m, t.0 as usize, Block(b as u32), 1); + changed = true; + } else if let Some(inner) = match_not_i1(m, c) { + m.insts[term_id as usize].op = Op::CondBr(inner, f, t); + changed = true; + } + } + Op::Switch(v, d, cases) => { + let mut old_targets = Vec::with_capacity(1 + cases.len()); + old_targets.push(d); + for &(_, target) in &cases { + if !old_targets.contains(&target) { + old_targets.push(target); + } + } + if let Some(cv) = const_int_u64(m, v) { + let target = cases + .iter() + .find(|&&(k, _)| const_int_u64(m, k) == Some(cv)) + .map_or(d, |&(_, dst)| dst); + m.insts[term_id as usize].op = Op::Br(target); + let pred = Block(b as u32); + for s in old_targets { + trim_phi_edges(m, s.0 as usize, pred, usize::from(s == target)); + } + changed = true; + } else { + let mut seen_vals = Vec::with_capacity(cases.len()); + let filtered: Vec<(Value, Block)> = cases + .iter() + .copied() + .filter(|&(cv, dst)| { + if dst == d { + return false; + } + if let Some(kv) = const_int_u64(m, cv) { + if seen_vals.contains(&kv) { + return false; + } + seen_vals.push(kv); + } + true + }) + .collect(); + if filtered.len() != cases.len() { + let pred = Block(b as u32); + if filtered.is_empty() { + m.insts[term_id as usize].op = Op::Br(d); + for s in old_targets { + trim_phi_edges(m, s.0 as usize, pred, usize::from(s == d)); + } + } else { + m.insts[term_id as usize].op = Op::Switch(v, d, filtered.clone()); + for s in old_targets { + let keep = usize::from(s == d) + filtered.iter().filter(|&&(_, x)| x == s).count(); + trim_phi_edges(m, s.0 as usize, pred, keep); + } + } + changed = true; + } + } + } + _ => {} + } + } + + // 2. Reachability and incoming PHI edge reconciliation. + let mut alive = vec![true; n]; + let rpo = compute_rpo(m, &alive); + let mut reach = vec![false; n]; + for &b in &rpo { + reach[b] = true; + } + if rpo.len() < n { + alive = reach.clone(); + changed = true; + } + + let mut edge_counts: HashMap<(u32, u32), usize> = HashMap::new(); + let mut preds: Vec<Vec<u32>> = vec![Vec::new(); n]; + for &b in &rpo { + for succ in block_succs(m, b) { + if alive[succ] { + *edge_counts.entry((b as u32, succ as u32)).or_insert(0) += 1; + preds[succ].push(b as u32); + } + } + } + + for &b in &rpo { + for k in 0..m.blocks[b].len() { + let id = m.blocks[b][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + let mut rem: HashMap<u32, usize> = HashMap::new(); + for &p in &preds[b] { + rem.insert(p, edge_counts[&(p, b as u32)]); + } + let orig_len = inc.len(); + inc.retain(|&(_, pb)| { + if !alive.get(pb.0 as usize).copied().unwrap_or(false) { + return false; + } + if let Some(cnt) = rem.get_mut(&pb.0) { + if *cnt > 0 { + *cnt -= 1; + return true; + } + } + false + }); + if inc.len() != orig_len { + changed = true; + } + } + } + + // 3. Bypass empty jump-only blocks (Br target with no other instructions). + for &b in &rpo { + if !alive[b] { + continue; + } + loop { + let succs = block_succs(m, b); + let mut bypassed = false; + for e in succs { + if e == 0 || e == b || !alive[e] || m.blocks[e].len() != 1 { + continue; + } + let Op::Br(t) = m.insts[m.blocks[e][0] as usize].op else { continue }; + let tu = t.0 as usize; + if tu == e { + continue; + } + let no_phis = !block_has_phis(m, tu); + let single_pred_no_dup = preds[e].len() == 1 + && preds[e][0] == b as u32 + && !block_succs(m, b).contains(&tu); + if no_phis || single_pred_no_dup { + let Some(&term_id) = m.blocks[b].last() else { break }; + let count = rewrite_term_target(&mut m.insts[term_id as usize].op, Block(e as u32), t); + if count > 0 { + if !no_phis { + replace_phi_pred_block(m, tu, Block(e as u32), Block(b as u32)); + } + let mut rem = count; + preds[e].retain(|&p| { + if rem > 0 && p == b as u32 { + rem -= 1; + false + } else { + true + } + }); + preds[tu].extend(std::iter::repeat_n(b as u32, count)); + if preds[e].is_empty() { + alive[e] = false; + if let Some(pos) = preds[tu].iter().position(|&p| p == e as u32) { + preds[tu].swap_remove(pos); + } + } + changed = true; + bypassed = true; + break; + } + } + } + if !bypassed { + break; + } + } + } + + // 4. Single-predecessor block merging (pred ends in `Br(succ)`, preds[succ] == [pred]). + let mut val_map: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut had_val_map = false; + for &pred in &rpo { + if !alive[pred] { + continue; + } + loop { + let Some(&last) = m.blocks[pred].last() else { break }; + let Op::Br(succ_b) = m.insts[last as usize].op else { break }; + let succ = succ_b.0 as usize; + if succ == 0 || succ == pred || !alive[succ] || preds[succ].len() != 1 { + break; + } + m.blocks[pred].pop(); + let succ_insts = std::mem::take(&mut m.blocks[succ]); + for id in succ_insts { + let ty = m.insts[id as usize].ty; + if let Op::Phi(inc) = &m.insts[id as usize].op { + let rep = inc + .iter() + .find(|&&(_, b)| b == Block(pred as u32)) + .map(|&(v, _)| resolve_val(v, &val_map)) + .unwrap_or_else(|| m.undef(ty)); + val_map[id as usize] = Some(rep); + had_val_map = true; + } else { + m.blocks[pred].push(id); + } + } + for s2 in block_succs(m, pred) { + replace_phi_pred_block(m, s2, Block(succ as u32), Block(pred as u32)); + for p in &mut preds[s2] { + if *p == succ as u32 { + *p = pred as u32; + } + } + } + preds[succ].clear(); + alive[succ] = false; + changed = true; + } + } + if had_val_map { + for &b in &rpo { + if !alive[b] { + continue; + } + for &id in &m.blocks[b] { + rewrite_op_values(&mut m.insts[id as usize].op, &val_map); + } + } + rewrite_md_values(m, &val_map); + } + + // 5. Dense RPO compaction & block index remapping. + let final_rpo = compute_rpo(m, &alive); + let already_ordered = final_rpo.len() == m.blocks.len() && final_rpo.iter().enumerate().all(|(i, &b)| i == b); + if !already_ordered { + let mut old_to_new: Vec<Option<Block>> = vec![None; m.blocks.len()]; + let mut new_blocks = Vec::with_capacity(final_rpo.len()); + for (new_idx, &old_idx) in final_rpo.iter().enumerate() { + old_to_new[old_idx] = Some(Block(new_idx as u32)); + new_blocks.push(std::mem::take(&mut m.blocks[old_idx])); + } + m.blocks = new_blocks; + for b in &m.blocks { + for &id in b { + match &mut m.insts[id as usize].op { + Op::Phi(inc) => { + for (_, pb) in inc { + *pb = old_to_new[pb.0 as usize].expect("live phi pred"); + } + } + Op::Br(t) => *t = old_to_new[t.0 as usize].expect("live br target"), + Op::CondBr(_, t, f) => { + *t = old_to_new[t.0 as usize].expect("live condbr true"); + *f = old_to_new[f.0 as usize].expect("live condbr false"); + } + Op::Switch(_, d, cases) => { + *d = old_to_new[d.0 as usize].expect("live switch default"); + for (_, t) in cases { + *t = old_to_new[t.0 as usize].expect("live switch target"); + } + } + _ => {} + } + } + } + m.cur = Block(0); + changed = true; + } + + changed +} + +// ------------------------------------------------------------ PHI simplify + +fn intersect_idom(idom: &[Option<usize>], mut b1: usize, mut b2: usize) -> usize { + while b1 != b2 { + while b1 > b2 { + b1 = idom[b1].expect("rpo pred must have idom"); + } + while b2 > b1 { + b2 = idom[b2].expect("rpo pred must have idom"); + } + } + b1 +} + +/// Cooper-Harvey-Kennedy iterative immediate dominators over RPO indices `0..n`. +fn compute_idom(m: &Module) -> Vec<Option<usize>> { + let n = m.blocks.len(); + let mut idom: Vec<Option<usize>> = vec![None; n]; + if n == 0 { + return idom; + } + let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n]; + for b in 0..n { + for s in block_succs(m, b) { + if s < n { + preds[s].push(b); + } + } + } + idom[0] = Some(0); + let mut dom_changed = true; + while dom_changed { + dom_changed = false; + for b in 1..n { + let Some(&first) = preds[b].iter().find(|&&p| idom[p].is_some()) else { + continue; + }; + let mut new_idom = first; + for &p in &preds[b] { + if p != first && idom[p].is_some() { + new_idom = intersect_idom(&idom, p, new_idom); + } + } + if idom[b] != Some(new_idom) { + idom[b] = Some(new_idom); + dom_changed = true; + } + } + } + idom +} + +fn dominates(idom: &[Option<usize>], dom: usize, mut node: usize) -> bool { + while node > dom { + let Some(p) = idom[node] else { return false }; + if p == node { + break; + } + node = p; + } + node == dom +} + +/// Eliminates trivial PHIs (`phi [v, ...], [self, ...] -> v`) and deduplicates +/// identical PHIs within the same block until reaching a fixed point. +pub(super) fn simplify_phis(m: &mut Module) -> bool { + let idom = compute_idom(m); + let mut inst_block: Vec<Option<usize>> = vec![None; m.insts.len()]; + for (bi, blk) in m.blocks.iter().enumerate() { + for &id in blk { + inst_block[id as usize] = Some(bi); + } + } + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut any_changed = false; + + loop { + let mut round_changed = false; + + for b in 0..m.blocks.len() { + let mut seen: HashMap<(Ty, Vec<(Option<Value>, u32)>), Value> = HashMap::new(); + let old_insts = std::mem::take(&mut m.blocks[b]); + let mut keep = Vec::with_capacity(old_insts.len()); + let mut in_phi_prefix = true; + + for id in old_insts { + if !in_phi_prefix || !matches!(m.insts[id as usize].op, Op::Phi(..)) { + in_phi_prefix = false; + if rewrite_op_values(&mut m.insts[id as usize].op, &repl) { + round_changed = true; + } + keep.push(id); + continue; + } + let phi_ty = m.insts[id as usize].ty; + let mut inc = match &mut m.insts[id as usize].op { + Op::Phi(v) => std::mem::take(v), + _ => unreachable!(), + }; + for (v, _) in inc.iter_mut() { + let nv = resolve_val(*v, &repl); + if nv != *v { + *v = nv; + round_changed = true; + } + } + + let self_val = Value::Inst(id); + + // Trivial PHI check: ignore self-references and undefs when looking for a unique value. + let mut unique: Option<Value> = None; + let mut non_trivial = false; + for &(v, _) in &inc { + if v == self_val || is_undef(m, v) { + continue; + } + match unique { + None => unique = Some(v), + Some(u) if u == v => {} + Some(_) => { + non_trivial = true; + break; + } + } + } + if !non_trivial { + let can_replace = match unique { + Some(Value::Inst(ui)) => match inst_block.get(ui as usize).copied().flatten() { + Some(db) if db != b => dominates(&idom, db, b), + Some(_) => matches!(m.insts[ui as usize].op, Op::Phi(..)), + None => false, + }, + _ => true, + }; + if can_replace { + let rep = unique.unwrap_or_else(|| m.undef(phi_ty)); + repl[id as usize] = Some(rep); + round_changed = true; + continue; + } + } + + // Duplicate-PHI check within block `b` (normalizing self-ref to `None`). + let mut key_edges: Vec<(Option<Value>, u32)> = inc + .iter() + .map(|&(v, pb)| (if v == self_val { None } else { Some(v) }, pb.0)) + .collect(); + key_edges.sort_unstable_by_key(|&(v, pb)| (pb, v)); + let key = (phi_ty, key_edges); + if let Some(&prev) = seen.get(&key) { + repl[id as usize] = Some(prev); + round_changed = true; + continue; + } + seen.insert(key, self_val); + m.insts[id as usize].op = Op::Phi(inc); + keep.push(id); + } + m.blocks[b] = keep; + } + + if !round_changed { + break; + } + any_changed = true; + // Propagate replacements into PHIs whose producers came later in the same block or backedges. + for b in 0..m.blocks.len() { + for &id in &m.blocks[b] { + if !matches!(m.insts[id as usize].op, Op::Phi(..)) { + break; + } + rewrite_op_values(&mut m.insts[id as usize].op, &repl); + } + } + } + + if any_changed { + rewrite_md_values(m, &repl); + } + any_changed +} + +// --------------------------------------------------- InstCombine & Folding + +fn eval_int_binop(op: BinOp, w: u32, ua: u64, ub: u64) -> Option<u64> { + let mask = mask_for(w); + let ua = ua & mask; + let ub = ub & mask; + let r = match op { + BinOp::Add => ua.wrapping_add(ub), + BinOp::Sub => ua.wrapping_sub(ub), + BinOp::Mul => ua.wrapping_mul(ub), + BinOp::And => ua & ub, + BinOp::Or => ua | ub, + BinOp::Xor => ua ^ ub, + BinOp::UDiv => { + if ub == 0 { + return None; + } + ua / ub + } + BinOp::URem => { + if ub == 0 { + return None; + } + ua % ub + } + BinOp::SDiv => { + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + let smin = sext_i64(1u64 << (w - 1), w); + if sb == 0 || (sb == -1 && sa == smin) { + return None; + } + (sa / sb) as u64 + } + BinOp::SRem => { + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + let smin = sext_i64(1u64 << (w - 1), w); + if sb == 0 || (sb == -1 && sa == smin) { + return None; + } + (sa % sb) as u64 + } + BinOp::Shl => { + if ub >= w as u64 { + return None; + } + ua.wrapping_shl(ub as u32) + } + BinOp::LShr => { + if ub >= w as u64 { + return None; + } + ua >> (ub as u32) + } + BinOp::AShr => { + if ub >= w as u64 { + return None; + } + (sext_i64(ua, w) >> (ub as u32)) as u64 + } + }; + Some(r & mask) +} + +fn eval_icmp(p: Pred, w: u32, ua: u64, ub: u64) -> Option<bool> { + let mask = mask_for(w); + let ua = ua & mask; + let ub = ub & mask; + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + Some(match p { + Pred::Eq => ua == ub, + Pred::Ne => ua != ub, + Pred::UGt => ua > ub, + Pred::UGe => ua >= ub, + Pred::ULt => ua < ub, + Pred::ULe => ua <= ub, + Pred::SGt => sa > sb, + Pred::SGe => sa >= sb, + Pred::SLt => sa < sb, + Pred::SLe => sa <= sb, + _ => return None, + }) +} + +fn make_not_op(m: &mut Module, x: Value) -> Op { + if let Value::Inst(xi) = x { + if let Op::Cmp(p, a, b) = m.insts[xi as usize].op { + return Op::Cmp(invert_pred(p), a, b); + } + } + let t = m.i1c(true); + Op::Bin(BinOp::Xor, x, t, 0) +} + +fn unwrap_bitcast_src(m: &mut Module, v: Value, dst: Ty) -> Option<Value> { + if m.value_ty(v) == dst { + return Some(v); + } + if let Some(c) = const_bitcast(m, v, dst) { + return Some(c); + } + if let Value::Inst(id) = v { + if let Op::Cast(CastOp::BitCast, inner, _) = m.insts[id as usize].op { + if m.value_ty(inner) == dst { + return Some(inner); + } + } + } + None +} + +fn simplify_int_bin(m: &mut Module, id: u32, ty: Ty, w: u32) -> Result<Value, Option<Op>> { + let Op::Bin(op, mut a, mut b, _flags) = m.insts[id as usize].op else { + return Err(None); + }; + if matches!(op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) + && const_int_u64(m, a).is_some() + && const_int_u64(m, b).is_none() + { + std::mem::swap(&mut a, &mut b); + return simplify_rewritten_bin(m, ty, w, op, a, b, true); + } + simplify_rewritten_bin(m, ty, w, op, a, b, false) +} + +fn simplify_rewritten_bin( + m: &mut Module, ty: Ty, w: u32, op: BinOp, a: Value, b: Value, swapped: bool, +) -> Result<Value, Option<Op>> { + let mask = mask_for(w); + let ca = const_int_u64(m, a); + let cb = const_int_u64(m, b); + if let (Some(ua), Some(ub)) = (ca, cb) { + if let Some(r) = eval_int_binop(op, w, ua, ub) { + return Ok(m.const_int(ty, r)); + } + } + + // Reassociate `(inner_op x, c1) outer_op c2` when `b = c2`. + if let (Value::Inst(ai), Some(c2)) = (a, cb) { + if let Op::Bin(op1, x, c1_val, _) = m.insts[ai as usize].op { + if let Some(c1) = const_int_u64(m, c1_val) { + let reassociated: Option<(BinOp, u64)> = match (op1, op) { + (BinOp::Add, BinOp::Add) => Some((BinOp::Add, c1.wrapping_add(c2) & mask)), + (BinOp::Sub, BinOp::Add) => Some((BinOp::Add, c2.wrapping_sub(c1) & mask)), + (BinOp::Add, BinOp::Sub) => Some((BinOp::Add, c1.wrapping_sub(c2) & mask)), + (BinOp::Sub, BinOp::Sub) => Some((BinOp::Add, 0u64.wrapping_sub(c1.wrapping_add(c2)) & mask)), + (BinOp::Mul, BinOp::Mul) => Some((BinOp::Mul, c1.wrapping_mul(c2) & mask)), + (BinOp::And, BinOp::And) => Some((BinOp::And, c1 & c2)), + (BinOp::Or, BinOp::Or) => Some((BinOp::Or, c1 | c2)), + (BinOp::Xor, BinOp::Xor) => Some((BinOp::Xor, c1 ^ c2)), + (BinOp::Shl, BinOp::Shl) + | (BinOp::LShr, BinOp::LShr) + | (BinOp::AShr, BinOp::AShr) + if (c1 as u128 + c2 as u128) < w as u128 => + { + Some((op, c1 + c2)) + } + _ => None, + }; + if let Some((new_op, nc)) = reassociated { + let nc_val = m.const_int(ty, nc); + // Apply immediate identity check (e.g. `(x ^ c) ^ c -> x`). + if let Ok(folded) = simplify_rewritten_bin(m, ty, w, new_op, x, nc_val, true) { + return Ok(folded); + } + return Err(Some(Op::Bin(new_op, x, nc_val, 0))); + } + } + } + } + + match op { + BinOp::Add => { + if cb == Some(0) { + return Ok(a); + } + if a == b && w == 1 { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Sub => { + if cb == Some(0) { + return Ok(a); + } + if a == b { + return Ok(m.const_int(ty, 0)); + } + if ca == Some(0) && w == 1 { + return Ok(b); + } + if let Some(c) = cb { + let neg = (0u64.wrapping_sub(c)) & mask; + let neg_val = m.const_int(ty, neg); + return Err(Some(Op::Bin(BinOp::Add, a, neg_val, 0))); + } + } + BinOp::Mul => { + if cb == Some(0) { + return Ok(m.const_int(ty, 0)); + } + if cb == Some(1) { + return Ok(a); + } + if a == b && w == 1 { + return Ok(a); + } + } + BinOp::UDiv | BinOp::SDiv => { + if cb == Some(1) { + return Ok(a); + } + } + BinOp::URem | BinOp::SRem => { + if cb == Some(1) { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Shl | BinOp::LShr | BinOp::AShr => { + if cb == Some(0) { + return Ok(a); + } + } + BinOp::And => { + if cb == Some(0) { + return Ok(m.const_int(ty, 0)); + } + if cb == Some(mask) || a == b { + return Ok(a); + } + // `x & ~x == 0` + let is_comp = |lhs: Value, rhs: Value| -> bool { + let Value::Inst(ri) = rhs else { return false }; + if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op { + (x == lhs && const_int_u64(m, y) == Some(mask)) + || (y == lhs && const_int_u64(m, x) == Some(mask)) + } else { + false + } + }; + if is_comp(a, b) || is_comp(b, a) { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Or => { + if cb == Some(0) || a == b { + return Ok(a); + } + if cb == Some(mask) { + return Ok(m.const_int(ty, mask)); + } + let is_comp = |lhs: Value, rhs: Value| -> bool { + let Value::Inst(ri) = rhs else { return false }; + if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op { + (x == lhs && const_int_u64(m, y) == Some(mask)) + || (y == lhs && const_int_u64(m, x) == Some(mask)) + } else { + false + } + }; + if is_comp(a, b) || is_comp(b, a) { + return Ok(m.const_int(ty, mask)); + } + } + BinOp::Xor => { + if cb == Some(0) { + return Ok(a); + } + if a == b { + return Ok(m.const_int(ty, 0)); + } + // `(x ^ y) ^ y -> x` + if let Value::Inst(ai) = a { + if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[ai as usize].op { + if v == b { + return Ok(u); + } + if u == b { + return Ok(v); + } + } + } + if let Value::Inst(bi) = b { + if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[bi as usize].op { + if v == a { + return Ok(u); + } + if u == a { + return Ok(v); + } + } + } + // `xor(cmp(p, u, v), true) -> cmp(invert(p), u, v)` + if cb == Some(1) && w == 1 { + if let Value::Inst(ai) = a { + if let Op::Cmp(p, u, v) = m.insts[ai as usize].op { + return Err(Some(Op::Cmp(invert_pred(p), u, v))); + } + } + } + } + } + + if swapped { + Err(Some(Op::Bin(op, a, b, 0))) + } else { + Err(None) + } +} + +fn simplify_cast(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Cast(op, v, dst) = m.insts[id as usize].op else { + return Err(None); + }; + let src = m.value_ty(v); + if src == dst && matches!(op, CastOp::Trunc | CastOp::ZExt | CastOp::SExt | CastOp::FPTrunc | CastOp::FPExt | CastOp::BitCast) { + return Ok(v); + } + + match op { + CastOp::Trunc | CastOp::ZExt => { + if let (Some(uv), Some(_)) = (const_int_u64(m, v), m.int_width(dst)) { + return Ok(m.const_int(dst, uv)); + } + } + CastOp::SExt => { + if let (Some(uv), Some(sw), Some(_)) = (const_int_u64(m, v), m.int_width(src), m.int_width(dst)) { + let sv = sext_i64(uv, sw); + return Ok(m.const_int(dst, sv as u64)); + } + } + CastOp::BitCast => { + if let Some(c) = const_bitcast(m, v, dst) { + return Ok(c); + } + } + _ => {} + } + + if let Value::Inst(vi) = v { + match (op, m.insts[vi as usize].op.clone()) { + (CastOp::Trunc, Op::Cast(CastOp::Trunc, x, _)) => return Err(Some(Op::Cast(CastOp::Trunc, x, dst))), + (CastOp::ZExt, Op::Cast(CastOp::ZExt, x, _)) => return Err(Some(Op::Cast(CastOp::ZExt, x, dst))), + (CastOp::SExt, Op::Cast(CastOp::SExt, x, _)) => return Err(Some(Op::Cast(CastOp::SExt, x, dst))), + (CastOp::SExt, Op::Cast(CastOp::ZExt, x, _)) => { + if let (Some(wx), Some(wsrc)) = (m.int_width(m.value_ty(x)), m.int_width(src)) { + if wx < wsrc { + return Err(Some(Op::Cast(CastOp::ZExt, x, dst))); + } + } + } + (CastOp::Trunc, Op::Cast(CastOp::ZExt, x, _)) => { + if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) { + if wx == wd { + return Ok(x); + } else if wx > wd { + return Err(Some(Op::Cast(CastOp::Trunc, x, dst))); + } else { + return Err(Some(Op::Cast(CastOp::ZExt, x, dst))); + } + } + } + (CastOp::Trunc, Op::Cast(CastOp::SExt, x, _)) => { + if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) { + if wx == wd { + return Ok(x); + } else if wx > wd { + return Err(Some(Op::Cast(CastOp::Trunc, x, dst))); + } else { + return Err(Some(Op::Cast(CastOp::SExt, x, dst))); + } + } + } + (CastOp::BitCast, Op::Cast(CastOp::BitCast, x, _)) => { + let xt = m.value_ty(x); + if xt == dst { + return Ok(x); + } + if scalar_bits(m, xt).is_some() && scalar_bits(m, xt) == scalar_bits(m, dst) { + return Err(Some(Op::Cast(CastOp::BitCast, x, dst))); + } + } + (CastOp::BitCast, Op::Select(c, a, b)) => { + if scalar_bits(m, src).is_some() && scalar_bits(m, src) == scalar_bits(m, dst) { + if let (Some(ua), Some(ub)) = (unwrap_bitcast_src(m, a, dst), unwrap_bitcast_src(m, b, dst)) { + if ua == ub { + return Ok(ua); + } + return Err(Some(Op::Select(c, ua, ub))); + } + } + } + _ => {} + } + } + + Err(None) +} + +fn simplify_cmp(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Cmp(mut p, mut a, mut b) = m.insts[id as usize].op else { + return Err(None); + }; + let ty = m.value_ty(a); + let Some(w) = m.int_width(ty) else { + return Err(None); + }; + let mut swapped = false; + if const_int_u64(m, a).is_some() && const_int_u64(m, b).is_none() { + std::mem::swap(&mut a, &mut b); + p = swap_pred(p); + swapped = true; + } + + if let (Some(ua), Some(ub)) = (const_int_u64(m, a), const_int_u64(m, b)) { + if let Some(res) = eval_icmp(p, w, ua, ub) { + return Ok(m.i1c(res)); + } + } + if a == b { + if let Some(res) = eval_icmp(p, w, 0, 0) { + return Ok(m.i1c(res)); + } + } + + let mask = mask_for(w); + if let Some(cb) = const_int_u64(m, b) { + if cb == 0 && p == Pred::ULt { + return Ok(m.i1c(false)); + } + if cb == 0 && p == Pred::UGe { + return Ok(m.i1c(true)); + } + if cb == mask && p == Pred::UGt { + return Ok(m.i1c(false)); + } + if cb == mask && p == Pred::ULe { + return Ok(m.i1c(true)); + } + if cb == 0 && p == Pred::ULe { + return Err(Some(Op::Cmp(Pred::Eq, a, b))); + } + if cb == 0 && p == Pred::UGt { + return Err(Some(Op::Cmp(Pred::Ne, a, b))); + } + if cb == mask && p == Pred::UGe { + return Err(Some(Op::Cmp(Pred::Eq, a, b))); + } + if cb == mask && p == Pred::ULt { + return Err(Some(Op::Cmp(Pred::Ne, a, b))); + } + + if w == 1 { + return match (p, cb) { + (Pred::Eq, 1) | (Pred::Ne, 0) => Ok(a), + (Pred::Eq, 0) | (Pred::Ne, 1) => Err(Some(make_not_op(m, a))), + _ => { + if swapped { + Err(Some(Op::Cmp(p, a, b))) + } else { + Err(None) + } + } + }; + } + + // Collapse `(zext i1 x) cmp k` and `(sext i1 x) cmp k` (`set_scc` / `scc_bit` idioms) + // and `select(c, const, const) cmp k`. + if let Value::Inst(ai) = a { + match m.insts[ai as usize].op { + Op::Cast(CastOp::ZExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => { + if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, 1, cb)) { + if f0 == f1 { + return Ok(m.i1c(f0)); + } + return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) }; + } + } + Op::Cast(CastOp::SExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => { + if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, mask, cb)) { + if f0 == f1 { + return Ok(m.i1c(f0)); + } + return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) }; + } + } + Op::Select(cond, tc, fc) => { + if let (Some(ct), Some(cf)) = (const_int_u64(m, tc), const_int_u64(m, fc)) { + if let (Some(bt), Some(bf)) = (eval_icmp(p, w, ct, cb), eval_icmp(p, w, cf, cb)) { + if bt == bf { + return Ok(m.i1c(bt)); + } + return if bt { Ok(cond) } else { Err(Some(make_not_op(m, cond))) }; + } + } + } + _ => {} + } + } + } + + if swapped { + Err(Some(Op::Cmp(p, a, b))) + } else { + Err(None) + } +} + +fn simplify_select(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Select(c, mut t, mut f) = m.insts[id as usize].op else { + return Err(None); + }; + if let Some(cv) = const_int_u64(m, c) { + return Ok(if cv & 1 != 0 { t } else { f }); + } + if t == f { + return Ok(t); + } + if let Some(inner) = match_not_i1(m, c) { + return Err(Some(Op::Select(inner, f, t))); + } + + let ty = m.insts[id as usize].ty; + if m.int_width(ty) == Some(1) { + let ct = const_int_u64(m, t); + let cf = const_int_u64(m, f); + if ct == Some(1) && cf == Some(0) { + return Ok(c); + } + if ct == Some(0) && cf == Some(1) { + return Err(Some(make_not_op(m, c))); + } + if (t == c && cf == Some(0)) || (ct == Some(1) && f == c) { + return Ok(c); + } + if t == c && cf == Some(1) { + return Ok(m.i1c(true)); + } + if ct == Some(0) && f == c { + return Ok(m.i1c(false)); + } + } + + // `select c, (select c, t1, _), f -> select c, t1, f` (and analogously in `f`). + let mut folded_arm = false; + if let Value::Inst(ti) = t { + if let Op::Select(c2, t2, _) = m.insts[ti as usize].op { + if c2 == c { + t = t2; + folded_arm = true; + } + } + } + if let Value::Inst(fi) = f { + if let Op::Select(c2, _, f2) = m.insts[fi as usize].op { + if c2 == c { + f = f2; + folded_arm = true; + } + } + } + if folded_arm { + if t == f { + return Ok(t); + } + return Err(Some(Op::Select(c, t, f))); + } + + Err(None) +} + +fn simplify_pure_dxop_call(m: &mut Module, id: u32) -> Option<Value> { + let Op::Call(f, args) = &m.insts[id as usize].op else { return None }; + let name = &m.funcs[*f as usize].name; + let opc = args.first().and_then(|&v| const_int_u64(m, v))?; + + if is_op_name(name, "dx.op.unaryBits") && args.len() == 2 { + let uv = const_int_u64(m, args[1])?; + let sw = m.int_width(m.value_ty(args[1]))?; + let mask = mask_for(sw); + let u = uv & mask; + let res = match opc { + 31 => u.count_ones() as u64, + 32 => { + if u == 0 { + u32::MAX as u64 + } else { + u.trailing_zeros() as u64 + } + } + 33 => { + if u == 0 { + u32::MAX as u64 + } else { + (u.leading_zeros() - (64 - sw)) as u64 + } + } + 34 => { + let sign = (u >> (sw - 1)) & 1 != 0; + let bits = if sign { (!u) & mask } else { u }; + if bits == 0 { + u32::MAX as u64 + } else { + (bits.leading_zeros() - (64 - sw)) as u64 + } + } + _ => return None, + }; + return Some(m.i32c(res as u32)); + } + + if is_op_name(name, "dx.op.unary") && opc == 30 && args.len() == 2 { + let ty = m.insts[id as usize].ty; + let sw = m.int_width(ty)?; + let uv = const_int_u64(m, args[1])?; + let rev = (uv & mask_for(sw)).reverse_bits() >> (64 - sw); + return Some(m.const_int(ty, rev)); + } + + if is_op_name(name, "dx.op.binary") && (37..=40).contains(&opc) && args.len() == 3 { + let (a, b) = (args[1], args[2]); + if a == b { + return Some(a); + } + let ty = m.insts[id as usize].ty; + let sw = m.int_width(ty)?; + let (ua, ub) = (const_int_u64(m, a)?, const_int_u64(m, b)?); + let r = match opc { + 37 => (sext_i64(ua, sw).max(sext_i64(ub, sw))) as u64, + 38 => (sext_i64(ua, sw).min(sext_i64(ub, sw))) as u64, + 39 => ua.max(ub), + 40 => ua.min(ub), + _ => unreachable!(), + }; + return Some(m.const_int(ty, r)); + } + + None +} + +/// RPO constant folding, cast simplification, integer identities/reassociation, +/// comparison and select simplifications. +pub(super) fn simplify_insts(m: &mut Module) -> bool { + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut changed = false; + + for b in 0..m.blocks.len() { + let mut keep = Vec::with_capacity(m.blocks[b].len()); + let old_insts = std::mem::take(&mut m.blocks[b]); + for id in old_insts { + if rewrite_op_values(&mut m.insts[id as usize].op, &repl) { + changed = true; + } + if matches!(m.insts[id as usize].op, Op::Phi(..)) { + keep.push(id); + continue; + } + let ty = m.insts[id as usize].ty; + let simplified = match &m.insts[id as usize].op { + Op::Bin(..) => { + if let Some(w) = m.int_width(ty) { + simplify_int_bin(m, id, ty, w) + } else { + Err(None) + } + } + Op::Cast(..) => simplify_cast(m, id), + Op::Cmp(..) => simplify_cmp(m, id), + Op::Select(..) => simplify_select(m, id), + Op::Call(..) => match simplify_pure_dxop_call(m, id) { + Some(v) => Ok(v), + None => Err(None), + }, + _ => Err(None), + }; + match simplified { + Ok(v) if v != Value::Inst(id) => { + repl[id as usize] = Some(v); + changed = true; + } + Err(Some(new_op)) => { + m.insts[id as usize].op = new_op; + changed = true; + keep.push(id); + } + _ => keep.push(id), + } + } + m.blocks[b] = keep; + } + + if changed { + for b in 0..m.blocks.len() { + for &id in &m.blocks[b] { + if !matches!(m.insts[id as usize].op, Op::Phi(..)) { + break; + } + rewrite_op_values(&mut m.insts[id as usize].op, &repl); + } + } + rewrite_md_values(m, &repl); + } + + changed +} + +// --------------------------------------------------------- Dominator CSE + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum CseKey { + Bin(u8, Value, Value, u64), + Cast(u8, Value, Ty), + Cmp(u8, Value, Value), + Select(Value, Value, Value), + Extract(Value, u32), + Gep(Value, Vec<Value>), + Call(u32, Vec<Value>), +} + +fn cse_key(m: &Module, op: &Op) -> Option<CseKey> { + match op { + Op::Bin(bin_op, a, b, flags) => { + let (mut x, mut y) = (*a, *b); + if matches!(bin_op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) && x > y { + std::mem::swap(&mut x, &mut y); + } + Some(CseKey::Bin(*bin_op as u8, x, y, *flags)) + } + Op::Cast(cop, v, ty) => Some(CseKey::Cast(*cop as u8, *v, *ty)), + Op::Cmp(p, a, b) => { + let (mut p, mut x, mut y) = (*p, *a, *b); + if x > y { + std::mem::swap(&mut x, &mut y); + p = swap_pred(p); + } + Some(CseKey::Cmp(p as u8, x, y)) + } + Op::Select(c, t, f) => Some(CseKey::Select(*c, *t, *f)), + Op::Extract(a, idx) => Some(CseKey::Extract(*a, *idx)), + Op::Gep(p, idx) => Some(CseKey::Gep(*p, idx.clone())), + Op::Call(f, args) => { + let fd = &m.funcs[*f as usize]; + if fd.attrs != FnAttrs::ReadNone { + return None; + } + // Implicit quad derivatives (`dx.op.unary` opcodes 83..=86) depend on + // CFG position even though declared `readnone`. Never CSE them. + if is_op_name(&fd.name, "dx.op.unary") { + let opc = args.first().and_then(|&v| const_int_u64(m, v)); + if !matches!(opc, Some(0..=30)) { + return None; + } + } + let mut norm_args = args.clone(); + if is_op_name(&fd.name, "dx.op.binary") + && norm_args.len() == 3 + && matches!(norm_args.first().and_then(|&v| const_int_u64(m, v)), Some(35..=40)) + && norm_args[1] > norm_args[2] + { + norm_args.swap(1, 2); + } + Some(CseKey::Call(*f, norm_args)) + } + _ => None, + } +} + +/// Dominator-tree scoped CSE assuming blocks `0..n` are already in RPO. +pub(super) fn cse(m: &mut Module) -> bool { + let n = m.blocks.len(); + if n == 0 { + return false; + } + + let idom = compute_idom(m); + let mut children: Vec<Vec<usize>> = vec![Vec::new(); n]; + for b in 1..n { + if let Some(p) = idom[b] { + children[p].push(b); + } + } + + enum DomFrame { + Enter(usize), + Exit(usize), + } + + let mut table: HashMap<CseKey, Value> = HashMap::new(); + let mut undo: Vec<CseKey> = Vec::new(); + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut changed = false; + let mut stack = vec![DomFrame::Enter(0)]; + + while let Some(frame) = stack.pop() { + match frame { + DomFrame::Enter(b) => { + let mark = undo.len(); + stack.push(DomFrame::Exit(mark)); ``` Could each dominator child get its own CSE table scope? This `Exit` runs only after every child has been visited, so an expression inserted in one branch remains available in its sibling even though that definition does not dominate the sibling. CSE can then replace the sibling value with a non-dominating SSA value. Please restore the table to the parent mark between child subtrees. AI-assisted review: I traced the sibling-block traversal and table lifetime.
Author
Owner

@⁠Roroca-1 on GitHub · 2026-11-24 19:19 UTC · original
On crates/xcl/src/gpu/dxil/opt.rs line 1795 (outdated):

@@ -0,0 +1,2770 @@
+//! Intra-function DXIL SSA IR optimization and module compaction pass suite.
+//!
+//! Runs after IR construction and before metadata/bitcode serialization:
+//! 1. Fixpoint loop over CFG simplification & RPO normalization, trivial/duplicate
+//!    PHI elimination, constant folding & algebraic/bitcast/select simplification,
+//!    dominator-scoped CSE (excluding implicit derivatives and non-pure intrinsics),
+//!    and iterative mark-and-sweep DCE.
+//! 2. Dense compaction of live instructions, constants, declarations, and globals.
+//! 3. Synchronization of [`Shader::features`] with the remaining live IR.
+//!
+//! All graph traversals use explicit stacks so large shaders cannot overflow.
+
+use std::collections::{BTreeSet, HashMap};
+
+use super::module::{BinOp, Block, CastOp, ConstDef, FnAttrs, MdDef, Module, Op, Pred, Ty, Value};
+use super::shader::{kind, Feature, Shader};
+
+const MAX_ROUNDS: usize = 8;
+
+/// Summary metrics of a DXIL [`Module`] (for diagnostics and optimization tests).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Stats {
+    pub blocks: usize,
+    pub insts: usize,
+    pub phis: usize,
+    pub consts: usize,
+    pub funcs: usize,
+    pub globals: usize,
+}
+
+/// Counts live blocks/instructions/PHIs and pooled constants/functions/globals.
+pub fn module_stats(m: &Module) -> Stats {
+    let mut insts = 0usize;
+    let mut phis = 0usize;
+    for b in &m.blocks {
+        insts += b.len();
+        for &id in b {
+            if matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                phis += 1;
+            }
+        }
+    }
+    Stats {
+        blocks: m.blocks.len(),
+        insts,
+        phis,
+        consts: m.consts.len(),
+        funcs: m.funcs.len(),
+        globals: m.globals.len(),
+    }
+}
+
+/// Optimizes `s.m`, compacts pooled module tables (updating `s.entry`), and
+/// synchronizes `s.features` against the remaining live IR.
+pub fn optimize(s: &mut Shader) {
+    if s.m.error().is_some() || s.m.blocks.is_empty() {
+        return;
+    }
+    optimize_core(&mut s.m);
+    compact_module(&mut s.m, Some(&mut s.entry));
+    sync_features(s);
+}
+
+/// Optimizes and compacts `m` without modifying wrapper shader metadata.
+pub fn optimize_module(m: &mut Module) {
+    if m.error().is_some() || m.blocks.is_empty() {
+        return;
+    }
+    optimize_core(m);
+    compact_module(m, None);
+}
+
+fn optimize_core(m: &mut Module) {
+    for _ in 0..MAX_ROUNDS {
+        let mut changed = false;
+        changed |= simplify_cfg(m);
+        changed |= simplify_phis(m);
+        changed |= simplify_insts(m);
+        changed |= cse(m);
+        changed |= dce(m);
+        if !changed {
+            break;
+        }
+    }
+    // Final normalization pass if the last DCE/CSE opened trivial CFG/PHI cleanup.
+    if simplify_cfg(m) {
+        let _ = simplify_phis(m);
+        let _ = dce(m);
+        let _ = simplify_cfg(m);
+    }
+}
+
+// ------------------------------------------------------------------ helpers
+
+fn mask_for(w: u32) -> u64 {
+    if w >= 64 {
+        u64::MAX
+    } else if w == 0 {
+        0
+    } else {
+        (1u64 << w) - 1
+    }
+}
+
+fn sext_i64(v: u64, w: u32) -> i64 {
+    if w >= 64 {
+        v as i64
+    } else if w == 0 {
+        0
+    } else {
+        ((v << (64 - w)) as i64) >> (64 - w)
+    }
+}
+
+fn const_int_u64(m: &Module, v: Value) -> Option<u64> {
+    match v {
+        Value::Const(c) => match &m.consts[c as usize] {
+            ConstDef::Int(t, x) => {
+                let w = m.int_width(*t)?;
+                Some((*x as u64) & mask_for(w))
+            }
+            ConstDef::Null(t) if m.int_width(*t).is_some() => Some(0),
+            _ => None,
+        },
+        _ => None,
+    }
+}
+
+fn scalar_bits(m: &Module, ty: Ty) -> Option<u32> {
+    if let Some(w) = m.int_width(ty) {
+        return Some(w);
+    }
+    if m.is_float(ty) {
+        return match m.alloc_size_layout(ty, true) {
+            2 => Some(16),
+            4 => Some(32),
+            8 => Some(64),
+            _ => None,
+        };
+    }
+    None
+}
+
+fn const_bitcast(m: &mut Module, v: Value, dst: Ty) -> Option<Value> {
+    if m.value_ty(v) == dst {
+        return Some(v);
+    }
+    let Value::Const(c) = v else { return None };
+    let dst_bits = scalar_bits(m, dst)?;
+    let def = m.consts[c as usize].clone();
+    match def {
+        ConstDef::Undef(t) => (scalar_bits(m, t) == Some(dst_bits)).then(|| m.undef(dst)),
+        ConstDef::Null(t) if scalar_bits(m, t) == Some(dst_bits) => {
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, 0))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, 0))
+            } else {
+                None
+            }
+        }
+        ConstDef::Int(t, x) => {
+            let w = m.int_width(t)?;
+            if w != dst_bits {
+                return None;
+            }
+            let raw = (x as u64) & mask_for(w);
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, raw))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, raw))
+            } else {
+                None
+            }
+        }
+        ConstDef::Float(t, bits) => {
+            let w = scalar_bits(m, t)?;
+            if w != dst_bits {
+                return None;
+            }
+            if m.int_width(dst).is_some() {
+                Some(m.const_int(dst, bits))
+            } else if m.is_float(dst) {
+                Some(m.const_float(dst, bits))
+            } else {
+                None
+            }
+        }
+        _ => None,
+    }
+}
+
+fn is_undef(m: &Module, v: Value) -> bool {
+    matches!(v, Value::Const(c) if matches!(m.consts[c as usize], ConstDef::Undef(_)))
+}
+
+fn is_op_name(full: &str, base: &str) -> bool {
+    full == base || full.strip_prefix(base).is_some_and(|s| s.starts_with('.'))
+}
+
+fn resolve_val(mut v: Value, repl: &[Option<Value>]) -> Value {
+    let mut steps = 0usize;
+    while let Value::Inst(id) = v {
+        let Some(next) = repl.get(id as usize).copied().flatten() else { break };
+        if next == v || steps >= repl.len() {
+            break;
+        }
+        v = next;
+        steps += 1;
+    }
+    v
+}
+
+fn visit_op_values_mut(op: &mut Op, f: &mut dyn FnMut(&mut Value)) {
+    match op {
+        Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => {
+            f(a);
+            f(b);
+        }
+        Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(v),
+        Op::Store(p, v, _) => {
+            f(p);
+            f(v);
+        }
+        Op::Select(c, t, e) | Op::CmpXchg(c, t, e) => {
+            f(c);
+            f(t);
+            f(e);
+        }
+        Op::Call(_, args) => {
+            for a in args {
+                f(a);
+            }
+        }
+        Op::Phi(inc) => {
+            for (v, _) in inc {
+                f(v);
+            }
+        }
+        Op::Gep(p, idx) => {
+            f(p);
+            for i in idx {
+                f(i);
+            }
+        }
+        Op::Alloca(_, n, _) => f(n),
+        Op::CondBr(c, _, _) => f(c),
+        Op::Switch(v, _, cases) => {
+            f(v);
+            for (cv, _) in cases {
+                f(cv);
+            }
+        }
+        Op::Br(_) | Op::Ret | Op::Unreachable => {}
+    }
+}
+
+fn rewrite_op_values(op: &mut Op, repl: &[Option<Value>]) -> bool {
+    let mut changed = false;
+    visit_op_values_mut(op, &mut |v| {
+        let nv = resolve_val(*v, repl);
+        if nv != *v {
+            *v = nv;
+            changed = true;
+        }
+    });
+    changed
+}
+
+fn rewrite_md_values(m: &mut Module, repl: &[Option<Value>]) {
+    for md in &mut m.md {
+        if let MdDef::Val(_, v) = md {
+            *v = resolve_val(*v, repl);
+        }
+    }
+}
+
+fn for_each_op_value(op: &Op, mut f: impl FnMut(Value)) {
+    match op {
+        Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => {
+            f(*a);
+            f(*b);
+        }
+        Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(*v),
+        Op::Store(p, v, _) => {
+            f(*p);
+            f(*v);
+        }
+        Op::Select(c, t, x) | Op::CmpXchg(c, t, x) => {
+            f(*c);
+            f(*t);
+            f(*x);
+        }
+        Op::Call(_, args) => {
+            for &a in args {
+                f(a);
+            }
+        }
+        Op::Phi(inc) => {
+            for &(v, _) in inc {
+                f(v);
+            }
+        }
+        Op::Gep(p, idx) => {
+            f(*p);
+            for &i in idx {
+                f(i);
+            }
+        }
+        Op::Alloca(_, n, _) => f(*n),
+        Op::CondBr(c, _, _) => f(*c),
+        Op::Switch(v, _, cases) => {
+            f(*v);
+            for &(cv, _) in cases {
+                f(cv);
+            }
+        }
+        Op::Br(_) | Op::Ret | Op::Unreachable => {}
+    }
+}
+
+fn block_succs(m: &Module, b: usize) -> Vec<usize> {
+    let Some(&last) = m.blocks[b].last() else { return Vec::new() };
+    match &m.insts[last as usize].op {
+        Op::Br(t) => vec![t.0 as usize],
+        Op::CondBr(_, t, f) => vec![t.0 as usize, f.0 as usize],
+        Op::Switch(_, d, cases) => {
+            let mut s = Vec::with_capacity(1 + cases.len());
+            s.push(d.0 as usize);
+            for &(_, c) in cases {
+                s.push(c.0 as usize);
+            }
+            s
+        }
+        _ => Vec::new(),
+    }
+}
+
+fn invert_pred(p: Pred) -> Pred {
+    match p {
+        Pred::Eq => Pred::Ne,
+        Pred::Ne => Pred::Eq,
+        Pred::UGt => Pred::ULe,
+        Pred::UGe => Pred::ULt,
+        Pred::ULt => Pred::UGe,
+        Pred::ULe => Pred::UGt,
+        Pred::SGt => Pred::SLe,
+        Pred::SGe => Pred::SLt,
+        Pred::SLt => Pred::SGe,
+        Pred::SLe => Pred::SGt,
+        Pred::FFalse => Pred::FTrue,
+        Pred::FTrue => Pred::FFalse,
+        Pred::FOEq => Pred::FUNe,
+        Pred::FUNe => Pred::FOEq,
+        Pred::FOGt => Pred::FULe,
+        Pred::FULe => Pred::FOGt,
+        Pred::FOGe => Pred::FULt,
+        Pred::FULt => Pred::FOGe,
+        Pred::FOLt => Pred::FUGe,
+        Pred::FUGe => Pred::FOLt,
+        Pred::FOLe => Pred::FUGt,
+        Pred::FUGt => Pred::FOLe,
+        Pred::FONe => Pred::FUEq,
+        Pred::FUEq => Pred::FONe,
+        Pred::FOrd => Pred::FUno,
+        Pred::FUno => Pred::FOrd,
+    }
+}
+
+fn swap_pred(p: Pred) -> Pred {
+    match p {
+        Pred::UGt => Pred::ULt,
+        Pred::ULt => Pred::UGt,
+        Pred::UGe => Pred::ULe,
+        Pred::ULe => Pred::UGe,
+        Pred::SGt => Pred::SLt,
+        Pred::SLt => Pred::SGt,
+        Pred::SGe => Pred::SLe,
+        Pred::SLe => Pred::SGe,
+        Pred::FOGt => Pred::FOLt,
+        Pred::FOLt => Pred::FOGt,
+        Pred::FOGe => Pred::FOLe,
+        Pred::FOLe => Pred::FOGe,
+        Pred::FUGt => Pred::FULt,
+        Pred::FULt => Pred::FUGt,
+        Pred::FUGe => Pred::FULe,
+        Pred::FULe => Pred::FUGe,
+        other => other,
+    }
+}
+
+/// If `v` computes logical NOT (`xor i1 x, true`) returns `Some(x)`.
+fn match_not_i1(m: &Module, v: Value) -> Option<Value> {
+    let Value::Inst(id) = v else { return None };
+    if m.int_width(m.insts[id as usize].ty) != Some(1) {
+        return None;
+    }
+    if let Op::Bin(BinOp::Xor, a, b, _) = m.insts[id as usize].op {
+        if const_int_u64(m, b) == Some(1) {
+            return Some(a);
+        }
+        if const_int_u64(m, a) == Some(1) {
+            return Some(b);
+        }
+    }
+    None
+}
+
+// ------------------------------------------------------------ CFG simplify
+
+fn compute_rpo(m: &Module, alive: &[bool]) -> Vec<usize> {
+    let n = m.blocks.len();
+    if n == 0 || !alive[0] {
+        return Vec::new();
+    }
+    let succs: Vec<Vec<usize>> = (0..n)
+        .map(|b| if alive[b] { block_succs(m, b) } else { Vec::new() })
+        .collect();
+    let mut state = vec![0u8; n];
+    let mut postorder = Vec::with_capacity(n);
+    let mut stack = vec![(0usize, 0usize)];
+    state[0] = 1;
+    while let Some((b, idx)) = stack.last_mut() {
+        let b = *b;
+        let sb = &succs[b];
+        if *idx < sb.len() {
+            // Visit successors in reverse order so reversed postorder places the
+            // primary/true branch before the fallback/exit branch.
+            let next = sb[sb.len() - 1 - *idx];
+            *idx += 1;
+            if alive.get(next).copied().unwrap_or(false) && state[next] == 0 {
+                state[next] = 1;
+                stack.push((next, 0));
+            }
+        } else {
+            state[b] = 2;
+            postorder.push(b);
+            stack.pop();
+        }
+    }
+    postorder.reverse();
+    postorder
+}
+
+/// Keeps at most `keep` entries from `pred` in every `Op::Phi` of block `succ`.
+fn trim_phi_edges(m: &mut Module, succ: usize, pred: Block, keep: usize) -> bool {
+    let mut changed = false;
+    for k in 0..m.blocks[succ].len() {
+        let id = m.blocks[succ][k] as usize;
+        let Op::Phi(inc) = &mut m.insts[id].op else { break };
+        let have = inc.iter().filter(|&&(_, b)| b == pred).count();
+        if have > keep {
+            let mut left = keep;
+            inc.retain(|&(_, b)| {
+                if b == pred {
+                    if left > 0 {
+                        left -= 1;
+                        true
+                    } else {
+                        false
+                    }
+                } else {
+                    true
+                }
+            });
+            changed = true;
+        }
+    }
+    changed
+}
+
+fn replace_phi_pred_block(m: &mut Module, succ: usize, from: Block, to: Block) {
+    for k in 0..m.blocks[succ].len() {
+        let id = m.blocks[succ][k] as usize;
+        let Op::Phi(inc) = &mut m.insts[id].op else { break };
+        for (_, b) in inc.iter_mut() {
+            if *b == from {
+                *b = to;
+            }
+        }
+    }
+}
+
+fn block_has_phis(m: &Module, b: usize) -> bool {
+    m.blocks[b].first().is_some_and(|&id| matches!(m.insts[id as usize].op, Op::Phi(..)))
+}
+
+fn rewrite_term_target(term: &mut Op, from: Block, to: Block) -> usize {
+    let mut count = 0;
+    match term {
+        Op::Br(t) if *t == from => {
+            *t = to;
+            count += 1;
+        }
+        Op::CondBr(_, t, f) => {
+            if *t == from {
+                *t = to;
+                count += 1;
+            }
+            if *f == from {
+                *f = to;
+                count += 1;
+            }
+        }
+        Op::Switch(_, d, cases) => {
+            if *d == from {
+                *d = to;
+                count += 1;
+            }
+            for (_, t) in cases {
+                if *t == from {
+                    *t = to;
+                    count += 1;
+                }
+            }
+        }
+        _ => {}
+    }
+    count
+}
+
+/// Simplifies terminators, drops unreachable blocks, trims dead PHI edges,
+/// bypasses empty jump blocks, merges single-predecessor blocks, and lays out
+/// reachable blocks in RPO.
+pub(super) fn simplify_cfg(m: &mut Module) -> bool {
+    let n = m.blocks.len();
+    if n == 0 {
+        return false;
+    }
+    let mut changed = false;
+
+    // 1. Fold constant / redundant terminators.
+    for b in 0..n {
+        let Some(&term_id) = m.blocks[b].last() else { continue };
+        let op = m.insts[term_id as usize].op.clone();
+        match op {
+            Op::CondBr(c, t, f) => {
+                if let Some(cv) = const_int_u64(m, c) {
+                    let target = if cv & 1 != 0 { t } else { f };
+                    m.insts[term_id as usize].op = Op::Br(target);
+                    let pred = Block(b as u32);
+                    trim_phi_edges(m, target.0 as usize, pred, 1);
+                    let other = if target == t { f } else { t };
+                    if other != target {
+                        trim_phi_edges(m, other.0 as usize, pred, 0);
+                    }
+                    changed = true;
+                } else if t == f {
+                    m.insts[term_id as usize].op = Op::Br(t);
+                    trim_phi_edges(m, t.0 as usize, Block(b as u32), 1);
+                    changed = true;
+                } else if let Some(inner) = match_not_i1(m, c) {
+                    m.insts[term_id as usize].op = Op::CondBr(inner, f, t);
+                    changed = true;
+                }
+            }
+            Op::Switch(v, d, cases) => {
+                let mut old_targets = Vec::with_capacity(1 + cases.len());
+                old_targets.push(d);
+                for &(_, target) in &cases {
+                    if !old_targets.contains(&target) {
+                        old_targets.push(target);
+                    }
+                }
+                if let Some(cv) = const_int_u64(m, v) {
+                    let target = cases
+                        .iter()
+                        .find(|&&(k, _)| const_int_u64(m, k) == Some(cv))
+                        .map_or(d, |&(_, dst)| dst);
+                    m.insts[term_id as usize].op = Op::Br(target);
+                    let pred = Block(b as u32);
+                    for s in old_targets {
+                        trim_phi_edges(m, s.0 as usize, pred, usize::from(s == target));
+                    }
+                    changed = true;
+                } else {
+                    let mut seen_vals = Vec::with_capacity(cases.len());
+                    let filtered: Vec<(Value, Block)> = cases
+                        .iter()
+                        .copied()
+                        .filter(|&(cv, dst)| {
+                            if dst == d {
+                                return false;
+                            }
+                            if let Some(kv) = const_int_u64(m, cv) {
+                                if seen_vals.contains(&kv) {
+                                    return false;
+                                }
+                                seen_vals.push(kv);
+                            }
+                            true
+                        })
+                        .collect();
+                    if filtered.len() != cases.len() {
+                        let pred = Block(b as u32);
+                        if filtered.is_empty() {
+                            m.insts[term_id as usize].op = Op::Br(d);
+                            for s in old_targets {
+                                trim_phi_edges(m, s.0 as usize, pred, usize::from(s == d));
+                            }
+                        } else {
+                            m.insts[term_id as usize].op = Op::Switch(v, d, filtered.clone());
+                            for s in old_targets {
+                                let keep = usize::from(s == d) + filtered.iter().filter(|&&(_, x)| x == s).count();
+                                trim_phi_edges(m, s.0 as usize, pred, keep);
+                            }
+                        }
+                        changed = true;
+                    }
+                }
+            }
+            _ => {}
+        }
+    }
+
+    // 2. Reachability and incoming PHI edge reconciliation.
+    let mut alive = vec![true; n];
+    let rpo = compute_rpo(m, &alive);
+    let mut reach = vec![false; n];
+    for &b in &rpo {
+        reach[b] = true;
+    }
+    if rpo.len() < n {
+        alive = reach.clone();
+        changed = true;
+    }
+
+    let mut edge_counts: HashMap<(u32, u32), usize> = HashMap::new();
+    let mut preds: Vec<Vec<u32>> = vec![Vec::new(); n];
+    for &b in &rpo {
+        for succ in block_succs(m, b) {
+            if alive[succ] {
+                *edge_counts.entry((b as u32, succ as u32)).or_insert(0) += 1;
+                preds[succ].push(b as u32);
+            }
+        }
+    }
+
+    for &b in &rpo {
+        for k in 0..m.blocks[b].len() {
+            let id = m.blocks[b][k] as usize;
+            let Op::Phi(inc) = &mut m.insts[id].op else { break };
+            let mut rem: HashMap<u32, usize> = HashMap::new();
+            for &p in &preds[b] {
+                rem.insert(p, edge_counts[&(p, b as u32)]);
+            }
+            let orig_len = inc.len();
+            inc.retain(|&(_, pb)| {
+                if !alive.get(pb.0 as usize).copied().unwrap_or(false) {
+                    return false;
+                }
+                if let Some(cnt) = rem.get_mut(&pb.0) {
+                    if *cnt > 0 {
+                        *cnt -= 1;
+                        return true;
+                    }
+                }
+                false
+            });
+            if inc.len() != orig_len {
+                changed = true;
+            }
+        }
+    }
+
+    // 3. Bypass empty jump-only blocks (Br target with no other instructions).
+    for &b in &rpo {
+        if !alive[b] {
+            continue;
+        }
+        loop {
+            let succs = block_succs(m, b);
+            let mut bypassed = false;
+            for e in succs {
+                if e == 0 || e == b || !alive[e] || m.blocks[e].len() != 1 {
+                    continue;
+                }
+                let Op::Br(t) = m.insts[m.blocks[e][0] as usize].op else { continue };
+                let tu = t.0 as usize;
+                if tu == e {
+                    continue;
+                }
+                let no_phis = !block_has_phis(m, tu);
+                let single_pred_no_dup = preds[e].len() == 1
+                    && preds[e][0] == b as u32
+                    && !block_succs(m, b).contains(&tu);
+                if no_phis || single_pred_no_dup {
+                    let Some(&term_id) = m.blocks[b].last() else { break };
+                    let count = rewrite_term_target(&mut m.insts[term_id as usize].op, Block(e as u32), t);
+                    if count > 0 {
+                        if !no_phis {
+                            replace_phi_pred_block(m, tu, Block(e as u32), Block(b as u32));
+                        }
+                        let mut rem = count;
+                        preds[e].retain(|&p| {
+                            if rem > 0 && p == b as u32 {
+                                rem -= 1;
+                                false
+                            } else {
+                                true
+                            }
+                        });
+                        preds[tu].extend(std::iter::repeat_n(b as u32, count));
+                        if preds[e].is_empty() {
+                            alive[e] = false;
+                            if let Some(pos) = preds[tu].iter().position(|&p| p == e as u32) {
+                                preds[tu].swap_remove(pos);
+                            }
+                        }
+                        changed = true;
+                        bypassed = true;
+                        break;
+                    }
+                }
+            }
+            if !bypassed {
+                break;
+            }
+        }
+    }
+
+    // 4. Single-predecessor block merging (pred ends in `Br(succ)`, preds[succ] == [pred]).
+    let mut val_map: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut had_val_map = false;
+    for &pred in &rpo {
+        if !alive[pred] {
+            continue;
+        }
+        loop {
+            let Some(&last) = m.blocks[pred].last() else { break };
+            let Op::Br(succ_b) = m.insts[last as usize].op else { break };
+            let succ = succ_b.0 as usize;
+            if succ == 0 || succ == pred || !alive[succ] || preds[succ].len() != 1 {
+                break;
+            }
+            m.blocks[pred].pop();
+            let succ_insts = std::mem::take(&mut m.blocks[succ]);
+            for id in succ_insts {
+                let ty = m.insts[id as usize].ty;
+                if let Op::Phi(inc) = &m.insts[id as usize].op {
+                    let rep = inc
+                        .iter()
+                        .find(|&&(_, b)| b == Block(pred as u32))
+                        .map(|&(v, _)| resolve_val(v, &val_map))
+                        .unwrap_or_else(|| m.undef(ty));
+                    val_map[id as usize] = Some(rep);
+                    had_val_map = true;
+                } else {
+                    m.blocks[pred].push(id);
+                }
+            }
+            for s2 in block_succs(m, pred) {
+                replace_phi_pred_block(m, s2, Block(succ as u32), Block(pred as u32));
+                for p in &mut preds[s2] {
+                    if *p == succ as u32 {
+                        *p = pred as u32;
+                    }
+                }
+            }
+            preds[succ].clear();
+            alive[succ] = false;
+            changed = true;
+        }
+    }
+    if had_val_map {
+        for &b in &rpo {
+            if !alive[b] {
+                continue;
+            }
+            for &id in &m.blocks[b] {
+                rewrite_op_values(&mut m.insts[id as usize].op, &val_map);
+            }
+        }
+        rewrite_md_values(m, &val_map);
+    }
+
+    // 5. Dense RPO compaction & block index remapping.
+    let final_rpo = compute_rpo(m, &alive);
+    let already_ordered = final_rpo.len() == m.blocks.len() && final_rpo.iter().enumerate().all(|(i, &b)| i == b);
+    if !already_ordered {
+        let mut old_to_new: Vec<Option<Block>> = vec![None; m.blocks.len()];
+        let mut new_blocks = Vec::with_capacity(final_rpo.len());
+        for (new_idx, &old_idx) in final_rpo.iter().enumerate() {
+            old_to_new[old_idx] = Some(Block(new_idx as u32));
+            new_blocks.push(std::mem::take(&mut m.blocks[old_idx]));
+        }
+        m.blocks = new_blocks;
+        for b in &m.blocks {
+            for &id in b {
+                match &mut m.insts[id as usize].op {
+                    Op::Phi(inc) => {
+                        for (_, pb) in inc {
+                            *pb = old_to_new[pb.0 as usize].expect("live phi pred");
+                        }
+                    }
+                    Op::Br(t) => *t = old_to_new[t.0 as usize].expect("live br target"),
+                    Op::CondBr(_, t, f) => {
+                        *t = old_to_new[t.0 as usize].expect("live condbr true");
+                        *f = old_to_new[f.0 as usize].expect("live condbr false");
+                    }
+                    Op::Switch(_, d, cases) => {
+                        *d = old_to_new[d.0 as usize].expect("live switch default");
+                        for (_, t) in cases {
+                            *t = old_to_new[t.0 as usize].expect("live switch target");
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+        m.cur = Block(0);
+        changed = true;
+    }
+
+    changed
+}
+
+// ------------------------------------------------------------ PHI simplify
+
+fn intersect_idom(idom: &[Option<usize>], mut b1: usize, mut b2: usize) -> usize {
+    while b1 != b2 {
+        while b1 > b2 {
+            b1 = idom[b1].expect("rpo pred must have idom");
+        }
+        while b2 > b1 {
+            b2 = idom[b2].expect("rpo pred must have idom");
+        }
+    }
+    b1
+}
+
+/// Cooper-Harvey-Kennedy iterative immediate dominators over RPO indices `0..n`.
+fn compute_idom(m: &Module) -> Vec<Option<usize>> {
+    let n = m.blocks.len();
+    let mut idom: Vec<Option<usize>> = vec![None; n];
+    if n == 0 {
+        return idom;
+    }
+    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
+    for b in 0..n {
+        for s in block_succs(m, b) {
+            if s < n {
+                preds[s].push(b);
+            }
+        }
+    }
+    idom[0] = Some(0);
+    let mut dom_changed = true;
+    while dom_changed {
+        dom_changed = false;
+        for b in 1..n {
+            let Some(&first) = preds[b].iter().find(|&&p| idom[p].is_some()) else {
+                continue;
+            };
+            let mut new_idom = first;
+            for &p in &preds[b] {
+                if p != first && idom[p].is_some() {
+                    new_idom = intersect_idom(&idom, p, new_idom);
+                }
+            }
+            if idom[b] != Some(new_idom) {
+                idom[b] = Some(new_idom);
+                dom_changed = true;
+            }
+        }
+    }
+    idom
+}
+
+fn dominates(idom: &[Option<usize>], dom: usize, mut node: usize) -> bool {
+    while node > dom {
+        let Some(p) = idom[node] else { return false };
+        if p == node {
+            break;
+        }
+        node = p;
+    }
+    node == dom
+}
+
+/// Eliminates trivial PHIs (`phi [v, ...], [self, ...] -> v`) and deduplicates
+/// identical PHIs within the same block until reaching a fixed point.
+pub(super) fn simplify_phis(m: &mut Module) -> bool {
+    let idom = compute_idom(m);
+    let mut inst_block: Vec<Option<usize>> = vec![None; m.insts.len()];
+    for (bi, blk) in m.blocks.iter().enumerate() {
+        for &id in blk {
+            inst_block[id as usize] = Some(bi);
+        }
+    }
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut any_changed = false;
+
+    loop {
+        let mut round_changed = false;
+
+        for b in 0..m.blocks.len() {
+            let mut seen: HashMap<(Ty, Vec<(Option<Value>, u32)>), Value> = HashMap::new();
+            let old_insts = std::mem::take(&mut m.blocks[b]);
+            let mut keep = Vec::with_capacity(old_insts.len());
+            let mut in_phi_prefix = true;
+
+            for id in old_insts {
+                if !in_phi_prefix || !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    in_phi_prefix = false;
+                    if rewrite_op_values(&mut m.insts[id as usize].op, &repl) {
+                        round_changed = true;
+                    }
+                    keep.push(id);
+                    continue;
+                }
+                let phi_ty = m.insts[id as usize].ty;
+                let mut inc = match &mut m.insts[id as usize].op {
+                    Op::Phi(v) => std::mem::take(v),
+                    _ => unreachable!(),
+                };
+                for (v, _) in inc.iter_mut() {
+                    let nv = resolve_val(*v, &repl);
+                    if nv != *v {
+                        *v = nv;
+                        round_changed = true;
+                    }
+                }
+
+                let self_val = Value::Inst(id);
+
+                // Trivial PHI check: ignore self-references and undefs when looking for a unique value.
+                let mut unique: Option<Value> = None;
+                let mut non_trivial = false;
+                for &(v, _) in &inc {
+                    if v == self_val || is_undef(m, v) {
+                        continue;
+                    }
+                    match unique {
+                        None => unique = Some(v),
+                        Some(u) if u == v => {}
+                        Some(_) => {
+                            non_trivial = true;
+                            break;
+                        }
+                    }
+                }
+                if !non_trivial {
+                    let can_replace = match unique {
+                        Some(Value::Inst(ui)) => match inst_block.get(ui as usize).copied().flatten() {
+                            Some(db) if db != b => dominates(&idom, db, b),
+                            Some(_) => matches!(m.insts[ui as usize].op, Op::Phi(..)),
+                            None => false,
+                        },
+                        _ => true,
+                    };
+                    if can_replace {
+                        let rep = unique.unwrap_or_else(|| m.undef(phi_ty));
+                        repl[id as usize] = Some(rep);
+                        round_changed = true;
+                        continue;
+                    }
+                }
+
+                // Duplicate-PHI check within block `b` (normalizing self-ref to `None`).
+                let mut key_edges: Vec<(Option<Value>, u32)> = inc
+                    .iter()
+                    .map(|&(v, pb)| (if v == self_val { None } else { Some(v) }, pb.0))
+                    .collect();
+                key_edges.sort_unstable_by_key(|&(v, pb)| (pb, v));
+                let key = (phi_ty, key_edges);
+                if let Some(&prev) = seen.get(&key) {
+                    repl[id as usize] = Some(prev);
+                    round_changed = true;
+                    continue;
+                }
+                seen.insert(key, self_val);
+                m.insts[id as usize].op = Op::Phi(inc);
+                keep.push(id);
+            }
+            m.blocks[b] = keep;
+        }
+
+        if !round_changed {
+            break;
+        }
+        any_changed = true;
+        // Propagate replacements into PHIs whose producers came later in the same block or backedges.
+        for b in 0..m.blocks.len() {
+            for &id in &m.blocks[b] {
+                if !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    break;
+                }
+                rewrite_op_values(&mut m.insts[id as usize].op, &repl);
+            }
+        }
+    }
+
+    if any_changed {
+        rewrite_md_values(m, &repl);
+    }
+    any_changed
+}
+
+// --------------------------------------------------- InstCombine & Folding
+
+fn eval_int_binop(op: BinOp, w: u32, ua: u64, ub: u64) -> Option<u64> {
+    let mask = mask_for(w);
+    let ua = ua & mask;
+    let ub = ub & mask;
+    let r = match op {
+        BinOp::Add => ua.wrapping_add(ub),
+        BinOp::Sub => ua.wrapping_sub(ub),
+        BinOp::Mul => ua.wrapping_mul(ub),
+        BinOp::And => ua & ub,
+        BinOp::Or => ua | ub,
+        BinOp::Xor => ua ^ ub,
+        BinOp::UDiv => {
+            if ub == 0 {
+                return None;
+            }
+            ua / ub
+        }
+        BinOp::URem => {
+            if ub == 0 {
+                return None;
+            }
+            ua % ub
+        }
+        BinOp::SDiv => {
+            let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+            let smin = sext_i64(1u64 << (w - 1), w);
+            if sb == 0 || (sb == -1 && sa == smin) {
+                return None;
+            }
+            (sa / sb) as u64
+        }
+        BinOp::SRem => {
+            let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+            let smin = sext_i64(1u64 << (w - 1), w);
+            if sb == 0 || (sb == -1 && sa == smin) {
+                return None;
+            }
+            (sa % sb) as u64
+        }
+        BinOp::Shl => {
+            if ub >= w as u64 {
+                return None;
+            }
+            ua.wrapping_shl(ub as u32)
+        }
+        BinOp::LShr => {
+            if ub >= w as u64 {
+                return None;
+            }
+            ua >> (ub as u32)
+        }
+        BinOp::AShr => {
+            if ub >= w as u64 {
+                return None;
+            }
+            (sext_i64(ua, w) >> (ub as u32)) as u64
+        }
+    };
+    Some(r & mask)
+}
+
+fn eval_icmp(p: Pred, w: u32, ua: u64, ub: u64) -> Option<bool> {
+    let mask = mask_for(w);
+    let ua = ua & mask;
+    let ub = ub & mask;
+    let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w));
+    Some(match p {
+        Pred::Eq => ua == ub,
+        Pred::Ne => ua != ub,
+        Pred::UGt => ua > ub,
+        Pred::UGe => ua >= ub,
+        Pred::ULt => ua < ub,
+        Pred::ULe => ua <= ub,
+        Pred::SGt => sa > sb,
+        Pred::SGe => sa >= sb,
+        Pred::SLt => sa < sb,
+        Pred::SLe => sa <= sb,
+        _ => return None,
+    })
+}
+
+fn make_not_op(m: &mut Module, x: Value) -> Op {
+    if let Value::Inst(xi) = x {
+        if let Op::Cmp(p, a, b) = m.insts[xi as usize].op {
+            return Op::Cmp(invert_pred(p), a, b);
+        }
+    }
+    let t = m.i1c(true);
+    Op::Bin(BinOp::Xor, x, t, 0)
+}
+
+fn unwrap_bitcast_src(m: &mut Module, v: Value, dst: Ty) -> Option<Value> {
+    if m.value_ty(v) == dst {
+        return Some(v);
+    }
+    if let Some(c) = const_bitcast(m, v, dst) {
+        return Some(c);
+    }
+    if let Value::Inst(id) = v {
+        if let Op::Cast(CastOp::BitCast, inner, _) = m.insts[id as usize].op {
+            if m.value_ty(inner) == dst {
+                return Some(inner);
+            }
+        }
+    }
+    None
+}
+
+fn simplify_int_bin(m: &mut Module, id: u32, ty: Ty, w: u32) -> Result<Value, Option<Op>> {
+    let Op::Bin(op, mut a, mut b, _flags) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    if matches!(op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor)
+        && const_int_u64(m, a).is_some()
+        && const_int_u64(m, b).is_none()
+    {
+        std::mem::swap(&mut a, &mut b);
+        return simplify_rewritten_bin(m, ty, w, op, a, b, true);
+    }
+    simplify_rewritten_bin(m, ty, w, op, a, b, false)
+}
+
+fn simplify_rewritten_bin(
+    m: &mut Module, ty: Ty, w: u32, op: BinOp, a: Value, b: Value, swapped: bool,
+) -> Result<Value, Option<Op>> {
+    let mask = mask_for(w);
+    let ca = const_int_u64(m, a);
+    let cb = const_int_u64(m, b);
+    if let (Some(ua), Some(ub)) = (ca, cb) {
+        if let Some(r) = eval_int_binop(op, w, ua, ub) {
+            return Ok(m.const_int(ty, r));
+        }
+    }
+
+    // Reassociate `(inner_op x, c1) outer_op c2` when `b = c2`.
+    if let (Value::Inst(ai), Some(c2)) = (a, cb) {
+        if let Op::Bin(op1, x, c1_val, _) = m.insts[ai as usize].op {
+            if let Some(c1) = const_int_u64(m, c1_val) {
+                let reassociated: Option<(BinOp, u64)> = match (op1, op) {
+                    (BinOp::Add, BinOp::Add) => Some((BinOp::Add, c1.wrapping_add(c2) & mask)),
+                    (BinOp::Sub, BinOp::Add) => Some((BinOp::Add, c2.wrapping_sub(c1) & mask)),
+                    (BinOp::Add, BinOp::Sub) => Some((BinOp::Add, c1.wrapping_sub(c2) & mask)),
+                    (BinOp::Sub, BinOp::Sub) => Some((BinOp::Add, 0u64.wrapping_sub(c1.wrapping_add(c2)) & mask)),
+                    (BinOp::Mul, BinOp::Mul) => Some((BinOp::Mul, c1.wrapping_mul(c2) & mask)),
+                    (BinOp::And, BinOp::And) => Some((BinOp::And, c1 & c2)),
+                    (BinOp::Or, BinOp::Or) => Some((BinOp::Or, c1 | c2)),
+                    (BinOp::Xor, BinOp::Xor) => Some((BinOp::Xor, c1 ^ c2)),
+                    (BinOp::Shl, BinOp::Shl)
+                    | (BinOp::LShr, BinOp::LShr)
+                    | (BinOp::AShr, BinOp::AShr)
+                        if (c1 as u128 + c2 as u128) < w as u128 =>
+                    {
+                        Some((op, c1 + c2))
+                    }
+                    _ => None,
+                };
+                if let Some((new_op, nc)) = reassociated {
+                    let nc_val = m.const_int(ty, nc);
+                    // Apply immediate identity check (e.g. `(x ^ c) ^ c -> x`).
+                    if let Ok(folded) = simplify_rewritten_bin(m, ty, w, new_op, x, nc_val, true) {
+                        return Ok(folded);
+                    }
+                    return Err(Some(Op::Bin(new_op, x, nc_val, 0)));
+                }
+            }
+        }
+    }
+
+    match op {
+        BinOp::Add => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b && w == 1 {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Sub => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b {
+                return Ok(m.const_int(ty, 0));
+            }
+            if ca == Some(0) && w == 1 {
+                return Ok(b);
+            }
+            if let Some(c) = cb {
+                let neg = (0u64.wrapping_sub(c)) & mask;
+                let neg_val = m.const_int(ty, neg);
+                return Err(Some(Op::Bin(BinOp::Add, a, neg_val, 0)));
+            }
+        }
+        BinOp::Mul => {
+            if cb == Some(0) {
+                return Ok(m.const_int(ty, 0));
+            }
+            if cb == Some(1) {
+                return Ok(a);
+            }
+            if a == b && w == 1 {
+                return Ok(a);
+            }
+        }
+        BinOp::UDiv | BinOp::SDiv => {
+            if cb == Some(1) {
+                return Ok(a);
+            }
+        }
+        BinOp::URem | BinOp::SRem => {
+            if cb == Some(1) {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Shl | BinOp::LShr | BinOp::AShr => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+        }
+        BinOp::And => {
+            if cb == Some(0) {
+                return Ok(m.const_int(ty, 0));
+            }
+            if cb == Some(mask) || a == b {
+                return Ok(a);
+            }
+            // `x & ~x == 0`
+            let is_comp = |lhs: Value, rhs: Value| -> bool {
+                let Value::Inst(ri) = rhs else { return false };
+                if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op {
+                    (x == lhs && const_int_u64(m, y) == Some(mask))
+                        || (y == lhs && const_int_u64(m, x) == Some(mask))
+                } else {
+                    false
+                }
+            };
+            if is_comp(a, b) || is_comp(b, a) {
+                return Ok(m.const_int(ty, 0));
+            }
+        }
+        BinOp::Or => {
+            if cb == Some(0) || a == b {
+                return Ok(a);
+            }
+            if cb == Some(mask) {
+                return Ok(m.const_int(ty, mask));
+            }
+            let is_comp = |lhs: Value, rhs: Value| -> bool {
+                let Value::Inst(ri) = rhs else { return false };
+                if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op {
+                    (x == lhs && const_int_u64(m, y) == Some(mask))
+                        || (y == lhs && const_int_u64(m, x) == Some(mask))
+                } else {
+                    false
+                }
+            };
+            if is_comp(a, b) || is_comp(b, a) {
+                return Ok(m.const_int(ty, mask));
+            }
+        }
+        BinOp::Xor => {
+            if cb == Some(0) {
+                return Ok(a);
+            }
+            if a == b {
+                return Ok(m.const_int(ty, 0));
+            }
+            // `(x ^ y) ^ y -> x`
+            if let Value::Inst(ai) = a {
+                if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[ai as usize].op {
+                    if v == b {
+                        return Ok(u);
+                    }
+                    if u == b {
+                        return Ok(v);
+                    }
+                }
+            }
+            if let Value::Inst(bi) = b {
+                if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[bi as usize].op {
+                    if v == a {
+                        return Ok(u);
+                    }
+                    if u == a {
+                        return Ok(v);
+                    }
+                }
+            }
+            // `xor(cmp(p, u, v), true) -> cmp(invert(p), u, v)`
+            if cb == Some(1) && w == 1 {
+                if let Value::Inst(ai) = a {
+                    if let Op::Cmp(p, u, v) = m.insts[ai as usize].op {
+                        return Err(Some(Op::Cmp(invert_pred(p), u, v)));
+                    }
+                }
+            }
+        }
+    }
+
+    if swapped {
+        Err(Some(Op::Bin(op, a, b, 0)))
+    } else {
+        Err(None)
+    }
+}
+
+fn simplify_cast(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Cast(op, v, dst) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    let src = m.value_ty(v);
+    if src == dst && matches!(op, CastOp::Trunc | CastOp::ZExt | CastOp::SExt | CastOp::FPTrunc | CastOp::FPExt | CastOp::BitCast) {
+        return Ok(v);
+    }
+
+    match op {
+        CastOp::Trunc | CastOp::ZExt => {
+            if let (Some(uv), Some(_)) = (const_int_u64(m, v), m.int_width(dst)) {
+                return Ok(m.const_int(dst, uv));
+            }
+        }
+        CastOp::SExt => {
+            if let (Some(uv), Some(sw), Some(_)) = (const_int_u64(m, v), m.int_width(src), m.int_width(dst)) {
+                let sv = sext_i64(uv, sw);
+                return Ok(m.const_int(dst, sv as u64));
+            }
+        }
+        CastOp::BitCast => {
+            if let Some(c) = const_bitcast(m, v, dst) {
+                return Ok(c);
+            }
+        }
+        _ => {}
+    }
+
+    if let Value::Inst(vi) = v {
+        match (op, m.insts[vi as usize].op.clone()) {
+            (CastOp::Trunc, Op::Cast(CastOp::Trunc, x, _)) => return Err(Some(Op::Cast(CastOp::Trunc, x, dst))),
+            (CastOp::ZExt, Op::Cast(CastOp::ZExt, x, _)) => return Err(Some(Op::Cast(CastOp::ZExt, x, dst))),
+            (CastOp::SExt, Op::Cast(CastOp::SExt, x, _)) => return Err(Some(Op::Cast(CastOp::SExt, x, dst))),
+            (CastOp::SExt, Op::Cast(CastOp::ZExt, x, _)) => {
+                if let (Some(wx), Some(wsrc)) = (m.int_width(m.value_ty(x)), m.int_width(src)) {
+                    if wx < wsrc {
+                        return Err(Some(Op::Cast(CastOp::ZExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::Trunc, Op::Cast(CastOp::ZExt, x, _)) => {
+                if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) {
+                    if wx == wd {
+                        return Ok(x);
+                    } else if wx > wd {
+                        return Err(Some(Op::Cast(CastOp::Trunc, x, dst)));
+                    } else {
+                        return Err(Some(Op::Cast(CastOp::ZExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::Trunc, Op::Cast(CastOp::SExt, x, _)) => {
+                if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) {
+                    if wx == wd {
+                        return Ok(x);
+                    } else if wx > wd {
+                        return Err(Some(Op::Cast(CastOp::Trunc, x, dst)));
+                    } else {
+                        return Err(Some(Op::Cast(CastOp::SExt, x, dst)));
+                    }
+                }
+            }
+            (CastOp::BitCast, Op::Cast(CastOp::BitCast, x, _)) => {
+                let xt = m.value_ty(x);
+                if xt == dst {
+                    return Ok(x);
+                }
+                if scalar_bits(m, xt).is_some() && scalar_bits(m, xt) == scalar_bits(m, dst) {
+                    return Err(Some(Op::Cast(CastOp::BitCast, x, dst)));
+                }
+            }
+            (CastOp::BitCast, Op::Select(c, a, b)) => {
+                if scalar_bits(m, src).is_some() && scalar_bits(m, src) == scalar_bits(m, dst) {
+                    if let (Some(ua), Some(ub)) = (unwrap_bitcast_src(m, a, dst), unwrap_bitcast_src(m, b, dst)) {
+                        if ua == ub {
+                            return Ok(ua);
+                        }
+                        return Err(Some(Op::Select(c, ua, ub)));
+                    }
+                }
+            }
+            _ => {}
+        }
+    }
+
+    Err(None)
+}
+
+fn simplify_cmp(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Cmp(mut p, mut a, mut b) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    let ty = m.value_ty(a);
+    let Some(w) = m.int_width(ty) else {
+        return Err(None);
+    };
+    let mut swapped = false;
+    if const_int_u64(m, a).is_some() && const_int_u64(m, b).is_none() {
+        std::mem::swap(&mut a, &mut b);
+        p = swap_pred(p);
+        swapped = true;
+    }
+
+    if let (Some(ua), Some(ub)) = (const_int_u64(m, a), const_int_u64(m, b)) {
+        if let Some(res) = eval_icmp(p, w, ua, ub) {
+            return Ok(m.i1c(res));
+        }
+    }
+    if a == b {
+        if let Some(res) = eval_icmp(p, w, 0, 0) {
+            return Ok(m.i1c(res));
+        }
+    }
+
+    let mask = mask_for(w);
+    if let Some(cb) = const_int_u64(m, b) {
+        if cb == 0 && p == Pred::ULt {
+            return Ok(m.i1c(false));
+        }
+        if cb == 0 && p == Pred::UGe {
+            return Ok(m.i1c(true));
+        }
+        if cb == mask && p == Pred::UGt {
+            return Ok(m.i1c(false));
+        }
+        if cb == mask && p == Pred::ULe {
+            return Ok(m.i1c(true));
+        }
+        if cb == 0 && p == Pred::ULe {
+            return Err(Some(Op::Cmp(Pred::Eq, a, b)));
+        }
+        if cb == 0 && p == Pred::UGt {
+            return Err(Some(Op::Cmp(Pred::Ne, a, b)));
+        }
+        if cb == mask && p == Pred::UGe {
+            return Err(Some(Op::Cmp(Pred::Eq, a, b)));
+        }
+        if cb == mask && p == Pred::ULt {
+            return Err(Some(Op::Cmp(Pred::Ne, a, b)));
+        }
+
+        if w == 1 {
+            return match (p, cb) {
+                (Pred::Eq, 1) | (Pred::Ne, 0) => Ok(a),
+                (Pred::Eq, 0) | (Pred::Ne, 1) => Err(Some(make_not_op(m, a))),
+                _ => {
+                    if swapped {
+                        Err(Some(Op::Cmp(p, a, b)))
+                    } else {
+                        Err(None)
+                    }
+                }
+            };
+        }
+
+        // Collapse `(zext i1 x) cmp k` and `(sext i1 x) cmp k` (`set_scc` / `scc_bit` idioms)
+        // and `select(c, const, const) cmp k`.
+        if let Value::Inst(ai) = a {
+            match m.insts[ai as usize].op {
+                Op::Cast(CastOp::ZExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => {
+                    if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, 1, cb)) {
+                        if f0 == f1 {
+                            return Ok(m.i1c(f0));
+                        }
+                        return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) };
+                    }
+                }
+                Op::Cast(CastOp::SExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => {
+                    if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, mask, cb)) {
+                        if f0 == f1 {
+                            return Ok(m.i1c(f0));
+                        }
+                        return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) };
+                    }
+                }
+                Op::Select(cond, tc, fc) => {
+                    if let (Some(ct), Some(cf)) = (const_int_u64(m, tc), const_int_u64(m, fc)) {
+                        if let (Some(bt), Some(bf)) = (eval_icmp(p, w, ct, cb), eval_icmp(p, w, cf, cb)) {
+                            if bt == bf {
+                                return Ok(m.i1c(bt));
+                            }
+                            return if bt { Ok(cond) } else { Err(Some(make_not_op(m, cond))) };
+                        }
+                    }
+                }
+                _ => {}
+            }
+        }
+    }
+
+    if swapped {
+        Err(Some(Op::Cmp(p, a, b)))
+    } else {
+        Err(None)
+    }
+}
+
+fn simplify_select(m: &mut Module, id: u32) -> Result<Value, Option<Op>> {
+    let Op::Select(c, mut t, mut f) = m.insts[id as usize].op else {
+        return Err(None);
+    };
+    if let Some(cv) = const_int_u64(m, c) {
+        return Ok(if cv & 1 != 0 { t } else { f });
+    }
+    if t == f {
+        return Ok(t);
+    }
+    if let Some(inner) = match_not_i1(m, c) {
+        return Err(Some(Op::Select(inner, f, t)));
+    }
+
+    let ty = m.insts[id as usize].ty;
+    if m.int_width(ty) == Some(1) {
+        let ct = const_int_u64(m, t);
+        let cf = const_int_u64(m, f);
+        if ct == Some(1) && cf == Some(0) {
+            return Ok(c);
+        }
+        if ct == Some(0) && cf == Some(1) {
+            return Err(Some(make_not_op(m, c)));
+        }
+        if (t == c && cf == Some(0)) || (ct == Some(1) && f == c) {
+            return Ok(c);
+        }
+        if t == c && cf == Some(1) {
+            return Ok(m.i1c(true));
+        }
+        if ct == Some(0) && f == c {
+            return Ok(m.i1c(false));
+        }
+    }
+
+    // `select c, (select c, t1, _), f -> select c, t1, f` (and analogously in `f`).
+    let mut folded_arm = false;
+    if let Value::Inst(ti) = t {
+        if let Op::Select(c2, t2, _) = m.insts[ti as usize].op {
+            if c2 == c {
+                t = t2;
+                folded_arm = true;
+            }
+        }
+    }
+    if let Value::Inst(fi) = f {
+        if let Op::Select(c2, _, f2) = m.insts[fi as usize].op {
+            if c2 == c {
+                f = f2;
+                folded_arm = true;
+            }
+        }
+    }
+    if folded_arm {
+        if t == f {
+            return Ok(t);
+        }
+        return Err(Some(Op::Select(c, t, f)));
+    }
+
+    Err(None)
+}
+
+fn simplify_pure_dxop_call(m: &mut Module, id: u32) -> Option<Value> {
+    let Op::Call(f, args) = &m.insts[id as usize].op else { return None };
+    let name = &m.funcs[*f as usize].name;
+    let opc = args.first().and_then(|&v| const_int_u64(m, v))?;
+
+    if is_op_name(name, "dx.op.unaryBits") && args.len() == 2 {
+        let uv = const_int_u64(m, args[1])?;
+        let sw = m.int_width(m.value_ty(args[1]))?;
+        let mask = mask_for(sw);
+        let u = uv & mask;
+        let res = match opc {
+            31 => u.count_ones() as u64,
+            32 => {
+                if u == 0 {
+                    u32::MAX as u64
+                } else {
+                    u.trailing_zeros() as u64
+                }
+            }
+            33 => {
+                if u == 0 {
+                    u32::MAX as u64
+                } else {
+                    (u.leading_zeros() - (64 - sw)) as u64
+                }
+            }
+            34 => {
+                let sign = (u >> (sw - 1)) & 1 != 0;
+                let bits = if sign { (!u) & mask } else { u };
+                if bits == 0 {
+                    u32::MAX as u64
+                } else {
+                    (bits.leading_zeros() - (64 - sw)) as u64
+                }
+            }
+            _ => return None,
+        };
+        return Some(m.i32c(res as u32));
+    }
+
+    if is_op_name(name, "dx.op.unary") && opc == 30 && args.len() == 2 {
+        let ty = m.insts[id as usize].ty;
+        let sw = m.int_width(ty)?;
+        let uv = const_int_u64(m, args[1])?;
+        let rev = (uv & mask_for(sw)).reverse_bits() >> (64 - sw);
+        return Some(m.const_int(ty, rev));
+    }
+
+    if is_op_name(name, "dx.op.binary") && (37..=40).contains(&opc) && args.len() == 3 {
+        let (a, b) = (args[1], args[2]);
+        if a == b {
+            return Some(a);
+        }
+        let ty = m.insts[id as usize].ty;
+        let sw = m.int_width(ty)?;
+        let (ua, ub) = (const_int_u64(m, a)?, const_int_u64(m, b)?);
+        let r = match opc {
+            37 => (sext_i64(ua, sw).max(sext_i64(ub, sw))) as u64,
+            38 => (sext_i64(ua, sw).min(sext_i64(ub, sw))) as u64,
+            39 => ua.max(ub),
+            40 => ua.min(ub),
+            _ => unreachable!(),
+        };
+        return Some(m.const_int(ty, r));
+    }
+
+    None
+}
+
+/// RPO constant folding, cast simplification, integer identities/reassociation,
+/// comparison and select simplifications.
+pub(super) fn simplify_insts(m: &mut Module) -> bool {
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut changed = false;
+
+    for b in 0..m.blocks.len() {
+        let mut keep = Vec::with_capacity(m.blocks[b].len());
+        let old_insts = std::mem::take(&mut m.blocks[b]);
+        for id in old_insts {
+            if rewrite_op_values(&mut m.insts[id as usize].op, &repl) {
+                changed = true;
+            }
+            if matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                keep.push(id);
+                continue;
+            }
+            let ty = m.insts[id as usize].ty;
+            let simplified = match &m.insts[id as usize].op {
+                Op::Bin(..) => {
+                    if let Some(w) = m.int_width(ty) {
+                        simplify_int_bin(m, id, ty, w)
+                    } else {
+                        Err(None)
+                    }
+                }
+                Op::Cast(..) => simplify_cast(m, id),
+                Op::Cmp(..) => simplify_cmp(m, id),
+                Op::Select(..) => simplify_select(m, id),
+                Op::Call(..) => match simplify_pure_dxop_call(m, id) {
+                    Some(v) => Ok(v),
+                    None => Err(None),
+                },
+                _ => Err(None),
+            };
+            match simplified {
+                Ok(v) if v != Value::Inst(id) => {
+                    repl[id as usize] = Some(v);
+                    changed = true;
+                }
+                Err(Some(new_op)) => {
+                    m.insts[id as usize].op = new_op;
+                    changed = true;
+                    keep.push(id);
+                }
+                _ => keep.push(id),
+            }
+        }
+        m.blocks[b] = keep;
+    }
+
+    if changed {
+        for b in 0..m.blocks.len() {
+            for &id in &m.blocks[b] {
+                if !matches!(m.insts[id as usize].op, Op::Phi(..)) {
+                    break;
+                }
+                rewrite_op_values(&mut m.insts[id as usize].op, &repl);
+            }
+        }
+        rewrite_md_values(m, &repl);
+    }
+
+    changed
+}
+
+// --------------------------------------------------------- Dominator CSE
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum CseKey {
+    Bin(u8, Value, Value, u64),
+    Cast(u8, Value, Ty),
+    Cmp(u8, Value, Value),
+    Select(Value, Value, Value),
+    Extract(Value, u32),
+    Gep(Value, Vec<Value>),
+    Call(u32, Vec<Value>),
+}
+
+fn cse_key(m: &Module, op: &Op) -> Option<CseKey> {
+    match op {
+        Op::Bin(bin_op, a, b, flags) => {
+            let (mut x, mut y) = (*a, *b);
+            if matches!(bin_op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) && x > y {
+                std::mem::swap(&mut x, &mut y);
+            }
+            Some(CseKey::Bin(*bin_op as u8, x, y, *flags))
+        }
+        Op::Cast(cop, v, ty) => Some(CseKey::Cast(*cop as u8, *v, *ty)),
+        Op::Cmp(p, a, b) => {
+            let (mut p, mut x, mut y) = (*p, *a, *b);
+            if x > y {
+                std::mem::swap(&mut x, &mut y);
+                p = swap_pred(p);
+            }
+            Some(CseKey::Cmp(p as u8, x, y))
+        }
+        Op::Select(c, t, f) => Some(CseKey::Select(*c, *t, *f)),
+        Op::Extract(a, idx) => Some(CseKey::Extract(*a, *idx)),
+        Op::Gep(p, idx) => Some(CseKey::Gep(*p, idx.clone())),
+        Op::Call(f, args) => {
+            let fd = &m.funcs[*f as usize];
+            if fd.attrs != FnAttrs::ReadNone {
+                return None;
+            }
+            // Implicit quad derivatives (`dx.op.unary` opcodes 83..=86) depend on
+            // CFG position even though declared `readnone`. Never CSE them.
+            if is_op_name(&fd.name, "dx.op.unary") {
+                let opc = args.first().and_then(|&v| const_int_u64(m, v));
+                if !matches!(opc, Some(0..=30)) {
+                    return None;
+                }
+            }
+            let mut norm_args = args.clone();
+            if is_op_name(&fd.name, "dx.op.binary")
+                && norm_args.len() == 3
+                && matches!(norm_args.first().and_then(|&v| const_int_u64(m, v)), Some(35..=40))
+                && norm_args[1] > norm_args[2]
+            {
+                norm_args.swap(1, 2);
+            }
+            Some(CseKey::Call(*f, norm_args))
+        }
+        _ => None,
+    }
+}
+
+/// Dominator-tree scoped CSE assuming blocks `0..n` are already in RPO.
+pub(super) fn cse(m: &mut Module) -> bool {
+    let n = m.blocks.len();
+    if n == 0 {
+        return false;
+    }
+
+    let idom = compute_idom(m);
+    let mut children: Vec<Vec<usize>> = vec![Vec::new(); n];
+    for b in 1..n {
+        if let Some(p) = idom[b] {
+            children[p].push(b);
+        }
+    }
+
+    enum DomFrame {
+        Enter(usize),
+        Exit(usize),
+    }
+
+    let mut table: HashMap<CseKey, Value> = HashMap::new();
+    let mut undo: Vec<CseKey> = Vec::new();
+    let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()];
+    let mut changed = false;
+    let mut stack = vec![DomFrame::Enter(0)];
+
+    while let Some(frame) = stack.pop() {
+        match frame {
+            DomFrame::Enter(b) => {
+                let mark = undo.len();
+                stack.push(DomFrame::Exit(mark));

The replacement at ce8c103 removes this branch’s CSE implementation and uses the optimizer from merged #1426. I checked its sibling scoping with a diamond test under Wine. Both arms compute the same expression, one arm repeats it, and the join PHI uses the two incoming values. The same-arm duplicate folded and each PHI edge kept its own arm’s definition (1 passed). T3 Code (Codex, gpt-6.2-astra) wrote and ran the probe.

**@⁠Roroca-1** on GitHub · 2026-11-24 19:19 UTC · [original](https://github.com/xcl-dev/xcl/pull/1546#discussion_r4685273869) On `crates/xcl/src/gpu/dxil/opt.rs` line 1795 (outdated): ```diff @@ -0,0 +1,2770 @@ +//! Intra-function DXIL SSA IR optimization and module compaction pass suite. +//! +//! Runs after IR construction and before metadata/bitcode serialization: +//! 1. Fixpoint loop over CFG simplification & RPO normalization, trivial/duplicate +//! PHI elimination, constant folding & algebraic/bitcast/select simplification, +//! dominator-scoped CSE (excluding implicit derivatives and non-pure intrinsics), +//! and iterative mark-and-sweep DCE. +//! 2. Dense compaction of live instructions, constants, declarations, and globals. +//! 3. Synchronization of [`Shader::features`] with the remaining live IR. +//! +//! All graph traversals use explicit stacks so large shaders cannot overflow. + +use std::collections::{BTreeSet, HashMap}; + +use super::module::{BinOp, Block, CastOp, ConstDef, FnAttrs, MdDef, Module, Op, Pred, Ty, Value}; +use super::shader::{kind, Feature, Shader}; + +const MAX_ROUNDS: usize = 8; + +/// Summary metrics of a DXIL [`Module`] (for diagnostics and optimization tests). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Stats { + pub blocks: usize, + pub insts: usize, + pub phis: usize, + pub consts: usize, + pub funcs: usize, + pub globals: usize, +} + +/// Counts live blocks/instructions/PHIs and pooled constants/functions/globals. +pub fn module_stats(m: &Module) -> Stats { + let mut insts = 0usize; + let mut phis = 0usize; + for b in &m.blocks { + insts += b.len(); + for &id in b { + if matches!(m.insts[id as usize].op, Op::Phi(..)) { + phis += 1; + } + } + } + Stats { + blocks: m.blocks.len(), + insts, + phis, + consts: m.consts.len(), + funcs: m.funcs.len(), + globals: m.globals.len(), + } +} + +/// Optimizes `s.m`, compacts pooled module tables (updating `s.entry`), and +/// synchronizes `s.features` against the remaining live IR. +pub fn optimize(s: &mut Shader) { + if s.m.error().is_some() || s.m.blocks.is_empty() { + return; + } + optimize_core(&mut s.m); + compact_module(&mut s.m, Some(&mut s.entry)); + sync_features(s); +} + +/// Optimizes and compacts `m` without modifying wrapper shader metadata. +pub fn optimize_module(m: &mut Module) { + if m.error().is_some() || m.blocks.is_empty() { + return; + } + optimize_core(m); + compact_module(m, None); +} + +fn optimize_core(m: &mut Module) { + for _ in 0..MAX_ROUNDS { + let mut changed = false; + changed |= simplify_cfg(m); + changed |= simplify_phis(m); + changed |= simplify_insts(m); + changed |= cse(m); + changed |= dce(m); + if !changed { + break; + } + } + // Final normalization pass if the last DCE/CSE opened trivial CFG/PHI cleanup. + if simplify_cfg(m) { + let _ = simplify_phis(m); + let _ = dce(m); + let _ = simplify_cfg(m); + } +} + +// ------------------------------------------------------------------ helpers + +fn mask_for(w: u32) -> u64 { + if w >= 64 { + u64::MAX + } else if w == 0 { + 0 + } else { + (1u64 << w) - 1 + } +} + +fn sext_i64(v: u64, w: u32) -> i64 { + if w >= 64 { + v as i64 + } else if w == 0 { + 0 + } else { + ((v << (64 - w)) as i64) >> (64 - w) + } +} + +fn const_int_u64(m: &Module, v: Value) -> Option<u64> { + match v { + Value::Const(c) => match &m.consts[c as usize] { + ConstDef::Int(t, x) => { + let w = m.int_width(*t)?; + Some((*x as u64) & mask_for(w)) + } + ConstDef::Null(t) if m.int_width(*t).is_some() => Some(0), + _ => None, + }, + _ => None, + } +} + +fn scalar_bits(m: &Module, ty: Ty) -> Option<u32> { + if let Some(w) = m.int_width(ty) { + return Some(w); + } + if m.is_float(ty) { + return match m.alloc_size_layout(ty, true) { + 2 => Some(16), + 4 => Some(32), + 8 => Some(64), + _ => None, + }; + } + None +} + +fn const_bitcast(m: &mut Module, v: Value, dst: Ty) -> Option<Value> { + if m.value_ty(v) == dst { + return Some(v); + } + let Value::Const(c) = v else { return None }; + let dst_bits = scalar_bits(m, dst)?; + let def = m.consts[c as usize].clone(); + match def { + ConstDef::Undef(t) => (scalar_bits(m, t) == Some(dst_bits)).then(|| m.undef(dst)), + ConstDef::Null(t) if scalar_bits(m, t) == Some(dst_bits) => { + if m.int_width(dst).is_some() { + Some(m.const_int(dst, 0)) + } else if m.is_float(dst) { + Some(m.const_float(dst, 0)) + } else { + None + } + } + ConstDef::Int(t, x) => { + let w = m.int_width(t)?; + if w != dst_bits { + return None; + } + let raw = (x as u64) & mask_for(w); + if m.int_width(dst).is_some() { + Some(m.const_int(dst, raw)) + } else if m.is_float(dst) { + Some(m.const_float(dst, raw)) + } else { + None + } + } + ConstDef::Float(t, bits) => { + let w = scalar_bits(m, t)?; + if w != dst_bits { + return None; + } + if m.int_width(dst).is_some() { + Some(m.const_int(dst, bits)) + } else if m.is_float(dst) { + Some(m.const_float(dst, bits)) + } else { + None + } + } + _ => None, + } +} + +fn is_undef(m: &Module, v: Value) -> bool { + matches!(v, Value::Const(c) if matches!(m.consts[c as usize], ConstDef::Undef(_))) +} + +fn is_op_name(full: &str, base: &str) -> bool { + full == base || full.strip_prefix(base).is_some_and(|s| s.starts_with('.')) +} + +fn resolve_val(mut v: Value, repl: &[Option<Value>]) -> Value { + let mut steps = 0usize; + while let Value::Inst(id) = v { + let Some(next) = repl.get(id as usize).copied().flatten() else { break }; + if next == v || steps >= repl.len() { + break; + } + v = next; + steps += 1; + } + v +} + +fn visit_op_values_mut(op: &mut Op, f: &mut dyn FnMut(&mut Value)) { + match op { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => { + f(a); + f(b); + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(v), + Op::Store(p, v, _) => { + f(p); + f(v); + } + Op::Select(c, t, e) | Op::CmpXchg(c, t, e) => { + f(c); + f(t); + f(e); + } + Op::Call(_, args) => { + for a in args { + f(a); + } + } + Op::Phi(inc) => { + for (v, _) in inc { + f(v); + } + } + Op::Gep(p, idx) => { + f(p); + for i in idx { + f(i); + } + } + Op::Alloca(_, n, _) => f(n), + Op::CondBr(c, _, _) => f(c), + Op::Switch(v, _, cases) => { + f(v); + for (cv, _) in cases { + f(cv); + } + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } +} + +fn rewrite_op_values(op: &mut Op, repl: &[Option<Value>]) -> bool { + let mut changed = false; + visit_op_values_mut(op, &mut |v| { + let nv = resolve_val(*v, repl); + if nv != *v { + *v = nv; + changed = true; + } + }); + changed +} + +fn rewrite_md_values(m: &mut Module, repl: &[Option<Value>]) { + for md in &mut m.md { + if let MdDef::Val(_, v) = md { + *v = resolve_val(*v, repl); + } + } +} + +fn for_each_op_value(op: &Op, mut f: impl FnMut(Value)) { + match op { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b); + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) => f(*v), + Op::Store(p, v, _) => { + f(*p); + f(*v); + } + Op::Select(c, t, x) | Op::CmpXchg(c, t, x) => { + f(*c); + f(*t); + f(*x); + } + Op::Call(_, args) => { + for &a in args { + f(a); + } + } + Op::Phi(inc) => { + for &(v, _) in inc { + f(v); + } + } + Op::Gep(p, idx) => { + f(*p); + for &i in idx { + f(i); + } + } + Op::Alloca(_, n, _) => f(*n), + Op::CondBr(c, _, _) => f(*c), + Op::Switch(v, _, cases) => { + f(*v); + for &(cv, _) in cases { + f(cv); + } + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } +} + +fn block_succs(m: &Module, b: usize) -> Vec<usize> { + let Some(&last) = m.blocks[b].last() else { return Vec::new() }; + match &m.insts[last as usize].op { + Op::Br(t) => vec![t.0 as usize], + Op::CondBr(_, t, f) => vec![t.0 as usize, f.0 as usize], + Op::Switch(_, d, cases) => { + let mut s = Vec::with_capacity(1 + cases.len()); + s.push(d.0 as usize); + for &(_, c) in cases { + s.push(c.0 as usize); + } + s + } + _ => Vec::new(), + } +} + +fn invert_pred(p: Pred) -> Pred { + match p { + Pred::Eq => Pred::Ne, + Pred::Ne => Pred::Eq, + Pred::UGt => Pred::ULe, + Pred::UGe => Pred::ULt, + Pred::ULt => Pred::UGe, + Pred::ULe => Pred::UGt, + Pred::SGt => Pred::SLe, + Pred::SGe => Pred::SLt, + Pred::SLt => Pred::SGe, + Pred::SLe => Pred::SGt, + Pred::FFalse => Pred::FTrue, + Pred::FTrue => Pred::FFalse, + Pred::FOEq => Pred::FUNe, + Pred::FUNe => Pred::FOEq, + Pred::FOGt => Pred::FULe, + Pred::FULe => Pred::FOGt, + Pred::FOGe => Pred::FULt, + Pred::FULt => Pred::FOGe, + Pred::FOLt => Pred::FUGe, + Pred::FUGe => Pred::FOLt, + Pred::FOLe => Pred::FUGt, + Pred::FUGt => Pred::FOLe, + Pred::FONe => Pred::FUEq, + Pred::FUEq => Pred::FONe, + Pred::FOrd => Pred::FUno, + Pred::FUno => Pred::FOrd, + } +} + +fn swap_pred(p: Pred) -> Pred { + match p { + Pred::UGt => Pred::ULt, + Pred::ULt => Pred::UGt, + Pred::UGe => Pred::ULe, + Pred::ULe => Pred::UGe, + Pred::SGt => Pred::SLt, + Pred::SLt => Pred::SGt, + Pred::SGe => Pred::SLe, + Pred::SLe => Pred::SGe, + Pred::FOGt => Pred::FOLt, + Pred::FOLt => Pred::FOGt, + Pred::FOGe => Pred::FOLe, + Pred::FOLe => Pred::FOGe, + Pred::FUGt => Pred::FULt, + Pred::FULt => Pred::FUGt, + Pred::FUGe => Pred::FULe, + Pred::FULe => Pred::FUGe, + other => other, + } +} + +/// If `v` computes logical NOT (`xor i1 x, true`) returns `Some(x)`. +fn match_not_i1(m: &Module, v: Value) -> Option<Value> { + let Value::Inst(id) = v else { return None }; + if m.int_width(m.insts[id as usize].ty) != Some(1) { + return None; + } + if let Op::Bin(BinOp::Xor, a, b, _) = m.insts[id as usize].op { + if const_int_u64(m, b) == Some(1) { + return Some(a); + } + if const_int_u64(m, a) == Some(1) { + return Some(b); + } + } + None +} + +// ------------------------------------------------------------ CFG simplify + +fn compute_rpo(m: &Module, alive: &[bool]) -> Vec<usize> { + let n = m.blocks.len(); + if n == 0 || !alive[0] { + return Vec::new(); + } + let succs: Vec<Vec<usize>> = (0..n) + .map(|b| if alive[b] { block_succs(m, b) } else { Vec::new() }) + .collect(); + let mut state = vec![0u8; n]; + let mut postorder = Vec::with_capacity(n); + let mut stack = vec![(0usize, 0usize)]; + state[0] = 1; + while let Some((b, idx)) = stack.last_mut() { + let b = *b; + let sb = &succs[b]; + if *idx < sb.len() { + // Visit successors in reverse order so reversed postorder places the + // primary/true branch before the fallback/exit branch. + let next = sb[sb.len() - 1 - *idx]; + *idx += 1; + if alive.get(next).copied().unwrap_or(false) && state[next] == 0 { + state[next] = 1; + stack.push((next, 0)); + } + } else { + state[b] = 2; + postorder.push(b); + stack.pop(); + } + } + postorder.reverse(); + postorder +} + +/// Keeps at most `keep` entries from `pred` in every `Op::Phi` of block `succ`. +fn trim_phi_edges(m: &mut Module, succ: usize, pred: Block, keep: usize) -> bool { + let mut changed = false; + for k in 0..m.blocks[succ].len() { + let id = m.blocks[succ][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + let have = inc.iter().filter(|&&(_, b)| b == pred).count(); + if have > keep { + let mut left = keep; + inc.retain(|&(_, b)| { + if b == pred { + if left > 0 { + left -= 1; + true + } else { + false + } + } else { + true + } + }); + changed = true; + } + } + changed +} + +fn replace_phi_pred_block(m: &mut Module, succ: usize, from: Block, to: Block) { + for k in 0..m.blocks[succ].len() { + let id = m.blocks[succ][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + for (_, b) in inc.iter_mut() { + if *b == from { + *b = to; + } + } + } +} + +fn block_has_phis(m: &Module, b: usize) -> bool { + m.blocks[b].first().is_some_and(|&id| matches!(m.insts[id as usize].op, Op::Phi(..))) +} + +fn rewrite_term_target(term: &mut Op, from: Block, to: Block) -> usize { + let mut count = 0; + match term { + Op::Br(t) if *t == from => { + *t = to; + count += 1; + } + Op::CondBr(_, t, f) => { + if *t == from { + *t = to; + count += 1; + } + if *f == from { + *f = to; + count += 1; + } + } + Op::Switch(_, d, cases) => { + if *d == from { + *d = to; + count += 1; + } + for (_, t) in cases { + if *t == from { + *t = to; + count += 1; + } + } + } + _ => {} + } + count +} + +/// Simplifies terminators, drops unreachable blocks, trims dead PHI edges, +/// bypasses empty jump blocks, merges single-predecessor blocks, and lays out +/// reachable blocks in RPO. +pub(super) fn simplify_cfg(m: &mut Module) -> bool { + let n = m.blocks.len(); + if n == 0 { + return false; + } + let mut changed = false; + + // 1. Fold constant / redundant terminators. + for b in 0..n { + let Some(&term_id) = m.blocks[b].last() else { continue }; + let op = m.insts[term_id as usize].op.clone(); + match op { + Op::CondBr(c, t, f) => { + if let Some(cv) = const_int_u64(m, c) { + let target = if cv & 1 != 0 { t } else { f }; + m.insts[term_id as usize].op = Op::Br(target); + let pred = Block(b as u32); + trim_phi_edges(m, target.0 as usize, pred, 1); + let other = if target == t { f } else { t }; + if other != target { + trim_phi_edges(m, other.0 as usize, pred, 0); + } + changed = true; + } else if t == f { + m.insts[term_id as usize].op = Op::Br(t); + trim_phi_edges(m, t.0 as usize, Block(b as u32), 1); + changed = true; + } else if let Some(inner) = match_not_i1(m, c) { + m.insts[term_id as usize].op = Op::CondBr(inner, f, t); + changed = true; + } + } + Op::Switch(v, d, cases) => { + let mut old_targets = Vec::with_capacity(1 + cases.len()); + old_targets.push(d); + for &(_, target) in &cases { + if !old_targets.contains(&target) { + old_targets.push(target); + } + } + if let Some(cv) = const_int_u64(m, v) { + let target = cases + .iter() + .find(|&&(k, _)| const_int_u64(m, k) == Some(cv)) + .map_or(d, |&(_, dst)| dst); + m.insts[term_id as usize].op = Op::Br(target); + let pred = Block(b as u32); + for s in old_targets { + trim_phi_edges(m, s.0 as usize, pred, usize::from(s == target)); + } + changed = true; + } else { + let mut seen_vals = Vec::with_capacity(cases.len()); + let filtered: Vec<(Value, Block)> = cases + .iter() + .copied() + .filter(|&(cv, dst)| { + if dst == d { + return false; + } + if let Some(kv) = const_int_u64(m, cv) { + if seen_vals.contains(&kv) { + return false; + } + seen_vals.push(kv); + } + true + }) + .collect(); + if filtered.len() != cases.len() { + let pred = Block(b as u32); + if filtered.is_empty() { + m.insts[term_id as usize].op = Op::Br(d); + for s in old_targets { + trim_phi_edges(m, s.0 as usize, pred, usize::from(s == d)); + } + } else { + m.insts[term_id as usize].op = Op::Switch(v, d, filtered.clone()); + for s in old_targets { + let keep = usize::from(s == d) + filtered.iter().filter(|&&(_, x)| x == s).count(); + trim_phi_edges(m, s.0 as usize, pred, keep); + } + } + changed = true; + } + } + } + _ => {} + } + } + + // 2. Reachability and incoming PHI edge reconciliation. + let mut alive = vec![true; n]; + let rpo = compute_rpo(m, &alive); + let mut reach = vec![false; n]; + for &b in &rpo { + reach[b] = true; + } + if rpo.len() < n { + alive = reach.clone(); + changed = true; + } + + let mut edge_counts: HashMap<(u32, u32), usize> = HashMap::new(); + let mut preds: Vec<Vec<u32>> = vec![Vec::new(); n]; + for &b in &rpo { + for succ in block_succs(m, b) { + if alive[succ] { + *edge_counts.entry((b as u32, succ as u32)).or_insert(0) += 1; + preds[succ].push(b as u32); + } + } + } + + for &b in &rpo { + for k in 0..m.blocks[b].len() { + let id = m.blocks[b][k] as usize; + let Op::Phi(inc) = &mut m.insts[id].op else { break }; + let mut rem: HashMap<u32, usize> = HashMap::new(); + for &p in &preds[b] { + rem.insert(p, edge_counts[&(p, b as u32)]); + } + let orig_len = inc.len(); + inc.retain(|&(_, pb)| { + if !alive.get(pb.0 as usize).copied().unwrap_or(false) { + return false; + } + if let Some(cnt) = rem.get_mut(&pb.0) { + if *cnt > 0 { + *cnt -= 1; + return true; + } + } + false + }); + if inc.len() != orig_len { + changed = true; + } + } + } + + // 3. Bypass empty jump-only blocks (Br target with no other instructions). + for &b in &rpo { + if !alive[b] { + continue; + } + loop { + let succs = block_succs(m, b); + let mut bypassed = false; + for e in succs { + if e == 0 || e == b || !alive[e] || m.blocks[e].len() != 1 { + continue; + } + let Op::Br(t) = m.insts[m.blocks[e][0] as usize].op else { continue }; + let tu = t.0 as usize; + if tu == e { + continue; + } + let no_phis = !block_has_phis(m, tu); + let single_pred_no_dup = preds[e].len() == 1 + && preds[e][0] == b as u32 + && !block_succs(m, b).contains(&tu); + if no_phis || single_pred_no_dup { + let Some(&term_id) = m.blocks[b].last() else { break }; + let count = rewrite_term_target(&mut m.insts[term_id as usize].op, Block(e as u32), t); + if count > 0 { + if !no_phis { + replace_phi_pred_block(m, tu, Block(e as u32), Block(b as u32)); + } + let mut rem = count; + preds[e].retain(|&p| { + if rem > 0 && p == b as u32 { + rem -= 1; + false + } else { + true + } + }); + preds[tu].extend(std::iter::repeat_n(b as u32, count)); + if preds[e].is_empty() { + alive[e] = false; + if let Some(pos) = preds[tu].iter().position(|&p| p == e as u32) { + preds[tu].swap_remove(pos); + } + } + changed = true; + bypassed = true; + break; + } + } + } + if !bypassed { + break; + } + } + } + + // 4. Single-predecessor block merging (pred ends in `Br(succ)`, preds[succ] == [pred]). + let mut val_map: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut had_val_map = false; + for &pred in &rpo { + if !alive[pred] { + continue; + } + loop { + let Some(&last) = m.blocks[pred].last() else { break }; + let Op::Br(succ_b) = m.insts[last as usize].op else { break }; + let succ = succ_b.0 as usize; + if succ == 0 || succ == pred || !alive[succ] || preds[succ].len() != 1 { + break; + } + m.blocks[pred].pop(); + let succ_insts = std::mem::take(&mut m.blocks[succ]); + for id in succ_insts { + let ty = m.insts[id as usize].ty; + if let Op::Phi(inc) = &m.insts[id as usize].op { + let rep = inc + .iter() + .find(|&&(_, b)| b == Block(pred as u32)) + .map(|&(v, _)| resolve_val(v, &val_map)) + .unwrap_or_else(|| m.undef(ty)); + val_map[id as usize] = Some(rep); + had_val_map = true; + } else { + m.blocks[pred].push(id); + } + } + for s2 in block_succs(m, pred) { + replace_phi_pred_block(m, s2, Block(succ as u32), Block(pred as u32)); + for p in &mut preds[s2] { + if *p == succ as u32 { + *p = pred as u32; + } + } + } + preds[succ].clear(); + alive[succ] = false; + changed = true; + } + } + if had_val_map { + for &b in &rpo { + if !alive[b] { + continue; + } + for &id in &m.blocks[b] { + rewrite_op_values(&mut m.insts[id as usize].op, &val_map); + } + } + rewrite_md_values(m, &val_map); + } + + // 5. Dense RPO compaction & block index remapping. + let final_rpo = compute_rpo(m, &alive); + let already_ordered = final_rpo.len() == m.blocks.len() && final_rpo.iter().enumerate().all(|(i, &b)| i == b); + if !already_ordered { + let mut old_to_new: Vec<Option<Block>> = vec![None; m.blocks.len()]; + let mut new_blocks = Vec::with_capacity(final_rpo.len()); + for (new_idx, &old_idx) in final_rpo.iter().enumerate() { + old_to_new[old_idx] = Some(Block(new_idx as u32)); + new_blocks.push(std::mem::take(&mut m.blocks[old_idx])); + } + m.blocks = new_blocks; + for b in &m.blocks { + for &id in b { + match &mut m.insts[id as usize].op { + Op::Phi(inc) => { + for (_, pb) in inc { + *pb = old_to_new[pb.0 as usize].expect("live phi pred"); + } + } + Op::Br(t) => *t = old_to_new[t.0 as usize].expect("live br target"), + Op::CondBr(_, t, f) => { + *t = old_to_new[t.0 as usize].expect("live condbr true"); + *f = old_to_new[f.0 as usize].expect("live condbr false"); + } + Op::Switch(_, d, cases) => { + *d = old_to_new[d.0 as usize].expect("live switch default"); + for (_, t) in cases { + *t = old_to_new[t.0 as usize].expect("live switch target"); + } + } + _ => {} + } + } + } + m.cur = Block(0); + changed = true; + } + + changed +} + +// ------------------------------------------------------------ PHI simplify + +fn intersect_idom(idom: &[Option<usize>], mut b1: usize, mut b2: usize) -> usize { + while b1 != b2 { + while b1 > b2 { + b1 = idom[b1].expect("rpo pred must have idom"); + } + while b2 > b1 { + b2 = idom[b2].expect("rpo pred must have idom"); + } + } + b1 +} + +/// Cooper-Harvey-Kennedy iterative immediate dominators over RPO indices `0..n`. +fn compute_idom(m: &Module) -> Vec<Option<usize>> { + let n = m.blocks.len(); + let mut idom: Vec<Option<usize>> = vec![None; n]; + if n == 0 { + return idom; + } + let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n]; + for b in 0..n { + for s in block_succs(m, b) { + if s < n { + preds[s].push(b); + } + } + } + idom[0] = Some(0); + let mut dom_changed = true; + while dom_changed { + dom_changed = false; + for b in 1..n { + let Some(&first) = preds[b].iter().find(|&&p| idom[p].is_some()) else { + continue; + }; + let mut new_idom = first; + for &p in &preds[b] { + if p != first && idom[p].is_some() { + new_idom = intersect_idom(&idom, p, new_idom); + } + } + if idom[b] != Some(new_idom) { + idom[b] = Some(new_idom); + dom_changed = true; + } + } + } + idom +} + +fn dominates(idom: &[Option<usize>], dom: usize, mut node: usize) -> bool { + while node > dom { + let Some(p) = idom[node] else { return false }; + if p == node { + break; + } + node = p; + } + node == dom +} + +/// Eliminates trivial PHIs (`phi [v, ...], [self, ...] -> v`) and deduplicates +/// identical PHIs within the same block until reaching a fixed point. +pub(super) fn simplify_phis(m: &mut Module) -> bool { + let idom = compute_idom(m); + let mut inst_block: Vec<Option<usize>> = vec![None; m.insts.len()]; + for (bi, blk) in m.blocks.iter().enumerate() { + for &id in blk { + inst_block[id as usize] = Some(bi); + } + } + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut any_changed = false; + + loop { + let mut round_changed = false; + + for b in 0..m.blocks.len() { + let mut seen: HashMap<(Ty, Vec<(Option<Value>, u32)>), Value> = HashMap::new(); + let old_insts = std::mem::take(&mut m.blocks[b]); + let mut keep = Vec::with_capacity(old_insts.len()); + let mut in_phi_prefix = true; + + for id in old_insts { + if !in_phi_prefix || !matches!(m.insts[id as usize].op, Op::Phi(..)) { + in_phi_prefix = false; + if rewrite_op_values(&mut m.insts[id as usize].op, &repl) { + round_changed = true; + } + keep.push(id); + continue; + } + let phi_ty = m.insts[id as usize].ty; + let mut inc = match &mut m.insts[id as usize].op { + Op::Phi(v) => std::mem::take(v), + _ => unreachable!(), + }; + for (v, _) in inc.iter_mut() { + let nv = resolve_val(*v, &repl); + if nv != *v { + *v = nv; + round_changed = true; + } + } + + let self_val = Value::Inst(id); + + // Trivial PHI check: ignore self-references and undefs when looking for a unique value. + let mut unique: Option<Value> = None; + let mut non_trivial = false; + for &(v, _) in &inc { + if v == self_val || is_undef(m, v) { + continue; + } + match unique { + None => unique = Some(v), + Some(u) if u == v => {} + Some(_) => { + non_trivial = true; + break; + } + } + } + if !non_trivial { + let can_replace = match unique { + Some(Value::Inst(ui)) => match inst_block.get(ui as usize).copied().flatten() { + Some(db) if db != b => dominates(&idom, db, b), + Some(_) => matches!(m.insts[ui as usize].op, Op::Phi(..)), + None => false, + }, + _ => true, + }; + if can_replace { + let rep = unique.unwrap_or_else(|| m.undef(phi_ty)); + repl[id as usize] = Some(rep); + round_changed = true; + continue; + } + } + + // Duplicate-PHI check within block `b` (normalizing self-ref to `None`). + let mut key_edges: Vec<(Option<Value>, u32)> = inc + .iter() + .map(|&(v, pb)| (if v == self_val { None } else { Some(v) }, pb.0)) + .collect(); + key_edges.sort_unstable_by_key(|&(v, pb)| (pb, v)); + let key = (phi_ty, key_edges); + if let Some(&prev) = seen.get(&key) { + repl[id as usize] = Some(prev); + round_changed = true; + continue; + } + seen.insert(key, self_val); + m.insts[id as usize].op = Op::Phi(inc); + keep.push(id); + } + m.blocks[b] = keep; + } + + if !round_changed { + break; + } + any_changed = true; + // Propagate replacements into PHIs whose producers came later in the same block or backedges. + for b in 0..m.blocks.len() { + for &id in &m.blocks[b] { + if !matches!(m.insts[id as usize].op, Op::Phi(..)) { + break; + } + rewrite_op_values(&mut m.insts[id as usize].op, &repl); + } + } + } + + if any_changed { + rewrite_md_values(m, &repl); + } + any_changed +} + +// --------------------------------------------------- InstCombine & Folding + +fn eval_int_binop(op: BinOp, w: u32, ua: u64, ub: u64) -> Option<u64> { + let mask = mask_for(w); + let ua = ua & mask; + let ub = ub & mask; + let r = match op { + BinOp::Add => ua.wrapping_add(ub), + BinOp::Sub => ua.wrapping_sub(ub), + BinOp::Mul => ua.wrapping_mul(ub), + BinOp::And => ua & ub, + BinOp::Or => ua | ub, + BinOp::Xor => ua ^ ub, + BinOp::UDiv => { + if ub == 0 { + return None; + } + ua / ub + } + BinOp::URem => { + if ub == 0 { + return None; + } + ua % ub + } + BinOp::SDiv => { + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + let smin = sext_i64(1u64 << (w - 1), w); + if sb == 0 || (sb == -1 && sa == smin) { + return None; + } + (sa / sb) as u64 + } + BinOp::SRem => { + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + let smin = sext_i64(1u64 << (w - 1), w); + if sb == 0 || (sb == -1 && sa == smin) { + return None; + } + (sa % sb) as u64 + } + BinOp::Shl => { + if ub >= w as u64 { + return None; + } + ua.wrapping_shl(ub as u32) + } + BinOp::LShr => { + if ub >= w as u64 { + return None; + } + ua >> (ub as u32) + } + BinOp::AShr => { + if ub >= w as u64 { + return None; + } + (sext_i64(ua, w) >> (ub as u32)) as u64 + } + }; + Some(r & mask) +} + +fn eval_icmp(p: Pred, w: u32, ua: u64, ub: u64) -> Option<bool> { + let mask = mask_for(w); + let ua = ua & mask; + let ub = ub & mask; + let (sa, sb) = (sext_i64(ua, w), sext_i64(ub, w)); + Some(match p { + Pred::Eq => ua == ub, + Pred::Ne => ua != ub, + Pred::UGt => ua > ub, + Pred::UGe => ua >= ub, + Pred::ULt => ua < ub, + Pred::ULe => ua <= ub, + Pred::SGt => sa > sb, + Pred::SGe => sa >= sb, + Pred::SLt => sa < sb, + Pred::SLe => sa <= sb, + _ => return None, + }) +} + +fn make_not_op(m: &mut Module, x: Value) -> Op { + if let Value::Inst(xi) = x { + if let Op::Cmp(p, a, b) = m.insts[xi as usize].op { + return Op::Cmp(invert_pred(p), a, b); + } + } + let t = m.i1c(true); + Op::Bin(BinOp::Xor, x, t, 0) +} + +fn unwrap_bitcast_src(m: &mut Module, v: Value, dst: Ty) -> Option<Value> { + if m.value_ty(v) == dst { + return Some(v); + } + if let Some(c) = const_bitcast(m, v, dst) { + return Some(c); + } + if let Value::Inst(id) = v { + if let Op::Cast(CastOp::BitCast, inner, _) = m.insts[id as usize].op { + if m.value_ty(inner) == dst { + return Some(inner); + } + } + } + None +} + +fn simplify_int_bin(m: &mut Module, id: u32, ty: Ty, w: u32) -> Result<Value, Option<Op>> { + let Op::Bin(op, mut a, mut b, _flags) = m.insts[id as usize].op else { + return Err(None); + }; + if matches!(op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) + && const_int_u64(m, a).is_some() + && const_int_u64(m, b).is_none() + { + std::mem::swap(&mut a, &mut b); + return simplify_rewritten_bin(m, ty, w, op, a, b, true); + } + simplify_rewritten_bin(m, ty, w, op, a, b, false) +} + +fn simplify_rewritten_bin( + m: &mut Module, ty: Ty, w: u32, op: BinOp, a: Value, b: Value, swapped: bool, +) -> Result<Value, Option<Op>> { + let mask = mask_for(w); + let ca = const_int_u64(m, a); + let cb = const_int_u64(m, b); + if let (Some(ua), Some(ub)) = (ca, cb) { + if let Some(r) = eval_int_binop(op, w, ua, ub) { + return Ok(m.const_int(ty, r)); + } + } + + // Reassociate `(inner_op x, c1) outer_op c2` when `b = c2`. + if let (Value::Inst(ai), Some(c2)) = (a, cb) { + if let Op::Bin(op1, x, c1_val, _) = m.insts[ai as usize].op { + if let Some(c1) = const_int_u64(m, c1_val) { + let reassociated: Option<(BinOp, u64)> = match (op1, op) { + (BinOp::Add, BinOp::Add) => Some((BinOp::Add, c1.wrapping_add(c2) & mask)), + (BinOp::Sub, BinOp::Add) => Some((BinOp::Add, c2.wrapping_sub(c1) & mask)), + (BinOp::Add, BinOp::Sub) => Some((BinOp::Add, c1.wrapping_sub(c2) & mask)), + (BinOp::Sub, BinOp::Sub) => Some((BinOp::Add, 0u64.wrapping_sub(c1.wrapping_add(c2)) & mask)), + (BinOp::Mul, BinOp::Mul) => Some((BinOp::Mul, c1.wrapping_mul(c2) & mask)), + (BinOp::And, BinOp::And) => Some((BinOp::And, c1 & c2)), + (BinOp::Or, BinOp::Or) => Some((BinOp::Or, c1 | c2)), + (BinOp::Xor, BinOp::Xor) => Some((BinOp::Xor, c1 ^ c2)), + (BinOp::Shl, BinOp::Shl) + | (BinOp::LShr, BinOp::LShr) + | (BinOp::AShr, BinOp::AShr) + if (c1 as u128 + c2 as u128) < w as u128 => + { + Some((op, c1 + c2)) + } + _ => None, + }; + if let Some((new_op, nc)) = reassociated { + let nc_val = m.const_int(ty, nc); + // Apply immediate identity check (e.g. `(x ^ c) ^ c -> x`). + if let Ok(folded) = simplify_rewritten_bin(m, ty, w, new_op, x, nc_val, true) { + return Ok(folded); + } + return Err(Some(Op::Bin(new_op, x, nc_val, 0))); + } + } + } + } + + match op { + BinOp::Add => { + if cb == Some(0) { + return Ok(a); + } + if a == b && w == 1 { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Sub => { + if cb == Some(0) { + return Ok(a); + } + if a == b { + return Ok(m.const_int(ty, 0)); + } + if ca == Some(0) && w == 1 { + return Ok(b); + } + if let Some(c) = cb { + let neg = (0u64.wrapping_sub(c)) & mask; + let neg_val = m.const_int(ty, neg); + return Err(Some(Op::Bin(BinOp::Add, a, neg_val, 0))); + } + } + BinOp::Mul => { + if cb == Some(0) { + return Ok(m.const_int(ty, 0)); + } + if cb == Some(1) { + return Ok(a); + } + if a == b && w == 1 { + return Ok(a); + } + } + BinOp::UDiv | BinOp::SDiv => { + if cb == Some(1) { + return Ok(a); + } + } + BinOp::URem | BinOp::SRem => { + if cb == Some(1) { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Shl | BinOp::LShr | BinOp::AShr => { + if cb == Some(0) { + return Ok(a); + } + } + BinOp::And => { + if cb == Some(0) { + return Ok(m.const_int(ty, 0)); + } + if cb == Some(mask) || a == b { + return Ok(a); + } + // `x & ~x == 0` + let is_comp = |lhs: Value, rhs: Value| -> bool { + let Value::Inst(ri) = rhs else { return false }; + if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op { + (x == lhs && const_int_u64(m, y) == Some(mask)) + || (y == lhs && const_int_u64(m, x) == Some(mask)) + } else { + false + } + }; + if is_comp(a, b) || is_comp(b, a) { + return Ok(m.const_int(ty, 0)); + } + } + BinOp::Or => { + if cb == Some(0) || a == b { + return Ok(a); + } + if cb == Some(mask) { + return Ok(m.const_int(ty, mask)); + } + let is_comp = |lhs: Value, rhs: Value| -> bool { + let Value::Inst(ri) = rhs else { return false }; + if let Op::Bin(BinOp::Xor, x, y, _) = m.insts[ri as usize].op { + (x == lhs && const_int_u64(m, y) == Some(mask)) + || (y == lhs && const_int_u64(m, x) == Some(mask)) + } else { + false + } + }; + if is_comp(a, b) || is_comp(b, a) { + return Ok(m.const_int(ty, mask)); + } + } + BinOp::Xor => { + if cb == Some(0) { + return Ok(a); + } + if a == b { + return Ok(m.const_int(ty, 0)); + } + // `(x ^ y) ^ y -> x` + if let Value::Inst(ai) = a { + if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[ai as usize].op { + if v == b { + return Ok(u); + } + if u == b { + return Ok(v); + } + } + } + if let Value::Inst(bi) = b { + if let Op::Bin(BinOp::Xor, u, v, _) = m.insts[bi as usize].op { + if v == a { + return Ok(u); + } + if u == a { + return Ok(v); + } + } + } + // `xor(cmp(p, u, v), true) -> cmp(invert(p), u, v)` + if cb == Some(1) && w == 1 { + if let Value::Inst(ai) = a { + if let Op::Cmp(p, u, v) = m.insts[ai as usize].op { + return Err(Some(Op::Cmp(invert_pred(p), u, v))); + } + } + } + } + } + + if swapped { + Err(Some(Op::Bin(op, a, b, 0))) + } else { + Err(None) + } +} + +fn simplify_cast(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Cast(op, v, dst) = m.insts[id as usize].op else { + return Err(None); + }; + let src = m.value_ty(v); + if src == dst && matches!(op, CastOp::Trunc | CastOp::ZExt | CastOp::SExt | CastOp::FPTrunc | CastOp::FPExt | CastOp::BitCast) { + return Ok(v); + } + + match op { + CastOp::Trunc | CastOp::ZExt => { + if let (Some(uv), Some(_)) = (const_int_u64(m, v), m.int_width(dst)) { + return Ok(m.const_int(dst, uv)); + } + } + CastOp::SExt => { + if let (Some(uv), Some(sw), Some(_)) = (const_int_u64(m, v), m.int_width(src), m.int_width(dst)) { + let sv = sext_i64(uv, sw); + return Ok(m.const_int(dst, sv as u64)); + } + } + CastOp::BitCast => { + if let Some(c) = const_bitcast(m, v, dst) { + return Ok(c); + } + } + _ => {} + } + + if let Value::Inst(vi) = v { + match (op, m.insts[vi as usize].op.clone()) { + (CastOp::Trunc, Op::Cast(CastOp::Trunc, x, _)) => return Err(Some(Op::Cast(CastOp::Trunc, x, dst))), + (CastOp::ZExt, Op::Cast(CastOp::ZExt, x, _)) => return Err(Some(Op::Cast(CastOp::ZExt, x, dst))), + (CastOp::SExt, Op::Cast(CastOp::SExt, x, _)) => return Err(Some(Op::Cast(CastOp::SExt, x, dst))), + (CastOp::SExt, Op::Cast(CastOp::ZExt, x, _)) => { + if let (Some(wx), Some(wsrc)) = (m.int_width(m.value_ty(x)), m.int_width(src)) { + if wx < wsrc { + return Err(Some(Op::Cast(CastOp::ZExt, x, dst))); + } + } + } + (CastOp::Trunc, Op::Cast(CastOp::ZExt, x, _)) => { + if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) { + if wx == wd { + return Ok(x); + } else if wx > wd { + return Err(Some(Op::Cast(CastOp::Trunc, x, dst))); + } else { + return Err(Some(Op::Cast(CastOp::ZExt, x, dst))); + } + } + } + (CastOp::Trunc, Op::Cast(CastOp::SExt, x, _)) => { + if let (Some(wx), Some(wd)) = (m.int_width(m.value_ty(x)), m.int_width(dst)) { + if wx == wd { + return Ok(x); + } else if wx > wd { + return Err(Some(Op::Cast(CastOp::Trunc, x, dst))); + } else { + return Err(Some(Op::Cast(CastOp::SExt, x, dst))); + } + } + } + (CastOp::BitCast, Op::Cast(CastOp::BitCast, x, _)) => { + let xt = m.value_ty(x); + if xt == dst { + return Ok(x); + } + if scalar_bits(m, xt).is_some() && scalar_bits(m, xt) == scalar_bits(m, dst) { + return Err(Some(Op::Cast(CastOp::BitCast, x, dst))); + } + } + (CastOp::BitCast, Op::Select(c, a, b)) => { + if scalar_bits(m, src).is_some() && scalar_bits(m, src) == scalar_bits(m, dst) { + if let (Some(ua), Some(ub)) = (unwrap_bitcast_src(m, a, dst), unwrap_bitcast_src(m, b, dst)) { + if ua == ub { + return Ok(ua); + } + return Err(Some(Op::Select(c, ua, ub))); + } + } + } + _ => {} + } + } + + Err(None) +} + +fn simplify_cmp(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Cmp(mut p, mut a, mut b) = m.insts[id as usize].op else { + return Err(None); + }; + let ty = m.value_ty(a); + let Some(w) = m.int_width(ty) else { + return Err(None); + }; + let mut swapped = false; + if const_int_u64(m, a).is_some() && const_int_u64(m, b).is_none() { + std::mem::swap(&mut a, &mut b); + p = swap_pred(p); + swapped = true; + } + + if let (Some(ua), Some(ub)) = (const_int_u64(m, a), const_int_u64(m, b)) { + if let Some(res) = eval_icmp(p, w, ua, ub) { + return Ok(m.i1c(res)); + } + } + if a == b { + if let Some(res) = eval_icmp(p, w, 0, 0) { + return Ok(m.i1c(res)); + } + } + + let mask = mask_for(w); + if let Some(cb) = const_int_u64(m, b) { + if cb == 0 && p == Pred::ULt { + return Ok(m.i1c(false)); + } + if cb == 0 && p == Pred::UGe { + return Ok(m.i1c(true)); + } + if cb == mask && p == Pred::UGt { + return Ok(m.i1c(false)); + } + if cb == mask && p == Pred::ULe { + return Ok(m.i1c(true)); + } + if cb == 0 && p == Pred::ULe { + return Err(Some(Op::Cmp(Pred::Eq, a, b))); + } + if cb == 0 && p == Pred::UGt { + return Err(Some(Op::Cmp(Pred::Ne, a, b))); + } + if cb == mask && p == Pred::UGe { + return Err(Some(Op::Cmp(Pred::Eq, a, b))); + } + if cb == mask && p == Pred::ULt { + return Err(Some(Op::Cmp(Pred::Ne, a, b))); + } + + if w == 1 { + return match (p, cb) { + (Pred::Eq, 1) | (Pred::Ne, 0) => Ok(a), + (Pred::Eq, 0) | (Pred::Ne, 1) => Err(Some(make_not_op(m, a))), + _ => { + if swapped { + Err(Some(Op::Cmp(p, a, b))) + } else { + Err(None) + } + } + }; + } + + // Collapse `(zext i1 x) cmp k` and `(sext i1 x) cmp k` (`set_scc` / `scc_bit` idioms) + // and `select(c, const, const) cmp k`. + if let Value::Inst(ai) = a { + match m.insts[ai as usize].op { + Op::Cast(CastOp::ZExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => { + if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, 1, cb)) { + if f0 == f1 { + return Ok(m.i1c(f0)); + } + return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) }; + } + } + Op::Cast(CastOp::SExt, inner, _) if m.int_width(m.value_ty(inner)) == Some(1) => { + if let (Some(f0), Some(f1)) = (eval_icmp(p, w, 0, cb), eval_icmp(p, w, mask, cb)) { + if f0 == f1 { + return Ok(m.i1c(f0)); + } + return if f1 { Ok(inner) } else { Err(Some(make_not_op(m, inner))) }; + } + } + Op::Select(cond, tc, fc) => { + if let (Some(ct), Some(cf)) = (const_int_u64(m, tc), const_int_u64(m, fc)) { + if let (Some(bt), Some(bf)) = (eval_icmp(p, w, ct, cb), eval_icmp(p, w, cf, cb)) { + if bt == bf { + return Ok(m.i1c(bt)); + } + return if bt { Ok(cond) } else { Err(Some(make_not_op(m, cond))) }; + } + } + } + _ => {} + } + } + } + + if swapped { + Err(Some(Op::Cmp(p, a, b))) + } else { + Err(None) + } +} + +fn simplify_select(m: &mut Module, id: u32) -> Result<Value, Option<Op>> { + let Op::Select(c, mut t, mut f) = m.insts[id as usize].op else { + return Err(None); + }; + if let Some(cv) = const_int_u64(m, c) { + return Ok(if cv & 1 != 0 { t } else { f }); + } + if t == f { + return Ok(t); + } + if let Some(inner) = match_not_i1(m, c) { + return Err(Some(Op::Select(inner, f, t))); + } + + let ty = m.insts[id as usize].ty; + if m.int_width(ty) == Some(1) { + let ct = const_int_u64(m, t); + let cf = const_int_u64(m, f); + if ct == Some(1) && cf == Some(0) { + return Ok(c); + } + if ct == Some(0) && cf == Some(1) { + return Err(Some(make_not_op(m, c))); + } + if (t == c && cf == Some(0)) || (ct == Some(1) && f == c) { + return Ok(c); + } + if t == c && cf == Some(1) { + return Ok(m.i1c(true)); + } + if ct == Some(0) && f == c { + return Ok(m.i1c(false)); + } + } + + // `select c, (select c, t1, _), f -> select c, t1, f` (and analogously in `f`). + let mut folded_arm = false; + if let Value::Inst(ti) = t { + if let Op::Select(c2, t2, _) = m.insts[ti as usize].op { + if c2 == c { + t = t2; + folded_arm = true; + } + } + } + if let Value::Inst(fi) = f { + if let Op::Select(c2, _, f2) = m.insts[fi as usize].op { + if c2 == c { + f = f2; + folded_arm = true; + } + } + } + if folded_arm { + if t == f { + return Ok(t); + } + return Err(Some(Op::Select(c, t, f))); + } + + Err(None) +} + +fn simplify_pure_dxop_call(m: &mut Module, id: u32) -> Option<Value> { + let Op::Call(f, args) = &m.insts[id as usize].op else { return None }; + let name = &m.funcs[*f as usize].name; + let opc = args.first().and_then(|&v| const_int_u64(m, v))?; + + if is_op_name(name, "dx.op.unaryBits") && args.len() == 2 { + let uv = const_int_u64(m, args[1])?; + let sw = m.int_width(m.value_ty(args[1]))?; + let mask = mask_for(sw); + let u = uv & mask; + let res = match opc { + 31 => u.count_ones() as u64, + 32 => { + if u == 0 { + u32::MAX as u64 + } else { + u.trailing_zeros() as u64 + } + } + 33 => { + if u == 0 { + u32::MAX as u64 + } else { + (u.leading_zeros() - (64 - sw)) as u64 + } + } + 34 => { + let sign = (u >> (sw - 1)) & 1 != 0; + let bits = if sign { (!u) & mask } else { u }; + if bits == 0 { + u32::MAX as u64 + } else { + (bits.leading_zeros() - (64 - sw)) as u64 + } + } + _ => return None, + }; + return Some(m.i32c(res as u32)); + } + + if is_op_name(name, "dx.op.unary") && opc == 30 && args.len() == 2 { + let ty = m.insts[id as usize].ty; + let sw = m.int_width(ty)?; + let uv = const_int_u64(m, args[1])?; + let rev = (uv & mask_for(sw)).reverse_bits() >> (64 - sw); + return Some(m.const_int(ty, rev)); + } + + if is_op_name(name, "dx.op.binary") && (37..=40).contains(&opc) && args.len() == 3 { + let (a, b) = (args[1], args[2]); + if a == b { + return Some(a); + } + let ty = m.insts[id as usize].ty; + let sw = m.int_width(ty)?; + let (ua, ub) = (const_int_u64(m, a)?, const_int_u64(m, b)?); + let r = match opc { + 37 => (sext_i64(ua, sw).max(sext_i64(ub, sw))) as u64, + 38 => (sext_i64(ua, sw).min(sext_i64(ub, sw))) as u64, + 39 => ua.max(ub), + 40 => ua.min(ub), + _ => unreachable!(), + }; + return Some(m.const_int(ty, r)); + } + + None +} + +/// RPO constant folding, cast simplification, integer identities/reassociation, +/// comparison and select simplifications. +pub(super) fn simplify_insts(m: &mut Module) -> bool { + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut changed = false; + + for b in 0..m.blocks.len() { + let mut keep = Vec::with_capacity(m.blocks[b].len()); + let old_insts = std::mem::take(&mut m.blocks[b]); + for id in old_insts { + if rewrite_op_values(&mut m.insts[id as usize].op, &repl) { + changed = true; + } + if matches!(m.insts[id as usize].op, Op::Phi(..)) { + keep.push(id); + continue; + } + let ty = m.insts[id as usize].ty; + let simplified = match &m.insts[id as usize].op { + Op::Bin(..) => { + if let Some(w) = m.int_width(ty) { + simplify_int_bin(m, id, ty, w) + } else { + Err(None) + } + } + Op::Cast(..) => simplify_cast(m, id), + Op::Cmp(..) => simplify_cmp(m, id), + Op::Select(..) => simplify_select(m, id), + Op::Call(..) => match simplify_pure_dxop_call(m, id) { + Some(v) => Ok(v), + None => Err(None), + }, + _ => Err(None), + }; + match simplified { + Ok(v) if v != Value::Inst(id) => { + repl[id as usize] = Some(v); + changed = true; + } + Err(Some(new_op)) => { + m.insts[id as usize].op = new_op; + changed = true; + keep.push(id); + } + _ => keep.push(id), + } + } + m.blocks[b] = keep; + } + + if changed { + for b in 0..m.blocks.len() { + for &id in &m.blocks[b] { + if !matches!(m.insts[id as usize].op, Op::Phi(..)) { + break; + } + rewrite_op_values(&mut m.insts[id as usize].op, &repl); + } + } + rewrite_md_values(m, &repl); + } + + changed +} + +// --------------------------------------------------------- Dominator CSE + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum CseKey { + Bin(u8, Value, Value, u64), + Cast(u8, Value, Ty), + Cmp(u8, Value, Value), + Select(Value, Value, Value), + Extract(Value, u32), + Gep(Value, Vec<Value>), + Call(u32, Vec<Value>), +} + +fn cse_key(m: &Module, op: &Op) -> Option<CseKey> { + match op { + Op::Bin(bin_op, a, b, flags) => { + let (mut x, mut y) = (*a, *b); + if matches!(bin_op, BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor) && x > y { + std::mem::swap(&mut x, &mut y); + } + Some(CseKey::Bin(*bin_op as u8, x, y, *flags)) + } + Op::Cast(cop, v, ty) => Some(CseKey::Cast(*cop as u8, *v, *ty)), + Op::Cmp(p, a, b) => { + let (mut p, mut x, mut y) = (*p, *a, *b); + if x > y { + std::mem::swap(&mut x, &mut y); + p = swap_pred(p); + } + Some(CseKey::Cmp(p as u8, x, y)) + } + Op::Select(c, t, f) => Some(CseKey::Select(*c, *t, *f)), + Op::Extract(a, idx) => Some(CseKey::Extract(*a, *idx)), + Op::Gep(p, idx) => Some(CseKey::Gep(*p, idx.clone())), + Op::Call(f, args) => { + let fd = &m.funcs[*f as usize]; + if fd.attrs != FnAttrs::ReadNone { + return None; + } + // Implicit quad derivatives (`dx.op.unary` opcodes 83..=86) depend on + // CFG position even though declared `readnone`. Never CSE them. + if is_op_name(&fd.name, "dx.op.unary") { + let opc = args.first().and_then(|&v| const_int_u64(m, v)); + if !matches!(opc, Some(0..=30)) { + return None; + } + } + let mut norm_args = args.clone(); + if is_op_name(&fd.name, "dx.op.binary") + && norm_args.len() == 3 + && matches!(norm_args.first().and_then(|&v| const_int_u64(m, v)), Some(35..=40)) + && norm_args[1] > norm_args[2] + { + norm_args.swap(1, 2); + } + Some(CseKey::Call(*f, norm_args)) + } + _ => None, + } +} + +/// Dominator-tree scoped CSE assuming blocks `0..n` are already in RPO. +pub(super) fn cse(m: &mut Module) -> bool { + let n = m.blocks.len(); + if n == 0 { + return false; + } + + let idom = compute_idom(m); + let mut children: Vec<Vec<usize>> = vec![Vec::new(); n]; + for b in 1..n { + if let Some(p) = idom[b] { + children[p].push(b); + } + } + + enum DomFrame { + Enter(usize), + Exit(usize), + } + + let mut table: HashMap<CseKey, Value> = HashMap::new(); + let mut undo: Vec<CseKey> = Vec::new(); + let mut repl: Vec<Option<Value>> = vec![None; m.insts.len()]; + let mut changed = false; + let mut stack = vec![DomFrame::Enter(0)]; + + while let Some(frame) = stack.pop() { + match frame { + DomFrame::Enter(b) => { + let mark = undo.len(); + stack.push(DomFrame::Exit(mark)); ``` The replacement at `ce8c103` removes this branch’s CSE implementation and uses the optimizer from merged #1426. I checked its sibling scoping with a diamond test under Wine. Both arms compute the same expression, one arm repeats it, and the join PHI uses the two incoming values. The same-arm duplicate folded and each PHI edge kept its own arm’s definition (1 passed). T3 Code (Codex, gpt-6.2-astra) wrote and ran the probe.
This pull request has changes conflicting with the target branch.
  • crates/xcl/src/gpu/dxil/kernel.rs
  • crates/xcl/src/gpu/dxil/module.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1546/head:github-bot/gh-1546'
git switch 'github-bot/gh-1546'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1546'
git switch 'github-bot/gh-1546'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1546'
git switch 'github-bot/gh-1546'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1546'
git switch 'main'
git merge --squash 'github-bot/gh-1546'
git switch 'main'
git merge --ff-only 'github-bot/gh-1546'
git switch 'main'
git merge 'github-bot/gh-1546'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.