Skip to content
Draft
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,8 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
configuration for offline preparation and play so the driver can reuse the results.
Graphics state combinations absent from the supplied recipes and local history can still
require a first-use compile during play.
- Split compute pipelines retain the smaller console source for any later whole-form build,
preserving the original memory-window and wave mode.
- For compute shaders that XCL can split, the runtime first tries the saved driver blob for
the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing
or the driver rejects it, XCL builds the split pieces.
Expand Down
7 changes: 4 additions & 3 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5940,7 +5940,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<Result<HRESULT, ()>> {
use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage};
use crate::gpu::recomp::pso::{console_to_dxil_in, is_console, mem_windows, Stage};
if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_COMPUTE_PIPELINE_STATE_DESC>()) {
return None;
}
Expand All @@ -5953,7 +5953,8 @@ 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 (wave32, windows) = (wave32_only(this), mem_windows());
let compiled = match console_to_dxil_in(cs, Stage::Compute, 0, wave32, windows) {
Ok(b) => b,
Err(e) => {
note_translation_error(format!("CS: {e}"));
Expand Down Expand Up @@ -5987,7 +5988,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const
(result.0 >= 0).then_some((rs, result))
});
if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) {
if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) {
if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, cs, wave32, windows, &compiled.samplers, plan) {
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))]);
Expand Down
101 changes: 91 additions & 10 deletions crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,29 @@ impl<T: Clone> WholeBuild<T> {
/// A transient whole-form OOM is retried after memory has had time to drain.
const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10);

/// What a chain's whole form is made from: its console program, translated again when the whole
/// form is first wanted (from the translation caches: the same DXIL). Most chains never want it
/// (only an indirect dispatch runs the whole form), and their whole DXIL kept in memory was a
/// retail title's 148 MB for 198 split programs, against 22 KB of console code on average.
struct WholeSource {
console: Vec<u8>,
wave32: bool,
// Preserve the first translation's window count and heap/switch form: a later worker
// does not inherit `in_switch_form` from the thread that built the split pieces.
windows: u32,
}

impl WholeSource {
fn code(&self) -> Result<Vec<u8>, String> {
pso::console_to_dxil_in(&self.console, pso::Stage::Compute, 0, self.wave32, self.windows).map(|c| c.dxil)
}
}

struct Chain {
builder: Arc<PipelineBuilder>,
tail: Vec<ID3D12PipelineState>,
words: u32,
whole_code: Vec<u8>,
whole_source: WholeSource,
whole: WholeBuild<ID3D12PipelineState>,
plan: Weak<DispatchChain>,
indirect: IndirectBuild,
Expand Down Expand Up @@ -224,7 +242,8 @@ impl Chain {
None => {
// (only when a title thread is held while this compile lasts, as in any other long PC call)
let _call = on_title_thread.then(super::super::pso_async::pc_call);
self.whole.get_or_build(std::time::Instant::now(), || self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)))
let code = self.whole_source.code().map_err(|e| format!("whole compute program: {e}"))?;
self.whole.get_or_build(std::time::Instant::now(), || self.builder.pipeline(&code, &pc_iid(Kind::PipelineState)))
}
};
result.map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") })
Expand Down Expand Up @@ -333,7 +352,12 @@ fn retain_indirect_plan(plan: Arc<DispatchChain>) {

fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> {
let plan = chain.plan.upgrade().ok_or(E_INVALIDARG)?;
let source_bytes = plan.pieces.iter().map(Vec::len).sum::<usize>().saturating_add(chain.whole_code.len());
// (the whole form is not kept: made again from the console program, `WholeSource`)
let whole_code = chain.whole_source.code().map_err(|e| {
crate::xlog_warn!("D3D12.X: whole compute program for an indirect split variant: {e}");
E_INVALIDARG
})?;
let source_bytes = plan.pieces.iter().map(Vec::len).sum::<usize>().saturating_add(whole_code.len());
if !reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, source_bytes, INDIRECT_VARIANT_BYTES) {
return Err(E_OUTOFMEMORY);
}
Expand All @@ -355,12 +379,14 @@ fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> {
for code in &plan.pieces {
pieces.push(unsafe { builder.pipeline(code, &pc_iid(Kind::PipelineState))? });
}
let whole = unsafe { builder.pipeline(&chain.whole_code, &pc_iid(Kind::PipelineState))? };
let whole = unsafe { builder.pipeline(&whole_code, &pc_iid(Kind::PipelineState))? };
Ok(Arc::new(IndirectChain { signature, whole, pieces, _charge: charge }))
}

fn indirect_blobs_present(chain: &Chain, plan: &DispatchChain) -> bool {
plan.pieces.iter().map(Vec::as_slice).chain([chain.whole_code.as_slice()]).all(|dxil| {
/// `whole`: the chain's whole DXIL, which its builder still has at hand (the chain keeps only
/// the console program it is made from).
fn indirect_blobs_present(chain: &Chain, plan: &DispatchChain, whole: &[u8]) -> bool {
plan.pieces.iter().map(Vec::as_slice).chain([whole]).all(|dxil| {
super::driver_cache::path_for_chain_root_node(
dxil,
chain.builder.flags.0,
Expand Down Expand Up @@ -412,7 +438,7 @@ unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler], ind
}

pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC,
iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler],
iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], console: &[u8], wave32: bool, windows: u32, samplers: &[pso::StaticSampler],
plan: Arc<DispatchChain>) -> Option<usize> {
if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; }
let dev = ID3D12Device::from_raw_borrowed(&this)?;
Expand All @@ -432,12 +458,12 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT
let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter();
let first = pieces.next()?;
let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group,
whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan),
whole_source: WholeSource { console: console.to_vec(), wave32, windows }, whole: WholeBuild::new(), plan: Arc::downgrade(&plan),
indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) });
retain_indirect_plan(plan.clone());
// Initialize the journal on this preparation worker, never on the first recording call.
let _ = indirect_used();
if EARLIER_INDIRECT_USED.contains(&record) && indirect_blobs_present(&chain, &plan) {
if EARLIER_INDIRECT_USED.contains(&record) && indirect_blobs_present(&chain, &plan, whole) {
request_indirect(&chain);
}
PROGRAMS.fetch_add(1, Ordering::Relaxed);
Expand Down Expand Up @@ -815,6 +841,61 @@ mod tests {
);
}

