diff --git a/crates/xcl/src/gpu/dxil/dispatchx_tests.rs b/crates/xcl/src/gpu/dxil/dispatchx_tests.rs new file mode 100644 index 0000000000..8cf2c8e6f5 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/dispatchx_tests.rs @@ -0,0 +1,112 @@ +use super::kernel::{self, KernelOptions}; +use crate::gpu::{rdna2::encode, recomp::{self, runner, CsInterface}}; + +// An unguarded store at the 3-D global thread index: only EXEC can suppress excess lanes. +fn stores(threads: [u32; 3], groups: [u32; 3]) -> Vec { + let mut code = Vec::new(); + let mut emit = |name, enc, fields: &[(&str, u64)], literal| { + code.extend(encode(name, enc, fields, literal).unwrap()); + }; + for k in 0..3u64 { + emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3 + k), ("SRC0", k), ("SRC1", 255)], Some(threads[k as usize])); + emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3 + k), ("SRC0", 259 + k), ("VSRC1", k)], None); + } + emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 261), ("SRC1", 255)], Some(threads[1] * groups[1])); + emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 261), ("VSRC1", 4)], None); + emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 260), ("SRC1", 255)], Some(threads[0] * groups[0])); + emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 260), ("VSRC1", 3)], None); + emit("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 3)], None); + emit("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None); + emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 129), ("VSRC1", 3)], None); + emit("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 8), ("SADDR", 0x7D)], None); + emit("S_ENDPGM", "ENC_SOPP", &[], None); + code +} + +fn interface(threads: [u32; 3]) -> CsInterface { + CsInterface { threads, user_sgprs: 0, tgid: [true; 3], tg_size: false, tid_components: 3 } +} + +pub(crate) fn wave32_store_container(groups: [u32; 3]) -> Vec { + use crate::gpu::xbox::tests::{fssm, sample}; + let mut header = fssm(&stores([32, 1, 1], groups), &[(6, 1)]); + header[0xd4] = 1 << 5; // wave32 + for (word, value) in header[0x138..0x148].chunks_exact_mut(4).zip([0x1380u32, 32, 1, 1]) { + word.copy_from_slice(&value.to_le_bytes()); + } + sample(5, &[header]) +} + +fn masked_stores(wave64: bool, split: bool) { + if recomp::dxc::location().is_err() { runner::skip_test("no DXC"); return; } + let supported = if wave64 && !split { runner::wave64_supported() } else { runner::wave32_supported() }; + if supported != Ok(true) { runner::skip_test("required wave size unavailable"); return; } + let x = if wave64 { 64 } else { 32 }; + let square = if wave64 { [8, 8, 1] } else { [8, 4, 1] }; + let cube = if wave64 { [4, 4, 4] } else { [4, 4, 2] }; + let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + for (threads, groups, limits) in [ + ([x, 1, 1], [128 / x, 1, 1], [100, 0, 0]), + ([x, 1, 1], [128 / x, 1, 1], [10, 0, 0]), + ([x, 1, 1], [128 / x, 1, 1], [0, 0, 0]), + (square, [2, 2, 1], [13, square[1] + 1, 0]), + (cube, [2, 2, 2], [7, 6, cube[2] * 2 - 1]), + ] { + let shape = std::array::from_fn::<_, 3, _>(|k| threads[k] * groups[k]); + let size = shape.iter().product::() as usize; + let code = stores(threads, groups); + let cs = interface(threads); + let mut io = vec![0; recomp::KERNEL_SGPRS]; + for k in 0..3 { io[recomp::IO_THREAD_LIMIT[k]] = limits[k]; } + let untouched = 0xDEAD_BEEF; + let input = vec![untouched; size]; + let base = kernel::translate_compute_on(&code, options, &cs, true).unwrap(); + let plain = runner::dispatch(&base.dxil, groups, &io, &input).unwrap(); + assert_eq!(plain, (1..=size as u32).collect::>(), "base ignores thread limits"); + let masked = kernel::translate_compute_with_thread_limits(&code, options, &cs, true).unwrap(); + let got = runner::dispatch(&masked.dxil, groups, &io, &input).unwrap(); + let mut expected = input; + for z in 0..shape[2] { + for y in 0..shape[1] { + for x in 0..shape[0] { + if [x, y, z].iter().zip(limits).all(|(&v, limit)| limit == 0 || v < limit) { + let i = ((z * shape[1] + y) * shape[0] + x) as usize; + expected[i] = i as u32 + 1; + } + } + } + } + assert_eq!(got, expected, "threads={threads:?}, groups={groups:?}, limits={limits:?}"); + } +} + +#[test] +fn dispatchx_wave32_masks_excess_lanes() { masked_stores(false, false); } +#[test] +fn dispatchx_split_wave64_masks_excess_lanes() { masked_stores(true, true); } +#[test] +fn dispatchx_native_wave64_masks_excess_lanes() { masked_stores(true, false); } + +#[test] +fn dispatchx_base_translation_stays_byte_identical() { + if recomp::dxc::location().is_err() { runner::skip_test("no DXC"); return; } + let cs = interface([64, 1, 1]); + let code = stores(cs.threads, [2, 1, 1]); + for (wave64, split) in [(false, false), (true, true), (true, false)] { + let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let base = kernel::translate_compute_on(&code, options, &cs, true).unwrap().dxil; + // The window's red/green harness records original-base bytes before installing the + // implementation, then compares them here (same toolchain, no brittle golden hash). + if let Some(dir) = std::env::var_os("XCL_TEST_DISPATCHX_BASELINE") { + let path = std::path::PathBuf::from(dir).join(format!("{wave64}-{split}.dxil")); + if std::env::var_os("XCL_TEST_DISPATCHX_RECORD").is_some() { + std::fs::write(&path, &base).unwrap(); + } else { + assert_eq!(std::fs::read(path).unwrap(), base, "original base translation changed"); + } + } + let _masked = kernel::translate_compute_with_thread_limits(&code, options, &cs, true).unwrap(); + assert_eq!(kernel::translate_compute_on(&code, options, &cs, true).unwrap().dxil, base, + "building a masked entry must not mutate subsequent base translations"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6ef85ad800..a8d7f5010d 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -131,6 +131,8 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res pub enum Entry { Kernel, Compute(CsInterface), + /// On-demand DispatchX variant; ordinary compute keeps its original prologue. + ComputeMasked(CsInterface), Mesh(MsInterface), Vertex(VsInterface), Pixel(PsInterface), @@ -148,6 +150,12 @@ pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wav translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) } +/// A partial DispatchX group: IO_THREAD_LIMIT bounds each axis (0 means unbounded). +pub fn translate_compute_with_thread_limits(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result { + let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; + translate_entry(code, o, Entry::ComputeMasked(cs.clone()), compact_mode(), None, tables) +} + fn translate_entry( code: &[u8], o: KernelOptions, @@ -203,9 +211,9 @@ fn translate_on_this_thread( None => Cfg::build(code)?, }; let kernel = matches!(entry, Entry::Kernel); - let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_)); + let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_) | Entry::ComputeMasked(_)); let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); - let compute = matches!(entry, Entry::Compute(_)); + let compute = matches!(entry, Entry::Compute(_) | Entry::ComputeMasked(_)); let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); @@ -223,10 +231,13 @@ fn translate_on_this_thread( lw.init.vgpr_base = Some(base); [if o.wave64 { 64 } else { 32 }, 1, 1] } - Entry::Compute(cs) => { + Entry::Compute(cs) | Entry::ComputeMasked(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); + if matches!(entry, Entry::ComputeMasked(_)) { + mask_compute_threads(&mut lw, cs, gtid); + } cs.threads } Entry::Mesh(ms) => { @@ -477,7 +488,7 @@ impl Lw { let split = o.wave64 && o.split; let kernel = matches!(entry, Entry::Kernel); let cs = match entry { - Entry::Compute(cs) => Some(cs.clone()), + Entry::Compute(cs) | Entry::ComputeMasked(cs) => Some(cs.clone()), _ => None, }; let ms = match entry { @@ -584,7 +595,7 @@ impl Lw { let group_threads: Option = match entry { Entry::Vertex(_) | Entry::Pixel(_) => None, Entry::Kernel => None, - Entry::Compute(cs) => Some(cs.threads.iter().product()), + Entry::Compute(cs) | Entry::ComputeMasked(cs) => Some(cs.threads.iter().product()), Entry::Mesh(ms) => Some(ms.threads), Entry::Geometry(_) => Some(64), }; @@ -749,6 +760,33 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); } +/// Apply the thread bounds after the existing padding-lane mask. Ballot exchanges the +/// two halves of a split wave64 before EXEC disables either half's out-of-range lanes. +fn mask_compute_threads(lw: &mut Lw, cs: &CsInterface, gtid: [Value; 3]) { + let io = lw.init.io.expect("compute I/O"); + let mut inside = lw.s.m.i1c(true); + let zero = lw.c(0); + for k in 0..3 { + let offset = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32); + let limit = lw.s.raw_load(io, offset, 1)[0]; + let group = lw.s.group_id(k as u32); + let size = lw.c(cs.threads[k]); + let base = lw.mul(group, size); + let global = lw.add(base, gtid[k]); + let unbounded = lw.s.m.cmp(Pred::Eq, limit, zero); + let in_range = lw.s.m.cmp(Pred::ULt, global, limit); + let axis = lw.or(unbounded, in_range); + inside = lw.and(inside, axis); + } + let (mask_lo, mask_hi) = lw.ballot(inside); + let init = lw.init.compute.as_ref().expect("compute entry"); + let (lo, hi) = (init.sgpr[&126], init.sgpr[&127]); + let (lo, hi) = (lw.and(lo, mask_lo), lw.and(hi, mask_hi)); + let init = lw.init.compute.as_mut().unwrap(); + init.sgpr.insert(126, lo); + init.sgpr.insert(127, hi); +} + /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the /// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot, /// other VGPRs 0; and the record slots. diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index a0ec94583f..bf4b4b12e6 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -42,6 +42,8 @@ mod compact_tests; #[cfg(test)] mod core_tests; #[cfg(test)] +pub(crate) mod dispatchx_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod ops_tests; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..bef0c6572d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -204,6 +204,11 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis +/// when it is not a whole number of groups (0: the last group is whole), so the program can leave +/// the lanes past it out of EXEC. Written by D3D12.X now; read by the compute prologue later. +/// (113 is left for the group-limit slot of #1428.) +pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116]; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index da4b25e5fb..0db17f3161 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -920,13 +920,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. pub fn compute_user_sgprs(blob: &[u8]) -> Option { + compute_interface(blob).map(|cs| cs.user_sgprs) +} + +/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape +/// (`numthreads`). None: not a console compute program. +pub fn compute_interface(blob: &[u8]) -> Option { if let Some(f) = fspx(blob) { - return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs); + return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2)); } let sh = xbox::parse(blob)?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; match interface(blob, &sh, f)? { - Mode::Compute(cs) => Some(cs.user_sgprs), + Mode::Compute(cs) => Some(cs), _ => None, } } @@ -948,6 +954,15 @@ fn direct_fallback(stage: &str, err: &str) { /// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). /// FSPX (driver) containers are left to the HLSL path. fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { + direct_compute_entry(blob, sampler_base, windows, split_wave64, false) +} + +/// DispatchX's distinct direct entry. A failed translation must not fall back to an unmasked shader. +pub(crate) fn masked_compute(blob: &[u8], windows: u32, split_wave64: bool) -> Result { + direct_compute_entry(blob, 0, windows, split_wave64, true) +} + +fn direct_compute_entry(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool, masked: bool) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; @@ -956,7 +971,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let wave64 = super::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses - if super::lower_dxil::enabled() { + if !masked && super::lower_dxil::enabled() { match super::lower_dxil::compute_with(code, &cs, o) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); @@ -969,8 +984,14 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; - dump_direct(blob, &k.dxil); + use crate::gpu::dxil::kernel; + let k = if masked { + kernel::translate_compute_with_thread_limits(code, o, &cs, split_wave64)? + } else { + let k = kernel::translate_compute_on(code, o, &cs, split_wave64)?; + dump_direct(blob, &k.dxil); + k + }; Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..cedb525787 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,9 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// the next dispatch's thread limits (`IO_THREAD_LIMIT`; a `DispatchX` with thread + /// dimensions), taken by its `bind_abi` + limits: [u32; 3], } static STATES: Mutex>> = Mutex::new(None); @@ -870,11 +873,33 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { - return super::pso_async::need_by_submit(pso); + dispatch_flags(this, x, y, z, 0); +} + +/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole +/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) +const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; + +/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread +/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run +/// as the console would (thread dimensions with a group shape not known). +fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return Some((dims, [0; 3])); + } + let threads = super::real::pso_threads(pso)?.map(|t| t.max(1)); + let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); + let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); + Some((groups, limits)) +} + +/// `Dispatch` / `DispatchX(x, y, z, flags)`. +pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + let bound = with(this, |s| s.pso); + if super::pso_async::is_pending(bound) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) { + return super::pso_async::need_by_submit(bound); } - let pso = super::pso_async::resolve_wait(pso); + let pso = super::pso_async::resolve_wait(bound); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that @@ -886,7 +911,41 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - match translated_dispatch(this, list, pso, x, y, z) { + let Some((groups, limits)) = dispatch_groups(pso, [x, y, z], flags) else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + }; + if flags != 0 { + // each kind of flags once: what titles pass, and what it launches + static SEEN: Mutex> = Mutex::new(Vec::new()); + let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; + if first { + crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + } + } + let target = super::real::masked_dispatch_pso(pso, limits, || { + super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) + }); + let done = match target { + Ok(Some((pso, owner))) => { + with(this, |s| s.limits = limits); + let result = translated_dispatch(this, list, pso, groups[0], groups[1], groups[2]); + if owner.is_some() { + // Internal SetPipelineState calls also update the list_x tracker used + // by Reset/Kickoff. Restore its title-visible binding after the variant. + super::list_x::on_set_pipeline_state(this, bound); + } + result + } + Ok(None) => return, + Err(reason) => Err(reason.into()), + }; + with(this, |s| s.limits = [0; 3]); + match done { Ok(()) => count(DISPATCHES), Err(e) => { count(DISPATCHES_SKIPPED); @@ -1039,6 +1098,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + if !gfx { + for (k, l) in with(this, |s| std::mem::take(&mut s.limits)).into_iter().enumerate() { + io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = l; + } + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); @@ -1403,6 +1467,34 @@ void main(uint t : SV_GroupIndex) { (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); } + /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes + /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves + /// the lanes past the count out; without the flag the counts are groups. With the flag + /// and a group shape not known, nothing is launched (the counts as groups was the bug). + #[test] + fn dispatch_x_with_thread_dimensions_launches_whole_groups() { + let pso = 0x7300_0001usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 640 threads in groups of 64: 10 groups, the last one whole + assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); + // 100 threads: 2 groups, and the lanes past 100 to leave out + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); + // the wave32 bit (0x8000) changes nothing here + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); + // a 2-D group shape + let pso2 = 0x7300_0002usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); + // group counts (Dispatch, DispatchX without the flag) are launched as they are + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); + // no threads: no groups + assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); + // thread dimensions on a pipeline whose group shape is not known: not launched + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); + } + #[test] fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { let mut orig_vt = [0usize; 64]; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..6bb30cd8fa 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -657,7 +657,8 @@ struct ListState { /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. pub(super) enum Deferred { - Dispatch(u32, u32, u32), + /// x, y, z and `DispatchX`'s flags (0 for `Dispatch`) + Dispatch(u32, u32, u32, u32), Indirect(usize, u32, usize, u64, usize, u64), } @@ -2707,7 +2708,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { real::dispatch_chain::list_follows(last as usize, seg as usize); } match what { - Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), + Deferred::Dispatch(x, y, z, flags) => super::bind::dispatch_flags(seg, x, y, z, flags), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } let ext = *(seg as *const usize); @@ -3064,8 +3065,8 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: } /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { - super::bind::dispatch(this, x, y, z); +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + super::bind::dispatch_flags(this, x, y, z, flags); } /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..643c8c2f0b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -23,6 +23,8 @@ struct Pending { done: Mutex, cv: Condvar, compute: bool, + /// Only workers may take this build, including nested worker waits and deferred replay. + worker_only: bool, /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) @@ -49,6 +51,8 @@ struct Demand { thread_local! { /// what this worker is building static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Pool helpers can run without a parent Pending (`build_pieces` called by a title thread). + static WORKER_THREAD: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the @@ -301,6 +305,7 @@ fn queue() -> &'static Mutex> { for k in 0..n { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { + WORKER_THREAD.with(|w| w.set(true)); let next = rx.lock().unwrap().recv(); let Ok(work) = next else { return }; while let Some(p) = next_needed() { @@ -366,7 +371,12 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_as(standin, compute, job, true, 0, false); +} + +/// Keep a build off title threads; a worker may build an unstarted dependency inline. +pub fn submit_worker_only(standin: usize, compute: bool, job: Job, key: u64) { + submit_as(standin, compute, job, true, key, true); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -382,10 +392,10 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); + submit_as(standin, compute, job, false, key, false); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { +fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, worker_only: bool) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), @@ -394,6 +404,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { done: Mutex::new(false), cv: Condvar::new(), compute, + worker_only, key, used: Default::default(), orphan: Default::default(), @@ -520,6 +531,7 @@ fn preload() -> Option<&'static Preload> { let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); for k in 0..n { let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + WORKER_THREAD.with(|w| w.set(true)); unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); @@ -560,6 +572,96 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + #[test] + fn worker_only_wait_does_not_take_an_unstarted_job() { + let caller = std::thread::current().id(); + let (send, recv) = mpsc::channel(); + let pso = 0x7E57_55A1; + // Leave the job unqueued, so the old resolver deterministically takes it locally. + submit_as(pso, true, Box::new(move || { send.send(std::thread::current().id()).unwrap(); 0 }), false, 0, true); + assert_eq!(resolve_wait_for(pso, None), pso); + let builder = recv.recv().unwrap(); + assert_eq!(released(pso), 0); + assert_ne!(builder, caller, "a worker-only job ran on the waiting caller"); + } + + #[test] + fn worker_only_submission_keeps_the_budget_and_used_key() { + let (send, recv) = mpsc::channel(); + let pso = 0x7E57_55A2; + let key = 0x7E57_55A3; + submit_worker_only(pso, true, Box::new(move || { recv.recv().unwrap(); 0 }), key); + let waiting = resolve_wait_for(pso, Some(std::time::Duration::ZERO)); + let noted = used::noted(key); + send.send(()).unwrap(); + assert_eq!(resolve_wait_for(pso, None), pso); + assert_eq!(released(pso), 0); + assert_eq!(waiting, pso, "the budget expires while the worker is held"); + assert!(noted, "worker-only use retains the supplied pipeline key"); + } + + #[test] + fn worker_only_policy_does_not_change_ordinary_local_waits() { + let caller = std::thread::current().id(); + let (send, recv) = mpsc::channel(); + let pso = 0x7E57_55A4; + submit_as(pso, true, Box::new(move || { send.send(std::thread::current().id()).unwrap(); 0 }), false, 0, false); + assert_eq!(resolve_wait_for(pso, None), pso); + let builder = recv.recv().unwrap(); + assert_eq!(released(pso), 0); + assert_eq!(builder, caller, "ordinary unstarted jobs retain the existing local fast path"); + } + + #[test] + fn worker_only_nested_wait_builds_an_unstarted_dependency_inline() { + nested_worker_wait(false); + } + + #[test] + fn worker_only_piece_helper_can_build_a_dependency_without_a_parent() { + nested_worker_wait(true); + } + + fn nested_worker_wait(piece_helper: bool) { + let offset = if piece_helper { 2 } else { 0 }; + let (child, parent) = (0x7E57_55A5 + offset, 0x7E57_55A6 + offset); + let (child_send, child_recv) = mpsc::channel(); + let (parent_send, parent_recv) = mpsc::channel(); + // The dependency is deliberately unstarted. Enter the same build_queued/build + // context as a pool worker, without needing to saturate the global test pool. + submit_as(child, true, Box::new(move || { + child_send.send(std::thread::current().id()).unwrap(); + 0 + }), false, 0, true); + submit_as(parent, true, Box::new(move || { + let outer = BUILDING.with(|b| b.borrow().clone()); + let resolved = resolve_wait_for(child, None); + let kept_context = BUILDING.with(|b| match (&outer, &*b.borrow()) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), (None, None) => true, _ => false, + }); + parent_send.send((std::thread::current().id(), resolved, kept_context)).unwrap(); + 0 + }), false, 0, false); + let pending = entry(parent).unwrap(); + std::thread::spawn(move || { + if piece_helper { + WORKER_THREAD.with(|w| w.set(true)); + assert!(!building_here()); // build_pieces helper whose submitting thread had no Pending + let job = pending.job.lock().unwrap().take().unwrap(); + complete(&pending, job()); + } else { + build_queued(&pending); + } + }).join().unwrap(); + let (worker, resolved, kept_context) = parent_recv.recv().unwrap(); + let dependency_worker = child_recv.recv().unwrap(); + assert_eq!(released(child), 0); + assert_eq!(released(parent), 0); + assert_eq!(resolved, child); + assert!(kept_context, "the parent build context survives the nested wait"); + assert_eq!(dependency_worker, worker, "an unstarted dependency must not wait behind a saturated worker pool"); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] @@ -1082,9 +1184,16 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { if let Some(budget) = budget { return resolve_within(&p, pso, budget); } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); + // A worker must drain an unstarted dependency itself: the pool may all be waiting. + if p.worker_only && !building_here() && !WORKER_THREAD.with(|w| w.get()) { + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + } else { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(&p, job()); + } } p.want(); let mut done = p.done.lock().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91085d3933..7ab53691bc 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1716,8 +1716,10 @@ pub(super) fn standin_released(pso: usize) { /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let masked = MASKED_COMPUTE.lock().unwrap().get(&(this as usize)).cloned(); let n = f(this); if n == 0 { + if let Some(source) = masked { forget_masked_source(this as usize, &source); } forget_pso(this as usize); super::pso_async::release(super::pso_async::released(this as usize)); } @@ -3882,14 +3884,26 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { } } -/// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +/// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline +static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.0) +} + +/// The console's group shape (`numthreads`) of a translated compute pipeline (None: not known). +pub fn pso_threads(pso: usize) -> Option<[u32; 3]> { + let pso = super::pso_async::resolve(pso); + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.1) +} + +/// (tests) A translated compute pipeline with this console group shape. +#[cfg(test)] +pub(crate) fn register_threads_for_test(pso: usize, threads: [u32; 3]) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (0, threads)); } /// The root signature a translated pipeline state was created with. @@ -4313,7 +4327,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { - use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + use crate::gpu::recomp::pso::{console_to_dxil_in, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -4326,7 +4340,9 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return Some(Err(())); } - let compiled = match console_to_dxil_for(cs, Stage::Compute, 0, wave32_only(this)) { + let split = wave32_only(this); + let windows = crate::gpu::recomp::pso::mem_windows(); + let compiled = match console_to_dxil_in(cs, Stage::Compute, 0, split, windows) { Ok(b) => b, Err(e) => { note_translation_error(format!("CS: {e}")); @@ -4347,10 +4363,11 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); + remember_masked_source(*ppv as usize, this, f, d, cs, windows, split); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); } @@ -4379,10 +4396,11 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(hr, ppv); + remember_masked_source(*ppv as usize, this, f, d, cs, windows, split); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", dxil.len(), @@ -5316,6 +5334,94 @@ pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { #[cfg(test)] mod shaders_key_tests { + #[test] + fn dispatchx_runtime_selects_and_reuses_a_masked_pipeline_only_for_partial_groups() { + use super::*; + use crate::gpu::{dxil, recomp}; + if recomp::dxc::location().is_err() || recomp::runner::wave32_supported() != Ok(true) { + recomp::runner::skip_test("requires DXC and wave32"); + return; + } + init().expect("create the XCL D3D12 device"); + let raw = device_raw(); + let device = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.expect("initialized D3D12 device"); + let groups = [4, 1, 1]; + let shader = dxil::dispatchx_tests::wave32_store_container(groups); + let create: PsoFn = unsafe { std::mem::transmute(orig_fn(raw, slot_of(raw, "CreateComputePipelineState"))) }; + let base_key = Box::new(0u8); + let base = &*base_key as *const u8 as usize; + let source_for = |shader| std::sync::Arc::new(MaskedComputeSource { + device: device.clone(), create, shader, windows: 1, split: false, + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, variant: OnceLock::new(), + }); + let old = source_for(Vec::new()); + MASKED_COMPUTE.lock().unwrap().insert(base, old.clone()); + let source = source_for(shader); + MASKED_COMPUTE.lock().unwrap().insert(base, source.clone()); + struct Unregister(usize, std::sync::Arc); + impl Drop for Unregister { + fn drop(&mut self) { forget_masked_source(self.0, &self.1); } + } + let _registration = Unregister(base, source.clone()); + forget_masked_source(base, &old); + assert!(std::sync::Arc::ptr_eq(&MASKED_COMPUTE.lock().unwrap()[&base], &source)); + let select = |limits| masked_dispatch_pso(base, limits, || false).unwrap().unwrap(); + assert_eq!(select([0; 3]).0, base); + assert!(source.variant.get().is_none()); + let (variant, _owner) = select([100, 0, 0]); + assert_ne!(variant, base); + assert_eq!(select([10, 0, 0]).0, variant); + assert_eq!(select([0; 3]).0, base); + let raw = variant as *mut c_void; + let root = pso_root_signature(variant).unwrap() as *mut c_void; + let (pso, rs) = unsafe { (ID3D12PipelineState::from_raw_borrowed(&raw).unwrap(), ID3D12RootSignature::from_raw_borrowed(&root).unwrap()) }; + let mut io = [0; recomp::KERNEL_SGPRS]; + io[recomp::IO_THREAD_LIMIT[0]] = 100; + let result = recomp::runner::dispatch_on(device, pso, rs, groups, &io, &[0; 128]).unwrap(); + assert_eq!(&result[..100], &(1..=100).collect::>()); + assert_eq!(&result[100..], &[0; 28]); + } + + #[test] + fn dispatchx_failed_variant_is_built_once_and_never_selects_its_token() { + use std::sync::{Arc, OnceLock, atomic::{AtomicUsize, Ordering}}; + + let builds = Arc::new(AtomicUsize::new(0)); + let variant = OnceLock::new(); + std::thread::scope(|scope| { + for _ in 0..4 { + scope.spawn(|| { + let pending = variant.get_or_init(|| { + let builds = builds.clone(); + super::QueuedMaskedPso::new(Box::new(move || { + builds.fetch_add(1, Ordering::Relaxed); + 0 + }), 0) + }); + assert!(pending.resolve_or_defer(|| false).is_err()); + }); + } + }); + assert_eq!(builds.load(Ordering::Relaxed), 1); + let pending = variant.into_inner().unwrap(); + let token = pending.token(); + drop(pending); + assert_eq!(super::super::pso_async::resolve_wait(token), token); + } + + #[test] + fn dispatchx_pending_variant_can_defer_and_replay_reports_failure() { + let (finish, wait) = std::sync::mpsc::channel(); + let queued = super::QueuedMaskedPso::new(Box::new(move || { + let _ = wait.recv_timeout(std::time::Duration::from_secs(5)); + 0 + }), 0); + let result = queued.resolve_or_defer(|| true); + let _ = finish.send(()); + assert_eq!(result.unwrap(), None); + assert!(queued.resolve_or_defer(|| false).is_err()); + } + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); @@ -5328,6 +5434,126 @@ mod shaders_key_tests { } } +/// An internal pending key with a unique address for as long as the variant can be selected. +struct QueuedMaskedPso(Box); + +impl QueuedMaskedPso { + fn new(job: super::pso_async::Job, key: u64) -> Self { + let pending = Self(Box::new(0)); + super::pso_async::submit_worker_only(pending.token(), true, job, key); + pending + } + + fn token(&self) -> usize { &*self.0 as *const u8 as usize } + + fn resolve_or_defer(&self, defer: impl FnOnce() -> bool) -> Result, &'static str> { + let token = self.token(); + if super::pso_async::is_pending(token) && defer() { + super::pso_async::need_by_submit(token); + return Ok(None); + } + let resolved = super::pso_async::resolve_wait(token); + (resolved != token && resolved != 0).then_some(Some(resolved)).ok_or("DispatchX masked pipeline unavailable") + } +} + +impl Drop for QueuedMaskedPso { + fn drop(&mut self) { + super::pso_async::release(super::pso_async::released(self.token())); + } +} + +pub(super) struct MaskedComputeSource { + device: ID3D12Device, + create: PsoFn, + shader: Vec, + windows: u32, + split: bool, + flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, + variant: OnceLock, +} + +static MASKED_COMPUTE: std::sync::LazyLock>>> = + std::sync::LazyLock::new(Default::default); + +fn forget_masked_source(base: usize, expected: &std::sync::Arc) { + let old = { + let mut sources = MASKED_COMPUTE.lock().unwrap(); + match sources.entry(base) { + std::collections::hash_map::Entry::Occupied(entry) if std::sync::Arc::ptr_eq(entry.get(), expected) => Some(entry.remove()), + _ => None, + } + }; + drop(old); +} + +unsafe fn remember_masked_source(base: usize, device: *mut c_void, create: PsoFn, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, shader: &[u8], windows: u32, split: bool) { + if base == 0 || !crate::gpu::dxil::kernel::enabled() || crate::gpu::recomp::lower_dxil::enabled() { + return; + } + let Some(device) = ID3D12Device::from_raw_borrowed(&device).cloned() else { return }; + let source = std::sync::Arc::new(MaskedComputeSource { + device, create, shader: shader.to_vec(), windows, split, flags: desc.Flags, + node: desc.NodeMask, variant: OnceLock::new(), + }); + let old = MASKED_COMPUTE.lock().unwrap().insert(base, source); + drop(old); +} + +/// Keep an owner of the variant through recording the dispatch. A known variant that +/// failed or reached the wait budget returns an error rather than executing excess lanes. +pub(super) fn masked_dispatch_pso(base: usize, limits: [u32; 3], defer: impl FnOnce() -> bool) + -> Result>)>, &'static str> { + if limits == [0; 3] { return Ok(Some((base, None))) } + let Some(source) = MASKED_COMPUTE.lock().unwrap().get(&base).cloned() else { return Ok(Some((base, None))) }; + let pending = source.variant.get_or_init(|| { + // Capture the inputs rather than the source itself, which owns this queued key. + let device = source.device.clone(); + let create = source.create; + let shader = source.shader.clone(); + let (windows, split, flags, node) = (source.windows, source.split, source.flags, source.node); + QueuedMaskedPso::new(Box::new(move || unsafe { + build_masked_compute(&device, create, &shader, windows, split, flags, node).unwrap_or(0) + }), 0) + }); + Ok(pending.resolve_or_defer(defer)?.map(|pso| (pso, Some(source)))) +} + +unsafe fn build_masked_compute(device: &ID3D12Device, create: PsoFn, shader: &[u8], windows: u32, + split: bool, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32) -> Option { + use crate::gpu::recomp::pso; + let compiled = pso::masked_compute(shader, windows, split).ok()?; + let iface = pso::compute_interface(shader)?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { Flags: flags, NodeMask: node, ..Default::default() }; + let record = crate::gpu::shader::fnv64(shader); + let iid = pc_iid(Kind::PipelineState); + let mut out = std::ptr::null_mut(); + let chain_rs = compiled.dispatch_chain.and_then(|chain| dispatch_chain::build( + device.as_raw(), create, &desc, &iid, &mut out, record, &compiled.dxil, &compiled.samplers, chain)); + let rs = if let Some(rs) = chain_rs { + // The scratch-allocation fallback uses the whole program. Resolve it here too + // so it cannot trigger a driver compile on a title or submit thread later. + if dispatch_chain::whole(out as usize).is_err() { + super::pso_async::release(out as usize); + return None; + } + rs as *mut c_void + } else { + let rs = abi_rs_for(device.as_raw(), &compiled.samplers)?; + if compute_container(device.as_raw(), create, &desc, rs, &compiled.dxil, record, &iid, &mut out, false).0 < 0 { + return None; + } + rs + }; + if out.is_null() { return None } + note_pso_rs(out, rs); + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(out as usize, (iface.user_sgprs, iface.threads)); + note_translated_compute(0, &mut out); + Some(out as usize) +} + impl OwnedDesc { fn shaders_key(&self) -> u64 { shaders_key(match self {