From 26a801e21a82f86e0744caaadc4b1e9f90487f74 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:05 -0600 Subject: [PATCH 1/6] Immediate sampler slots are kept apart by comparison mode (upstream 2286e03) One constant used by a comparison and an ordinary sample became a comparison sampler for both. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 41 +++++------ crates/victory-shader/src/emit/mod.rs | 92 +++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 24 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 899255f..c44548a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -50,7 +50,7 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, - /// Bit n: immediate sampler n is used for comparisons. + /// Bit n: immediate sampler n is a comparison sampler. pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, @@ -6467,23 +6467,8 @@ impl<'a> Lower<'a> { Ok(h) } Source::Constant(words) if sampler => { - let words: [u32; 4] = words - .get(..4) - .and_then(|w| w.try_into().ok()) - .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { - Some(n) => n, - None => { - self.samplers.push(words); - self.samplers.len() - 1 - } - }; - if props.0 & 0x8000 != 0 { - // shortcut: one sampler used with and without comparison - // would need two static samplers; it becomes a comparison one. - self.s.cmp_samplers |= 1 << n; - } - Ok(self.s.sampler_handle(self.cur, n as u32)) + let n = self.register_sampler(words, props.0 & 0x8000 != 0)?; + Ok(self.s.sampler_handle(self.cur, n)) } Source::Constant(_) => Err("a constant resource descriptor"), Source::Built { address, .. } => { @@ -6594,22 +6579,30 @@ impl<'a> Lower<'a> { Ok(phi) } - /// Registers an immediate sampler constant and returns its slot index. + /// Registers an immediate sampler constant and returns its slot index: a + /// constant used with and without comparison takes one slot for each. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result { let words: [u32; 4] = words .get(..4) .and_then(|w| w.try_into().ok()) .ok_or("a sampler constant")?; - let n = match self.samplers.iter().position(|w| *w == words) { + let slot = self + .samplers + .iter() + .enumerate() + .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp); + let n = match slot { Some(n) => n, None => { + let n = self.samplers.len(); + if n >= u64::BITS as usize { + return Err("more than 64 immediate sampler slots"); + } self.samplers.push(words); - self.samplers.len() - 1 + self.s.cmp_samplers |= u64::from(cmp) << n; + n } }; - if cmp && n < 64 { - self.s.cmp_samplers |= 1 << n; - } Ok(n as u32) } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d919660..eb30697 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -989,6 +989,98 @@ mod tests { assert!(lower(unmarked).is_err()); } + #[test] + fn immediate_sampler_slots_distinguish_comparison_uses() { + let words = [ + 0xBE81_0380u32, // s_mov_b32 s1, 0 + 0xF40C_0000, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[0:1], null + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E00_02F0, // v_mov_b32 v0, 0.5 (comparison reference) + 0x7E02_02F0, // v_mov_b32 v1, 0.5 (u) + 0x7E04_02F0, // v_mov_b32 v2, 0.5 (v) + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF080_0108, + 0x0040_0301, // image_sample v3, v[1:2], s[0:7], s[8:11] + 0xF0A0_0108, + 0x0040_0400, // image_sample_c v4, v[0:2], s[0:7], s[8:11] + 0xF0BC_0108, + 0x0040_0500, // image_sample_c_lz v5, v[0:2], s[0:7], s[8:11] + 0xF080_0108, + 0x0040_0601, // image_sample v6, v[1:2], s[0:7], s[8:11] + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF800_180F, + 0x0605_0403, // exp mrt0, v3, v4, v5, v6 done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 7, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let output = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[output], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + + let sampler = StaticSampler::from_words([0; 4]); + let comparison = StaticSampler { + filter: sampler.filter | 0x80, + ..sampler + }; + assert_eq!(out.samplers, [[0; 4]; 2]); + assert_eq!(out.static_samplers, [sampler, comparison]); + #[cfg(windows)] + if let Some(path) = super::validator::Validator::default_path() { + let mut v = super::validator::Validator::load(Some(&path)).unwrap(); + v.validate(&mut out.dxil.clone()).unwrap(); + } + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit From 77b82c9c22c97700277789e45265882515084046 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:23 -0600 Subject: [PATCH 2/6] Mesh primitive exports: corner indices are nine bits, the edge flags dropped (upstream c0228d9) Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 9 +- crates/victory-shader/src/emit/mod.rs | 178 ++++++++++++++++++++++++ crates/victory-shader/src/io.rs | 8 +- 3 files changed, 188 insertions(+), 7 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c44548a..062bf06 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11354,8 +11354,11 @@ impl<'a> Lower<'a> { Ok(()) } - /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all - /// indices 0: no area). + /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten + /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19 + /// and 29), which only the console's edge-flag rasterisation reads and + /// which is no part of the index. Bit 31 culls it (all indices 0: no + /// area). fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; @@ -11388,7 +11391,7 @@ impl<'a> Lower<'a> { }); let mut indices = [z; 3]; for (k, slot) in indices.iter_mut().enumerate() { - let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); if let Some(n) = written { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index eb30697..986e669 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1318,6 +1318,184 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. + const TRIANGLE: u32 = 1 << 10 | 2 << 20; + /// The edge flags of the three corners (bits 9, 19 and 29). + const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; + /// The culling bit. + const CULL: u32 = 1 << 31; + + /// A one-wave (32-lane) triangle mesh program whose lanes all export + /// primitive `prim` and, as vertex `lane`, the position + /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) + /// covers the whole target. + fn triangle_mesh(prim: u32) -> Result { + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04F6, // v_mul_f32 v4, 4.0, v2 + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06F4, // v_mul_f32 v5, 2.0, v3 + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// A primitive export's corners are 9-bit indices: the edge flag above + /// each (bits 9, 19, 29) is no part of it. Masking ten bits made a + /// flagged corner index 512 or more, past any mesh program's vertices + /// (the draw test below shows the triangle). Flagged, unflagged and + /// culled exports translate, and dxil.dll, where there is one, takes + /// each module. + #[test] + fn primitive_export_indices_drop_the_edge_flags() { + #[cfg(windows)] + let mut validator = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) + .ok(); + for prim in [ + TRIANGLE, + TRIANGLE | EDGE_FLAGS, + TRIANGLE | EDGE_FLAGS | CULL, + ] { + let ms = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut ms.dxil.clone()) + .unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + } + } + } + + /// A triangle mesh program on the host GPU and on WARP (where they have + /// mesh shaders): triangle (0, 1, 2) covers the target with its corners' + /// edge flags set as without them; with the culling bit, nothing is lit. + #[test] + #[cfg(windows)] + fn edge_flagged_triangles_draw_as_unflagged_ones() { + use super::host::{Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_MESH, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let ps = constant_color(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + if queried.is_err() || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + eprintln!("no mesh shaders on the {label} device; skipped"); + continue; + } + for (prim, culled) in [ + (TRIANGLE, false), + (TRIANGLE | EDGE_FLAGS, false), + (TRIANGLE | EDGE_FLAGS | CULL, true), + ] { + let ms = triangle_mesh(prim).unwrap(); + let root = host + .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &ms.dxil, &ps) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0]))], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit = texels.iter().filter(|t| t[3] != 0.0).count(); + if culled { + assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels"); + continue; + } + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}, {prim:#x}: {lit} of 256 texels lit" + ); + } + eprintln!("{label}: edge-flagged triangles drew"); + ran += 1; + } + if ran == 0 { + eprintln!("no device with mesh shaders; skipped"); + } + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 3899cc9..ba53eb0 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -26,10 +26,10 @@ //! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and //! its group id from v5 of the first lane (`v_readfirstlane`: the group //! times the group size). Lane n exports vertex n (`exp pos`, `exp param`) -//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20, -//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One -//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | -//! primitives << 12). +//! and primitive n (`exp prim`: 9-bit vertex indices at bits 0, 10, 20, +//! each with an edge flag above it, bit 31 culls); `param` entries with +//! bit 7 are per-primitive outputs. One lane sends the output counts +//! (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). use crate::ShaderError; use crate::gfx10::{Fields, Operand}; From c5a2f8d6fd018da23599dadaf0721c7637360b81 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:50 -0600 Subject: [PATCH 3/6] Upstream instruction fixes: 64-bit literals, exact normalized ends, flat offsets, rare forms Ports of 7d04943 (a signed 64-bit operand sign-extends its literal), 645391b (a normalized buffer format's ends load as exactly 1.0 and -1.0), 40f30be (FLAT offsets ignore bit 11), 3d71ad1, 344704e, 5d6889e, 78c1267, c3a04e2, e3fe5bf and the tests 259ba31, 8610ffb, 41b2472, 45ed8e3, 8d67fa5. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 195 +++++++++++++++- crates/victory-shader/src/emit/valu_tests.rs | 222 +++++++++++++++++++ crates/victory-shader/src/gfx10/fields.rs | 31 ++- crates/victory-shader/src/gfx10/mod.rs | 15 ++ crates/victory-shader/src/gfx10/sp3.rs | 80 ++++++- 5 files changed, 529 insertions(+), 14 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 062bf06..c3bda73 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5226,6 +5226,10 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(*k).ok_or("a special operand")?; Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) } + // Of a signed operand, a literal sign-extends too. + Some(&Operand::Literal(x)) if name.ends_with("_i64") => { + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } _ => Ok(l.s.m.i32(0)), } }; @@ -5312,6 +5316,20 @@ impl<'a> Lower<'a> { l.s.m.cmp(c, pred::NE, o, z) }; return match name { + "s_quadmask_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let low = self.quad_mask(a); + let high = self.quad_mask(b); + let k8 = self.s.m.i32(8); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let mask = self.s.m.bin(c, Bin::Or, low, high); + let zero = self.s.m.i32(0); + self.set(lo, Val::I32(mask)); + self.set(hi, Val::I32(zero)); + let nonzero = self.s.m.cmp(c, pred::NE, mask, zero); + self.set(scc, Val::Bit(nonzero)); + Ok(()) + } "s_bcnt1_i32_b64" => { let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); let i32t = self.s.t.i32; @@ -5437,6 +5455,10 @@ impl<'a> Lower<'a> { let (r, carry): (V, Option) = match name { "s_mov_b32" => (src32(self, 0)?, None), "s_movk_i32" => (sext16(self), None), + "s_quadmask_b32" => { + let pixels = src32(self, 0)?; + (self.quad_mask(pixels), None) + } "s_cselect_b32" => { let cond = self.scc_in(inst)?; let (a, b) = (src32(self, 0)?, src32(self, 1)?); @@ -5630,6 +5652,29 @@ impl<'a> Lower<'a> { Ok(()) } + /// Packs whether each consecutive group of four pixels has a set bit. + fn quad_mask(&mut self, pixels: V) -> V { + let c = self.cur; + let one = self.s.m.i32(1); + let shifted = self.s.m.bin(c, Bin::LShr, pixels, one); + let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted); + // Fold each nibble into its bottom bit, then gather those bits into + // the low byte in three stages without needing a 64-bit operation. + for (distance, keep) in [ + (2, 0x1111_1111), + (3, 0x0303_0303), + (6, 0x000f_000f), + (12, 0x0000_00ff), + ] { + let distance = self.s.m.i32(distance); + let shifted = self.s.m.bin(c, Bin::LShr, mask, distance); + let combined = self.s.m.bin(c, Bin::Or, mask, shifted); + let keep = self.s.m.i32(keep); + mask = self.s.m.bin(c, Bin::And, combined, keep); + } + mask + } + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the /// scalar and vector add-with-carry instructions set it. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { @@ -6300,20 +6345,34 @@ impl<'a> Lower<'a> { l.s.m.bin(c, Bin::AShr, t, k) }; let f32t = self.s.t.f32; + // A normalized format's ends are exactly 1.0 and -1.0. The host + // may divide through a reciprocal and land just below 1.0: RDNA + // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00. let x = match numeric { Numeric::Unorm => { let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); - let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + let top = (1u64 << w) - 1; + let max = self.s.m.f32((top as f32).to_bits()); let q = self.s.m.bin(c, Bin::SDiv, f, max); + let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::EQ, field, high); + let q = self.s.m.select(c, at_top, one, q); float(self, q) } Numeric::Snorm => { let s = signed(self); let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); - let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + let top = (1u32 << (w - 1)) - 1; + let max = self.s.m.f32((top as f32).to_bits()); let q = self.s.m.bin(c, Bin::SDiv, f, max); - let lo = self.s.m.f32((-1.0f32).to_bits()); - let q = self.binary(35, q, lo); + // The lowest value is -1.0 too, as is the one above it. + let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::SGE, s, high); + let q = self.s.m.select(c, at_top, one, q); + let low = self.s.m.i32(top.wrapping_neg()); + let minus_one = self.s.m.f32((-1.0f32).to_bits()); + let at_bottom = self.s.m.cmp(c, pred::SLE, s, low); + let q = self.s.m.select(c, at_bottom, minus_one, q); float(self, q) } Numeric::Uscaled => { @@ -7623,6 +7682,17 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_off_f32_i4" => { + // The low nibble as a signed 4-bit integer, over 16. + let a = s(self, 0)?; + let k28 = self.s.m.i32(28); + let a = self.s.m.bin(c, Bin::Shl, a, k28); + let a = self.s.m.bin(c, Bin::AShr, a, k28); + let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32); + let k = self.s.m.f32(0.0625f32.to_bits()); + let r = self.s.m.bin(c, Bin::Mul, f, k); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -8058,8 +8128,14 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(k).ok_or("a special operand")?; Ok(self.s.m.int_const(i64t, i64::from(x as i32))) } + // A signed 64-bit operand sign-extends its 32-bit literal, as + // the hardware does (LLVM's AMDGPU operand rules). + Operand::Literal(x) if inst.name().ends_with("_i64") => { + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } _ => { - // Literals and the null register: zero-extended. + // Literals (of unsigned and bit operands) and the null + // register: zero-extended. let x = self.operand(inst, &op)?; Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) } @@ -9012,6 +9088,18 @@ impl<'a> Lower<'a> { let b = self.s.m.bin(c, op, b, sh); self.s.m.bin(c, Bin::Mul, a, b) } + "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => { + // The high dword of the same 48-bit product: the low 24 bits + // of each operand, zero- or sign-extended, multiplied. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let signed = name == "v_mul_hi_i32_i24"; + let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr }); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.mul_hi(a, b, signed) + } "v_bfe_u32" | "v_bfe_i32" => { let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); let w = m31(self, w); @@ -9090,6 +9178,44 @@ impl<'a> Lower<'a> { let m = self.s.m.bin(c, Bin::Mul, a, b); self.s.m.bin(c, Bin::Add, m, d) } + "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => { + // src2 plus the sum of the unsigned differences |a - b| of + // the operands' bytes, halves or whole dwords, wrapping at 32 + // bits. v_sad_hi_u8 adds the sum shifted to the high half; + // v_msad_u8 leaves out a byte whose mask byte (src1) is 0. + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (width, parts) = match name { + "v_sad_u16" => (16, 2), + "v_sad_u32" => (32, 1), + _ => (8, 4), + }; + let zero = k(self, 0); + let mut sum = zero; + for i in 0..parts { + let (mut x, mut y) = (a, b); + if width < 32 { + let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1)); + x = self.s.m.bin(c, Bin::LShr, x, sh); + x = self.s.m.bin(c, Bin::And, x, mask); + y = self.s.m.bin(c, Bin::LShr, y, sh); + y = self.s.m.bin(c, Bin::And, y, mask); + } + let above = self.s.m.cmp(c, pred::IUGT, x, y); + let hi = self.s.m.select(c, above, x, y); + let lo = self.s.m.select(c, above, y, x); + let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo); + if name == "v_msad_u8" { + let masked = self.s.m.cmp(c, pred::NE, y, zero); + diff = self.s.m.select(c, masked, diff, zero); + } + sum = self.s.m.bin(c, Bin::Add, sum, diff); + } + if name == "v_sad_hi_u8" { + let k16 = k(self, 16); + sum = self.s.m.bin(c, Bin::Shl, sum, k16); + } + self.s.m.bin(c, Bin::Add, sum, d) + } "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" | "v_med3_u32" => { let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); @@ -11990,6 +12116,55 @@ mod tests { } } + /// Lowers a one-thread compute program that copies four root constants + /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a + /// descriptor table, so the vector instructions in `body` have an effect. + fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00_0000, + ]; + // v_mov_b32 v1..v4, s0..s3 + words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); + words.extend_from_slice(body); + words.extend_from_slice(&[ + 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002_0000, + S_ENDPGM, + ]); + let constants = RootParam { + sgprs: 4, + ..root(RootType::Constants, 0, 0) + }; + let buffer = UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + lower_with( + &words, + vec![constants, root(RootType::Table, 4, 1)], + vec![buffer], + ) + .map(|_| ()) + } + + #[test] + fn the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low + // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). + for op in [0x09u32, 0x0A, 0x0B, 0x0C] { + let word = op << 25 | 2 << 9 | 0x101; + lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); + } + } + #[test] fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the @@ -11998,6 +12173,16 @@ mod tests { assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); } + #[test] + fn sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, + // v_sad_u32 and v_msad_u8. + for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { + let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; + lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); + } + } + #[test] fn a_scalar_carry_chain_reaches_the_select() { // The high dword of a 64-bit add or subtract, then a select on the diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f5c2014..ee69d98 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -259,6 +259,39 @@ fn run_cases_on( assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } +#[test] +fn scalar_quad_masks_pack_nibbles_and_set_scc() { + let pack_words = |opcode: u32| { + [ + 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64) + sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0 + sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16 + sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18 + vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16 + ] + }; + let cases = [ + ([0, 0, 0, 0], [0, 0]), + ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]), + ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]), + ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]), + ]; + let inputs = cases.map(|(input, _)| input); + for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() { + let shader = build_valu_cs(&pack_words(opcode)); + run_cases(&shader, &inputs, |backend, i, _, got| { + assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}"); + }); + } + let high = build_valu_cs(&[ + 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1] + vop1(1, 0, sgpr(17)), + ]); + run_cases(&high, &inputs, |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: high dword"); + }); +} + fn is_f16_nan(bits: u16) -> bool { (bits & 0x7FFF) > 0x7C00 } @@ -287,6 +320,33 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +#[test] +fn normalized_buffer_formats_load_their_ends_exactly() { + // tbuffer_load_format_x. + let x = 0; + // (format, dword stored, value loaded) + let cases: &[(u8, u32, f32)] = &[ + (1, 0xFF, 1.0), // 8_UNORM + (7, 0xFFFF, 1.0), // 16_UNORM + (2, 0x7F, 1.0), // 8_SNORM: the top, the one above the lowest, the lowest + (2, 0x81, -1.0), + (2, 0x80, -1.0), + (8, 0x7FFF, 1.0), // 16_SNORM + (8, 0x8001, -1.0), + (8, 0x8000, -1.0), + ]; + for &(format, stored, want) in cases { + let shader = tbuffer_load_of_v1(x, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, + want.to_bits(), + "{backend}: format {format} of {stored:#x} = {got:#010x}, want {want}", + ); + }); + } +} + #[test] fn packed_add_selects_halves_of_inline_constants() { // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. @@ -486,6 +546,77 @@ fn max_and_min_order_negative_zero_below_positive_zero() { } } +/// The f16 forms go through the same `max_min` helper, after widening to f32. +#[test] +fn f16_max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_u32); + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f16", 0x139, pz), + ("v_min_f16", 0x13A, nz), + ("v_max3_f16", 0x354, pz), + ("v_min3_f16", 0x351, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + // The f16 result is the low half of v0. + assert_eq!(got & 0xFFFF, want, "{backend}: {name} {inp:x?}"); + }); + } +} + +#[test] +fn v_min3_max3_med3_integer_forms_match_rdna2() { + // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159). + type Pick = fn([u32; 3]) -> u32; + let ops: [(&str, u16, Pick); 6] = [ + ("v_min3_i32", 0x152, |t| { + t.into_iter().min_by_key(|&x| x as i32).unwrap() + }), + ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()), + ("v_max3_i32", 0x155, |t| { + t.into_iter().max_by_key(|&x| x as i32).unwrap() + }), + ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()), + ("v_med3_i32", 0x158, |mut t| { + t.sort_by_key(|&x| x as i32); + t[1] + }), + ("v_med3_u32", 0x159, |mut t| { + t.sort_unstable(); + t[1] + }), + ]; + // Every ordering of three values, with the sign bit set on some so that + // the signed and unsigned answers differ. + let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF]; + let mut cases = Vec::new(); + for a in values { + for b in values { + for c in values { + cases.push([a, b, c, 0]); + } + } + } + for (name, op, pick) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + let want = pick([inp[0], inp[1], inp[2]]); + assert_eq!( + got, want, + "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) @@ -579,6 +710,31 @@ fn v_cmp_lg_is_false_for_nan() { } } +#[test] +fn v_cvt_off_f32_i4_uses_the_signed_low_nibble() { + // v_cvt_off_f32_i4 v0, v1 (VOP1 opcode 0x00e) + let shader = build_valu_cs(&[vop1(0x00e, 0, vgpr(1))]); + let nibble = |n: u32| (((n as i32) << 28) >> 28) as f32 / 16.0; + + let mut cases: Vec = (0..16).collect(); + // Bits above the low nibble are ignored. + cases.extend([0xABCD_EF05, 0xFFFF_FFF8, 0x1234_5670, 0x8000_000F, 0x0000_00F7]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|&x| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = nibble(cases[i]).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_off_f32_i4({:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + inp[0], + f32::from_bits(got), + ); + }); + // Spot-check the reference itself: 0x5 -> 0.3125, 0x8 -> -0.5, 0xF -> -0.0625. + assert_eq!(nibble(0xABCD_EF05), 0.3125); + assert_eq!(nibble(8), -0.5); + assert_eq!(nibble(0xF), -0.0625); +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) @@ -865,6 +1021,40 @@ fn v_cvt_u16_and_i16_f16_saturate() { } } +#[test] +fn v_cvt_f16_u16_and_i16_widen_the_integer_first() { + // v_mov_b32 v0, 0; v_cvt_f16_u16 / v_cvt_f16_i16 v0, v1 (VOP1 0x050 / 0x051). + // Only integers f16 holds exactly: how the others round is the narrowing's + // business, not this conversion's. `None`: the result depends on rounding. + let cases: &[(u16, Option, Option)] = &[ + // (u16 / i16 input bits, f16 of the unsigned value, f16 of the signed value) + (0x0000, Some(0x0000), Some(0x0000)), // 0 + (0x0001, Some(0x3C00), Some(0x3C00)), // 1.0 + (0x07FF, Some(0x67FF), Some(0x67FF)), // 2047, the last integer below 2048 that f16 holds + (0x8000, Some(0x7800), Some(0xF800)), // 32768 / -32768 + (0xFC00, Some(0x7BE0), Some(0xE400)), // 64512 / -1024 + (0xFFFE, None, Some(0xC000)), // 65534 does not fit f16 / -2 + (0xFFFF, None, Some(0xBC00)), // 65535 does not fit f16 / -1 + ]; + for (op, what, pick) in [ + (0x050u16, "v_cvt_f16_u16", 0usize), + (0x051, "v_cvt_f16_i16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + let Some(want) = want else { return }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f16_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); @@ -946,6 +1136,38 @@ fn v_sin_and_v_cos_f16_reduce_large_turns() { }); } +/// A 32-bit literal in a signed 64-bit operand is sign-extended (an +/// unsigned one's is zero-extended): -100 compared with `v[1:2]`, and +/// shifted by `s_ashr_i64`. +#[test] +fn signed_64_bit_operands_sign_extend_their_literal() { + const MINUS_100: u32 = -100_i32 as u32; + let check = |name: &str, body: &[u32], cases: &[([u32; 4], u32)]| { + let shader = build_valu_cs(body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + }; + // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then + // v_cndmask_b32 v0, 0, 1, s6. + let compare = |op: u16| { + let [a, b] = vop3(op, 6, vgpr(1), 255, 0); + let [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + [a, b, MINUS_100, c, d] + }; + // An i64 as the two input dwords of `v[1:2]`. + let pair = |n: i64| [n as u32, (n >> 32) as u32, 0, 0]; + let eq = [(pair(-100), 1), ([MINUS_100, 0, 0, 0], 0), (pair(0), 0)]; + check("v_cmp_eq_i64", &compare(0x0A2), &eq); + let lt = [(pair(-200), 1), (pair(-50), 0), (pair(0), 0)]; + check("v_cmp_lt_i64", &compare(0x0A1), <); + // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword. + let ashr = [sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))]; + check("s_ashr_i64", &ashr, &[([0; 4], u32::MAX)]); +} + #[test] fn bfe_signed_and_unsigned_match_rdna2() { // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 2773b3c..bcc0dd3 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -235,19 +235,32 @@ impl Instruction { } Encoding::Sopp => Fields::Sopp { imm: w0 as u16 }, Encoding::Smem => { - let data = match name { - "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, - n if n.starts_with("s_dcache_discard") => None, - "s_memtime" | "s_memrealtime" => Some(2), - _ => Some(data_dwords(name)), + let sdata = (w0 >> 6 & 0x7F) as u8; + // s_atc_probe*: SDATA is a 7-bit immediate, not an SGPR. The + // buffer form's resource is 4 dwords. GLC and DLC are not operands. + let probe = matches!(name, "s_atc_probe" | "s_atc_probe_buffer"); + let data = if probe { + Some(Operand::Literal(u32::from(sdata))) + } else { + match name { + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None, + n if n.starts_with("s_dcache_discard") => None, + "s_memtime" | "s_memrealtime" => Some(scalar(sdata, 2)), + _ => Some(scalar(sdata, data_dwords(name))), + } }; - let base = 2 + 2 * u8::from(name.starts_with("s_buffer_")); + let base = + 2 + 2 * u8::from(name.starts_with("s_buffer_") || name == "s_atc_probe_buffer"); Fields::Smem { - data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)), + data, base: scalar(((w0 & 0x3F) << 1) as u8, base), offset: (w1 << 11) as i32 >> 11, soffset: scalar((w1 >> 25) as u8, 1), - cache: cache(bit(w0, 16), false, bit(w0, 14)), + cache: if probe { + Cache::default() + } else { + cache(bit(w0, 16), false, bit(w0, 14)) + }, } } Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => { @@ -405,6 +418,8 @@ impl Instruction { saddr: (self.encoding != Encoding::Flat) .then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))), offset: match self.encoding { + // GFX10 FLAT offsets are 11-bit and unsigned: the + // hardware ignores bit 11. Encoding::Flat => (w0 & 0x7FF) as i16, _ => ((w0 << 4) as i16) >> 4, }, diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index f029ff4..57e6ea2 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -352,6 +352,21 @@ mod tests { .collect() } + #[test] + fn flat_offsets_ignore_bit_eleven() { + let offset = |word0: u32| { + let code = bytes(&[word0, 0x0000_0001, S_ENDPGM]); + match decode(&code).unwrap()[0].fields(false) { + Fields::Flat { offset, .. } => offset, + fields => panic!("{fields:?}"), + } + }; + // flat_load_dword v0, v[1:2]: the FLAT offset is 11-bit and + // unsigned, so bit 11 is ignored (0x800 -> 0, 0xfff -> 0x7ff). + assert_eq!(offset(0xDC30_0800), 0); + assert_eq!(offset(0xDC30_0FFF), 0x7FF); + } + #[test] fn tables_are_sorted() { for t in [ diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs index 0ca5ab4..baf0e82 100644 --- a/crates/victory-shader/src/gfx10/sp3.rs +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -137,6 +137,12 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { cache, } => { if let Some(data) = data { + let data = match (name, data) { + ("s_atc_probe" | "s_atc_probe_buffer", Operand::Literal(imm)) => { + atc_immediate(*imm) + } + _ => data.to_string(), + }; let off = match (soffset, offset) { (Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(), (Operand::Scalar { code: NULL, .. }, _) => { @@ -335,6 +341,15 @@ fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { out } +/// `s_atc_probe` immediate: 0..=64 in decimal, larger values in hex. +fn atc_immediate(imm: u32) -> String { + if imm <= 64 { + imm.to_string() + } else { + format!("0x{imm:x}") + } +} + /// Cache flags; images write `dlc` first. fn flags(out: &mut String, cache: &Cache, dlc_first: bool) { let dlc = (cache.dlc, " dlc"); @@ -660,7 +675,7 @@ fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { #[cfg(test)] mod tests { - use crate::gfx10::{Fields, Operand, decode}; + use crate::gfx10::{Cache, Fields, Operand, decode}; /// Text of each instruction in `words` (a straight-line program). fn texts(words: &[u32], wave64: bool) -> Vec { @@ -700,6 +715,69 @@ mod tests { ); } + /// `s_atc_probe` / `s_atc_probe_buffer`: SDATA is a 7-bit immediate, the + /// buffer resource is 4 dwords, and GLC/DLC are not operands. + /// + /// Words checked with `llvm-mc -arch=amdgcn -mcpu=gfx1030 --disassemble`. + /// The offset keeps this printer's 6-digit hex (`0x000064`, not `0x64`). + #[test] + fn atc_probe_immediate_is_not_a_register() { + let cases = [ + ( + [0xF498_01C2, 0xFA00_0064], + "s_atc_probe 7, s[4:5], 0x000064", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ( + [0xF498_1FF4, 0x0A00_0001], + "s_atc_probe 0x7f, s[104:105], s5 offset:0x000001", + Operand::Literal(0x7f), + Operand::Scalar { + code: 104, + dwords: 2, + }, + ), + ( + [0xF498_0000, 0xFA00_0000], + "s_atc_probe 0, s[0:1], null", + Operand::Literal(0), + Operand::Scalar { code: 0, dwords: 2 }, + ), + ( + [0xF49C_01C4, 0xFA00_0020], + "s_atc_probe_buffer 7, s[8:11], 0x000020", + Operand::Literal(7), + Operand::Scalar { code: 8, dwords: 4 }, + ), + ( + [0xF499_41C2, 0xFA00_0000], + "s_atc_probe 7, s[4:5], null", + Operand::Literal(7), + Operand::Scalar { code: 4, dwords: 2 }, + ), + ]; + for (words, text, data, base) in cases { + assert_eq!(one(&words, false), text, "{words:08x?}"); + assert_eq!(one(&words, true), text, "{words:08x?}"); + let mut code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + code.extend(0xBF81_0000u32.to_le_bytes()); + let inst = &decode(&code).unwrap()[0]; + let Fields::Smem { + data: got, + base: got_base, + cache, + .. + } = inst.fields(false) + else { + panic!("not an SMEM instruction"); + }; + assert_eq!(got, Some(data), "{words:08x?}"); + assert_eq!(got_base, base, "{words:08x?}"); + assert_eq!(cache, Cache::default(), "{words:08x?}"); + } + } + #[test] fn lane_masks_follow_the_wave_size() { let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3 From 011735ff809d8655f697d5b2749e2a79d5faabb1 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:24:56 -0600 Subject: [PATCH 4/6] Anisotropic samplers with point mips keep them where the card has them (upstream e45bacd, 23fc8a5, 7dfa86f) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline/host.rs | 15 +++++- crates/victory-shader/src/emit/host.rs | 14 ++++- crates/victory-shader/src/emit/sampler.rs | 64 ++++++++++++++++++++++- 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 9acd1d2..706758d 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -437,6 +437,19 @@ impl HostPipeline { } let host = host()?; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); + // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); // The ranges table parameters point at, alive until the root @@ -544,7 +557,7 @@ impl HostPipeline { } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(s.filter as i32), + Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32), AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 8f5407a..4bb533f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -185,12 +185,24 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(d.filter as i32), + Filter: D3D12_FILTER(d.filter_for_host(aniso_point_mip_supported) as i32), AddressU: u, AddressV: v, AddressW: w, diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs index e10c0c1..ca010e5 100644 --- a/crates/victory-shader/src/emit/sampler.rs +++ b/crates/victory-shader/src/emit/sampler.rs @@ -34,6 +34,18 @@ pub struct StaticSampler { impl Eq for StaticSampler {} impl StaticSampler { + /// The filter supported by the host device. Anisotropic point-mip + /// filtering is optional (`D3D12_OPTIONS19`); older devices retain the + /// previous linear-mip approximation. Comparison/min/max reduction + /// bits and the sampler's LOD bounds are unchanged. + pub fn filter_for_host(&self, aniso_point_mip_supported: bool) -> u32 { + if !aniso_point_mip_supported && self.filter & !0x180 == 0x54 { + self.filter | 1 + } else { + self.filter + } + } + /// Decodes the four sampler words. pub fn from_words(w: [u32; 4]) -> Self { let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); @@ -47,7 +59,7 @@ impl StaticSampler { _ => 0, }; let filter = if mag >= 2 || min >= 2 { - 0x55 | reduction << 7 + 0x54 | u32::from(mip == 2) | reduction << 7 } else { (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 }; @@ -122,4 +134,54 @@ mod tests { (0x1D5, 16, 15.0) ); } + + #[test] + fn anisotropic_samplers_preserve_mip_point_filtering() { + for (reduction, base) in [(0u32, 0x54u32), (1, 0x154), (2, 0x1D4)] { + let w0 = reduction << 29; + for mip in [0u32, 1] { + let w2 = (mip << 26) | 0x00F0_0000; // mag = 3, min = 3 + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base, "reduction={reduction} mip={mip}"); + } + let w2 = (2 << 26) | 0x00F0_0000; // mip = 2 (linear) + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base | 1, "reduction={reduction} mip=2"); + } + // Mixed anisotropic mag (2) with linear min (1) and point mip (1). + let mixed = StaticSampler::from_words([0, 0, (1 << 26) | (1 << 22) | (2 << 20), 0]); + assert_eq!(mixed.filter, 0x54); + } + + #[test] + fn host_filter_falls_back_without_changing_reduction_or_lod() { + for (filter, fallback) in [(0x54, 0x55), (0xD4, 0xD5), (0x154, 0x155), (0x1D4, 0x1D5)] { + for mip in [0u32, 1] { + let s = StaticSampler { + filter, + ..StaticSampler::from_words([0, 0x0054_0100, (mip << 26) | 0x00F0_0000, 0]) + }; + assert_eq!(s.filter_for_host(false), fallback); + assert_eq!(s.filter_for_host(true), filter); + assert_eq!( + (s.min_lod, s.max_lod), + if mip == 0 { (0.0, 0.0) } else { (1.0, 5.25) } + ); + } + } + } + + #[test] + fn host_filter_keeps_other_filters_unchanged() { + for reduction in [0, 0x80, 0x100, 0x180] { + for base in [0, 1, 4, 5, 0x10, 0x11, 0x14, 0x15, 0x55] { + let s = StaticSampler { + filter: base | reduction, + ..StaticSampler::from_words([0; 4]) + }; + assert_eq!(s.filter_for_host(false), s.filter); + assert_eq!(s.filter_for_host(true), s.filter); + } + } + } } From 75cfb234e5bf9fa4e1e9912bd6d850860e82f5da Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:25:15 -0600 Subject: [PATCH 5/6] Upstream graphics state fixes: rectangle attributes, sampler bounds, A8 copies, depth footprints Ports of 6f36cdf (normalized attributes of rectangle lists), 97c8783 (A8_UNORM is not of the R8 typeless family), b956320 (copy footprints of depth-stencil textures), c1c3281 (the descriptor ring's wrap), e6fe8ec and e34cb53 (CreateSamplerX bounds), 691236d (appended elements are aligned). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 28 ++++- crates/victory-gpu/src/pipeline/host.rs | 69 ++++++++++- crates/victory-gpu/src/primitive.rs | 48 +++++++- crates/victory-gpu/src/resource.rs | 97 +++++++++++++--- crates/victory-gpu/src/sampler.rs | 132 ++++++++++++++++++++-- 5 files changed, 344 insertions(+), 30 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 213a11a..39cfb15 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -861,8 +861,12 @@ impl HostHeap { let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); let n = n as usize; - // Search from `next` on, then from the start. - let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); + // Search from `next` on, then from the start (extending past cursor by + // n - 1 so contiguous runs crossing the cursor are not missed). + let cursor = *next as usize; + let end = self.dynamic as usize; + let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); + let starts = (cursor..end).chain(0..second_end); let mut run = 0; let mut found = None; let mut last = usize::MAX; @@ -2836,4 +2840,24 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// Contiguous free dynamic slot ranges that cross the search cursor are found. + #[test] + fn dynamic_allocation_finds_contiguous_range_crossing_search_cursor() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + // Allocate slots 0..8, advancing cursor to 8. + let a = heap.dynamic(8).unwrap(); + // Allocate slots 8..16, advancing cursor to 16. + let b = heap.dynamic(8).unwrap(); + assert_eq!((a, b), (4, 12)); + + // Release slots 10..14 (crossing cursor at 12). + // Before the fix, a request of 4 slots starting search at 12 scanned 12..end then 0..12, + // missing the contiguous run at 10..14. + heap.release(14, 4); + let c = heap.dynamic(4); + assert_eq!(c, Some(14)); + } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 706758d..e3559c3 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -296,13 +296,19 @@ impl GraphicsState { .map(|e| { let slot = e.InputSlot.min(31) as usize; let format = e.Format.0 as u32; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + // An appended element starts at the next multiple of + // min(4, its size) after the previous one, where D3D12 (and + // vkd3d) place it; the host pipeline gets the title's + // descriptions, so the offsets read here must match. let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { next[slot] + .checked_next_multiple_of(bytes.clamp(1, 4)) + .unwrap_or(u32::MAX) } else { e.AlignedByteOffset }; - let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); - next[slot] = offset + bytes; + next[slot] = offset.saturating_add(bytes); Input { slot: slot as u32, offset, @@ -1444,4 +1450,63 @@ mod tests { assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected"); assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); } + + fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC { + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()), + SemanticIndex: 0, + Format: format, + InputSlot: 0, + AlignedByteOffset: offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + } + } + + fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec { + let state = GraphicsState { + inputs: inputs.to_vec(), + ..GraphicsState::default() + }; + state.elements().iter().map(|e| e.offset).collect() + } + + /// An appended element after one of 1 or 2 bytes started right after + /// it; D3D12 aligns it to min(4, its size), so the rectangle expansion + /// read its vertices from the wrong bytes. + #[test] + fn appended_elements_are_aligned() { + const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT; + // RG8 (2 bytes) then RG32 float: 4, not 2. + let a = [ + element(DXGI_FORMAT_R8G8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&a), [0, 4]); + // R8 then R16 float: 2, not 1; then R8 packs right after it. + let b = [ + element(DXGI_FORMAT_R8_UNORM, 0), + element(DXGI_FORMAT_R16_FLOAT, APPEND), + element(DXGI_FORMAT_R8_UNORM, APPEND), + ]; + assert_eq!(offsets(&b), [0, 2, 4]); + // Already aligned layouts are unchanged. + let c = [ + element(DXGI_FORMAT_R8G8B8A8_UNORM, 0), + element(DXGI_FORMAT_R32G32_FLOAT, APPEND), + element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND), + ]; + assert_eq!(offsets(&c), [0, 4, 12]); + } + + /// An explicit offset near 4 GiB overflowed the next appended offset + /// (a panic in debug builds). + #[test] + fn a_huge_explicit_offset_does_not_overflow() { + let inputs = [ + element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8), + element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT), + ]; + let _ = offsets(&inputs); + } } diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index 3f73ee7..180e43e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -55,6 +55,8 @@ enum Kind { F16, Unorm8, Unorm16, + Snorm8, + Snorm16, } /// Component count and kind of the vertex formats rectangles use. @@ -69,7 +71,16 @@ fn components(format: u32) -> Option<(usize, Kind)> { 54 => (1, Kind::F16), 11 => (4, Kind::Unorm16), 35 => (2, Kind::Unorm16), + 56 => (1, Kind::Unorm16), 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + 49 => (2, Kind::Unorm8), + 61 => (1, Kind::Unorm8), + 13 => (4, Kind::Snorm16), + 37 => (2, Kind::Snorm16), + 58 => (1, Kind::Snorm16), + 31 => (4, Kind::Snorm8), + 51 => (2, Kind::Snorm8), + 63 => (1, Kind::Snorm8), _ => return None, }) } @@ -78,8 +89,8 @@ impl Kind { fn bytes(self) -> usize { match self { Kind::F32 => 4, - Kind::F16 | Kind::Unorm16 => 2, - Kind::Unorm8 => 1, + Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2, + Kind::Unorm8 | Kind::Snorm8 => 1, } } @@ -90,6 +101,8 @@ impl Kind { Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, Kind::Unorm8 => f32::from(b[0]) / 255.0, + Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0), + Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0), } } @@ -103,6 +116,10 @@ impl Kind { b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) } Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + Kind::Snorm16 => { + b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()) + } + Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8, } } } @@ -218,6 +235,33 @@ mod tests { assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } + #[test] + fn normalized_attributes_are_interpolated_in_their_own_range() { + let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| { + [ + &rg[..], + &u16_value.to_le_bytes(), + &[u8_value, snorm8 as u8], + &snorm16.to_le_bytes(), + ] + .concat() + }; + let src = [ + vertex([3, 250], 1000, 10, i8::MIN, -23000), + vertex([8, 200], 500, 3, -120, -18000), + vertex([20, 253], 10000, 100, -120, -32000), + ] + .concat(); + let mut dst = [0; 6 * 8]; + expand_rects( + &src, + &mut dst, + 8, + &[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)], + ); + assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767)); + } + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be /// able to write them back instead of flushing every one to zero. #[test] diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 1b74262..3cdd30f 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -585,7 +585,7 @@ pub(crate) fn family(format: u32) -> u32 { (44, 47), (48, 52), (53, 59), - (60, 65), + (60, 64), (70, 72), (73, 75), (76, 78), @@ -695,8 +695,7 @@ const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { row_pitch: 0, }; -/// One subresource's size in an upload buffer: footprint (offset 0), rows -/// and bytes per row. Planes of depth-stencil formats are not told apart. +/// One subresource's upload footprint (offset 0), row count and unpadded row size. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { const PITCH: u64 = 256; if desc.dimension == BUFFER { @@ -716,11 +715,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, } else { u32::from(desc.depth_or_array_size).max(1) }; - let (mip, slice) = (index % mips, index / mips); - if slice >= slices { - return None; - } - let (element, block) = element(desc.format)?; + let mip = index % mips; + let plane = index / mips / slices; + let depth_stencil = matches!(desc.format, 19..=22 | 44..=47); + // Each plane contains all the mip levels and array slices. Depth and + // stencil copies use separate formats and 512-byte row alignment. + let (format, pitch_alignment) = match (depth_stencil, plane) { + (true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS + (true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS + (false, 0) => (desc.format, PITCH), + _ => return None, + }; + let (element, block) = element(format)?; let width = (desc.width >> mip).max(1).next_multiple_of(block); let height = (u64::from(desc.height) >> mip) .max(1) @@ -733,18 +739,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, let row_size = width / block * element; let footprint = PlacedFootprint { offset: 0, - format: desc.format, + format, width: u32::try_from(width).ok()?, height: u32::try_from(height).ok()?, depth, - row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?, }; Some((footprint, u32::try_from(height / block).ok()?, row_size)) } -/// Device method: where each subresource goes in an upload buffer, rows -/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give -/// the documented all-ones values. +/// Places subresources at 512-byte boundaries in an upload buffer. +/// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes +/// otherwise. Unknown sizes give the documented all-ones values. pub(crate) extern "system" fn copyable_footprints( _: This, desc: *const ResourceDesc, @@ -2559,6 +2565,22 @@ mod tests { use super::*; use crate::object::slot; + #[test] + fn a8_unorm_is_not_in_the_r8_typeless_family() { + // DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT, + // 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is + // 60..=64; A8_UNORM has no typeless family and cannot be cast to R8, + // so it must stand alone rather than fold into R8_TYPELESS. + assert_eq!(family(60), 60); + for f in 61..=64 { + assert_eq!(family(f), 60); + } + assert_eq!(family(65), 65); + // Boundaries: 59 belongs to the preceding family, 66 is unmapped. + assert_eq!(family(59), 53); + assert_eq!(family(66), 66); + } + type Release = extern "system" fn(This) -> u32; type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; type Address = extern "system" fn(This) -> u64; @@ -2790,6 +2812,55 @@ mod tests { assert_eq!(t, u64::MAX, "no second subresource"); } + #[test] + fn depth_stencil_footprints_follow_the_pc_plane_order() { + // Native D3D12 reports the same layout for both depth/stencil families + // and their view formats. Mips vary fastest, then array slices, then planes. + let expected = [ + (512, 39, 16, 8), + (4_608, 39, 8, 4), + (6_656, 39, 16, 8), + (10_752, 39, 8, 4), + (12_800, 60, 16, 8), + (16_896, 60, 8, 4), + (18_944, 60, 16, 8), + (23_040, 60, 8, 4), + ]; + for format in (19..=22).chain(44..=47) { + let desc = ResourceDesc { + depth_or_array_size: 2, + ..texture(16, 8, format, 2) + }; + let mut layouts = [NO_FOOTPRINT; 8]; + let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0); + copyable_footprints( + std::ptr::null(), + &desc, + 0, + 8, + 512, + layouts.as_mut_ptr(), + rows.as_mut_ptr(), + sizes.as_mut_ptr(), + &mut total, + ); + + assert_eq!( + layouts.map(|l| (l.offset, l.format, l.width, l.height)), + expected, + "format {format}" + ); + assert!( + layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512), + "format {format}" + ); + assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}"); + assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}"); + assert_eq!(total, 24_072, "format {format}"); + assert!(subresource(&desc, 8).is_none(), "format {format}"); + } + } + /// A 4x4 texture filled from a title buffer through our list and queue, /// then read back from the host GPU. #[cfg(windows)] diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs index ee95da3..2132273 100644 --- a/crates/victory-gpu/src/sampler.rs +++ b/crates/victory-gpu/src/sampler.rs @@ -47,30 +47,58 @@ impl Fields { } else { linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) }; + let min_lod = finite_lod(self.min_lod, 0.0); + // Without a mip filter the console clamps sampling to `min_lod`. + let max_lod = if self.mip == 0 { + min_lod + } else { + finite_lod(self.max_lod, min_lod).max(min_lod) + }; D3D12_SAMPLER_DESC { Filter: D3D12_FILTER((reduction << 7 | filter) as i32), - AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), - AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), - AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), - MipLODBias: self.bias, + AddressU: address_mode(self.address[0]), + AddressV: address_mode(self.address[1]), + AddressW: address_mode(self.address[2]), + MipLODBias: if self.bias.is_nan() { + 0.0 + } else { + self.bias + .clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX) + }, MaxAnisotropy: if aniso { self.anisotropy.clamp(1, 16) } else { 1 }, - ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), - BorderColor: self.border, - MinLOD: self.min_lod, - // Without a mip filter the console samples mip 0 only. - MaxLOD: if self.mip == 0 { - self.min_lod + ComparisonFunc: if reduction == 1 { + D3D12_COMPARISON_FUNC(self.compare as i32) } else { - self.max_lod + D3D12_COMPARISON_FUNC_NEVER }, + BorderColor: self.border, + MinLOD: min_lod, + MaxLOD: max_lod, } } } +/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`. +fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE { + match mode { + 1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32), + _ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + } +} + +/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities. +fn finite_lod(value: f32, fallback: f32) -> f32 { + if value.is_nan() { + fallback + } else { + value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX) + } +} + /// The console's sampler description (27 words): flags, magnification, /// minification, mip and depth filters, filter mode, three address modes, /// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias @@ -116,4 +144,86 @@ mod tests { w[16] = 1; assert_eq!(console(&w).Filter.0, 0x5); } + + #[test] + fn mip_none_clamps_to_min_lod_and_inverted_lod_range_clamps() { + let mut w = [0u32; 27]; + w[3] = 0; // mip none + w[9] = 3.0f32.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (3.0, 3.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0)); + + w[9] = f32::INFINITY.to_bits(); + w[10] = 8.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX)); + + w[3] = 2; // linear mips + w[9] = 4.0f32.to_bits(); + w[10] = 1.0f32.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0)); + + w[9] = f32::NAN.to_bits(); + w[10] = f32::INFINITY.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX)); + + w[9] = 2.5f32.to_bits(); + w[10] = f32::NAN.to_bits(); + let d = console(&w); + assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5)); + + w[9] = f32::NEG_INFINITY.to_bits(); + w[10] = f32::NEG_INFINITY.to_bits(); + let d = console(&w); + assert_eq!( + (d.MinLOD, d.MaxLOD), + (-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX) + ); + } + + #[test] + fn bias_address_and_comparison_stay_in_host_bounds() { + let mut w = [0u32; 27]; + w[6..9].copy_from_slice(&[0, 6, 3]); + w[11] = 24.0f32.to_bits(); + w[16] = 99; + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = (-24.0f32).to_bits(); + w[5] = 1; // minimum reduction + w[16] = 4; // less-or-equal, ignored when reduction != 1 + let d = console(&w); + assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); + + w[11] = f32::NAN.to_bits(); + w[5] = 0; // plain mode, reduction == 1 from compare == 4 + w[6..9].copy_from_slice(&[1, 4, 5]); + w[16] = 4; + let d = console(&w); + assert_eq!(d.MipLODBias, 0.0); + assert_eq!( + [d.AddressU, d.AddressV, d.AddressW], + [ + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE_BORDER, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, + ] + ); + assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + } } From 4e3e0654bf9b2cb554849123a95d51b3ce3d7b4e Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 23:25:32 -0600 Subject: [PATCH 6/6] Typed buffer loads of 16-bit channels pack two per register; skipped devices say why (upstream c430b1d, 100de0e) Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/diff_tests.rs | 36 ++++++++----- crates/victory-shader/src/emit/lower.rs | 44 +++++++++++++-- crates/victory-shader/src/emit/mod.rs | 9 ++-- crates/victory-shader/src/emit/valu_tests.rs | 54 +++++++++++++++++-- .../src/emit/waterfall_tests.rs | 9 ++-- 5 files changed, 128 insertions(+), 24 deletions(-) diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 4727b92..b43a0a7 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -718,9 +718,12 @@ fn translated_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -874,9 +877,12 @@ fn translated_mesh_shaders_draw_as_pc_ones() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -991,9 +997,12 @@ fn float_semantics_are_the_consoles() { eprintln!("no console compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -1080,9 +1089,12 @@ fn translated_compute_matches_pc() { eprintln!("no console or PC compiler; skipped"); return; }; - let Ok(host) = Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c3bda73..7598738 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6414,6 +6414,39 @@ impl<'a> Lower<'a> { Ok(out) } + /// Channels of buffer format `format`, as [`Self::format_load`] gives + /// them, as d16 data: 16 bits each, two per dword, low half first (an + /// odd last high half 0). Integer formats keep their low 16 bits; the + /// others become f16. + fn d16_channels(&mut self, format: u8, channels: Vec) -> Result, Why> { + let (_, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let mut halves = Vec::new(); + for x in channels { + halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) { + let m = self.s.m.i32(0xFFFF); + self.s.m.bin(c, Bin::And, x, m) + } else { + let (f, i32t) = (self.as_float(x), self.s.t.i32); + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }); + } + let mut out = Vec::new(); + for pair in halves.chunks(2) { + out.push(match *pair { + [lo, hi] => { + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + [lo] => lo, + _ => unreachable!("chunks of one or two"), + }); + } + Ok(out) + } + /// The byte offset a buffer descriptor built around a root descriptor adds /// (constant and computed parts); none for other descriptors. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { @@ -10808,8 +10841,9 @@ impl<'a> Lower<'a> { "buffer_load_sshort" => Some((16, true)), _ => None, }; - // d16: two 16-bit channels per VGPR, low half first. - let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + // d16: two 16-bit channels per VGPR, low half first (buffer and + // tbuffer formats alike). + let d16 = name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); let (typed, count) = match plain .strip_prefix("buffer_load_") @@ -11143,7 +11177,11 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + let mut xs = self.format_load(h, off, f, count)?; + if d16 { + xs = self.d16_channels(f, xs)?; + } + for (k, x) in xs.into_iter().enumerate() { self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 986e669..248e8c9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -1252,9 +1252,12 @@ mod tests { #[test] #[cfg(windows)] fn stub_pipeline_is_created() { - let Ok(host) = super::host::Host::new(false) else { - eprintln!("no SM 6.6 device; skipped"); - return; + let host = match super::host::Host::new(false) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 device ({e}); skipped"); + return; + } }; let ps = super::HostShader { stage: crate::HwStage::Ps, diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index ee69d98..65c0c9d 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -219,9 +219,12 @@ fn run_cases_on( let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for &(label, warp) in devices { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = host .compute_pipeline(shader) @@ -320,6 +323,51 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +/// MTBUF `op vdata, off, s[srsrc:srsrc+3], 0 format:format` (at byte 0). +const fn mtbuf(op: u8, vdata: u8, srsrc: u8, format: u8) -> [u32; 2] { + [ + 0x3A << 26 | (format as u32 & 0x7F) << 19 | (op as u32 & 7) << 16, + 0x80 << 24 + | (op as u32 >> 3 & 1) << 21 + | (srsrc as u32 >> 2 & 0x1F) << 16 + | (vdata as u32) << 8, + ] +} + +/// Stores `v1` to the buffer, then reads it back into `v0` with the tbuffer +/// load `op` in buffer format `format`. +fn tbuffer_load_of_v1(op: u8, format: u8) -> HostShader { + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(op, 0, 8, format)); + build_valu_cs(&body) +} + +#[test] +fn tbuffer_d16_loads_pack_two_channels_per_dword() { + // tbuffer_load_format_d16_x and tbuffer_load_format_d16_xy. + let (x, xy) = (8, 9); + // (opcode, format, dword stored, dword loaded) + let cases: &[(u8, u8, u32, u32)] = &[ + // 16_16_FLOAT: the f16 pair (1.0, 2.0) as it was stored. + (xy, 29, 0x4000_3C00, 0x4000_3C00), + // 16_16_UINT: the 16-bit integers as they were stored. + (xy, 27, 0xBEEF_1234, 0xBEEF_1234), + // 16_16_UNORM: 0.0 and 1.0, as f16. + (xy, 23, 0xFFFF_0000, 0x3C00_0000), + // 16_FLOAT, one channel: the high half is 0. + (x, 13, 0x4000_3C00, 0x0000_3C00), + ]; + for &(op, format, stored, want) in cases { + let shader = tbuffer_load_of_v1(op, format); + run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| { + assert_eq!( + got, want, + "{backend}: d16 opcode {op} format {format} of {stored:#010x} = {got:#010x}, want {want:#010x}", + ); + }); + } +} + #[test] fn normalized_buffer_formats_load_their_ends_exactly() { // tbuffer_load_format_x. diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 31dadd6..85e2b1a 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -115,9 +115,12 @@ pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec .lock() .unwrap_or_else(|e| e.into_inner()); for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {label} device ({e}); skipped"); + continue; + } }; let (root, pso) = match host.compute_pipeline(shader) { Ok(p) => p,