#[test]
fn the_whole_form_is_made_again_from_the_console_program() {
use crate::gpu::recomp::pso::{console_to_dxil_in, mem_windows, Stage};
use crate::gpu::xbox::tests::{fssm, sample, CODE};
// (a compute program of one thread group of 1x1x1, as `pso::compile_time_bench` makes it)
let mut f = fssm(&CODE, &[(6, 0)]);
for offset in [0x13C, 0x140, 0x144] {
f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes());
}
let blob = sample(5, &[f]);
let windows = mem_windows();
let first = match console_to_dxil_in(&blob, Stage::Compute, 0, false, windows) {
Ok(c) => c.dxil,
// (no DXC here)
Err(e) if e.contains("dxcompiler") || e.contains("DXC") => {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
Err(e) => panic!("the console program does not translate: {e}"),
};
let source = super::WholeSource { console: blob.clone(), wave32: false, windows };
assert_eq!(source.code().unwrap(), first, "the DXIL the chain was split from");
assert!(source.console.len() < first.len(), "a chain keeps less than the DXIL: {} against {}", source.console.len(), first.len());
}

#[test]
fn the_whole_worker_preserves_each_programs_memory_windows() {
use crate::gpu::{rdna2::encode, recomp::{dxc, pso, HEAP_WINDOWS}, xbox::tests::{fssm, sample}};
use std::sync::mpsc;
if dxc::location().is_err() {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
// A memory write keeps the window access in both translated programs. This test
// compiles only; it never dispatches the synthetic program to a GPU.
let mut code = encode("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None).unwrap();
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
let mut f = fssm(&code, &[(6, 0)]);
for offset in [0x13C, 0x140, 0x144] {
f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes());
}
let blob = sample(5, &[f]);
let mut forms = Vec::new();
for windows in [4, 4 | HEAP_WINDOWS] {
let expected = pso::console_to_dxil_in(&blob, pso::Stage::Compute, 0, false, windows).unwrap().dxil;
let source = super::WholeSource { console: blob.clone(), wave32: false, windows };
let (tx, rx) = mpsc::channel();
assert!(super::enqueue_whole(Box::new(move || { let _ = tx.send(source.code()); })));
let actual = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("whole worker completed").unwrap();
assert_eq!(actual, expected, "the worker must keep the original window form {windows:#x}");
forms.push(actual);
}
assert_ne!(forms[0], forms[1], "the fixture must distinguish root-UAV and descriptor-heap access");
}

const MB: u64 = 1 << 20;

#[test]
Expand Down Expand Up @@ -985,7 +1066,7 @@ mod tests {
indirect_build.requested.store(true, Ordering::Relaxed);
indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!());
CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4,
whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build,
whole_source: WholeSource { console: Vec::new(), wave32: false, windows: 0 }, whole, plan: Arc::downgrade(&plan), indirect: indirect_build,
indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }));
let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
Expand Down
Loading