diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 8d95d677..e6553756 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -60,12 +60,11 @@ pub(crate) struct Shader { pub(crate) stage: &'static str, /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, + #[cfg(windows)] + full_hash: [u8; 32], /// The container's length, as logged once its bytes are gone. size: usize, - /// The container, until `translated` has made its translation (or its - /// refusal) and let it go: a run holds one per distinct shader its title - /// passes, and nothing reads it after. Off Windows nothing translates, - /// so only tests keep it. + /// Released after translation unless an experimental mesh/pixel pair may need it. #[cfg(any(windows, test))] container: Mutex>, #[cfg(windows)] @@ -88,15 +87,21 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { shaders .get_or_insert_with(HashMap::new) .entry(*full.as_bytes()) - .or_insert_with(|| Arc::new(Shader::new(stage, bytes))) + .or_insert_with(|| Arc::new(Shader::with_hash(stage, bytes, full))) .clone() } impl Shader { fn new(stage: &'static str, bytes: &[u8]) -> Shader { + Self::with_hash(stage, bytes, blake3::hash(bytes)) + } + + fn with_hash(stage: &'static str, bytes: &[u8], digest: blake3::Hash) -> Shader { Shader { stage, - hash: blake3::hash(bytes).to_hex()[..16].to_owned(), + hash: digest.to_hex()[..16].to_owned(), + #[cfg(windows)] + full_hash: *digest.as_bytes(), size: bytes.len(), #[cfg(any(windows, test))] container: Mutex::new(bytes.to_vec()), @@ -126,7 +131,17 @@ impl Shader { let done = translate(&container); // After the translation, not before: if it panics, the // bytes are still there for the next try. - *container = Vec::new(); + let keep = link_mesh_outputs() && done.0.as_ref().is_ok_and(|t| { + self.stage == "pixel" + || (self.stage == "mesh" + && victory_shader::emit::mesh_outputs(&t.host.dxil) + .is_some_and(|o| { + o.bytes() > victory_shader::emit::METAL_MESH_OUTPUT_BYTES + })) + }); + if !keep { + *container = Vec::new(); + } done }; let ms = started.elapsed().as_millis() as u64; @@ -233,6 +248,117 @@ fn with_resources( Ok(Translated { host, used }) } +#[cfg(windows)] +fn link_mesh_outputs() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_LINK_MESH_OUTPUTS")) +} + +#[cfg(windows)] +struct LinkedPair { + mesh: Arc, + pixel: Option>, +} + +#[cfg(windows)] +type LinkedKey = ([u8; 32], Option<[u8; 32]>); + +#[cfg(windows)] +impl Shader { + fn with_translation(&self, translated: Translated) -> Arc { + let cell = OnceLock::new(); + let _ = cell.set(Some(translated)); + Arc::new(Shader { + stage: self.stage, + hash: self.hash.clone(), + full_hash: self.full_hash, + size: self.size, + container: Mutex::new(Vec::new()), + translated: cell, + }) + } +} + +/// Re-translates a mesh shader together with its paired pixel shader (if any) +/// so arbitrary mesh outputs unread by the pixel shader are pruned under +/// Metal's 32 KiB mesh output limit (`victory_shader::emit::METAL_MESH_OUTPUT_BYTES`). +#[cfg(windows)] +pub(crate) fn translate_linked( + ms: &Shader, + ps: Option<&Shader>, +) -> Option<(Arc, Option>)> { + static LINKED: Mutex>>> = Mutex::new(None); + let key = (ms.full_hash, ps.map(|p| p.full_hash)); + if let Some(hit) = LINKED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|m| m.get(&key)) + { + return hit + .as_ref() + .map(|pair| (pair.mesh.clone(), pair.pixel.clone())); + } + let mesh_bytes = ms + .container + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); + let pixel_bytes = ps.map(|p| { + p.container + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + }); + let options = crate::shader_cache::runtime_options(); + let result = match victory_shader::emit::translate_linked( + &mesh_bytes, + pixel_bytes.as_deref(), + options, + ) { + Ok((ms_host, ps_host)) => { + let ms_bytes = victory_shader::emit::mesh_outputs(&ms_host.dxil).map(|o| o.bytes()); + let ms_used = ms.translated()?.used.clone(); + let mesh = ms.with_translation(Translated { + host: ms_host, + used: ms_used, + }); + let pixel = match (ps, ps_host) { + (Some(p), Some(host)) => Some(p.with_translation(Translated { + host, + used: p.translated()?.used.clone(), + })), + _ => None, + }; + tracing::info!( + mesh = %ms.hash, + pixel = ps.map_or("none", |p| p.hash.as_str()), + bytes = ms_bytes, + "mesh and pixel linked under 32 KiB output budget" + ); + Some(LinkedPair { mesh, pixel }) + } + Err(e) => { + tracing::warn!( + mesh = %ms.hash, + pixel = ps.map_or("none", |p| p.hash.as_str()), + error = %e, + "linked mesh/pixel translation failed; using standalone translation" + ); + None + } + }; + let out = result + .as_ref() + .map(|pair| (pair.mesh.clone(), pair.pixel.clone())); + LINKED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(HashMap::new) + .insert(key, result); + out +} + #[repr(C)] struct Pipeline { object: Object, diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index bbb2d9ab..221a81dc 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -355,6 +355,26 @@ impl HostPipeline { for (s, _) in &stages { s.translated()?; } + // Mesh shaders whose standalone output footprint exceeds Metal's 32 KiB + // limit are re-translated together with their paired pixel shader, + // pruning outputs the pixel shader never reads. + let linked = mesh.filter(|_| super::link_mesh_outputs()).and_then(|ms| { + let bytes = victory_shader::emit::mesh_outputs(&ms.translated()?.host.dxil)?.bytes(); + if bytes <= victory_shader::emit::METAL_MESH_OUTPUT_BYTES { + return None; + } + super::translate_linked(ms, find("pixel").map(Arc::as_ref)) + }); + let stages: Vec<(&Arc, D3D12_SHADER_VISIBILITY)> = match &linked { + Some((ms, ps)) => { + let mut v = vec![(ms, D3D12_SHADER_VISIBILITY_MESH)]; + if let Some(ps) = ps { + v.push((ps, D3D12_SHADER_VISIBILITY_PIXEL)); + } + v + } + None => stages, + }; let host = host()?; // `SFI0`: 64-bit atomics on typed resources and on heap resources. let atomics64 = stages.iter().any(|(s, _)| { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 9e70b35f..a71346ad 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -156,19 +156,23 @@ fn options_build(locks: bool, bias: bool, narrow: bool) -> &'static [u8; 32] { }) } -/// The translation of a console shader container, from the cache when -/// there is one, and whether it came from there. -pub fn host_shader(container: &[u8]) -> (Result, bool) { +pub(crate) fn runtime_options() -> victory_shader::emit::Options { // Writes through views mark their pages: copy-backs compare only those // (`crate::shadow::copy_back_marks`). // Under Wine (D3DMetal), 64-bit image atomics run under locks: its own // leave the texels untouched (`emit`, "Atomic locks"). - let options = victory_shader::emit::Options { + victory_shader::emit::Options { view_marks: true, atomic_locks: atomic_locks(), bias_as_gradients: bias_as_gradients(), narrow_waves: narrow_waves(), - }; + } +} + +/// The translation of a console shader container, from the cache when +/// there is one, and whether it came from there. +pub fn host_shader(container: &[u8]) -> (Result, bool) { + let options = runtime_options(); let translate = |c: &[u8]| victory_shader::emit::translate_with(c, options).map_err(|e| e.to_string()); let build = if options.atomic_locks || options.bias_as_gradients || options.narrow_waves { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1414e306..35febc49 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -21,6 +21,9 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Map, Set, Structured}; mod bvh; +mod mesh; +pub(crate) use mesh::KeptOutputs; +use mesh::prune_signature; type Why = &'static str; @@ -104,9 +107,16 @@ enum Stop { } pub(crate) fn lower(parts: &Parts) -> Result { + lower_pruned(parts, None) +} + +pub(crate) fn lower_pruned( + parts: &Parts, + keep: Option<&KeptOutputs>, +) -> Result { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad).run() { + match Lower::new(parts, &bad, keep).run() { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -559,7 +569,7 @@ fn smem_dwords(name: &str) -> Option { } impl<'a> Lower<'a> { - fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { + fn new(x: &'a Parts<'a>, bad: &'a HashMap, keep: Option<&KeptOutputs>) -> Self { let p = x.p; let mut phi_at = Map::default(); for (b, block) in p.blocks.iter().enumerate() { @@ -570,6 +580,13 @@ impl<'a> Lower<'a> { let mut s = Shader::new(x.native.stage == HwStage::Ps); s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); + if let Some(keep) = keep { + if x.native.stage == HwStage::Ps { + prune_signature(&mut s.inputs, keep); + } else if x.native.stage == HwStage::Ms { + prune_signature(&mut s.outputs, keep); + } + } let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) @@ -643,11 +660,22 @@ impl<'a> Lower<'a> { let mut no_barrier = Set::default(); if let StageIo::Ms(ms) = &x.native.io { s.prims = x.prims.clone(); + if let Some(keep) = keep { + prune_signature(&mut s.prims, keep); + } s.threads = Some([ms.threads, 1, 1]); s.lds_dwords = ms.lds_bytes.div_ceil(4); + let mut max_vertices = ms.max_vertices; + let mut max_primitives = ms.max_primitives; + let declared = + super::MeshOutputs::of(&s.outputs, &s.prims, max_vertices, max_primitives); + if declared.bytes() > super::METAL_MESH_OUTPUT_BYTES { + max_vertices = max_vertices.min(ms.threads); + max_primitives = max_primitives.min(ms.threads); + } s.mesh = Some(super::shader::Mesh { - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, + max_vertices, + max_primitives, topology: ms.topology, }); // Barriers order the lanes' LDS accesses; the console's @@ -2974,65 +3002,6 @@ impl<'a> Lower<'a> { }) } - /// Mesh: the counts and the primitives no lane exports. The console's - /// counts come from one lane's allocation request, which DXIL cannot - /// express (one call, dominating every output write). - // shortcut: the counts are the declared maxima and each lane first culls - // its primitive (all indices 0, zero area), so primitives past the - // program's count are culled and vertices past it unused; this costs - // the host the unused vertex and primitive slots. Pass the program's own - // counts if that shows in frame time. - fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> { - let threads = self.s.threads.expect("mesh")[0]; - if mesh.topology != 2 { - return Err("a mesh shader not drawing triangles"); - } - if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { - return Err("a mesh shader beyond the host's limits"); - } - let e = self.s.entry; - let void = self.s.t.void; - let (v, p) = ( - self.s.m.i32(mesh.max_vertices), - self.s.m.i32(mesh.max_primitives), - ); - self.s - .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); - let flat = self.mesh_thread(); - let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); - let at = self.begin_guarded(guard); - let z = self.s.m.i32(0); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[flat, z, z, z], - ); - self.end_guarded(at, &[]); - Ok(()) - } - - /// Mesh: the thread's index in the group, which is its vertex and - /// primitive index. - fn mesh_thread(&mut self) -> V { - if let Some(f) = self.flat { - return f; - } - let e = self.s.entry; - let f = self.s.op( - e, - "flattenedThreadIdInGroup.i32", - Attr::ReadNone, - self.s.t.i32, - 96, - &[], - ); - self.flat = Some(f); - f - } - /// The console wave size. fn wave(&self) -> u32 { if self.x.native.wave64 { 64 } else { 32 } @@ -8123,7 +8092,7 @@ impl<'a> Lower<'a> { // per dword (`packed_half`); the host's are 32-bit floats. let half = |l: &mut Self, h: u8| -> Result, Why> { let src = if pack2 { - packed_half(&l.s.inputs, attribute.row, h) + packed_half(&l.x.inputs, attribute.row, h) } else { h.is_multiple_of(2).then_some((attribute.row, h / 2)) }; @@ -9973,7 +9942,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let h = 2 * ch + u8::from(high); let src = if pack2 { - packed_half(outputs, row, h) + packed_half(&self.x.outputs, row, h) } else { (!high).then_some((row, ch)) }; @@ -10175,7 +10144,7 @@ impl<'a> Lower<'a> { .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) }; let free: std::collections::BTreeSet = self - .s + .x .outputs .iter() .filter(|o| o.kind == 0) diff --git a/crates/victory-shader/src/emit/lower/mesh.rs b/crates/victory-shader/src/emit/lower/mesh.rs new file mode 100644 index 00000000..b758f37f --- /dev/null +++ b/crates/victory-shader/src/emit/lower/mesh.rs @@ -0,0 +1,94 @@ +//! Mesh shader output signatures, counts and lane indices. + +use super::{Attr, HashMap, Lower, SigElement, V, Why, pred}; +use crate::emit::shader::Mesh; + +/// Semantic key `(UPPERCASE_NAME, index)` -> 4-bit absolute channel mask of +/// arbitrary (`kind == 0`) inputs read by the paired pixel shader. +pub(crate) type KeptOutputs = HashMap<(String, u32), u8>; + +/// Keeps only arbitrary (`kind == 0`) signature elements whose semantic has at +/// least one channel read in `keep`, trimming unread leading and trailing +/// channels. System values (`kind != 0`) stay untouched. +pub(super) fn prune_signature(elements: &mut Vec, keep: &KeptOutputs) { + elements.retain_mut(|e| { + if e.kind != 0 { + return true; + } + if e.row.is_none() { + return false; + } + let key = (e.name.to_ascii_uppercase(), e.index); + let used = keep.get(&key).copied().unwrap_or(0); + let rel = (used >> e.col) & ((1u8 << e.cols) - 1); + if rel == 0 { + return false; + } + let first = rel.trailing_zeros() as u8; + let last = 7 - rel.leading_zeros() as u8; + e.col += first; + e.cols = last - first + 1; + true + }); +} + +impl Lower<'_> { + /// Mesh: the counts and the primitives no lane exports. The console's + /// counts come from one lane's allocation request, which DXIL cannot + /// express (one call, dominating every output write). + // shortcut: the counts are the declared maxima and each lane first culls + // its primitive (all indices 0, zero area), so primitives past the + // program's count are culled and vertices past it unused; this costs + // the host the unused vertex and primitive slots. Pass the program's own + // counts if that shows in frame time. + pub(super) fn mesh_prologue(&mut self, mesh: Mesh) -> Result<(), Why> { + let threads = self.s.threads.expect("mesh")[0]; + if mesh.topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { + return Err("a mesh shader beyond the host's limits"); + } + let e = self.s.entry; + let void = self.s.t.void; + let (v, p) = ( + self.s.m.i32(mesh.max_vertices), + self.s.m.i32(mesh.max_primitives), + ); + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + let flat = self.mesh_thread(); + let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); + let at = self.begin_guarded(guard); + let z = self.s.m.i32(0); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[flat, z, z, z], + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: the thread's index in the group, which is its vertex and + /// primitive index. + pub(super) fn mesh_thread(&mut self) -> V { + if let Some(f) = self.flat { + return f; + } + let e = self.s.entry; + let f = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + self.s.t.i32, + 96, + &[], + ); + self.flat = Some(f); + f + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index d60b18e1..30f57fe3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -242,9 +242,10 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ - HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, - ATOMIC_LOCKS, ATOMIC_LOCKS_AT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_READS, VIEW_SIGNED, - VIEW_STRIDE_BITS, VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, VIEW_WRITES_BYTES, + ATOMIC_LOCKS, ATOMIC_LOCKS_AT, HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, + ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, + VIEW_READS, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, + VIEW_WRITES_BYTES, }; /// The loop limit without an override: 2^14. @@ -422,6 +423,28 @@ impl MeshOutputs { pub fn bytes(&self) -> u32 { 4 * (self.vertex_components * self.vertices + self.primitive_components * self.primitives) } + + /// The outputs of a mesh shader being lowered: its declared counts and + /// the components of the signature elements that have a register. + pub(crate) fn of( + outputs: &[container::SigElement], + prims: &[container::SigElement], + vertices: u32, + primitives: u32, + ) -> Self { + let components = |els: &[container::SigElement]| { + els.iter() + .filter(|e| e.row.is_some()) + .map(|e| u32::from(e.cols)) + .sum() + }; + MeshOutputs { + vertices, + primitives, + vertex_components: components(outputs), + primitive_components: components(prims), + } + } } /// The declared outputs of a translated mesh shader: the counts from its @@ -461,14 +484,16 @@ pub fn mesh_outputs(dxil: &[u8]) -> Option { }) } -/// Translates the vertex, pixel, compute or mesh program of a console -/// shader container, without write marks. -pub fn translate(container: &[u8]) -> Result { - translate_with(container, Options::default()) +struct Prepared<'a> { + c: Container<'a>, + native: NativeProgram, + p: ir::Program, + st: structure::Structured, + io: io::Io, + res: resource::Resources, } -/// [`translate`] made as `options` say. -pub fn translate_with(container: &[u8], options: Options) -> Result { +fn prepare(container: &[u8]) -> Result, ShaderError> { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -492,7 +517,138 @@ pub fn translate_with(container: &[u8], options: Options) -> Result 4-bit absolute channel mask. +fn pixel_input_reads(dxil: &[u8]) -> Result { + let c = Container::parse(dxil)?; + let Some(part) = c.part(FourCC::ISG1) else { + return Ok(lower::KeptOutputs::new()); + }; + let mut reads = lower::KeptOutputs::new(); + let count = crate::dxbc::u32_at(part.data, 0)? as usize; + let base = crate::dxbc::u32_at(part.data, 4)? as usize; + for i in 0..count { + let at = base + 32 * i; + // System value at +12: 0 is arbitrary (non-SV). + if crate::dxbc::u32_at(part.data, at + 12)? != 0 { + continue; + } + let name_at = crate::dxbc::u32_at(part.data, at + 4)? as usize; + let name = part + .data + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let index = crate::dxbc::u32_at(part.data, at + 8)?; + let rw = *part + .data + .get(at + 25) + .ok_or(ShaderError::Malformed("truncated"))?; + if rw != 0 { + let key = (String::from_utf8_lossy(name).to_ascii_uppercase(), index); + *reads.entry(key).or_insert(0) |= rw; + } + } + Ok(reads) +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container, without write marks. +pub fn translate(container: &[u8]) -> Result { + translate_with(container, Options::default()) +} + +/// [`translate`] made as `options` say. +pub fn translate_with(container: &[u8], options: Options) -> Result { + let prep = prepare(container)?; + emit_pruned( + &EmitInput { + c: &prep.c, + native: &prep.native, + p: &prep.p, + st: &prep.st, + io: &prep.io, + res: &prep.res, + }, + options, + None, + ) +} + +/// Re-translates a mesh shader together with its paired pixel shader (or +/// `None` for depth-only draws), pruning arbitrary mesh outputs the pixel +/// shader never reads so the mesh shader fits within [`METAL_MESH_OUTPUT_BYTES`] +/// (32 KiB) while keeping both stages' signatures linked for D3D12. +pub fn translate_linked( + mesh: &[u8], + pixel: Option<&[u8]>, + options: Options, +) -> Result<(HostShader, Option), ShaderError> { + let mp = prepare(mesh)?; + let ms_in = EmitInput { + c: &mp.c, + native: &mp.native, + p: &mp.p, + st: &mp.st, + io: &mp.io, + res: &mp.res, + }; + let emit_mesh = |reads: &lower::KeptOutputs| { + let linked = emit_pruned(&ms_in, options, Some(reads))?; + let bytes = mesh_outputs(&linked.dxil) + .ok_or(ShaderError::Malformed( + "linked shader has no mesh output declaration", + ))? + .bytes(); + if bytes > METAL_MESH_OUTPUT_BYTES { + return Err(ShaderError::Unsupported { + offset: 0, + what: "mesh outputs required by the next stage exceed 32 KiB", + }); + } + Ok(linked) + }; + let Some(ps_bytes) = pixel else { + return Ok((emit_mesh(&lower::KeptOutputs::new())?, None)); + }; + let pp = prepare(ps_bytes)?; + if pp.native.stage != HwStage::Ps { + return Err(ShaderError::Malformed( + "mesh output consumer is not a pixel shader", + )); + } + let ps_in = EmitInput { + c: &pp.c, + native: &pp.native, + p: &pp.p, + st: &pp.st, + io: &pp.io, + res: &pp.res, + }; + let full_ps = emit_pruned(&ps_in, options, None)?; + let reads = pixel_input_reads(&full_ps.dxil)?; + let linked_ms = emit_mesh(&reads)?; + let linked_ps = emit_pruned(&ps_in, options, Some(&reads))?; + Ok((linked_ms, Some(linked_ps))) +} + +struct EmitInput<'a> { + c: &'a Container<'a>, + native: &'a NativeProgram, + p: &'a ir::Program, + st: &'a structure::Structured, + io: &'a io::Io, + res: &'a resource::Resources, } /// Emits a program whose earlier stages already ran, without write marks. @@ -517,6 +673,33 @@ pub fn emit_with( res: &resource::Resources, options: Options, ) -> Result { + emit_pruned( + &EmitInput { + c, + native, + p, + st, + io, + res, + }, + options, + None, + ) +} + +fn emit_pruned( + input: &EmitInput<'_>, + options: Options, + keep: Option<&lower::KeptOutputs>, +) -> Result { + let EmitInput { + c, + native, + p, + st, + io, + res, + } = *input; let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { Some(part) => signature(part.data), @@ -591,14 +774,14 @@ pub fn emit_with( bias_as_gradients: options.bias_as_gradients, narrow_waves: options.narrow_waves, }; - let l = match lower::lower(&parts(st, res)) { + let l = match lower::lower_pruned(&parts(st, res), keep) { // Discarded lanes kept on as helpers can read what no surviving // lane does (a register only killed lanes skipped writing); such a // program kills them as the console does (`structure::killing`). Err(_) if !st.discards.is_empty() => { let st = structure::killing(p)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; - lower::lower(&parts(&st, &res))? + lower::lower_pruned(&parts(&st, &res), keep)? } l => l?, }; @@ -742,6 +925,11 @@ mod tests { use super::container::SigElement; use super::shader::Shader; use super::*; + + /// A translated mesh shader's output bytes, as the runtime counts them. + fn mesh_bytes(dxil: &[u8]) -> Option { + mesh_outputs(dxil).map(|o| o.bytes()) + } use crate::native::{ComputeIo, StageIo}; #[test] @@ -1846,28 +2034,33 @@ mod tests { /// `PSV0` and signatures, and their size is Metal's count: 4 bytes per /// component of each declared vertex and primitive. 17 full rows of /// 128 vertices are 34816 bytes; 17 rows of 59 components are under - /// the limit. Other stages have none. + /// the limit. A shader over the limit has its counts capped at its 32 + /// lanes, which export one vertex and one primitive each (the last two + /// columns). Other stages have none. #[test] fn mesh_outputs_are_counted_as_metal_counts_them() { - for (v, p, vr, pr, bytes) in [ - (32, 32, 1, 0, 512), - (128, 128, 16, 0, METAL_MESH_OUTPUT_BYTES), - (128, 128, 17, 0, 34816), - (128, 64, 16, 1, 33792), - (64, 128, 24, 4, METAL_MESH_OUTPUT_BYTES), + for (v, p, vr, pr, ev, ep) in [ + (32, 32, 1, 0, 32, 32), + (128, 128, 16, 0, 128, 128), + (128, 128, 17, 0, 32, 32), + (128, 64, 16, 1, 32, 32), + (64, 128, 24, 4, 64, 128), ] { let ms = sized_mesh(v, p, vr, pr).unwrap_or_else(|e| panic!("{v} {p} {vr} {pr}: {e}")); let o = mesh_outputs(&ms.dxil).expect("a mesh shader's outputs"); assert_eq!( o, MeshOutputs { - vertices: v, - primitives: p, + vertices: ev, + primitives: ep, vertex_components: 4 * vr, primitive_components: 4 * pr, } ); - assert_eq!(o.bytes(), bytes, "{o:?}"); + assert_eq!(o.bytes(), 4 * (4 * vr * ev + 4 * pr * ep), "{o:?}"); + if (ev, ep) == (v, p) { + assert!(o.bytes() <= METAL_MESH_OUTPUT_BYTES, "{o:?}"); + } } let ms = shaped_mesh(128, 128, &HALF_FILLED, 0).unwrap(); let o = mesh_outputs(&ms.dxil).unwrap(); @@ -2448,4 +2641,332 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + /// Builds a synthetic mesh shader declaring `SV_Position` plus 16 `float4` + /// `TEXCOORD` outputs (68 components total). At 128 vertices that is + /// 34,816 bytes (> 32 KiB DXIL budget). + fn wide_mesh_parts( + threads: u32, + max_vertices: u32, + max_primitives: u32, + ) -> (Vec, NativeProgram) { + let mut words = vec![ + 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 + 0x7E10_02FF, // v_mov_b32 v8, 0.25 + 0.25f32.to_bits(), + 0x7E12_02FF, // v_mov_b32 v9, TRIANGLE + TRIANGLE, + 0x7E14_0280, // v_mov_b32 v10, 0.0 + ]; + // param0 = (1.0, 0.5, 0.0, 0.0) + words.extend([0xF800_000F | (32 << 4), 0x0A0A_0607]); + // param1..14 = (0.0, 0.0, 0.0, 0.0) + for k in 1..15u32 { + words.extend([0xF800_000F | ((32 + k) << 4), 0x0A0A_0A0A]); + } + // param15 = (0.0, 0.0, 0.25, 1.0) + words.extend([0xF800_000F | ((32 + 15) << 4), 0x0708_0A0A]); + words.extend([ + 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 outputs: Vec = (0..16u8) + .map(|k| crate::native::VsOutput { + usage: crate::native::Usage::Generic, + row: k + 1, + param: k, + fp16: false, + pack2: false, + }) + .collect(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 12, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs, + clip_cntl: 0, + threads, + max_vertices, + max_primitives, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut sig = vec![SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }]; + for k in 0..16u32 { + sig.push(SigElement { + name: "TEXCOORD".into(), + index: k, + kind: 0, + comp: 9, + interp: 0, + row: Some(k + 1), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }); + } + let osg1 = container::signature(&sig, false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + (bytes, native) + } + + /// A 64-lane mesh shader whose declared `max_vertices`/`max_primitives` + /// (128) would push its 68 output components past 32 KiB tightens those + /// maxima down to its thread count (64), fitting in 17,408 bytes and + /// passing DXIL validation standalone. + #[test] + fn mesh_exceeding_32k_tightens_counts_to_group_threads() { + let (bytes, native) = wide_mesh_parts(64, 128, 128); + 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 ms = emit(&c, &native, &p, &st, &io, &res).unwrap(); + assert_eq!(mesh_bytes(&ms.dxil), Some(68 * 4 * 64)); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut ms.dxil.clone()).unwrap(); + } + } + + /// A 128-lane mesh shader with 68 output components (34,816 B > 32 KiB + /// even at one vertex per lane) linked with its pixel shader: pruning + /// unread attributes (`TEXCOORD1..14`) and unread leading/trailing channels + /// (`TEXCOORD0.zw`, `TEXCOORD15.xy`) brings both stages into matching + /// signatures under 32 KiB, passes DXIL validation, and draws the exact + /// pixel output on hardware and WARP. + #[test] + fn linked_mesh_and_pixel_prune_unused_outputs_under_32k_and_draw() { + let (ms_bytes, ms_native) = wide_mesh_parts(128, 128, 128); + let mc = Container::parse(&ms_bytes).unwrap(); + let mp = ir::build(&ms_native.patched_code(), ms_native.wave64, ms_native.vgprs).unwrap(); + let mst = structure::structure(&mp).unwrap(); + let mres = resource::track(&mp, &ms_native.layout, ms_native.stage, Some(&mst)).unwrap(); + let mio = io::raise(&mp, &ms_native).unwrap(); + let ms_in = EmitInput { + c: &mc, + native: &ms_native, + p: &mp, + st: &mst, + io: &mio, + res: &mres, + }; + // Standalone emission stays over 32 KiB (68 * 4 * 128 = 34,816 B). + let standalone = emit_pruned(&ms_in, Options::default(), None).unwrap(); + assert_eq!(mesh_bytes(&standalone.dxil), Some(34_816)); + assert!(mesh_bytes(&standalone.dxil).unwrap() > METAL_MESH_OUTPUT_BYTES); + + // Depth-only linking (no pixel shader) drops all arbitrary outputs. + let empty = lower::KeptOutputs::new(); + let depth_ms = emit_pruned(&ms_in, Options::default(), Some(&empty)).unwrap(); + assert_eq!(mesh_bytes(&depth_ms.dxil), Some(4 * 4 * 128)); + + // Paired pixel shader declaring the same 17 rows, reading only + // TEXCOORD0.xy and TEXCOORD15.zw. + let p1 = |vdst: u32, attr: u32, ch: u32| { + 0xC800_0000u32 | (vdst << 18) | (attr << 10) | (ch << 8) + }; + let p2 = |vdst: u32, attr: u32, ch: u32| { + 0xC801_0001u32 | (vdst << 18) | (attr << 10) | (ch << 8) + }; + let ps_words = [ + p1(2, 0, 0), + p2(2, 0, 0), // v2 = TEXCOORD0.x (1.0) + p1(3, 0, 1), + p2(3, 0, 1), // v3 = TEXCOORD0.y (0.5) + p1(4, 15, 2), + p2(4, 15, 2), // v4 = TEXCOORD15.z (0.25) + p1(5, 15, 3), + p2(5, 15, 3), // v5 = TEXCOORD15.w (1.0) + 0xF800_180F, + 0x0504_0302, // exp mrt0, v2, v3, v4, v5 done vm + 0xBF81_0000, // s_endpgm + ]; + let ps_inputs: Vec = (0..16u8) + .map(|k| crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: k + 1, + mask: 0xF, + attr: k, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }) + .collect(); + let ps_native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: ps_inputs, + input_addr: 1 << 1, + db_shader_control: 0, + patches: vec![], + }, + code: ps_words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut ps_sig = vec![SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }]; + for k in 0..16u32 { + ps_sig.push(SigElement { + name: "TEXCOORD".into(), + index: k, + kind: 0, + comp: 9, + interp: 0, + row: Some(k + 1), + col: 0, + cols: 4, + usage: 0, + half: false, + }); + } + let isg1 = container::signature(&ps_sig, true); + let osg1 = rows(&[("SV_Target", 16, false)], false); + let ps_bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let pc = Container::parse(&ps_bytes).unwrap(); + let pp = ir::build(&ps_native.patched_code(), ps_native.wave64, ps_native.vgprs).unwrap(); + let pst = structure::structure(&pp).unwrap(); + let pres = resource::track(&pp, &ps_native.layout, ps_native.stage, Some(&pst)).unwrap(); + let pio = io::raise(&pp, &ps_native).unwrap(); + let ps_in = EmitInput { + c: &pc, + native: &ps_native, + p: &pp, + st: &pst, + io: &pio, + res: &pres, + }; + let full_ps = emit_pruned(&ps_in, Options::default(), None).unwrap(); + let reads = pixel_input_reads(&full_ps.dxil).unwrap(); + assert_eq!(reads.len(), 2); + assert_eq!(reads.get(&("TEXCOORD".into(), 0)), Some(&0b0011)); + assert_eq!(reads.get(&("TEXCOORD".into(), 15)), Some(&0b1100)); + + let linked_ms = emit_pruned(&ms_in, Options::default(), Some(&reads)).unwrap(); + let linked_ps = emit_pruned(&ps_in, Options::default(), Some(&reads)).unwrap(); + // SV_Position (4) + TEXCOORD0.xy (2) + TEXCOORD15.zw (2) = 8 components. + assert_eq!(mesh_bytes(&linked_ms.dxil), Some(8 * 4 * 128)); + assert!(!linked_ps.dxil.is_empty()); + + #[cfg(windows)] + { + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut depth_ms.dxil.clone()).unwrap(); + v.validate(&mut linked_ms.dxil.clone()).unwrap(); + v.validate(&mut linked_ps.dxil.clone()).unwrap(); + } + 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, + D3D12_SHADER_VISIBILITY_PIXEL, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .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 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; + } + let root = host + .root_signature_for(&[ + (&linked_ms, D3D12_SHADER_VISIBILITY_MESH), + (&linked_ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &linked_ms.dxil, &linked_ps.dxil) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Constants(vec![0])), + ], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}: unexpected pixel {:?}", + texels.first() + ); + } + } + } }