Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions crates/xcl/src/gpu/dxil/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,13 +248,22 @@ pub fn percentiles(v: &[u64]) -> (u64, u64, u64) {
/// own thread) come back as `"panic: …"`; `validate` runs DXC's validator on the result
/// (the translator itself only validates in debug / test builds).
pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool) -> Result<Vec<u8>, String> {
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match mode {
Mode::Kernel => kernel::translate_full(code, o),
Mode::Compute(cs) => kernel::translate_compute(code, o, cs),
Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs),
Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps),
Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms),
Mode::Geometry(g) => kernel::translate_geometry(code, o, g),
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if o.wave64
&& o.split
&& matches!(mode, Mode::Vertex(_) | Mode::Pixel(_))
&& crate::gpu::recomp::needs_upper_lanes(code)
{
return Err("wave64 VS / PS in 32-lane waves needs upper-lane emulation".into());
}
match mode {
Mode::Kernel => kernel::translate_full(code, o),
Mode::Compute(cs) => kernel::translate_compute(code, o, cs),
Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs),
Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps),
Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms),
Mode::Geometry(g) => kernel::translate_geometry(code, o, g),
}
}));
let k = match r {
Ok(r) => r?,
Expand Down Expand Up @@ -412,6 +421,34 @@ mod tests {
assert_eq!(r.stages["GS"].translated, 1, "{}", r.text(5));
}

#[test]
fn split_wave64_graphics_refuses_upper_lane_read() {
let mut code = rdna2::encode("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 20), ("SRC1", 128 + 32)], None).expect("encode");
code.extend(rdna2::encode("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", 256 + 6), ("SRC1", 128 + 32)], None).expect("encode"));
code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).expect("encode"));
assert!(crate::gpu::recomp::needs_upper_lanes(&code));
let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
for mode in [Mode::Vertex(Default::default()), Mode::Pixel(Default::default())] {
let err = translate_mode(&code, &mode, o, false).unwrap_err();
assert!(err.contains("upper-lane emulation"), "{mode:?}: {err}");
}
}

#[test]
fn split_wave64_graphics_refuses_incomplete_decode() {
let unknown = 0x0000_003fu32.to_le_bytes();
let mut truncated = rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).expect("encode");
truncated.extend([1, 2]);
let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
for code in [&unknown[..], &truncated[..]] {
assert!(crate::gpu::recomp::needs_upper_lanes(code));
for mode in [Mode::Vertex(Default::default()), Mode::Pixel(Default::default())] {
let err = translate_mode(code, &mode, o, false).unwrap_err();
assert!(err.contains("upper-lane emulation"), "{mode:?}: {err}");
}
}
}

#[test]
fn live_fallback_summary() {
record_translated("CS");
Expand Down
21 changes: 21 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,27 @@ pub fn wave_hazards(code: &[u8]) -> BTreeSet<&'static str> {
wave_lane_reads(code).0
}

/// Whether a wave64 VS / PS needs the HLSL `upper_lanes` form when graphics waves may have
/// 32 lanes. Direct DXIL can only take programs whose cross-lane reads are native in that
/// case; constant, shadowed and unresolved upper-half reads need the HLSL emulation.
pub fn needs_upper_lanes(code: &[u8]) -> bool {
let mut insts = Vec::new();
let mut off = 0;
while off + 4 <= code.len() {
let Ok(d) = rdna2::decode(&code[off..], off as u64) else { return true };
if d.len > code.len() - off {
return true;
}
off += d.len;
insts.push(d);
}
if off != code.len() {
return true;
}
rdna2::resolve_far_jumps(&mut insts);
upper_lanes::analyze(&insts).reads.values().any(|&r| r != upper_lanes::Read::Native)
}

