diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..8cee056 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -921,6 +921,9 @@ fn create() -> windows::core::Result { { tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.) + let amd = crate::indirect::amd(&device); + victory_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } let messages = debug .then(|| device.cast::().ok()) @@ -968,6 +971,15 @@ fn create() -> windows::core::Result { } } +impl Host { + /// The driver's version, as the system counts it (0: not known). + pub(crate) fn driver(&self) -> i64 { + let adapter = self.adapter.as_ref(); + // SAFETY: a plain query. + adapter.map_or(0, |a| unsafe { a.CheckInterfaceSupport(&IDXGIDevice::IID) }.unwrap_or(0)) + } +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. pub(crate) fn warp_adapter() -> windows::core::Result { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index b48b71d..d74b748 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -268,7 +268,7 @@ fn widest(amd: bool) -> u32 { } /// Whether `device` is an AMD card's. -fn amd(device: &ID3D12Device) -> bool { +pub(crate) fn amd(device: &ID3D12Device) -> bool { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4}; // SAFETY: plain queries. unsafe { diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 89dc8b7..4fb2940 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -399,6 +399,82 @@ impl Module { Some((bits, *x as u64 & mask(bits))) } + /// The bits of a 32-bit float that is a constant, given as one or as a + /// cast of an integer constant. + pub(crate) fn float_k(&self, v: V) -> Option { + let (v, cast) = match v { + V::Inst(i) => match self.insts[i as usize].op { + Op::Cast(Cast::Bitcast, x) => (x, true), + _ => return None, + }, + _ => (v, false), + }; + let V::Const(i) = v else { return None }; + match &self.consts[i as usize].1 { + Const::Float(bits) if !cast => Some(f32::from_bits(*bits)), + Const::Int(_) if cast => { + let (bits, x) = self.int_k(v)?; + (bits == 32).then_some(f32::from_bits(x as u32)) + } + _ => None, + } + } + + /// For a float that is a number and not an infinity whatever the program + /// reads: a power of two its magnitude does not pass. + pub(crate) fn bounded(&self, v: V, depth: u32) -> Option { + if let Some(k) = self.float_k(v) { + return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil()); + } + let V::Inst(i) = v else { return None }; + let depth = depth.checked_sub(1)?; + let of = |v: V| self.bounded(v, depth); + // (A power that overflows, or might with rounding, is no bound.) + let held = |b: f32| (b < 126.0).then_some(b); + match &self.insts[i as usize].op { + Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0), + Op::Cast(Cast::Bitcast, x) => match *x { + V::Inst(j) => match self.insts[j as usize].op { + Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y), + _ => None, + }, + _ => None, + }, + Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?), + Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0), + Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)), + Op::Call(_, args) => { + let (_, code) = self.int_k(*args.first()?)?; + match (code, &args[1..]) { + // Saturated, a fraction, a cosine or sine (of a number). + (7, [_]) => Some(0.0), + (6, [x]) => of(*x), + (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0), + (26..=29, [x]) => held(of(*x)? + 1.0), + // Of two numbers; or one of them the other way round: the + // minimum (36) of a constant and a maximum of another. + (35 | 36, [a, b]) => match (of(*a), of(*b)) { + (Some(x), Some(y)) => Some(x.max(y)), + _ => { + let other = if code == 35 { 36 } else { 35 }; + let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) }; + let k = self.float_k(k).and_then(|_| of(k))?; + let V::Inst(j) = inner else { return None }; + let Op::Call(_, inner) = &self.insts[j as usize].op else { return None }; + let (_, code) = self.int_k(*inner.first()?)?; + let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?; + (code == other).then_some(())?; + Some(k.max(of(*low)?)) + } + }, + (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0), + _ => None, + } + } + _ => None, + } + } + /// The constant `x` of the integer type `ty`, kept sign-extended as /// [`Module::i32`] and [`Module::bool`] keep theirs. fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..6fa3cbb 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1111,9 +1111,33 @@ fn own_bits_on() -> bool { } /// What the translator was told of the host, for a cache's key: the widest -/// wave, the view heap's limit and where the raw twins of its views start. -pub fn host_settings() -> [u32; 3] { - [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()] +/// wave, the view heap's limit, where the raw twins of its views start, and +/// what it writes for the console's own hardware. +pub fn host_settings() -> [u32; 4] { + [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()] +} + +static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator that the host's shaders run on AMD RDNA hardware +/// ([`super::rdna_float`]). +pub fn set_host_rdna(on: bool) { + HOST_RDNA.store(on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_rdna`], for its thread only. + pub(super) static TEST_RDNA: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The bits of [`super::rdna`] that count on this host. +pub(super) fn host_rdna() -> u32 { + #[cfg(test)] + if let Some(bits) = TEST_RDNA.get() { + return bits; + } + if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) { super::rdna_float() } else { 0 } } /// The refusal of a first half of an interpolation whose result is read @@ -3674,6 +3698,9 @@ impl<'a> Lower<'a> { fn max_min(&mut self, max: bool, a: V, b: V) -> V { let c = self.cur; let r = self.binary(if max { 35 } else { 36 }, a, b); + if host_rdna() & super::rdna::MAX_MIN != 0 { + return r; + } let (ia, ib) = (self.as_int(a), self.as_int(b)); let either = self.s.m.bin(c, Bin::Or, ia, ib); let magnitude = self.s.m.i32(0x7FFF_FFFF); @@ -3807,6 +3834,25 @@ impl<'a> Lower<'a> { /// is the smallest number among them). fn med3(&mut self, a: V, b: V, third: V) -> V { let c = self.cur; + // Between two constants in order: the lower one for a NaN either way. + if host_rdna() & super::rdna::MED3 != 0 { + let k = [a, b, third].map(|x| self.s.m.float_k(x)); + let ordered = match k { + [None, Some(x), Some(y)] => Some((a, b, third, x, y)), + [Some(x), None, Some(y)] => Some((b, a, third, x, y)), + [Some(x), Some(y), None] => Some((third, a, b, x, y)), + _ => None, + }; + if let Some((v, p, q, x, y)) = ordered + && !x.is_nan() + && !y.is_nan() + && x != y + { + let (low, high) = if x < y { (p, q) } else { (q, p) }; + let t = self.binary(35, v, low); + return self.binary(36, t, high); + } + } let lo = self.binary(36, a, b); let hi = self.binary(35, a, b); let t = self.binary(36, hi, third); @@ -3829,6 +3875,9 @@ impl<'a> Lower<'a> { fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { let c = self.cur; let r = self.unary(22, a); + if host_rdna() & super::rdna::FRACT != 0 && below_one == f32::from_bits(0x3F7F_FFFF) { + return r; + } let limit = self.s.m.f32(threshold.to_bits()); let k = self.s.m.f32(below_one.to_bits()); let over = self.s.m.cmp(c, pred::OGE, r, limit); @@ -3878,6 +3927,28 @@ impl<'a> Lower<'a> { /// `0 × anything = 0`, as in D3D9. fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; + if host_rdna() & super::rdna::LEGACY != 0 { + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + // A product is not 0 only where one factor is 0 and the other an + // infinity or no number: never of a value with itself, nor of two + // finite ones, and only where the finite one of two is 0. + let (fa, fb) = (self.s.m.bounded(a, 12).is_some(), self.s.m.bounded(b, 12).is_some()); + let not_zero = |l: &Self, x: V| l.s.m.float_k(x).is_some_and(|k| k != 0.0 && k.is_finite()); + if a == b || fa && fb || not_zero(self, a) || not_zero(self, b) { + return m; + } + let asked = match (fa, fb) { + (true, _) => a, + (_, true) => b, + _ => { + let (a, b) = (self.unary(6, a), self.unary(6, b)); + self.binary(36, a, b) + } + }; + let z = self.s.m.cmp(c, pred::OEQ, asked, zero); + return self.s.m.select(c, z, zero, m); + } let m = self.s.m.bin(c, Bin::Mul, a, b); let zero = self.s.m.f32(0); let az = self.s.m.cmp(c, pred::OEQ, a, zero); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..479d149 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod probe_tests; +#[cfg(all(test, windows))] mod size_tests; #[cfg(all(test, windows))] mod valu_tests; @@ -114,7 +116,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave}; +pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, @@ -200,6 +202,57 @@ pub fn shader_opt() -> u32 { *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) } +/// On a host whose shaders run on the console's own kind of hardware (AMD +/// RDNA, [`set_host_rdna`]): which of the console's float instructions are +/// written as the one host operation the driver makes the same instruction +/// of, instead of spelled out in operations every host agrees on. +/// `VICTORY_RDNA_FLOAT`: a set of [`rdna`]'s bits (decimal or `0x` hex); all +/// of them when it is unset, `0` none. Nothing on other hosts. +/// +/// Measured on an RX 7900 XTX (a frame of the yard, replayed turn by turn with +/// and without): the title's dispatches and draws 18.4 -> 17.6 ms, 0.4 of it +/// without [`rdna::LEGACY`]. Tried and worth nothing there: `v_mad_f32` as one +/// multiply-add, a fast reciprocal, scalar buffer loads of four dwords at once, +/// a wave size for every compute program (32, 64, the console's). +/// +/// Part of the translation: the shader cache keys on it ([`host_settings`]). +pub fn rdna_float() -> u32 { + static BITS: std::sync::OnceLock = std::sync::OnceLock::new(); + *BITS.get_or_init(|| { + let value = std::env::var("VICTORY_RDNA_FLOAT").ok(); + parse_set(value.as_deref(), rdna::ALL, rdna::ALL) + }) +} + +/// The bits of [`rdna_float`]. +pub mod rdna { + /// `v_max_f32` and the like: the host's FMax and FMin, without the code + /// that orders -0 below +0. + pub const MAX_MIN: u32 = 1; + /// `v_mul_legacy_f32` and the like (0 times anything is 0): a plain product + /// where no factor can be an infinity or no number where the other is 0, + /// and one comparison where it can. A zero may have the other sign. + pub const LEGACY: u32 = 2; + /// `v_med3_f32` of a value between two ordered constants: a minimum of a + /// maximum. + pub const MED3: u32 = 4; + /// `v_fract_f32`: the host's Frc as it is. + pub const FRACT: u32 = 8; + pub const ALL: u32 = 15; +} + +/// A switch's set of bits; `unset` when it is unset or unreadable. Pure, for +/// testing. +fn parse_set(value: Option<&str>, unset: u32, all: u32) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(unset, |n| n & all) +} + /// Everything a translation depends on besides the container: the /// translator's own source (hashed at build time), the value of every /// `VICTORY_*` switch it reads, the host facts the device hands it (widest @@ -220,6 +273,7 @@ pub fn translation_fingerprint() -> Vec { out.push(0); } out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&lower::host_rdna().to_le_bytes()); out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); out.extend_from_slice(&shader::raw_views().to_le_bytes()); out.extend_from_slice(&loop_limit().to_le_bytes()); diff --git a/crates/victory-shader/src/emit/probe_tests.rs b/crates/victory-shader/src/emit/probe_tests.rs new file mode 100644 index 0000000..fd109ba --- /dev/null +++ b/crates/victory-shader/src/emit/probe_tests.rs @@ -0,0 +1,74 @@ +//! Not a test of the translator: what the host's compiler makes of DXIL. +//! `VICTORY_PROBE=` and `--ignored probe`: each `.dxil` there (a +//! compute program with a constant buffer `b0` of four dwords and a raw +//! buffer, slot 0 of the view heap) is run on the card. `sem*` programs are +//! given the bits of 0.0, infinity, -0.0 and a NaN and what they store is +//! printed; of the others the time is (several runs of 4096 groups). + +use super::HostShader; +use super::host::{Dispatch, Host, Root, View}; +use crate::native::{HwStage, RootType}; + +#[test] +#[ignore = "a tool: VICTORY_PROBE="] +fn probe() { + let Some(folder) = std::env::var_os("VICTORY_PROBE") else { return }; + let host = Host::new(false).expect("a card"); + let mut files: Vec<_> = std::fs::read_dir(folder) + .expect("the folder") + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|e| e == "dxil")) + .collect(); + files.sort(); + for file in files { + let name = file.file_stem().unwrap_or_default().to_string_lossy().into_owned(); + let shader = HostShader { + stage: HwStage::Cs, + dxil: std::fs::read(&file).expect("the file"), + user_data: (0..4) + .map(|n| super::UserData { index: n, slot: 0, root: RootType::Constants, dword: n }) + .collect(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(made) => made, + Err(e) => { + println!("{name}: {e}"); + continue; + } + }; + let run = |constants: [u32; 4], groups: u32| { + let began = std::time::Instant::now(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(constants.to_vec()))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [groups, 1, 1], + }, + ) + .expect("a dispatch"); + (out[0].clone(), began.elapsed().as_secs_f64() * 1e3) + }; + if name.starts_with("sem") { + let (out, _) = run([0, 0x7F80_0000, 0x8000_0000, 0x7FC0_0000], 1); + for (n, x) in out.iter().enumerate().take(40) { + println!("{name} {n:>2}: {x:08x} {}", f32::from_bits(*x)); + } + continue; + } + let constants = [0.37f32.to_bits(), 0.11f32.to_bits(), 16384, 0]; + run(constants, 64); + let mut times: Vec = (0..9).map(|_| run(constants, 4096).1).collect(); + times.sort_by(f64::total_cmp); + println!("{name}: {:.2} ms (least {:.2})", times[times.len() / 2], times[0]); + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index cd2806f..1062843 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -1912,3 +1912,88 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { } } } + +/// Whether the hardware adapter is an AMD RDNA card's: what the translator +/// writes for one ([`super::rdna`]) holds there. +fn rdna_card() -> bool { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::*; + let Ok(host) = Host::new(false) else { return false }; + let mut waves = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: plain queries. + unsafe { + let amd = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(host.device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + .is_ok_and(|d| d.VendorId == 0x1002); + amd && host + .device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut waves).cast(), + size_of_val(&waves) as u32, + ) + .is_ok() + && waves.WaveLaneCountMin == 32 + && waves.WaveLaneCountMax == 64 + } +} + +/// The forms written for the console's own kind of hardware give, on such a +/// card, what the ones spelled out for every host give; a legacy product's +/// zero may have the other sign. +#[test] +fn rdna_forms_give_what_the_spelled_out_ones_give() { + if !rdna_card() { + eprintln!("no RDNA card; skipped"); + return; + } + const ONE: u16 = 242; + const MINUS_ONE: u16 = 243; + let (a, b, c) = (vgpr(1), vgpr(2), vgpr(3)); + let saturated = vop3_mod(0x110, 5, vgpr(1), vgpr(1), 0, 0, 0, 0, true); + let two = |x: [u32; 2], y: [u32; 2]| [x, y].concat(); + let bodies: [(&str, Vec, bool); 14] = [ + ("max", vop3(0x110, 0, a, b, 0).to_vec(), true), + ("min", vop3(0x10F, 0, a, b, 0).to_vec(), true), + ("max3", vop3(0x154, 0, a, b, c).to_vec(), true), + ("min3", vop3(0x151, 0, a, b, c).to_vec(), true), + ("med3 0 1", vop3(0x157, 0, a, 128, ONE).to_vec(), true), + ("med3 1 0", vop3(0x157, 0, ONE, a, 128).to_vec(), true), + ("med3 1 -1", vop3(0x157, 0, ONE, MINUS_ONE, a).to_vec(), true), + ("fract", vec![vop1(0x020, 0, a)], true), + ("mul_legacy", vop3(0x107, 0, a, b, 0).to_vec(), false), + ("mul_legacy by itself", vop3(0x107, 0, a, a, 0).to_vec(), false), + ("mul_legacy by a constant", vop3(0x107, 0, a, MINUS_ONE, 0).to_vec(), false), + ("mul_legacy of a saturated", two(saturated, vop3(0x107, 0, vgpr(5), b, 0)), false), + ("mad_legacy", vop3(0x140, 0, a, b, c).to_vec(), false), + ("max of a mul_legacy", two(vop3(0x107, 5, a, b, 0), vop3(0x110, 0, vgpr(5), c, 0)), false), + ]; + let numbers = [0.0f32, -0.0, 1.0, -1.0, 0.3, -2.5e-7, 3e38, f32::INFINITY, f32::NEG_INFINITY, f32::NAN]; + let mut cases = Vec::new(); + for (i, x) in numbers.iter().enumerate() { + for (j, y) in numbers.iter().enumerate() { + let z = numbers[(3 * i + j) % numbers.len()]; + cases.push([x.to_bits(), y.to_bits(), z.to_bits(), 0]); + } + } + for (name, body, exact) in bodies { + let mut got: Vec> = Vec::new(); + let mut written = Vec::new(); + for bits in [0, super::rdna::ALL] { + lower::TEST_RDNA.set(Some(bits)); + let shader = build_valu_cs(&body); + lower::TEST_RDNA.set(None); + written.push(shader.dxil.clone()); + let mut all = Vec::new(); + run_cases_on(&shader, &cases, &[("hardware", false)], |_, _, _, r| all.push(r)); + got.push(all); + } + assert_ne!(written[0], written[1], "{name}: written alike"); + for (case, (&was, &is)) in cases.iter().zip(got[0].iter().zip(&got[1])) { + let (x, y) = (f32::from_bits(was), f32::from_bits(is)); + let same = was == is || x.is_nan() && y.is_nan() || !exact && x == 0.0 && y == 0.0; + assert!(same, "{name} of {:?}: {x} ({was:#x}), now {y} ({is:#x})", case.map(f32::from_bits)); + } + } +}