diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 242ea26261..c941034877 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -270,12 +270,12 @@ pub fn run( t.unlisted ); println!( - "I/O {} of {} vertex and pixel programs raised ({} interpolations, \ + "I/O {} of {} vertex, geometry and pixel programs raised ({} interpolations, \ {} vertex values; exports {:?}, {} still f16 pairs)", t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed ); println!( - "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines", + "DXIL {} emitted of {} vertex, geometry and pixel programs; {} validated, {} pipelines", t.emitted, t.emit_programs, t.validated, t.pipelines ); println!( @@ -508,14 +508,22 @@ fn translate( }; for p in programs { t.programs += 1; - match victory_shader::range::build(&p.patched_code(), p.wave64, p.vgprs) { + match p + .translation_code() + .and_then(|code| victory_shader::range::build(&code, p.wave64, p.vgprs)) + { Ok((program, structured)) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); // Per-lane descriptors are traced on the per-lane form; its // failure is listed after the resources' and I/O's. let lanes = structured.as_ref().ok(); - let res = match resource::track(&program, &p.layout, p.stage, lanes) { + let io = io::raise(&program, &p); + let res = match &io { + Ok(io) => resource::track_io(&program, &p.layout, p.stage, lanes, io), + Err(_) => resource::track(&program, &p.layout, p.stage, lanes), + }; + let res = match res { Ok(r) => { tally_resources(&p, &r, t); Some(r) @@ -531,12 +539,12 @@ fn translate( None } }; - let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); + let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps | HwStage::Gs); let compute = p.stage == HwStage::Cs; let mut raised = None; if graphics || compute || p.stage == HwStage::Ms { t.io_programs += usize::from(graphics); - match io::raise(&program, &p) { + match io { Ok(r) => { if graphics { tally_io(&r, t); @@ -620,6 +628,8 @@ fn check( let made = match shader.stage { HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), HwStage::Cs => h.compute_pipeline(&shader).map(drop), + HwStage::Gs => host::stub_vs(&shader) + .and_then(|vs| h.geometry_pipeline(&vs, &shader, stub_ps).map(drop)), HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop), _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)), }; @@ -703,6 +713,15 @@ fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize { fn tally_io(r: &io::Io, t: &mut Tally) { t.io_raised += 1; + if let Some(gs) = &r.geometry { + for op in gs.messages.values() { + let name = match op { + victory_shader::geometry::StreamOp::Emit(_) => "geometry vertex", + victory_shader::geometry::StreamOp::Cut => "strip cut", + }; + *t.exports.entry(name).or_default() += 1; + } + } for (_, i) in &r.interps { match i { io::Interp::Interpolated { .. } => t.interpolated += 1, diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index e03ca0d261..c5e7aadeef 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -9,9 +9,8 @@ //! containers are shared by content hash and translated once, on first //! use (decision 0003). //! -//! shortcut: only vertex plus pixel pipelines from streams and compute -//! pipelines get host pipelines; mesh, tessellation and geometry stages, -//! and the plain graphics description, keep their containers only. The 32-byte +//! Host graphics streams support vertex, geometry, mesh and pixel stages. +//! Tessellation and the plain graphics description keep their containers only. The 32-byte //! packet after the header stays zero: titles only copy it inline, which //! our null command-list limits keep from running. #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -187,18 +186,13 @@ fn with_resources( container: &[u8], host: victory_shader::emit::HostShader, ) -> Result { - use victory_shader::{Container, FourCC, HwStage}; + use victory_shader::{Container, FourCC}; let c = Container::parse(container).map_err(|e| e.to_string())?; let used = match c.part(FourCC::DXIL).or(c.part(FourCC::ACCC)) { Some(part) => victory_shader::native_programs(part.data) .map_err(|e| e.to_string())? .into_iter() - .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs - ) - }) + .find(|p| p.stage == host.stage) .map(|p| p.used) .unwrap_or_default(), None => Vec::new(), diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 354fc721ae..49c20ad005 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -407,14 +407,18 @@ impl HostPipeline { if compute.is_none() && shaders .iter() - .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh")) + .any(|s| !matches!(s.stage, "vertex" | "pixel" | "geometry" | "mesh")) { return refuse( - "only vertex, mesh, pixel and compute stages are translated", + "only vertex, geometry, mesh, pixel and compute stages are translated", shaders, ); } let mesh = find("mesh"); + let geometry = find("geometry"); + if mesh.is_some() && geometry.is_some() { + return refuse("geometry and mesh stages in one pipeline", shaders); + } let stages = if let Some(cs) = compute { vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] } else { @@ -425,6 +429,7 @@ impl HostPipeline { }; let mut stages = vec![first]; stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + stages.extend(geometry.map(|gs| (gs, D3D12_SHADER_VISIBILITY_GEOMETRY))); stages }; if mesh.is_some() && !host()?.mesh_shaders() { @@ -688,24 +693,42 @@ impl HostPipeline { }); } - // Rectangle lists: a geometry shader made for the vertex shader adds - // each rectangle's fourth corner (else rectangles are expanded on - // the CPU from vertex inputs, see `draw`). - let gs = match (g.topology.0, stages.first().and_then(|(s, _)| s.translated())) { - (RECTANGLES, Some(vs)) => match victory_shader::emit::rectangle_gs(&vs.host.dxil) { - Ok(gs) => gs, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "no rectangle geometry shader"); - Vec::new() + let pixel = stages + .iter() + .position(|(_, vis)| *vis == D3D12_SHADER_VISIBILITY_PIXEL) + .map_or_else(Default::default, code); + // A translated geometry stage (which does not complete + // rectangles); or, for rectangle lists, a geometry shader made + // for the vertex shader that adds each rectangle's fourth corner + // (else rectangles are expanded on the CPU from vertex inputs, + // see `draw`). Only the made shader completes rectangles. + let (gs, rectangles) = + match (geometry, g.topology.0, stages.first().and_then(|(s, _)| s.translated())) { + (Some(gs), RECTANGLES, _) => { + let _ = gs; + return refuse("a geometry stage drawing rectangle lists", shaders); } - }, - _ => Vec::new(), - }; + (Some(gs), _, _) => ( + gs.translated() + .map_or_else(Vec::new, |s| s.host.dxil.clone()), + false, + ), + (None, RECTANGLES, Some(vs)) => { + match victory_shader::emit::rectangle_gs(&vs.host.dxil) { + Ok(gs) => (gs, true), + Err(e) => { + tracing::warn!(error = %e, ?shaders, "no rectangle geometry shader"); + (Vec::new(), false) + } + } + } + _ => (Vec::new(), false), + }; let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), - PS: code(1), + PS: pixel, GS: D3D12_SHADER_BYTECODE { pShaderBytecode: if gs.is_empty() { std::ptr::null() } else { gs.as_ptr().cast() }, BytecodeLength: gs.len(), @@ -729,7 +752,7 @@ impl HostPipeline { let name = super::library::name( "graphics", &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs], + &[&code_bytes(&code(0)), &code_bytes(&pixel), &gs], &state, ); let started = std::time::Instant::now(); @@ -765,7 +788,7 @@ impl HostPipeline { return None; } }; - tracing::info!(?shaders, ms = started.elapsed().as_millis(), rectangles = !gs.is_empty(), "host pipeline"); + tracing::info!(?shaders, ms = started.elapsed().as_millis(), rectangles, "host pipeline"); crate::host::name(&pso, || format!("{shaders:?}")); tracing::debug!( ?shaders, @@ -783,7 +806,7 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), - rectangles: !gs.is_empty(), + rectangles, slots: g.slots(), inputs: g.elements(), marks, diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 222deb74da..2e4235e159 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -150,7 +150,7 @@ pub(crate) struct Binding { } pub(crate) struct Psv<'a> { - /// PSV shader kind: 0 pixel, 1 vertex, 5 compute. + /// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. pub stage: u8, /// Vertex: writes `SV_Position`. Pixel: writes depth. pub flag: bool, diff --git a/crates/victory-shader/src/emit/geometry_tests.rs b/crates/victory-shader/src/emit/geometry_tests.rs new file mode 100644 index 0000000000..48c72b3a6d --- /dev/null +++ b/crates/victory-shader/src/emit/geometry_tests.rs @@ -0,0 +1,446 @@ +//! A synthetic GS loads three different vertices, moves the first one, +//! and emits a triangle strip. Compare its actual rasterized coverage +//! with the same operation compiled to DXIL by the Windows SDK. + +fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +fn geometry_part() -> Vec { + geometry_part_with(false) +} + +fn geometry_part_with(params: bool) -> Vec { + fixture(params, false, false) +} + +/// The GS of [`geometry_part`]; with `params`, each vertex also carries its +/// input row 1 (TEXCOORD0.xy, LDS dwords 4-5) in ring dwords 4-5, which the +/// copy VS exports as param0 (signature row 1). With `rewrite`, the GS +/// stores to vertex 0's slot again after emitting all three. With +/// `batched`, it stores all three vertices before the first EMIT (a +/// compiler batching ring writes). +fn fixture(params: bool, rewrite: bool, batched: bool) -> Vec { + let vertex_dwords = if params { 6 } else { 4 }; + let stride = 4 * 3 * vertex_dwords; + let mut words = vec![ + // Establish EXEC from the merged GS lane count in s3. + 0x9404ff03, + 0x80008, + 0x92fe8004, + 0xbf06c004, + 0x85fe7ec1, + // Read the ring page from the internal table, then add the wave offset. + 0xbe8a0308, + 0x870bff09, + 255, + 0xf4000305, + 0xfa0000b8, + 0x8f0c880c, + 0x810c020c, + // Lane within the wave; v5 = wave base + lane * stride bytes. + 0xd7650004, + 0x000100c1, + 0xd7660004, + 0x000208c1, + 0xd5430005, + ]; + if stride == 48 { + words.push((12 << 18) | (260 << 9) | 176); + } else { + words.extend([(12 << 18) | (260 << 9) | 255, stride]); + } + words.extend([ + // Unpack the first, second, and third vertex offsets to v6/v7/v8. + 0x340c0082, + 0x360c0cff, + 0x3fffc, + 0x340e00f9, + 0x05860682, + 0x34100282, + 0x361010ff, + 0x3fffc, + ]); + for v in 0..3 { + let addr = 6 + v; + words.extend([0xd8dc0100, 10 << 24 | addr, 0xd8dc0302, 12 << 24 | addr]); + if params { + words.extend([0xd8dc0504, 14 << 24 | addr]); // ds_read2_b32 v[14:15], dwords 4, 5 + } + if v == 0 { + // v_add_f32 v10, 0.5, v10 + words.push(0x06000000 | 10 << 17 | 10 << 9 | 240); + } + for pair in 0..vertex_dwords / 2 { + let k = vertex_dwords * v + 2 * pair; + let src = 10 + 2 * pair; + words.extend([ + 0xd8380000 | (k + 1) << 8 | k, + (src + 1) << 16 | src << 8 | 5, + ]); + } + if !batched { + words.push(0xbf900022); // emit + } + } + if batched { + words.extend([0xbf900022; 3]); + } + if rewrite { + words.extend([0xd8380100, 11 << 16 | 10 << 8 | 5]); // ds_write2_b32 v5, v10, v11 offsets 0, 1 + } + words.extend([0xbf900012, 0xbf900003, 0xbf810000]); // cut, done, endpgm + let mut copy = vec![ + 0x8701ff01, + 255, + 0x34000082, + 0xf4000000, + 0xfa0000b8, + 0xd7460006, + 0x04011000, // byte address of this vertex + 0xd8dc0100, + 6, + 0xd8dc0302, + 2 << 24 | 6, + ]; + if params { + // ds_read2_b32 v[8:9], dwords 4, 5; exp param0 v8, v9, off, off + copy.extend([0xd8dc0504, 8 << 24 | 6, 0xf8000203, 0x0000_0908]); + } + copy.extend([0xf80008cf, 0x03020100, 0xbf810000]); // exp pos0, v0..v3 + // param0 is generic (6) output row 1. + let outputs: &[[u8; 6]] = if params { &[[6, 1, 0, 0, 0, 0]] } else { &[] }; + crate::native::tests::geometry_part_sized(&bytes(&words), &bytes(©), vertex_dwords, outputs) +} + +#[cfg(windows)] +#[test] +fn geometry_vertices_match_reference_draw() { + reference_draw(false); +} + +/// The parameter-export path: a ring dword the copy VS exports as param0 +/// reaches the pixel shader's TEXCOORD0 (signature row 1). +#[cfg(windows)] +#[test] +fn geometry_parameters_match_reference_draw() { + reference_draw(true); +} + +#[cfg(windows)] +fn reference_draw(params: bool) { + use super::{HostShader, container, host, translate, validator::Validator}; + use crate::{Container, FourCC, HwStage}; + let Some(dxc) = Validator::default_path() + .map(|p| p.with_file_name("dxc.exe")) + .filter(|p| p.exists()) + else { + eprintln!("no dxc.exe beside dxil.dll: the reference draw was skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!( + "victory-gs-draw-{}-{}", + std::process::id(), + u8::from(params) + )); + std::fs::create_dir_all(&dir).unwrap(); + let hlsl = dir.join("triangle.hlsl"); + let source = if params { + r#" + struct V { float4 p: SV_Position; float2 t: TEXCOORD0; }; + V vs(float4 p: POSITION) { V v; v.p=p; v.t=p.xy*0.5+0.5; return v; } + [maxvertexcount(3)] void gs(triangle V v[3], inout TriangleStream s) { + v[0].p.x += 0.5; s.Append(v[0]); s.Append(v[1]); s.Append(v[2]); s.RestartStrip(); + } + float4 ps(V v): SV_Target { return float4(1, v.t, 1); } + "# + } else { + r#" + struct V { float4 p: SV_Position; }; + V vs(float4 p: POSITION) { V v; v.p=p; return v; } + [maxvertexcount(3)] void gs(triangle V v[3], inout TriangleStream s) { + v[0].p.x += 0.5; s.Append(v[0]); s.Append(v[1]); s.Append(v[2]); s.RestartStrip(); + } + float4 ps(): SV_Target { return float4(1, 0, 0, 1); } + "# + }; + std::fs::write(&hlsl, source).unwrap(); + let compile = |entry, stage| { + let output = dir.join(format!("{entry}.dxil")); + let proc = std::process::Command::new(&dxc) + .args(["-T", &format!("{entry}_6_6"), "-E", entry, "-Fo"]) + .arg(&output) + .arg(&hlsl) + .output() + .unwrap(); + assert!( + proc.status.success(), + "{}", + String::from_utf8_lossy(&proc.stderr) + ); + HostShader { + stage, + dxil: std::fs::read(output).unwrap(), + ..host::stub_ps() + } + }; + let vs = compile("vs", HwStage::Vs); + let ps = compile("ps", HwStage::Ps); + let reference = compile("gs", HwStage::Gs); + let native = geometry_part_with(params); + let packed = Container::parse(&reference.dxil).unwrap(); + let parts: Vec<_> = packed + .parts + .iter() + .map(|p| { + ( + &p.fourcc.0, + if p.fourcc == FourCC::DXIL { + &native + } else { + p.data + }, + ) + }) + .collect(); + let mut gs = translate(&container::build(&parts)).unwrap(); + Validator::load(Validator::default_path().as_deref()) + .unwrap() + .validate(&mut gs.dxil) + .unwrap(); + let vertices = [ + -0.75, -0.75, 0.5, 1.0, -0.75, 0.75, 0.5, 1.0, 0.75, -0.75, 0.5, 1.0, + ]; + let draw = host::Draw { + roots: vec![], + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 16, + size: (16, 16), + mesh_groups: 0, + }; + // Two GPU tests dispatching at once can crash the WARP adapter, as on + // CI: take the same lock as the other dispatching tests. + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for warp in [false, true] { + let backend = if warp { "WARP" } else { "the default adapter" }; + let Ok(host) = host::Host::new(warp) else { + eprintln!("no device on {backend}: its draw was skipped"); + continue; + }; + let run = |stage| { + let (root, pso) = host.geometry_pipeline(&vs, stage, &ps).unwrap(); + host.draw(&root, &pso, &draw).unwrap() + }; + let expected = run(&reference); + let covered = expected.iter().filter(|p| p[0] == 1.0).count(); + assert!( + (10..190).contains(&covered), + "reference covered {covered}/256 pixels" + ); + assert_eq!(run(&gs), expected); + eprintln!( + "{backend}, params {params}: the translated GS drew the reference's {covered}/256 pixels" + ); + } + for name in ["triangle.hlsl", "vs.dxil", "ps.dxil", "gs.dxil"] { + std::fs::remove_file(dir.join(name)).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); +} + +#[test] +fn geometry_copy_rejects_a_change_to_the_active_lanes() { + let native = crate::native_programs(&geometry_part()) + .unwrap() + .pop() + .unwrap(); + let program = + crate::ir::build(&native.translation_code().unwrap(), native.wave64, native.vgprs).unwrap(); + let crate::native::StageIo::Gs(mut geometry) = native.io else { + panic!("missing GS data"); + }; + let original = geometry.copy.code.clone(); + let mut with_mov = |mov| { + geometry.copy.code = bytes(&[mov]); + geometry.copy.code.extend_from_slice(&original); + crate::geometry::raise(&program, &geometry) + }; + with_mov(0xbe94_0380).unwrap(); // s_mov_b32 s20, 0 + for mov in [0xbefe_0380, 0xbeff_0380] { + // s_mov_b32 exec_lo / exec_hi, 0 + let error = + with_mov(mov).expect_err("masked copy exports cannot be emitted unconditionally"); + assert!(matches!( + error, + crate::ShaderError::Unsupported { + offset: 0, + what: "a geometry copy execution mask" + } + )); + } +} + +#[test] +fn geometry_copy_rejects_untraced_reads_and_exports() { + let native = crate::native_programs(&geometry_part()) + .unwrap() + .pop() + .unwrap(); + let program = crate::ir::build(&native.translation_code().unwrap(), native.wave64, native.vgprs).unwrap(); + let crate::native::StageIo::Gs(mut geometry) = native.io else { + panic!("missing GS data"); + }; + let original = geometry.copy.code.clone(); + // The first paired load now reads at the uninitialised v17 instead + // of the copy vertex address in v6. + geometry.copy.code[8 * 4..9 * 4].copy_from_slice(&17u32.to_le_bytes()); + assert!(crate::geometry::raise(&program, &geometry).is_err()); + geometry.copy.code = original; + // Redirect an export source to an unwritten VGPR. + let last_export_sources = geometry.copy.code.len() - 8; + geometry.copy.code[last_export_sources] = 19; + assert!(crate::geometry::raise(&program, &geometry).is_err()); + // Unconditional early termination cannot be reported as a successful + // copy of an empty output signature. + geometry.copy.code = bytes(&[0xbf810000]); + assert!(crate::geometry::raise(&program, &geometry).is_err()); +} + +#[test] +fn geometry_io_keeps_component_order_and_constants_in_the_copy_export() { + use crate::geometry::{Component, StreamOp}; + let native = crate::native_programs(&geometry_part()) + .unwrap() + .pop() + .unwrap(); + let program = crate::ir::build(&native.translation_code().unwrap(), native.wave64, native.vgprs).unwrap(); + let crate::native::StageIo::Gs(mut geometry) = native.io else { + panic!("missing GS data"); + }; + geometry.copy.code.truncate(geometry.copy.code.len() - 4); + // v_mov_b32 v4, 1.0; exp param0, v2, v0, v4, v1; endpgm + geometry + .copy + .code + .extend(bytes(&[0x7e0802f2, 0xf800020f, 0x01040002, 0xbf810000])); + let streams = crate::geometry::raise(&program, &geometry).unwrap(); + let mut vertices = 0; + for (index, operation) in streams.messages.values().enumerate() { + match operation { + StreamOp::Emit(outputs) => { + let [pos, param] = outputs.as_slice() else { + panic!("copy exports"); + }; + assert_eq!( + param.channels, + [ + pos.channels[2], + pos.channels[0], + Some(Component::Constant(1f32.to_bits())), + pos.channels[1] + ] + ); + vertices += 1; + } + StreamOp::Cut => assert_eq!(index, 3), + } + } + assert_eq!(vertices, 3); +} + +/// The program and stage data of a fixture. +fn raised(part: &[u8]) -> Result { + let native = crate::native_programs(part).unwrap().pop().unwrap(); + let program = + crate::ir::build(&native.translation_code().unwrap(), native.wave64, native.vgprs).unwrap(); + let crate::native::StageIo::Gs(geometry) = native.io else { + panic!("missing GS data"); + }; + crate::geometry::raise(&program, &geometry) +} + +#[test] +fn geometry_parameters_raise_into_their_copy_export() { + use crate::geometry::StreamOp; + let streams = raised(&geometry_part_with(true)).unwrap(); + let emits: Vec<_> = streams + .messages + .values() + .filter_map(|m| match m { + StreamOp::Emit(outputs) => Some(outputs), + StreamOp::Cut => None, + }) + .collect(); + assert_eq!(emits.len(), 3); + for outputs in emits { + let [param, pos] = outputs.as_slice() else { + panic!("copy exports: {outputs:?}"); + }; + assert_eq!((param.target, pos.target), (32, 12)); + assert!(pos.channels.iter().all(Option::is_some)); + assert!(param.channels[..2].iter().all(Option::is_some)); + assert_eq!(param.channels[2..], [None, None]); + } + // Vertex i reads input dwords 0-5: rows 0 and 1. + let reads: Vec<_> = streams.reads.values().flatten().map(|r| (r.1, r.2)).collect(); + for v in 0..3 { + for dword in 0..6 { + assert!(reads.contains(&(v, dword)), "vertex {v} dword {dword}"); + } + } +} + +#[test] +fn a_ring_store_after_its_vertex_was_emitted_is_refused() { + assert!(raised(&fixture(false, false, false)).is_ok()); + assert!(matches!( + raised(&fixture(false, true, false)), + Err(crate::ShaderError::Unsupported { + what: "a geometry ring store to a vertex already emitted", + .. + }) + )); +} + +/// A GS that stores every vertex's ring slots before the first EMIT (the +/// write batching that made #1399 draw nothing): each EMIT still takes its +/// own vertex's values, read from that vertex's input. +#[test] +fn ring_writes_batched_before_the_emits_stay_with_their_vertex() { + use crate::geometry::{Component, StreamOp}; + let streams = raised(&fixture(false, false, true)).unwrap(); + let read = |v: crate::ir::Value| { + streams + .reads + .values() + .flatten() + .find(|r| r.0 == v) + .map(|r| (r.1, r.2)) + }; + let emits: Vec<_> = streams + .messages + .values() + .filter_map(|m| match m { + StreamOp::Emit(outputs) => Some(outputs), + StreamOp::Cut => None, + }) + .collect(); + assert_eq!(emits.len(), 3); + for (k, outputs) in emits.into_iter().enumerate() { + let [pos] = outputs.as_slice() else { + panic!("copy exports: {outputs:?}"); + }; + // y, z, w come straight from vertex k's input dwords 1-3 (x of + // vertex 0 is moved by 0.5 before it is stored). + for ch in 1..4 { + let Some(Component::Value(v)) = pos.channels[ch] else { + panic!("emit {k} channel {ch}: {:?}", pos.channels[ch]); + }; + assert_eq!(read(v), Some((k as u8, ch as u16)), "emit {k} channel {ch}"); + } + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index da16ad7d2c..3fa17e04bc 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -388,6 +388,22 @@ impl Host { Ok((root, pso)) } + /// A triangle pipeline with a geometry stage between VS and PS. + pub fn geometry_pipeline( + &self, + vs: &HostShader, + gs: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[ + (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + (gs, D3D12_SHADER_VISIBILITY_GEOMETRY), + ])?; + let pso = self.pipeline_gs(&root, &vs.dxil, &gs.dxil, &ps.dxil)?; + Ok((root, pso)) + } + /// A graphics pipeline with the given root signature; vertex inputs /// packed in register order. pub fn pipeline_with( diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 4c00811670..0dbc0a752e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -21,6 +21,7 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Structured}; mod bvh; +mod geometry; type Why = &'static str; @@ -550,6 +551,9 @@ impl<'a> Lower<'a> { } } let mut s = Shader::new(x.native.stage == HwStage::Ps); + if let StageIo::Gs(gs) = &x.native.io { + s.gs = Some(gs.max_vertices); + } s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); let insts = || p.blocks.iter().flat_map(|b| &b.insts); @@ -1468,6 +1472,7 @@ impl<'a> Lower<'a> { Some(&input) => self.input(input), // Registers no one set read as zero (the validator // refuses reads of undef). + None if self.s.gs.is_some() => Val::Missing("a geometry VGPR input"), None => Val::I32(self.s.m.i32(0)), }, }; @@ -1588,46 +1593,7 @@ impl<'a> Lower<'a> { /// An input element's channel as declared (16-bit ones as 32-bit floats). fn load_any_input(&mut self, id: usize, col: u8) -> Val { - let e = &mut self.s.inputs[id]; - e.usage |= 1 << col; - let (int, bit) = (e.comp != 9, e.comp == 1); - let ty = if bit { - self.s.t.i1 - } else if int { - self.s.t.i32 - } else { - self.s.t.f32 - }; - let suffix = if bit { - ".i1" - } else if int { - ".i32" - } else { - ".f32" - }; - let entry = self.s.entry; - let args = [ - self.s.m.i32(id as u32), - self.s.m.i32(0), - self.s.m.i8(col), - self.s.m.undef(self.s.t.i32), - ]; - let v = self.s.op( - entry, - &format!("loadInput{suffix}"), - Attr::ReadNone, - ty, - 4, - &args, - ); - if bit { - let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32); - Val::I32(z) - } else if int { - Val::I32(v) - } else { - Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32)) - } + self.load_vertex_input(id, col, None) } /// The DXIL form of an IR value. @@ -3502,6 +3468,9 @@ impl<'a> Lower<'a> { fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; let offset = inst.machine.offset; + if self.geometry_inst(inst, offset)? { + return Ok(()); + } let name = inst.name(); self.mask_ok = match self.mask_data { MaskData::Console => true, diff --git a/crates/victory-shader/src/emit/lower/geometry.rs b/crates/victory-shader/src/emit/lower/geometry.rs new file mode 100644 index 0000000000..510173b81b --- /dev/null +++ b/crates/victory-shader/src/emit/lower/geometry.rs @@ -0,0 +1,193 @@ +//! Geometry-stage lowering: the single-stream triangle geometry +//! programs of decision 0003's lowering, moved out of `lower.rs` so +//! that file stays under the asset policy's 512 KiB limit. + +use super::{Lower, StageIo, Stop, Val, Why, unsupported}; +use crate::emit::bitcode::{Attr, Cast}; +use crate::ir::Inst; + +impl<'a> Lower<'a> { + pub(crate) fn load_vertex_input(&mut self, id: usize, col: u8, vertex: Option) -> Val { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let (int, bit) = (e.comp != 9, e.comp == 1); + let ty = if bit { + self.s.t.i1 + } else if int { + self.s.t.i32 + } else { + self.s.t.f32 + }; + let suffix = if bit { + ".i1" + } else if int { + ".i32" + } else { + ".f32" + }; + let entry = self.s.entry; + let index = match vertex { + Some(n) => self.s.m.i32(u32::from(n)), + None => self.s.m.undef(self.s.t.i32), + }; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + index, + ]; + let v = self.s.op( + entry, + &format!("loadInput{suffix}"), + Attr::ReadNone, + ty, + 4, + &args, + ); + if bit { + let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32); + Val::I32(z) + } else if int { + Val::I32(v) + } else { + Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32)) + } + } + + /// A geometry program's instruction: ring addresses, ring reads, + /// and stream messages are handled here; anything else falls + /// through to the ordinary instruction path. Returns whether it + /// handled the instruction. + pub(crate) fn geometry_inst(&mut self, inst: &'a Inst, offset: usize) -> Result { + let Some(gs) = self.x.io.geometry.as_deref() else { + return Ok(false); + }; + if gs.address_steps.contains(&offset) { + for &(_, value) in &inst.writes { + self.vals.insert( + value, + Val::Missing("a geometry ring address used as shader data"), + ); + } + return Ok(true); + } + if let Some(reads) = gs.reads.get(&offset) { + for &(v, index, word) in reads { + let row = u8::try_from(word / 4) + .map_err(|_| unsupported(offset, "a geometry input row"))?; + let (id, col) = self.find_input(row, (word % 4) as u8).ok_or(unsupported( + offset, + "a geometry input missing from the signature", + ))?; + if self.s.inputs[id].half || index >= 3 { + return Err(unsupported(offset, "a geometry input format or vertex")); + } + let input = self.load_vertex_input(id, col, Some(index)); + self.vals.insert(v, input); + } + return Ok(true); + } + if let Some(message) = gs.messages.get(&offset) { + self.geometry_message(message) + .map_err(|why| unsupported(offset, why))?; + return Ok(true); + } + if inst.name() == "ds_write2_b32" { + // Raising captured each stored SSA value at its emit site. + return Ok(true); + } + Ok(false) + } + + fn geometry_message(&mut self, message: &crate::geometry::StreamOp) -> Result<(), Why> { + use crate::geometry::{Component, StreamOp}; + let (name, opcode) = match message { + StreamOp::Cut => ("cutStream", 98), + StreamOp::Emit(exports) => { + let StageIo::Gs(gs) = &self.x.native.io else { + return Err("geometry stage data"); + }; + let StageIo::Vs { outputs, .. } = &gs.copy.io else { + return Err("geometry copy outputs"); + }; + let mut written = vec![0u8; self.s.outputs.len()]; + for export in exports { + let row = match export.target { + 12 => self + .s + .outputs + .iter() + .find(|e| e.kind == 3) + .and_then(|e| e.row), + t @ 32..=63 => { + let o = outputs + .iter() + .find(|o| o.param == t - 32) + .ok_or("a geometry output parameter")?; + if o.fp16 || o.pack2 { + return Err("a packed geometry output"); + } + Some(u32::from(o.row)) + } + _ => return Err("a geometry copy export target"), + } + .ok_or("a geometry output signature row")?; + for (channel, source) in export.channels.iter().enumerate() { + let Some(src) = source else { + continue; + }; + let ch = channel as u8; + let Some(id) = self.s.outputs.iter().position(|e| { + e.row == Some(row) && (e.col..e.col + e.cols).contains(&ch) + }) else { + continue; + }; + if self.s.outputs[id].half { + return Err("a 16-bit geometry output"); + } + let col = ch - self.s.outputs[id].col; + let bits = match *src { + Component::Value(v) => self.i32_of(v)?, + Component::Constant(n) => self.s.m.i32(n), + }; + let (op, x) = if self.s.outputs[id].comp == 9 { + ("storeOutput.f32", self.as_float(bits)) + } else { + ("storeOutput.i32", bits) + }; + written[id] |= 1 << col; + self.s.outputs[id].usage |= 1 << col; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + x, + ]; + self.s + .op(self.cur, op, Attr::NoUnwind, self.s.t.void, 5, &args); + } + } + if self + .s + .outputs + .iter() + .zip(written) + .any(|(e, w)| w != (1 << e.cols) - 1) + { + return Err("a geometry output missing from the copy exports"); + } + ("emitStream", 97) + } + }; + let stream = self.s.m.i8(0); + self.s.op( + self.cur, + name, + Attr::NoUnwind, + self.s.t.void, + opcode, + &[stream], + ); + Ok(()) + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 91a5e64b98..cff80f6fcf 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -207,6 +207,8 @@ mod crosslane_tests; mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; +#[cfg(test)] +mod geometry_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; @@ -390,23 +392,35 @@ pub fn translate_with(container: &[u8], options: Options) -> Result> 16 == 2); let native = crate::native_programs(dxil.data)? .into_iter() .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms - ) + if geometry { + p.stage == HwStage::Gs + } else { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms + ) + } }) .ok_or(ShaderError::Unsupported { offset: 0, - what: "a container without a vertex, pixel, compute or mesh program", + what: "a container without a vertex, geometry, pixel, compute or mesh program", })?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). - let (p, st) = crate::range::build(&native.patched_code(), native.wave64, native.vgprs)?; - let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; - let io = io::raise(&p, &native)?; + let code = native.translation_code()?; + let (p, st) = crate::range::build(&code, native.wave64, native.vgprs)?; + let io = io::raise(&p, &native); + let res = match &io { + Ok(raised) => { + resource::track_io(&p, &native.layout, native.stage, st.as_ref().ok(), raised) + } + Err(_) => resource::track(&p, &native.layout, native.stage, st.as_ref().ok()), + }?; + let io = io?; let st = st?; emit_with(&c, &native, &p, &st, &io, &res, options) } @@ -439,9 +453,65 @@ pub fn emit_with( None => Ok(Vec::new()), } }; + if native.stage == HwStage::Gs + && (io.geometry.is_none() || !matches!(native.io, crate::native::StageIo::Gs(_))) + { + return Err(ShaderError::Unsupported { + offset: 0, + what: "unraised geometry stream I/O", + }); + } let pixel = native.stage == HwStage::Ps; let mut inputs = sig(FourCC::ISG1)?; let mut outputs = sig(FourCC::OSG1)?; + if let crate::native::StageIo::Gs(gs) = &native.io { + use crate::dxbc::u32_at; + let info = c.part(FourCC::PSV0).and_then(|p| { + let size = u32_at(p.data, 0).ok()? as usize; + p.data.get(4..)?.get(..size) + }); + let supported = info.is_some_and(|i| { + i.len() >= 36 + && i[24] == 2 + && i[25] == 0 + && u32_at(i, 0) == Ok(3) + && u32_at(i, 4) == Ok(5) + && u32_at(i, 8) == Ok(1) + && u32::from(u16::from_le_bytes([i[26], i[27]])) == gs.max_vertices + && (1..=1024).contains(&gs.max_vertices) + }); + if !supported { + return Err(ShaderError::Unsupported { + offset: 0, + what: "the geometry primitive or stream configuration", + }); + } + for e in &mut inputs { + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0, 9) => 2, + (0, _) => 1, + _ => { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a geometry system input", + }); + } + }; + } + // DXIL wants one interpolation mode per packed row: a row holding + // an integer element is constant throughout. + let constant: Vec = inputs + .iter() + .filter(|e| e.interp == 1) + .filter_map(|e| e.row) + .collect(); + for e in &mut inputs { + if e.row.is_some_and(|r| constant.contains(&r)) { + e.interp = 1; + } + } + } // Interpolation as DXC declares it by default; pixel inputs that are // read get the mode their barycentrics say. let interpolated = if pixel { &mut inputs } else { &mut outputs }; diff --git a/crates/victory-shader/src/geometry.rs b/crates/victory-shader/src/geometry.rs new file mode 100644 index 0000000000..397c17cac9 --- /dev/null +++ b/crates/victory-shader/src/geometry.rs @@ -0,0 +1,503 @@ +//! LDS-backed geometry stage I/O. One GS invocation receives its input +//! vertices' LDS offsets packed in v0/v1. It writes a private slice of the +//! GS-to-VS ring and sends stream messages. Its copy VS selects components +//! of each vertex from that slice and exports them. + +use std::collections::{BTreeMap, HashMap}; + +use crate::gfx10::{Fields, Operand, Sdwa}; +use crate::ir::{Inst, Program, Reg, Value}; +use crate::native::{GeometryIo, StageIo}; +use crate::{ShaderError, ir}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Component { + Value(Value), + Constant(u32), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VertexOutput { + /// Native export target (12 for position, 32+ for parameters). + pub target: u8, + pub channels: [Option; 4], +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StreamOp { + Emit(Vec), + Cut, +} + +/// The SSA values supplied by each input load, and the outputs live at +/// each stream instruction. Offsets are relative to the GS machine code. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Streams { + /// (destination SSA value, input vertex, signature dword). + pub reads: BTreeMap>, + pub messages: BTreeMap, + pub(crate) address_steps: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Word { + Unknown, + Imm(u32), + Packed(u8), + Shifted(u8), + Input(u8), + TableLo, + TableHi, + MaskedHi, + RingPage, + RingBase, + WaveOffset, + WaveBase, + LaneLo, + Lane, + Output, + VertexOffset, + VertexBytes, + RingElement(u32), +} + +fn fail(inst: &Inst, what: &'static str) -> ShaderError { + ShaderError::Unsupported { + offset: inst.machine.offset, + what, + } +} + +#[derive(Default)] +struct Origins(HashMap); + +impl Origins { + fn get(&self, i: &Inst, op: &Operand) -> Word { + let r = match *op { + Operand::Vector { reg, .. } => Reg::V(reg), + Operand::Scalar { code, .. } => Reg::S(code), + Operand::Literal(n) => return Word::Imm(n), + Operand::Const(n) => { + return crate::resource::inline(n).map_or(Word::Unknown, Word::Imm); + } + _ => return Word::Unknown, + }; + i.read(r) + .and_then(|v| self.0.get(&v).copied()) + .unwrap_or(Word::Unknown) + } + + fn input(&mut self, p: &Program, reg: Reg, word: Word) { + if let Some((_, v)) = p.inputs.iter().find(|(r, _)| *r == reg) { + self.0.insert(*v, word); + } + } + + fn step(&mut self, i: &Inst, stride: u32) -> Option { + use Word::*; + let (dst, value) = match &i.fields { + Fields::Sop { + dst: Some(dst), + src, + .. + } => { + let a = src.iter().map(|o| self.get(i, o)).collect::>(); + ( + dst, + match (i.name(), a.as_slice()) { + ("s_mov_b32", [x]) => *x, + ("s_and_b32", [TableHi, Imm(255)]) => MaskedHi, + ("s_lshl_b32", [RingPage, Imm(8)]) => RingBase, + ("s_add_i32", [RingBase, WaveOffset] | [WaveOffset, RingBase]) => WaveBase, + _ => return None, + }, + ) + } + Fields::Valu(v) + if v.neg == 0 + && v.abs == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.dpp.is_none() => + { + let a = v.src.iter().map(|o| self.get(i, o)).collect::>(); + let high_word = Some(Sdwa { + dst_sel: 6, + dst_unused: 0, + src_sel: [6, 5], + sext: 0, + }); + ( + v.dst.as_ref()?, + match (i.name(), a.as_slice(), v.sdwa) { + ("v_mov_b32", [x], None) => *x, + ("v_mbcnt_lo_u32_b32", [Imm(u32::MAX), Imm(0)], None) => LaneLo, + ("v_mbcnt_hi_u32_b32", [Imm(u32::MAX), LaneLo], None) => Lane, + ("v_lshlrev_b32", [Imm(2), Packed(n)], None) => Shifted(*n), + ("v_lshlrev_b32", [Imm(2), Packed(n)], s) if s == high_word => Input(n + 1), + ("v_and_b32", [Imm(0x3fffc), Shifted(n)], None) => Input(*n), + ("v_mad_u32_u24", [Imm(n), Lane, WaveBase], None) if *n == stride => Output, + ("v_lshlrev_b32", [Imm(2), VertexOffset], None) => VertexBytes, + ("v_lshl_add_u32", [RingPage, Imm(8), VertexBytes], None) => Output, + _ => return None, + }, + ) + } + Fields::Smem { + data: Some(dst), + base: Operand::Scalar { code, dwords: 2 }, + offset: 0xb8, + soffset: Operand::Scalar { code: 125, .. }, + .. + } if i.name() == "s_load_dword" + && i.read(Reg::S(*code)).and_then(|v| self.0.get(&v)) == Some(&TableLo) + && i.read(Reg::S(code + 1)).and_then(|v| self.0.get(&v)) == Some(&MaskedHi) => + { + (dst, RingPage) + } + _ => return None, + }; + let reg = match *dst { + Operand::Vector { reg, .. } => Reg::V(reg), + Operand::Scalar { code, .. } => Reg::S(code), + _ => return None, + }; + self.0.insert(i.write(reg)?, value); + Some(value) + } +} + +#[derive(Clone, Copy)] +enum CopySource { + Word(u32), + Constant(u32), +} + +struct CopyExport { + target: u8, + channels: [Option; 4], +} + +fn copy_exports(gs: &GeometryIo) -> Result, ShaderError> { + let copy = &gs.copy; + let p = ir::build(©.code, copy.wave64, copy.vgprs)?; + // Each translated EMIT runs the same copy exports for every active invocation. + // An EXEC write in the copy can suppress those exports for individual lanes. + if let Some(i) = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.writes.iter().any(|(r, _)| matches!(r, Reg::S(126 | 127)))) + { + return Err(fail(i, "a geometry copy execution mask")); + } + // Stream-zero copies either execute straight through or branch directly + // to endpgm when the stream number in s3[31:24] is nonzero. + let body = match p.blocks.as_slice() { + [b] if b.exit == ir::Exit::End => &b.insts[..], + [entry, body, end] + if entry.exit + == (ir::Exit::Branch { + taken: 2, + not_taken: 1, + }) + && body.exit == ir::Exit::Jump(2) + && end.insts.len() == 1 + && end.insts[0].name() == "s_endpgm" => + { + let mut ops = entry + .insts + .iter() + .filter(|i| !matches!(i.name(), "v_nop" | "s_inst_prefetch" | "s_setprio")); + let predicate = (ops.next(), ops.next(), ops.next(), ops.next()); + let (Some(shift), Some(cmp), Some(branch), None) = predicate else { + return Err(fail(&entry.insts[0], "the geometry copy stream predicate")); + }; + let r = (shift.machine.words[0] >> 16) & 127; + if shift.machine.words != [0x90009803 | (r << 16)] + || cmp.machine.words != [0xbf078000 | r] + || branch.name() != "s_cbranch_scc1" + { + return Err(fail(branch, "the geometry copy stream predicate")); + } + &body.insts[..] + } + _ => { + return Err(ShaderError::Unsupported { + offset: 0, + what: "geometry copy control flow", + }); + } + }; + let mut origins = Origins::default(); + origins.input(&p, Reg::S(0), Word::TableLo); + origins.input(&p, Reg::S(1), Word::TableHi); + origins.input(&p, Reg::V(0), Word::VertexOffset); + let mut exports = Vec::new(); + for i in body { + let origin = origins.step(i, 0); + match &i.fields { + Fields::Ds { + addr: Some(a), + dst: Some(Operand::Vector { reg, .. }), + offset0, + offset1, + gds: false, + .. + } if i.name() == "ds_read2_b32" && origins.get(i, a) == Word::Output => { + for (k, off) in [*offset0, *offset1].into_iter().enumerate() { + let v = i + .write(Reg::V(reg + k as u8)) + .ok_or(fail(i, "a geometry copy load destination"))?; + if u32::from(off) >= gs.vertex_dwords { + return Err(fail(i, "a geometry copy read outside the vertex")); + } + origins.0.insert(v, Word::RingElement(u32::from(off))); + } + } + Fields::Exp { + target, + src, + compr: false, + .. + } => { + let mut channels = [None; 4]; + for (ch, src) in src.iter().enumerate() { + if let Some(src) = src { + channels[ch] = Some(match origins.get(i, src) { + Word::RingElement(k) => CopySource::Word(k), + Word::Imm(n) => CopySource::Constant(n), + _ => { + return Err(fail( + i, + "a geometry copy export with an untraced source", + )); + } + }); + } + } + exports.push(CopyExport { + target: *target, + channels, + }); + } + Fields::Exp { .. } => return Err(fail(i, "a compressed geometry copy export")), + _ if origin.is_some_and(|x| x != Word::Unknown) + || matches!( + i.name(), + "s_endpgm" | "s_waitcnt" | "s_nop" | "v_nop" | "s_inst_prefetch" + ) => {} + _ => return Err(fail(i, "an unmodelled geometry copy instruction")), + } + } + if exports.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "an empty geometry copy program", + }); + } + Ok(exports) +} + +pub(crate) fn raise(p: &Program, gs: &GeometryIo) -> Result { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + let stride_bytes = gs + .invocation_dwords + .checked_mul(4) + .ok_or(unsupported("the geometry ring size"))?; + if gs.stream_config != [1, 0] + || gs.vertex_dwords == 0 + || gs.vertex_dwords.checked_mul(gs.max_vertices) != Some(gs.invocation_dwords) + || !matches!(gs.copy.io, StageIo::Vs { .. }) + { + return Err(unsupported("the geometry output ring layout")); + } + if p.blocks.len() != 1 + || p.blocks[0].exit != ir::Exit::End + || p.blocks[0] + .insts + .iter() + .any(|i| i.writes.iter().any(|(r, _)| matches!(r, Reg::S(126 | 127)))) + { + return Err(unsupported("geometry stream I/O across control flow")); + } + let exports = copy_exports(gs)?; + let mut origins = Origins::default(); + for (reg, word) in [ + (Reg::V(0), Word::Packed(0)), + (Reg::V(1), Word::Packed(2)), + (Reg::S(8), Word::TableLo), + (Reg::S(9), Word::TableHi), + (Reg::S(2), Word::WaveOffset), + ] { + origins.input(p, reg, word); + } + let mut streams = Streams::default(); + let mut ring = HashMap::new(); + let mut vertex: u32 = 0; + for i in &p.blocks[0].insts { + if matches!(i.fields, Fields::Exp { .. }) + || i.name().starts_with("s_sendmsg") && i.name() != "s_sendmsg" + { + return Err(fail(i, "an additional geometry export or message")); + } + if origins + .step(i, stride_bytes) + .is_some_and(|w| !matches!(w, Word::Imm(_) | Word::Unknown)) + { + streams.address_steps.push(i.machine.offset); + } + match &i.fields { + Fields::Ds { + addr: Some(a), + dst: Some(Operand::Vector { reg, .. }), + offset0, + offset1, + gds: false, + .. + } => { + let Word::Input(index) = origins.get(i, a) else { + return Err(fail(i, "a geometry input vertex address")); + }; + let mut reads = Vec::new(); + let mut read = |k, dword| { + let v = i + .write(Reg::V(reg + k)) + .ok_or(fail(i, "a geometry input destination"))?; + reads.push((v, index, dword)); + Ok(()) + }; + match i.name() { + "ds_read_b32" => { + let bytes = u16::from_le_bytes([*offset0, *offset1]); + if bytes % 4 != 0 { + return Err(fail(i, "an unaligned geometry input")); + } + read(0, bytes / 4)?; + } + "ds_read2_b32" => { + read(0, u16::from(*offset0))?; + read(1, u16::from(*offset1))?; + } + _ => return Err(fail(i, "a geometry input load")), + } + streams.reads.insert(i.machine.offset, reads); + } + Fields::Ds { + addr: Some(a), + data, + offset0, + offset1, + gds: false, + .. + } if i.name() == "ds_write2_b32" && origins.get(i, a) == Word::Output => { + for (src, off) in data.iter().zip([*offset0, *offset1]) { + let Operand::Vector { reg, .. } = src else { + return Err(fail(i, "a geometry ring store operand")); + }; + let v = i + .read(Reg::V(*reg)) + .ok_or(fail(i, "a geometry ring store source"))?; + if u32::from(off) >= gs.invocation_dwords { + return Err(fail(i, "a geometry ring store outside the invocation")); + } + // The console's copy VS reads the ring after the GS ends; + // the translation takes each slot's value at its EMIT. A + // slot written after its vertex was emitted would differ. + if u32::from(off) < vertex * gs.vertex_dwords { + return Err(fail(i, "a geometry ring store to a vertex already emitted")); + } + ring.insert(u32::from(off), v); + } + } + Fields::Ds { .. } => return Err(fail(i, "a geometry LDS operation")), + Fields::Sopp { imm } if i.name() == "s_sendmsg" => { + let op = match *imm { + 0x22 => { + if vertex >= gs.max_vertices { + return Err(fail(i, "too many geometry output vertices")); + } + let mut output = Vec::new(); + for e in &exports { + let mut channels = [None; 4]; + for (ch, src) in e.channels.iter().enumerate() { + channels[ch] = match src { + Some(CopySource::Word(off)) => { + let v = *ring + .get(&(vertex * gs.vertex_dwords + off)) + .ok_or(fail( + i, + "a geometry output the invocation did not write", + ))?; + Some(Component::Value(v)) + } + Some(CopySource::Constant(n)) => Some(Component::Constant(*n)), + None => None, + }; + } + output.push(VertexOutput { + target: e.target, + channels, + }); + } + vertex += 1; + StreamOp::Emit(output) + } + 0x12 => StreamOp::Cut, + 3 => continue, + _ => return Err(fail(i, "a geometry stream message")), + }; + streams.messages.insert(i.machine.offset, op); + } + _ => {} + } + } + Ok(streams) +} + +/// The code a host GS invocation runs: one active console invocation, so +/// the two writes that establish the console wave's EXEC are no-ops. +pub(crate) fn invocation_code(native: &crate::NativeProgram) -> Result, ShaderError> { + let mut code = native.code.clone(); + let list = crate::gfx10::decode(&code)?; + // The GS body runs on the low GSVertCount lanes. The host invokes + // the shader only for an active primitive. Preserve the count and + // SCC calculations, removing only the two writes that establish EXEC. + let mut established = false; + for (n, i) in list.iter().enumerate() { + if i.name() != Some("s_bfm_b64") { + continue; + } + let Some(prefix) = n.checked_sub(1).and_then(|k| list.get(k..k + 4)) else { + continue; + }; + // s_bfe_i32 r, s3, (8:8); s_bfm_b64 exec, r, 0; + // s_cmp_eq_u32 r, 64; s_cselect_b64 exec, -1, exec. + let r = (prefix[0].words[0] >> 16) & 127; + if established + || list[..n - 1] + .iter() + .any(|op| !matches!(op.name(), Some("v_nop" | "s_nop" | "s_inst_prefetch"))) + || !native.wave64 + || prefix[0].words != [0x9400ff03 | r << 16, 0x80008] + || i.words != [0x92fe8000 | r] + || prefix[2].words != [0xbf06c000 | r] + || prefix[3].words != [0x85fe7ec1] + { + continue; + } + for inst in [i, &prefix[3]] { + code[inst.offset..inst.offset + 4].copy_from_slice(&0xbf800000u32.to_le_bytes()); + } + established = true; + } + // One block and no other EXEC write are checked by `raise`. + if !established { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a geometry invocation mask", + }); + } + Ok(code) +} diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index e53b25b866..a8de53aecd 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -193,6 +193,7 @@ pub struct Export { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Io { + pub geometry: Option>, /// Input values the hardware loads, with their meaning; other VGPRs /// read before written hold undefined values. pub inputs: Vec<(Value, Input)>, @@ -210,6 +211,12 @@ pub struct Io { /// stages whose stage data is not read and on constructs not covered yet. pub fn raise(p: &Program, native: &NativeProgram) -> Result { let unsupported = |offset, what| ShaderError::Unsupported { offset, what }; + if let (StageIo::Gs(gs), HwStage::Gs) = (&native.io, native.stage) { + return Ok(Io { + geometry: Some(Box::new(crate::geometry::raise(p, gs)?)), + ..Io::default() + }); + } let (loaded, ps_inputs, params) = match (&native.io, native.stage) { ( StageIo::Ps { diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index b4b7c844cc..4b5ef6c842 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -9,6 +9,7 @@ pub mod dxbc; pub mod dxil; pub mod emit; +pub mod geometry; pub mod gfx10; pub mod io; pub mod ir; diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 2a16ac1d70..72c9e633c0 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -9,6 +9,7 @@ //! ```text //! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry: //! u32 kind, u32 offset, u32 size +//! kind 0x0c uncompressed FSSM //! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size, //! zlib stream //! unpacked "FSSM" u32 version (0x101), u64 payload size, payload @@ -61,7 +62,11 @@ //! ``` //! //! Rows are registers of the container's signature parts (`ISG1`, `OSG1`). -//! Merged stages keep their stage data in another layout (not read). +//! A GS keeps its copy VS record at E+0x34. Its code and resource tables +//! are payload-relative like a top-level record. The copy VS reads each +//! emitted vertex out of LDS and exports it using its own output table. +//! E+0x27c is the per-invocation output size in dwords, E+0x284 the +//! maximum vertices, and E+0x28c the per-vertex size in dwords. //! //! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), //! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and @@ -73,6 +78,7 @@ use crate::dxbc::{u16_at, u32_at, u64_at}; const XDAT_OFFSET: usize = 0x18; const MAX_XDAT_ENTRIES: usize = 64; +const KIND_NATIVE_RAW: u32 = 0x0c; const KIND_NATIVE: u32 = 0x0d; const XBCH_VERSION: u32 = 3; const XBCH_HEADER: usize = 0x18; @@ -192,6 +198,16 @@ impl NativeProgram { } code } + + /// The code translation builds its program from: [`Self::patched_code`], + /// or for a geometry program the code one host GS invocation runs (one + /// active console invocation). + pub fn translation_code(&self) -> Result, ShaderError> { + if self.stage == HwStage::Gs { + return crate::geometry::invocation_code(self); + } + Ok(self.patched_code()) + } } /// What a semantic is, as the stage data names it. @@ -280,6 +296,19 @@ pub enum StageIo { }, Cs(ComputeIo), Ms(MeshIo), + Gs(GeometryIo), +} + +/// The GS writes vertices into LDS. A separate VS reads them back and +/// maps their components to position and parameter exports. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GeometryIo { + pub invocation_dwords: u32, + pub vertex_dwords: u32, + pub max_vertices: u32, + /// Native stream/instance configuration following the ring size. + pub stream_config: [u32; 2], + pub copy: Box, } /// A mesh program's outputs and limits. It runs as one hardware NGG stage: @@ -437,11 +466,24 @@ pub fn native_programs(part: &[u8]) -> Result, ShaderError> { let mut out = Vec::new(); for i in 0..count { let at = XDAT_OFFSET + 12 + 12 * i; - if u32_at(part, at)? != KIND_NATIVE { + let kind = u32_at(part, at)?; + if !matches!(kind, KIND_NATIVE_RAW | KIND_NATIVE) { continue; } let offset = u32_at(part, at + 4)?.into(); let size = u32_at(part, at + 8)?.into(); + if kind == KIND_NATIVE_RAW { + // Uncompressed entries were skipped before they were read: one + // that is not a valid FSSM is skipped still, and does not cost + // the container its other entries. + if size <= MAX_UNPACKED + && let Some(blob) = bytes(part, offset, size) + && let Ok(found) = programs(blob) + { + out.extend(found); + } + continue; + } let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?; out.extend(programs(&unpack(blob)?)?); } @@ -607,85 +649,106 @@ fn programs(fssm: &[u8]) -> Result, ShaderError> { if start == ABSENT { continue; } - let record = - bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; - let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) - .ok_or(Malformed("native code out of bounds"))?; - let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; - if vgprs > 256 { - return Err(Malformed("implausible VGPR count")); - } - let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> { - let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?); - if len == 0 { - return Ok(&[]); - } - bytes(payload, u64_at(record, at)?, len) - .ok_or(Malformed("FSSM root table out of bounds")) - }; - let layout = table(RECORD_LAYOUT, RECORD_COUNTS)? - .as_chunks::<{ ENTRY_SIZE as usize }>() - .0 - .iter() - .map(|e| RootParam { - root: RootType::from_raw(le32(e, 0)), - table_offset_dwords: le32(e, 4), - sgprs: le32(e, 8), - base_register: le32(e, 12), - user_data: e[16], - slot: e[17], - }) - .collect(); - let used = table(RECORD_USED, RECORD_COUNTS + 4)? - .as_chunks::<{ ENTRY_SIZE as usize }>() - .0 - .iter() - .map(|e| UsedResource { - kind: match e[0] { - 0 => ResourceType::Srv, - 1 => ResourceType::Sampler, - 2 => ResourceType::Cbv, - 3 => ResourceType::Uav, - n => ResourceType::Other(n), - }, - root: RootType::from_raw(e[1].into()), - table_offset_dwords: le32(e, 4), - lower_bound: le32(e, 8), - stride: le32(e, 12), - dwords: e[16], - user_data: e[17], - slot: e[18], - }) - .collect(); - // The record is in bounds, so its end is too. - let stage_data = &payload[(start + RECORD_SIZE) as usize..]; - let io = match stage { - HwStage::Ps => ps_io(stage_data, code.len())?, - HwStage::Vs => vs_io(stage_data)?, - HwStage::Cs => StageIo::Cs(ComputeIo { - rsrc2: u32_at(stage_data, CS_RSRC2)?, - threads: [ - u32_at(stage_data, CS_THREADS)?, - u32_at(stage_data, CS_THREADS + 4)?, - u32_at(stage_data, CS_THREADS + 8)?, - ], - }), - HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, - _ => StageIo::None, - }; - out.push(NativeProgram { - stage, - wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, - vgprs, - layout, - used, - io, - code: code.to_vec(), - }); + out.push(read_program(payload, start, stage)?); } Ok(out) } +fn read_program(payload: &[u8], start: u64, stage: HwStage) -> Result { + let record = + bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; + let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) + .ok_or(Malformed("native code out of bounds"))?; + let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; + if vgprs > 256 { + return Err(Malformed("implausible VGPR count")); + } + let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> { + let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?); + if len == 0 { + return Ok(&[]); + } + bytes(payload, u64_at(record, at)?, len) + .ok_or(Malformed("FSSM root table out of bounds")) + }; + let layout = table(RECORD_LAYOUT, RECORD_COUNTS)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| RootParam { + root: RootType::from_raw(le32(e, 0)), + table_offset_dwords: le32(e, 4), + sgprs: le32(e, 8), + base_register: le32(e, 12), + user_data: e[16], + slot: e[17], + }) + .collect(); + let used = table(RECORD_USED, RECORD_COUNTS + 4)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| UsedResource { + kind: match e[0] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root: RootType::from_raw(e[1].into()), + table_offset_dwords: le32(e, 4), + lower_bound: le32(e, 8), + stride: le32(e, 12), + dwords: e[16], + user_data: e[17], + slot: e[18], + }) + .collect(); + // The record is in bounds, so its end is too. + let stage_data = &payload[(start + RECORD_SIZE) as usize..]; + let io = match stage { + HwStage::Ps => ps_io(stage_data, code.len())?, + HwStage::Vs => vs_io(stage_data)?, + HwStage::Cs => StageIo::Cs(ComputeIo { + rsrc2: u32_at(stage_data, CS_RSRC2)?, + threads: [ + u32_at(stage_data, CS_THREADS)?, + u32_at(stage_data, CS_THREADS + 4)?, + u32_at(stage_data, CS_THREADS + 8)?, + ], + }), + // A geometry record whose copy program or stage data does not + // parse keeps no stage I/O, as every geometry record did before: + // translation refuses it, and the container's other programs stay. + HwStage::Gs => gs_io(payload, start, stage_data).unwrap_or(StageIo::None), + HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, + _ => StageIo::None, + }; + Ok(NativeProgram { + stage, + wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, + vgprs, + layout, + used, + io, + code: code.to_vec(), + }) +} + +/// A geometry program's stage I/O: its copy VS (the record after its own) +/// and the GS-to-VS ring layout in its stage data. +fn gs_io(payload: &[u8], start: u64, stage_data: &[u8]) -> Result { + let copy = read_program(payload, start + RECORD_SIZE + 0x34, HwStage::Vs)?; + Ok(StageIo::Gs(GeometryIo { + invocation_dwords: u32_at(stage_data, 0x27c)?, + max_vertices: u32_at(stage_data, 0x284)?, + stream_config: [u32_at(stage_data, 0x280)?, u32_at(stage_data, 0x288)?], + vertex_dwords: u32_at(stage_data, 0x28c)?, + copy: Box::new(copy), + })) +} + /// The entries of `size` bytes from `at`, with their count at `count_at`. fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> { let count = u32_at(data, count_at)?; @@ -892,6 +955,47 @@ pub(crate) mod tests { out } + /// Synthetic geometry record with the embedded copy VS following its + /// graphics header, `vertex_dwords` ring dwords per vertex (three + /// vertices) and the copy VS's output table (`usage, row, param, _, _, + /// flags` per entry). + pub(crate) fn geometry_part_sized( + code: &[u8], + copy: &[u8], + vertex_dwords: u32, + outputs: &[[u8; 6]], + ) -> Vec { + let mut blob = fssm(&[(HwStage::Gs, code)]); + let e = stage_data_at(&blob, HwStage::Gs); + blob[e..e + STAGE_DATA].fill(0); + let record = e + 0x34; + let start = (blob.len() - FSSM_HEADER) as u64; + blob[record..record + 8].copy_from_slice(&start.to_le_bytes()); + blob[record + 8..record + 16].copy_from_slice(&(copy.len() as u64).to_le_bytes()); + for (offset, value) in [ + (0x27c, 3 * vertex_dwords), + (0x280, 1), + (0x284, 3), + (0x28c, vertex_dwords), + ] { + blob[e + offset..e + offset + 4].copy_from_slice(&value.to_le_bytes()); + } + // The copy VS's own stage data follows its record. + let copy_data = record + RECORD_SIZE as usize; + for (k, o) in outputs.iter().enumerate() { + let at = copy_data + VS_OUTPUTS + 6 * k; + blob[at..at + 6].copy_from_slice(o); + } + let count = copy_data + VS_OUTPUT_COUNT; + blob[count..count + 4].copy_from_slice(&(outputs.len() as u32).to_le_bytes()); + blob.extend(copy); + let payload = (blob.len() - FSSM_HEADER) as u64; + blob[8..16].copy_from_slice(&payload.to_le_bytes()); + let mut result = part(&[(KIND_NATIVE_RAW, &blob)]); + result[..4].copy_from_slice(&0x00020066u32.to_le_bytes()); + result + } + #[test] fn finds_graphics_programs() { let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)])); @@ -930,6 +1034,32 @@ pub(crate) mod tests { ); } + #[test] + fn raw_fssm_uses_the_same_program_and_io_layout_as_packed_fssm() { + let blob = fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]); + let raw = part(&[(KIND_NATIVE_RAW, &blob)]); + let packed = part(&[(KIND_NATIVE, &xbch(&blob))]); + assert_eq!(native_programs(&raw).unwrap(), native_programs(&packed).unwrap()); + // An uncompressed entry that is no FSSM is skipped, as all were + // before they were read, and keeps the container's other entries. + assert_eq!(native_programs(&part(&[(KIND_NATIVE_RAW, &blob[..16])])).unwrap(), []); + let beside = part(&[(KIND_NATIVE_RAW, &blob[..16]), (KIND_NATIVE, &xbch(&blob))]); + assert_eq!(native_programs(&beside).unwrap(), native_programs(&packed).unwrap()); + } + + #[test] + fn a_geometry_record_without_a_copy_program_keeps_no_stage_io() { + let mut blob = fssm(&[(HwStage::Gs, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Gs); + blob[e..e + STAGE_DATA].fill(0); + // The copy VS's record points past the payload. + blob[e + 0x34..e + 0x3c].copy_from_slice(&u64::MAX.to_le_bytes()); + let found = native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].stage, HwStage::Gs); + assert_eq!(found[0].io, StageIo::None); + } + #[test] fn reads_root_tables() { let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 7f51ee6c8c..bc2f59a54e 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -163,7 +163,24 @@ pub fn track( stage: HwStage, lanes: Option<&Structured>, ) -> Result { - let t = Tracer::new(p, layout, stage, lanes)?; + trace(Tracer::new(p, layout, stage, lanes)?, &[]) +} + +/// Geometry uses an internal table for its output ring. Only instructions +/// proved to construct that address are exempt from root resource tracking. +pub fn track_io( + p: &Program, + layout: &[RootParam], + stage: HwStage, + lanes: Option<&Structured>, + io: &crate::io::Io, +) -> Result { + let skipped = io.geometry.as_ref().map_or(&[][..], |g| &g.address_steps); + trace(Tracer::new(p, layout, stage, lanes)?, skipped) +} + +fn trace(t: Tracer, skipped: &[usize]) -> Result { + let p = t.p; let mut out = Resources { params: p .inputs @@ -185,6 +202,9 @@ pub fn track( std::collections::BTreeMap::, Vec, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { + if skipped.contains(&inst.machine.offset) { + continue; + } let site = (b, i); let fail = |what| ShaderError::Unsupported { offset: inst.machine.offset,