Merge day/shaders

This commit is contained in:
local committed 2026-11-25 13:29:56 -06:00
commit 01e1f525d7
10 files changed
+594 -30

No files matched your search

@@ -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<f32> {
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<f32> {
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 {
+74 -3
View File
@@ -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<Option<u32>> = 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
@@ -3686,6 +3710,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);
@@ -3819,6 +3846,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);
@@ -3841,6 +3887,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);
@@ -3890,6 +3939,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);
+55 -1
View File
@@ -101,6 +101,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;
@@ -116,7 +118,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,
@@ -219,6 +221,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<u32> = 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
@@ -239,6 +292,7 @@ pub fn translation_fingerprint() -> Vec<u8> {
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());
@@ -0,0 +1,74 @@
//! Not a test of the translator: what the host's compiler makes of DXIL.
//! `VICTORY_PROBE=<folder>` 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=<folder>"]
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<f64> = (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]);
}
}
@@ -1972,3 +1972,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::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
.and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(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<u32>, 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<u32>> = 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));
}
}
}