/// `wave_hazards` and the kinds of reads `upper_lanes` resolves.
pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'static str>) {
let mut insts = Vec::new();
Expand Down
39 changes: 34 additions & 5 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
if dxc::defer() {
return Err("DXIL not compiled yet".into());
}
match direct_graphics(blob, stage, sampler_base, windows) {
match direct_graphics(blob, stage, sampler_base, windows, split_wave64) {
Ok(c) => {
crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" });
return Ok(c);
Expand Down Expand Up @@ -662,7 +662,7 @@ fn cached_shader(
}

fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool {
!["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"]
!["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"]
.iter()
.any(|name| present(name))
&& (stage != Stage::Pixel
Expand Down Expand Up @@ -752,14 +752,19 @@ fn dump_direct(blob: &[u8], dxil: &[u8]) {
}

/// A console vertex / pixel shader through the direct DXIL translator.
fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) -> Result<Compiled, String> {
fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
let sh = xbox::parse(blob).ok_or("not a console shader container")?;
let want = if stage == Stage::Vertex { 4 } else { 5 };
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == want)).ok_or("no hardware variant")?;
let mode = interface(blob, &sh, f).ok_or("unknown shader interface")?;
let p = f.programs.first().ok_or("FSSM without a program")?;
let code = &f.data[p.offset..p.offset + p.len];
let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::detect_wave64(code), split: false, mem_windows: windows, sampler_base };
let wave64 = super::detect_wave64(code);
if wave64 && split_wave64 && super::needs_upper_lanes(code) {
return Err("wave64 VS / PS in 32-lane waves needs upper-lane emulation".into());
}
// Direct graphics has no split-wave64 form; programs needing upper-lane emulation fell back above.
let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: windows, sampler_base };
let k = match (&mode, stage) {
(Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?,
(Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?,
Expand Down Expand Up @@ -1044,6 +1049,30 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S
mod shader_cache_tests {
use super::*;

#[test]
fn direct_graphics_routes_written_upper_lane_to_hlsl() {
use crate::gpu::{
rdna2,
xbox::tests::{fssm, sample},
};

let mut code = rdna2::encode("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 20), ("SRC1", 128 + 32)], None).unwrap();
code.extend(rdna2::encode("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", 256 + 6), ("SRC1", 128 + 32)], None).unwrap());
code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
for (kind, hw, api, stage) in [(1, 4, 0, Stage::Vertex), (0, 5, 1, Stage::Pixel)] {
let blob = sample(kind, &[fssm(&code, &[(hw, api)])]);
let err = match direct_graphics(&blob, stage, 0, 1, true) {
Err(e) => e,
Ok(_) => panic!("{stage:?}: direct graphics accepted a written upper lane"),
};
assert!(err.contains("upper-lane emulation"), "{stage:?}: {err}");
let (hlsl, profile) = console_translation(&blob, stage, 0, 1, true).unwrap();
assert!(hlsl.complete(), "{stage:?}: {:?}", hlsl.unsupported_why);
let dxil = dxc::compile(&hlsl.hlsl, "main", profile, &[]).unwrap();
assert!(!dxil.is_empty(), "{stage:?}: DXC produced no DXIL");
}
}

#[test]
fn translated_identity_tracks_sources_and_dxc() {
let built_source = env!("XCL_TRANSLATOR_SOURCE_ID");
Expand Down Expand Up @@ -1359,7 +1388,7 @@ mod shader_cache_tests {

#[test]
fn shader_cache_bypasses_debug_overrides() {
for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] {
for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] {
assert!(!cache_allowed(Stage::Compute, |v| v == name));
assert!(!cache_allowed(Stage::Vertex, |v| v == name));
assert!(!cache_allowed(Stage::Pixel, |v| v == name));
Expand Down
9 changes: 8 additions & 1 deletion crates/xcl/src/gpu/recomp/upper_lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -823,9 +823,14 @@ mod tests {
const V: u64 = 256;
type I = (&'static str, &'static str, &'static [(&'static str, u64)], Option<u32>);

fn program(lines: &[I]) -> Vec<Decoded> {
fn code(lines: &[I]) -> Vec<u8> {
let mut bytes: Vec<u8> = lines.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect();
bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
bytes
}

fn program(lines: &[I]) -> Vec<Decoded> {
let bytes = code(lines);
let mut out = Vec::new();
let mut off = 0usize;
while off < bytes.len() {
Expand Down Expand Up @@ -859,6 +864,8 @@ mod tests {
#[test]
fn a_whole_wave_reduction_reads_its_identity() {
assert_eq!(reads(&[WWM, MASK, SEED, X1, MIRROR, PX16, COMBINE, READ32, RESTORE]), vec![Read::Const(u32::MAX)]);
assert!(super::super::needs_upper_lanes(&code(&[WWM, MASK, SEED, X1, MIRROR, PX16, COMBINE, READ32, RESTORE])));
assert!(!super::super::needs_upper_lanes(&code(&[])));
}

#[test]
Expand Down
Loading