From 9dbe28bec7604679316c7a774cf03b56a95e4778 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:51:40 +0300 Subject: [PATCH] Recompiler: fold 64-bit ints, bitcast selects and commutative CSE in direct DXIL Extend `gpu::dxil::module::opt` to fold remaining post-phi redundancies in direct-DXIL shaders without colliding with CFG-level folding or violating DXC validator shader-flag invariants: - Enable 64-bit integer constant/identity folding and DCE (`i64` arithmetic, shifts, `LShr(ZExt)` / `LShr(Or(ZExt, Shl(ZExt)))` window-high patterns, `Trunc(ZExt|SExt)`, and `i1` / `ZExt(i1)` compares) and clear `Feature::Int64Ops` in `Shader::infer_type_features` when no surviving instruction uses `i64`. - Fold finite constant `BitCast` (`i32 <-> f32`, `i16 <-> f16`, excluding NaN and Inf in both directions), reuse dominating `BitCast`s from CSE, collapse nested same-condition `Select` chains, and push `BitCast` through `Select` only when the `Select` has no surviving non-bitcast uses (preventing select duplication). - Canonicalize commutative integer binops (`Add`/`Mul`/`And`/`Or`/`Xor`) and integer `Cmp` predicates before dominator CSE, separate `XCL_DXIL_NO_OPT=fold` from `cse`, and expand flag-neutral `ReadNone` intrinsic DCE. - Add validator + RTX 4060 GPU execution parity tests (direct-DXIL cache invalidation is automatic via `XCL_DIRECT_DXIL_SOURCE_ID`). On a 252-program validated direct-DXIL corpus sample (100% across CS/GS/MS/PS/VS): -3.25% DXIL bytes (-397 KB, 252/252 shrank), -6.33% instructions, -28.74% bitcasts, -2.30% selects, -38.32% i64 ops, 0 validator errors (and 0 errors across 977 programs in a 1,000-record sample). Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/core_tests.rs | 104 ++++++++++ crates/xcl/src/gpu/dxil/module/opt.rs | 277 ++++++++++++++++++++++---- crates/xcl/src/gpu/dxil/shader.rs | 2 + 3 files changed, 347 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index cb12a577f..a00f1f7e6 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -612,3 +612,107 @@ fn window_at_lowers_to_32bit_carry_without_int64() { assert!(!body0.contains("icmp ult"), "zero-offset window_at must not emit carry compare:\n{dis0}"); } } + +/// Post-phi folding: i64 window-high + `Int64Ops` cleanup, finite constant `BitCast` +/// (preserving Inf/NaN bitcasts), `bitcast(select)`, nested same-condition selects, +/// commutative integer/compare CSE, `zext(i1)` compares, and GPU execution parity. +#[test] +fn opt_folds_i64_bitcast_selects_and_commutative_cse() { + use super::{container::Stage, module::{BinOp, CastOp, Pred}, shader::{Feature, Shader}, validate}; + use crate::gpu::recomp::runner; + + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (io, res, lane) = (s.raw_uav(0, 0), s.raw_uav(1, 0), s.thread_id_in_group(0)); + let (i32t, f32t, i64t) = (s.m.i32(), s.m.f32(), s.m.i64()); + s.require(Feature::Int64Ops); + let (c0, c2, c4, c99) = (s.m.i32c(0), s.m.i32c(2), s.m.i32c(4), s.m.i32c(99)); + let (c32_64, k15, k25, kinf) = (s.m.const_int(i64t, 32), s.m.i32c(1.5f32.to_bits()), s.m.f32c(2.5f32.to_bits()), s.m.i32c(0x7F80_0000)); + let off = s.m.bin(BinOp::Shl, lane, c2); + let off4 = s.m.bin(BinOp::Add, off, c4); + let (a, b) = (s.raw_load(io, off, 1)[0], s.raw_load(io, off4, 1)[0]); + + // Commutative Add + flipped integer Cmp CSE and zext(i1) compare folding. + let (sum1, sum2) = (s.m.bin(BinOp::Add, a, b), s.m.bin(BinOp::Add, b, a)); + let diff = s.m.bin(BinOp::Sub, sum1, sum2); + let (cmp1, cmp2) = (s.m.cmp(Pred::ULt, a, b), s.m.cmp(Pred::UGt, b, a)); + let same_cmp = s.m.cmp(Pred::Eq, cmp1, cmp2); + let same_z = s.m.cast(CastOp::ZExt, same_cmp, i32t); + let same_b = s.m.cmp(Pred::Ne, same_z, c0); + + // 64-bit window-high extraction folds to 0 and drops Int64Ops cleanly. + let z64 = s.m.cast(CastOp::ZExt, a, i64t); + let shr64 = s.m.bin(BinOp::LShr, z64, c32_64); + let hi = s.m.cast(CastOp::Trunc, shr64, i32t); + + // Finite constant BitCast, nested same-condition Select, and bitcast(select(...)). + let f1 = s.m.bitcast(k15, f32t); + let f2 = s.m.fbin(BinOp::Add, f1, k25, 0); + let (b1, b2) = (s.m.bitcast(f1, i32t), s.m.bitcast(f2, i32t)); + let s1 = s.m.select(cmp1, b1, hi); + let s2 = s.m.select(cmp1, b2, s1); + let f_out = s.m.bitcast(s2, f32t); + let bits_out = s.m.bitcast(f_out, i32t); + + // Non-finite (+Inf) constant BitCast must not materialize an invalid float constant. + let inf_f = s.m.bitcast(kinf, f32t); + let inf_bits = s.m.bitcast(inf_f, i32t); + let inf_zero = s.m.bin(BinOp::Sub, inf_bits, kinf); + let extra = s.m.bin(BinOp::Add, diff, inf_zero); + let v0 = s.m.bin(BinOp::Add, bits_out, extra); + let out = s.m.select(same_b, v0, c99); + s.raw_store(res, off, &[out]); + let dxil = s.finish([32, 1, 1], Some(32)); + validate::validate(&dxil).expect("synthetic shader validates"); + let dis = validate::disassemble(&dxil).expect("disasm"); + assert!(!dis.contains("64-Bit integer") && !dis.contains("bitcast i32 1069547520"), "{dis}"); + + // Multi-window RDNA2 loop: i64 pack/unpack and float-const bitcasts fold away. + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 132)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 242)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 132), ("VSRC1", 0)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 240), ("VSRC1", 2)], None), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 242), ("VSRC1", 2)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 2), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None), + ]); + let dx4 = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }).expect("4w"); + validate::validate(&dx4).expect("4w validates"); + let dis4 = validate::disassemble(&dx4).expect("disasm4"); + assert!( + !dis4.contains("64-Bit integer") && !dis4.contains("bitcast i32 1065353216"), + "expected 4-window loop i64 and const bitcast to fold away:\n{dis4}" + ); + + if !matches!(runner::wave32_supported(), Ok(true)) { + return runner::skip_test("no wave32"); + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let mut sgpr = vec![0u32; 128]; + for l in 0..33 { + sgpr[l] = if l % 2 == 0 { 1 } else { 5 }; + } + let r = runner::run(&dxil, &runner::KernelState { sgpr, vgpr: vec![vec![0; 256]; 64], scc: 0 }, &[]).expect("GPU"); + for l in 0..32 { + assert_eq!(r.raw[l], if l % 2 == 0 { 4.0f32.to_bits() } else { 0 }, "lane {l}"); + } + let dx1 = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }).expect("1w"); + let hlsl = crate::gpu::recomp::translate(&code, &crate::gpu::recomp::Options { wave64: false, ..Default::default() }) + .expect("hlsl") + .hlsl; + let dxc = crate::gpu::recomp::dxc::compile(&hlsl, "main", "cs_6_6", &[]).expect("dxc"); + let mut state = runner::KernelState { sgpr: vec![0u32; 128], vgpr: vec![vec![0; 256]; 64], scc: 0 }; + for l in 0..32 { + state.vgpr[l][0] = (l as u32) * 4; + } + let mem: Vec = (0..64).map(|i| i * 7 + 1).collect(); + let got = runner::run(&dx1, &state, &mem).expect("direct"); + let want = runner::run(&dxc, &state, &mem).expect("hlsl"); + for l in 0..32 { + assert_eq!(got.vgpr[l][2..=3], want.vgpr[l][2..=3], "lane {l}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 7a3454d53..43afa2e14 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; -use super::{BinOp, Block, CastOp, FnAttrs, Module, Op, Pred, Ty, Value}; +use super::{BinOp, Block, CastOp, ConstDef, FnAttrs, Module, Op, Pred, Ty, TypeDef, Value}; impl Op { /// Calls `f` on every value operand. @@ -105,10 +105,108 @@ impl Module { } } + fn zext_src(&self, v: Value) -> Option<(Value, u32)> { + let Value::Inst(j) = v else { return None }; + let Op::Cast(CastOp::ZExt, inner, _) = self.insts[j as usize].op else { return None }; + self.int_width(self.value_ty(inner)).map(|sw| (inner, sw)) + } + + /// Reinterprets `v` as `to` for free: inverse `BitCast`, dominating `BitCast` in CSE, + /// or finite constant bitcast (excluding NaN and Inf in both directions). + fn free_bitcast(&mut self, v: Value, to: Ty, table: &HashMap<(Op, Ty), Value>) -> Option { + let from = self.value_ty(v); + if self.types[from.0 as usize] == TypeDef::Double || self.types[to.0 as usize] == TypeDef::Double { + return None; + } + if let Value::Inst(j) = v { + if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + } + if let Some(&hit) = table.get(&(Op::Cast(CastOp::BitCast, v, to), to)) { + return Some(hit); + } + let fbits = |v| match v { + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Float(_, b) => Some(*b), + ConstDef::Null(t) if self.is_float(*t) => Some(0), + _ => None, + }, + _ => None, + }; + match (&self.types[from.0 as usize], &self.types[to.0 as usize]) { + (TypeDef::Int(32), TypeDef::Float) => self.const_u64(v).filter(|&b| (b as u32 & 0x7FFF_FFFF) < 0x7F80_0000).map(|b| self.const_float(to, b & 0xFFFF_FFFF)), + (TypeDef::Float, TypeDef::Int(32)) => fbits(v).filter(|&b| (b as u32 & 0x7FFF_FFFF) < 0x7F80_0000).map(|b| self.const_int(to, b & 0xFFFF_FFFF)), + (TypeDef::Int(16), TypeDef::Half) => self.const_u64(v).filter(|&b| (b as u16 & 0x7FFF) < 0x7C00).map(|b| self.const_float(to, b & 0xFFFF)), + (TypeDef::Half, TypeDef::Int(16)) => fbits(v).filter(|&b| (b as u16 & 0x7FFF) < 0x7C00).map(|b| self.const_int(to, b & 0xFFFF)), + _ => None, + } + } + + /// Pushes `bitcast(select(c, a, b), to)` into `select` in place when `select` has no + /// non-bitcast uses (so the original select dies in DCE) and both arms convert for free, + /// returning the original `(op, ty)` so CSE can still reuse the bitcast key in dominated blocks. + fn simplify_bitcast_select(&mut self, op: &mut Op, repl: &mut [Option], table: &HashMap<(Op, Ty), Value>, bc_only: &[Option>]) -> Option<(Op, Ty)> { + let Op::Cast(CastOp::BitCast, Value::Inst(j), to) = *op else { return None }; + if bc_only[j as usize] != Some(Some(to)) { + return None; + } + let Op::Select(c, t, f) = self.insts[j as usize].op else { return None }; + let nt = self.free_bitcast(resolve(repl, t), to, table)?; + let nf = self.free_bitcast(resolve(repl, f), to, table)?; + let orig = (op.clone(), to); + *op = Op::Select(resolve(repl, c), resolve(repl, nt), resolve(repl, nf)); + Some(orig) + } + + /// Collapses nested same-condition selects (`select(c, t, select(c, _, f)) -> select(c, t, f)`). + fn simplify_select(&self, op: &mut Op, ty: Ty, repl: &mut [Option]) { + let Op::Select(c, t, f) = op else { return }; + if self.types[ty.0 as usize] == TypeDef::Double { + return; + } + if let Value::Inst(j) = *f { + if let Op::Select(c2, _, f2) = self.insts[j as usize].op { + if resolve(repl, c2) == *c { + *f = resolve(repl, f2); + } + } + } + if let Value::Inst(j) = *t { + if let Op::Select(c2, t2, _) = self.insts[j as usize].op { + if resolve(repl, c2) == *c { + *t = resolve(repl, t2); + } + } + } + } + + /// Canonicalizes operand order on commutative integer ops and integer compares for CSE. + fn canonicalize_commutative(&self, op: &mut Op, ty: Ty) { + match op { + Op::Bin(BinOp::Add | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor, a, b, _) + if self.int_width(ty).is_some() && *b < *a => std::mem::swap(a, b), + Op::Cmp(p, a, b) if self.int_width(self.value_ty(*a)).is_some() && *b < *a => { + *p = match *p { + Pred::Eq => Pred::Eq, Pred::Ne => Pred::Ne, + 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, + _ => return, + }; + std::mem::swap(a, b); + } + _ => {} + } + } + /// Cheap algebraic & constant simplification on already-resolved operands. - fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { - // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. - if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + fn simplify_op(&mut self, op: &Op, ty: Ty, table: &HashMap<(Op, Ty), Value>) -> Option { + // Keep f64 instructions intact so Doubles / DoubleExtensions shader flags stay consistent. + if matches!(self.types[ty.0 as usize], TypeDef::Double) { return None; } match *op { @@ -119,18 +217,19 @@ impl Module { match self.const_u64(c) { Some(1) => Some(t), Some(0) => Some(f), - _ => None, + _ => (self.int_width(ty) == Some(1) && self.const_u64(t) == Some(1) && self.const_u64(f) == Some(0)) + .then_some(c), } } Op::Bin(bop, a, b, 0) => { let w = self.int_width(ty)?; - // avoid dropping 64-bit ops that keep Int64Ops shader flags consistent - if w > 32 { + if w > 64 { return None; } - let mask = (1u64 << w) - 1; + let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 }; let (ca, cb) = (self.const_u64(a), self.const_u64(b)); if let (Some(x), Some(y)) = (ca, cb) { + let sx = if w >= 64 { x as i64 } else { ((x << (64 - w)) as i64) >> (64 - w) }; let r = match bop { BinOp::Add => Some(x.wrapping_add(y)), BinOp::Sub => Some(x.wrapping_sub(y)), @@ -140,7 +239,7 @@ impl Module { BinOp::Xor => Some(x ^ y), BinOp::Shl if y < w as u64 => Some(x << y), BinOp::LShr if y < w as u64 => Some(x >> y), - BinOp::AShr if y < w as u64 => Some((((x << (64 - w)) as i64) >> (64 - w + y as u32)) as u64), + BinOp::AShr if y < w as u64 => Some((sx >> (y as u32)) as u64), BinOp::UDiv if y != 0 => Some(x / y), BinOp::URem if y != 0 => Some(x % y), _ => None, @@ -152,6 +251,7 @@ impl Module { match (bop, cb) { (BinOp::Add | BinOp::Sub | BinOp::Or | BinOp::Xor | BinOp::Shl | BinOp::LShr | BinOp::AShr, Some(0)) => return Some(a), (BinOp::And, Some(m)) if m == mask => return Some(a), + (BinOp::Or, Some(m)) if m == mask => return Some(b), (BinOp::And | BinOp::Mul, Some(0)) => return Some(b), (BinOp::Mul, Some(1)) => return Some(a), _ => {} @@ -159,7 +259,8 @@ impl Module { match (bop, ca) { (BinOp::Add | BinOp::Or | BinOp::Xor, Some(0)) => return Some(b), (BinOp::And, Some(m)) if m == mask => return Some(b), - (BinOp::And | BinOp::Mul | BinOp::Shl | BinOp::LShr, Some(0)) => return Some(a), + (BinOp::Or, Some(m)) if m == mask => return Some(a), + (BinOp::And | BinOp::Mul | BinOp::Shl | BinOp::LShr | BinOp::AShr, Some(0)) => return Some(a), (BinOp::Mul, Some(1)) => return Some(b), _ => {} } @@ -170,16 +271,41 @@ impl Module { _ => {} } } + if bop == BinOp::LShr { + if let Some(sh) = cb.filter(|&sh| sh < w as u64) { + if self.zext_src(a).is_some_and(|(_, sw)| sh >= sw as u64) { + return Some(self.const_int(ty, 0)); + } + if let Value::Inst(j) = a { + if let Op::Bin(BinOp::Or, x, y, 0) = self.insts[j as usize].op { + for (lo, hi) in [(x, y), (y, x)] { + let lo_cleared = self.const_u64(lo) == Some(0) + || self.zext_src(lo).is_some_and(|(_, sw)| sh >= sw as u64); + if let (true, Value::Inst(hj)) = (lo_cleared, hi) { + if let Op::Bin(BinOp::Shl, z, k, 0) = self.insts[hj as usize].op { + if self.const_u64(k) == Some(sh) + && self.zext_src(z).is_some_and(|(_, sw)| (sw as u64) + sh <= w as u64) + { + return Some(z); + } + } + } + } + } + } + } + } None } Op::Cmp(p, a, b) => { let at = self.value_ty(a); let w = self.int_width(at)?; - if w > 32 { + if w > 64 { return None; } - if let (Some(x), Some(y)) = (self.const_u64(a), self.const_u64(b)) { - let sx = |v: u64| ((v << (64 - w)) as i64) >> (64 - w); + let (ca, cb) = (self.const_u64(a), self.const_u64(b)); + if let (Some(x), Some(y)) = (ca, cb) { + let sx = |v: u64| if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; let r = match p { Pred::Eq => Some(x == y), Pred::Ne => Some(x != y), @@ -207,29 +333,53 @@ impl Module { return Some(self.const_int(ty, r as u64)); } } - None - } - Op::Cast(CastOp::BitCast, Value::Inst(j), to) => { - if matches!(self.types[self.insts[j as usize].ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { - return None; + if w == 1 { + if matches!((p, cb), (Pred::Eq, Some(1)) | (Pred::Ne, Some(0))) { + return Some(a); + } + if matches!((p, ca), (Pred::Eq, Some(1)) | (Pred::Ne, Some(0))) { + return Some(b); + } } - if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { - if self.value_ty(inner) == to { + if let Some((inner, 1)) = self.zext_src(a) { + if matches!((p, cb), (Pred::Ne | Pred::UGt, Some(0)) | (Pred::Eq, Some(1))) { + return Some(inner); + } + } + if let Some((inner, 1)) = self.zext_src(b) { + if matches!((p, ca), (Pred::Ne | Pred::ULt, Some(0)) | (Pred::Eq, Some(1))) { return Some(inner); } } None } + Op::Cast(CastOp::BitCast, v, to) => self.free_bitcast(v, to, table), Op::Cast(cop @ (CastOp::ZExt | CastOp::SExt | CastOp::Trunc), v, to) => { let sw = self.int_width(self.value_ty(v))?; let dw = self.int_width(to)?; - if sw > 32 || dw > 32 { + if sw > 64 || dw > 64 { return None; } + if sw == dw { + return Some(v); + } + if cop == CastOp::Trunc { + if let Value::Inst(j) = v { + if let Op::Cast(CastOp::ZExt | CastOp::SExt, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + } + } let x = self.const_u64(v)?; + let dm = if dw >= 64 { u64::MAX } else { (1u64 << dw) - 1 }; let r = match cop { - CastOp::ZExt | CastOp::Trunc => x & ((1u64 << dw) - 1), - CastOp::SExt => ((((x << (64 - sw)) as i64) >> (64 - sw)) as u64) & ((1u64 << dw) - 1), + CastOp::ZExt | CastOp::Trunc => x & dm, + CastOp::SExt => { + let sx = if sw >= 64 { x as i64 } else { ((x << (64 - sw)) as i64) >> (64 - sw) }; + (sx as u64) & dm + } _ => unreachable!(), }; Some(self.const_int(to, r)) @@ -238,8 +388,8 @@ impl Module { } } - /// Whether an unused instruction can go. 64-bit values stay: helpers already set - /// the Int64Ops / Doubles / DoubleExtensions flags for them. + /// Whether an unused instruction can go. Double values stay: helpers already set + /// the Doubles / DoubleExtensions flags for them (`Int64Ops` is refreshed in `infer_type_features`). fn removable(&self, op: &Op, ty: Ty, wide: &[Ty]) -> bool { if wide.contains(&ty) { return false; @@ -257,9 +407,15 @@ impl Module { let d = &self.funcs[*f as usize]; matches!(d.attrs, FnAttrs::ReadNone | FnAttrs::ReadOnly) && !d.name.ends_with(".f64") - && ["dx.op.unary.", "dx.op.binary.", "dx.op.tertiary.", "dx.op.loadInput.", "dx.op.annotateHandle", "dx.op.createHandleFromBinding", "dx.op.cbufferLoadLegacy."] - .iter() - .any(|p| d.name.starts_with(p)) + && [ + "dx.op.unary.", "dx.op.unaryBits.", "dx.op.binary.", "dx.op.tertiary.", "dx.op.quaternary.", + "dx.op.dot", "dx.op.legacyF16ToF32", "dx.op.legacyF32ToF16", "dx.op.bitcast", + "dx.op.isSpecialFloat.", "dx.op.threadId", "dx.op.groupId.", "dx.op.flattenedThreadIdInGroup.", + "dx.op.loadInput.", "dx.op.annotateHandle", "dx.op.createHandleFromBinding", + "dx.op.cbufferLoadLegacy.", + ] + .iter() + .any(|p| d.name.starts_with(p)) } _ => false, } @@ -347,7 +503,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,fold,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -428,7 +584,42 @@ impl Module { Enter(usize), Leave(usize), } - let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let (do_fold, do_cse) = (!skip("fold"), !skip("cse")); + // None = unseen, Some(Some(to)) = only used by BitCast(_, to), Some(None) = other use. + let mut bc_only: Vec>> = vec![None; if do_fold { self.insts.len() } else { 0 }]; + if do_fold { + for &b in &order { + for &u in &self.blocks[b as usize] { + if repl[u as usize].is_some() { + continue; + } + match self.insts[u as usize].op { + Op::Cast(CastOp::BitCast, v, to) => if let Value::Inst(j) = resolve(&mut repl, v) { + bc_only[j as usize] = match bc_only[j as usize] { + None => Some(Some(to)), + Some(Some(prev)) if prev == to => Some(Some(to)), + _ => Some(None), + }; + }, + Op::Select(c, t, f) if self.types[self.insts[u as usize].ty.0 as usize] != TypeDef::Double => { + let rc = resolve(&mut repl, c); + if let Value::Inst(j) = rc { bc_only[j as usize] = Some(None); } + for arm in [t, f] { + if let Value::Inst(j) = resolve(&mut repl, arm) { + if !matches!(self.insts[j as usize].op, Op::Select(c2, _, _) if resolve(&mut repl, c2) == rc) { + bc_only[j as usize] = Some(None); + } + } + } + } + _ => self.insts[u as usize].op.for_each_operand(|v| { + if let Value::Inst(j) = resolve(&mut repl, v) { bc_only[j as usize] = Some(None); } + }), + } + } + } + } + let mut stack = if !do_fold && !do_cse { Vec::new() } else { vec![Step::Enter(0)] }; let mut cse_replaced = false; while let Some(step) = stack.pop() { let b = match step { @@ -448,16 +639,26 @@ impl Module { let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); for k in 0..self.blocks[b].len() { let i = self.blocks[b][k] as usize; + let ty = self.insts[i].ty; let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); op.map_operands(|v| resolve(&mut repl, v)); if repl[i].is_none() { - if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { - repl[i] = Some(s); - cse_replaced = true; + let alias_key = if do_fold { + let k = self.simplify_bitcast_select(&mut op, &mut repl, &table, &bc_only); + self.simplify_select(&mut op, ty, &mut repl); + if let Some(s) = self.simplify_op(&op, ty, &table) { + repl[i] = Some(resolve(&mut repl, s)); + cse_replaced = true; + } + k } else { + None + }; + if repl[i].is_none() && do_cse { + self.canonicalize_commutative(&mut op, ty); let kind = self.cse_kind(&op); if kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); + let key = (op.clone(), ty); let t = if kind == Cse::Dom { &mut table } else { &mut local }; if let Some(&v) = t.get(&key) { repl[i] = Some(v); @@ -474,6 +675,10 @@ impl Module { local.clear(); } } + if let (true, Some(akey)) = (do_cse, alias_key) { + let old = table.insert(akey.clone(), repl[i].unwrap_or(Value::Inst(i as u32))); + undo.push((akey, old)); + } } self.insts[i].op = op; } @@ -526,8 +731,8 @@ impl Module { } // dead instructions: live = side effects, terminators and their operands, transitively - let (i64t, f64t) = self.existing_i64_f64(); - let wide: Vec = i64t.into_iter().chain(f64t).collect(); + let (_, f64t) = self.existing_i64_f64(); + let wide: Vec = f64t.into_iter().collect(); let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); for &b in &order { diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index 5e77eb659..2f8666164 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -492,6 +492,8 @@ impl Shader { let (i64, f64) = self.m.existing_i64_f64(); if i64.is_some_and(|t| self.m.insts_use_type(t)) { self.require(Feature::Int64Ops); + } else { + self.features.remove(&Feature::Int64Ops); } if f64.is_some_and(|t| self.m.insts_use_type(t)) { self.require(Feature::Doubles);