diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 0668b8043..f8b399583 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -947,8 +947,7 @@ impl Shader { let outs = io.place(Dir::Out); let prims = io.place(Dir::Prim); - let mut flags: u64 = self.features.iter().map(|f| f.metadata_bit()).fold(0, |a, b| a | b); - let mut sfi0: u64 = self.features.iter().map(|f| f.container_bit()).fold(0, |a, b| a | b); + let (mut flags, mut sfi0) = self.feature_flags(); let rt_vp = outs.iter().chain(&prims).any(|e| matches!(e.e.kind, SemKind::RenderTargetArrayIndex | SemKind::ViewportArrayIndex)); // DXC sets this for vertex shaders only (not for mesh shaders). if rt_vp && self.stage == Stage::Vertex { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 3b8c98449..71a0402b1 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -37,7 +37,7 @@ pub struct KernelOptions { /// Version of the direct translator's output, part of the on-disk translation cache's /// identity (`recomp::pso`): bump it on any change that alters the emitted containers /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 8; +pub const TRANSLATOR_VERSION: u32 = 9; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index a171fd099..171de5610 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -174,6 +174,7 @@ impl Lw { } /// `mad_nf`: separately rounded multiply and add (`precise`). pub fn mad_nf(&mut self, a: Value, b: Value, c: Value) -> Value { + self.s.require(super::shader::Feature::DisableMathRefactoring); let p = self.fmul(a, b); self.fadd(p, c) } @@ -486,3 +487,154 @@ impl Lw { self.land(eq, lz) } } + +#[cfg(test)] +mod disable_math_refactoring_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2; + use crate::gpu::recomp::PsInterface; + + fn opts() -> KernelOptions { + KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 } + } + + /// Parses the entry-point shader flags (`!dx.entryPoints` property tag `0`) + /// from DXIL disassembly. Returns `0` if tag `0` is absent. + fn entry_point_flags(dis: &str) -> u64 { + let props_id = dis + .lines() + .find_map(|line| { + if !line.contains("!\"main\"") { + return None; + } + let start = line.rfind('!')?; + let rest = &line[start..]; + let end = rest.find(|c: char| !c.is_ascii_digit() && c != '!').unwrap_or(rest.len()); + Some(&rest[..end]) + }) + .expect("entry point metadata node"); + let props_line = dis + .lines() + .find(|line| line.trim_start().starts_with(&format!("{props_id} ="))) + .expect("entry point properties node"); + let marker = "i32 0, i64 "; + let Some(idx) = props_line.find(marker) else { + return 0; + }; + let rest = &props_line[idx + marker.len()..]; + let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()); + rest[..end].parse::().expect("valid u64 flags") + } + + fn v_mad_f32(vdst: u64, s0: u64, s1: u64, s2: u64) -> Vec { + rdna2::encode("V_MAD_F32", "ENC_VOP3", &[("VDST", vdst), ("SRC0", 256 + s0), ("SRC1", 256 + s1), ("SRC2", 256 + s2)], None).unwrap() + } + + fn v_mac_f32(vdst: u64, s0: u64, s1: u64) -> Vec { + rdna2::encode("V_MAC_F32", "ENC_VOP2", &[("VDST", vdst), ("SRC0", 256 + s0), ("VSRC1", s1)], None).unwrap() + } + + fn v_fma_f32(vdst: u64, s0: u64, s1: u64, s2: u64) -> Vec { + rdna2::encode("V_FMA_F32", "ENC_VOP3", &[("VDST", vdst), ("SRC0", 256 + s0), ("SRC1", 256 + s1), ("SRC2", 256 + s2)], None).unwrap() + } + + fn v_add_f32(vdst: u64, s0: u64, s1: u64) -> Vec { + rdna2::encode("V_ADD_F32", "ENC_VOP2", &[("VDST", vdst), ("SRC0", 256 + s0), ("VSRC1", s1)], None).unwrap() + } + + fn s_endpgm() -> Vec { + rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap() + } + + #[test] + fn compute_unfused_mad_sets_disable_math_refactoring() { + for inst in [v_mad_f32(3, 0, 1, 2), v_mac_f32(2, 0, 1)] { + let mut code = inst; + code.extend(s_endpgm()); + let dxil = kernel::translate(&code, opts()).expect("translate compute unfused mad"); + validate::validate(&dxil).expect("dxil validate compute unfused mad"); + let dis = validate::disassemble(&dxil).expect("disassemble compute unfused mad"); + let flags = entry_point_flags(&dis); + assert_ne!(flags & (1 << 1), 0, "expected DisableMathRefactoring (bit 1) in flags={flags:#x}:\n{dis}"); + } + } + + fn ps_with_pos() -> PsInterface { + use crate::gpu::dxbc::SigElement; + // SPI_PS_INPUT_ENA bits 8..11: SV_Position.xyzw in v0..v3; SV_Target0 so EXP TGT=0 stays live. + PsInterface { + inputs: vec![SigElement { name: "SV_Position".into(), index: 0, system_value: 1, component_type: 3, register: 0, mask: 0xF, rw_mask: 0xF, stream: 0 }], + outputs: vec![SigElement { name: "SV_Target".into(), index: 0, system_value: 64, component_type: 3, register: 0, mask: 0xF, rw_mask: 0xF, stream: 0 }], + input_ena: 0x0F00, + attrs: None, + } + } + + #[test] + fn pixel_unfused_mad_sets_disable_math_refactoring() { + let mut code = v_mad_f32(3, 0, 1, 2); + code.extend(rdna2::encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 3), ("VSRC1", 3), ("VSRC2", 3), ("VSRC3", 3), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(s_endpgm()); + let ps = ps_with_pos(); + let k = kernel::translate_pixel(&code, opts(), &ps).expect("translate pixel unfused mad"); + validate::validate(&k.dxil).expect("dxil validate pixel unfused mad"); + let dis = validate::disassemble(&k.dxil).expect("disassemble pixel unfused mad"); + assert!(dis.contains("fmul float") && dis.contains("fadd float"), "expected live fmul+fadd:\n{dis}"); + let flags = entry_point_flags(&dis); + assert_ne!(flags & (1 << 1), 0, "expected DisableMathRefactoring (bit 1) in pixel flags={flags:#x}:\n{dis}"); + } + + #[test] + fn fmad_suppresses_disable_math_refactoring_in_compute_and_pixel() { + let mut cs_code = v_mad_f32(3, 0, 1, 2); + cs_code.extend(v_fma_f32(4, 0, 1, 3)); + cs_code.extend(s_endpgm()); + let dxil = kernel::translate(&cs_code, opts()).expect("translate compute mad+fma"); + validate::validate(&dxil).expect("dxil validate compute mad+fma"); + let dis = validate::disassemble(&dxil).expect("disassemble compute mad+fma"); + assert!(dis.contains("dx.op.tertiary.f32(i32 46,"), "expected live FMad in compute shader:\n{dis}"); + let flags = entry_point_flags(&dis); + assert_eq!(flags & (1 << 1), 0, "DisableMathRefactoring must be omitted when FMad is used (flags={flags:#x}):\n{dis}"); + + let mut ps_code = v_mad_f32(3, 0, 1, 2); + ps_code.extend(v_fma_f32(4, 0, 1, 3)); + ps_code.extend(rdna2::encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)], None).unwrap()); + ps_code.extend(s_endpgm()); + let ps = ps_with_pos(); + let k = kernel::translate_pixel(&ps_code, opts(), &ps).expect("translate pixel mad+fma"); + validate::validate(&k.dxil).expect("dxil validate pixel mad+fma"); + let dis = validate::disassemble(&k.dxil).expect("disassemble pixel mad+fma"); + assert!(dis.contains("dx.op.tertiary.f32(i32 46,"), "expected live FMad in pixel shader:\n{dis}"); + let flags = entry_point_flags(&dis); + assert_eq!(flags & (1 << 1), 0, "DisableMathRefactoring must be omitted in pixel shader when FMad is used (flags={flags:#x}):\n{dis}"); + } + + #[test] + fn plain_float_add_does_not_set_disable_math_refactoring() { + let mut code = v_add_f32(2, 0, 1); + code.extend(s_endpgm()); + let dxil = kernel::translate(&code, opts()).expect("translate compute v_add_f32"); + validate::validate(&dxil).expect("dxil validate compute v_add_f32"); + let dis = validate::disassemble(&dxil).expect("disassemble compute v_add_f32"); + let flags = entry_point_flags(&dis); + assert_eq!(flags & (1 << 1), 0, "plain v_add_f32 must not set DisableMathRefactoring (flags={flags:#x}):\n{dis}"); + } + + #[test] + fn dead_fmad_eliminated_by_dce_still_allows_disable_math_refactoring() { + // v5 is written by v_fma_f32 and never read, so DCE eliminates the FMad + // while v4's v_mad_f32 stays live through the pixel export. + let mut code = v_fma_f32(5, 0, 1, 2); + code.extend(v_mad_f32(4, 0, 1, 2)); + code.extend(rdna2::encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(s_endpgm()); + let ps = ps_with_pos(); + let k = kernel::translate_pixel(&code, opts(), &ps).expect("translate pixel dead-fma+mad"); + validate::validate(&k.dxil).expect("dxil validate pixel dead-fma+mad"); + let dis = validate::disassemble(&k.dxil).expect("disassemble pixel dead-fma+mad"); + assert!(!dis.contains("dx.op.tertiary.f32(i32 46,"), "expected dead FMad to be eliminated by DCE:\n{dis}"); + let flags = entry_point_flags(&dis); + assert_ne!(flags & (1 << 1), 0, "post-DCE dead FMad should not suppress DisableMathRefactoring (flags={flags:#x}):\n{dis}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index bbe90ac00..52c28fb3a 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -18,6 +18,9 @@ pub const DATALAYOUT: &str = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16 /// for most, a container feature bit (`SFI0`). #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Feature { + /// Prevents drivers from refactoring floating-point operations (e.g. + /// contracting separate `fmul` + `fadd` into FMA). + DisableMathRefactoring, Doubles, RawAndStructuredBuffers, WaveOps, @@ -57,6 +60,7 @@ impl Feature { Feature::DoubleExtensions => 6, Feature::TiledResources => 12, Feature::TypedUavLoadAdditionalFormats => 13, + Feature::DisableMathRefactoring => 1, } } /// `D3D_SHADER_REQUIRES_*` container feature bit. @@ -75,6 +79,7 @@ impl Feature { Feature::DoubleExtensions => 0x20, Feature::TiledResources => 0x100, Feature::TypedUavLoadAdditionalFormats => 0x800, + Feature::DisableMathRefactoring => 0, } } } @@ -486,8 +491,7 @@ impl Shader { } self.m.optimize(); self.infer_type_features(); - let flags: u64 = self.features.iter().map(|f| f.metadata_bit()).fold(0, |a, b| a | b); - let sfi0: u64 = self.features.iter().map(|f| f.container_bit()).fold(0, |a, b| a | b); + let (flags, sfi0) = self.feature_flags(); let m = &mut self.m; let one = m.md_i32(1); @@ -543,6 +547,42 @@ impl Shader { let psv = Psv { stage: self.stage, min_wave, max_wave, numthreads, resources: psv_res, entry: "main".into() }; Ok(container::container(self.stage, self.sm, &bitcode, sfi0, &psv)) } + + /// Computes `(metadata_flags, container_sfi0)` from required features. + /// + /// Omits `DisableMathRefactoring` when the optimized module still invokes + /// `dx.op.tertiary.*` `FMad` (op 46), since DXIL validation forbids `FMad` + /// together with `DisableMathRefactoring`. + pub(super) fn feature_flags(&self) -> (u64, u64) { + let drop_no_refactor = self.features.contains(&Feature::DisableMathRefactoring) && self.uses_fmad(); + let mut flags = 0u64; + let mut sfi0 = 0u64; + for &f in &self.features { + if drop_no_refactor && f == Feature::DisableMathRefactoring { + continue; + } + flags |= f.metadata_bit(); + sfi0 |= f.container_bit(); + } + (flags, sfi0) + } + + /// True if any surviving instruction calls `dx.op.tertiary.*` with opcode + /// `46` (`Tertiary::FMad`). + fn uses_fmad(&self) -> bool { + use super::module::{Block, InstInfo}; + for b in 0..self.m.block_count() { + for &inst in self.m.block_insts(Block(b as u32)) { + let InstInfo::Call(name, args) = self.m.inst_info(inst) else { continue }; + if name.starts_with("dx.op.tertiary.") + && args.first().and_then(|&v| self.m.const_u64(v)) == Some(46) + { + return true; + } + } + } + false + } } /// The function attributes DXC gives each `dx.op` declaration (DXC 1.9