Merge local/next (a79e248) into local/copies; a test of the bits against remapping
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
2c066abd1a
25 files changed
+3022
-191
No files matched your search
@@ -53,12 +53,21 @@ pub(crate) struct Replay {
|
||||
/// Leave out the argument clamps: what they bound is kept from a first run.
|
||||
#[arg(long)]
|
||||
skip_clamps: bool,
|
||||
/// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2:
|
||||
/// a wait before every indirect dispatch).
|
||||
#[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)]
|
||||
batch_clamps: u32,
|
||||
/// Leave out the hash and compare passes over card buffers.
|
||||
#[arg(long)]
|
||||
skip_hash_passes: bool,
|
||||
/// Where buffers lie.
|
||||
#[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
|
||||
buffers: Buffers,
|
||||
/// With --buffers, only the buffers all of these match: `name=<text>`,
|
||||
/// `min=<bytes>`, `max=<bytes>`, `seen=<No, Cached, Combined>`,
|
||||
/// `id=<a>..<b>`, or `!` and one of those (may be given several times).
|
||||
#[arg(long)]
|
||||
only_buffers: Vec<String>,
|
||||
/// One ExecuteCommandLists for the whole frame.
|
||||
#[arg(long)]
|
||||
one_submit: bool,
|
||||
@@ -119,6 +128,9 @@ pub(crate) struct Replay {
|
||||
/// capture's `shaders` folder.
|
||||
#[arg(long)]
|
||||
dump: Option<String>,
|
||||
/// Only write the frame's buffers and the commands of these lists (`3..7`).
|
||||
#[arg(long)]
|
||||
listing: Option<String>,
|
||||
/// Use the D3D12 debug layer (slow).
|
||||
#[arg(long)]
|
||||
debug_layer: bool,
|
||||
@@ -139,6 +151,10 @@ pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(text) = &r.listing {
|
||||
let lists = range(text).with_context(|| format!("--listing {text}"))?;
|
||||
return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
|
||||
}
|
||||
let only = match &r.only {
|
||||
Some(text) => Some(
|
||||
range(text)
|
||||
@@ -157,9 +173,11 @@ pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
Buffers::Vram => play::Buffers::Card,
|
||||
Buffers::Sysmem => play::Buffers::Pc,
|
||||
},
|
||||
only_buffers: r.only_buffers,
|
||||
no_barriers: r.no_barriers,
|
||||
merge_barriers: r.merge_barriers,
|
||||
skip_clamps: r.skip_clamps,
|
||||
batch_clamps: r.batch_clamps,
|
||||
skip_hash_passes: r.skip_hash_passes,
|
||||
one_submit: r.one_submit,
|
||||
merge: !r.no_merge,
|
||||
|
||||
@@ -598,6 +598,12 @@ fn check(
|
||||
if let Some(keep) = &checks.keep {
|
||||
lock(keep).push((label(), shader.clone()));
|
||||
}
|
||||
// With `--list`: a hash of the module and of what the host binds for it,
|
||||
// to show which shaders a change to the translator touches.
|
||||
if t.list {
|
||||
let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex();
|
||||
t.lines.push(format!("{} emitted {}", label(), &hash[..16]));
|
||||
}
|
||||
// `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
|
||||
if t.list
|
||||
&& let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
|
||||
|
||||
@@ -186,6 +186,67 @@ fn windows() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// Whether indirect executions of one record are clamped in batches
|
||||
/// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own,
|
||||
/// or in windows ([`windows`])).
|
||||
///
|
||||
/// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh
|
||||
/// draws, 948 dispatches, 338 draws), and with the windows still 2,355
|
||||
/// clamps: each a dispatch between two full waits, with the scratch buffer
|
||||
/// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in
|
||||
/// 133 passes, and 77.7 ms in the 980 of this.
|
||||
///
|
||||
/// A batch is opened by the first execution after a point where arguments
|
||||
/// may have changed, and all executions up to the next such point read
|
||||
/// theirs from it, each exactly the record it asks for (windows guess which
|
||||
/// are next, and clamp what they do not know). Arguments in buffers change
|
||||
/// by dispatches and by draws whose shaders store to buffers; those end the
|
||||
/// batch, so the record an execution reads is clamped after all that was
|
||||
/// recorded before it, and the pass waits for all of it, exactly as the
|
||||
/// clamp of its own did. Between two executions of a batch is no wait of
|
||||
/// ours: there is nothing between them to wait for but draws that store to
|
||||
/// no buffer.
|
||||
///
|
||||
/// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the
|
||||
/// title waits for it (a barrier, or a pipeline sync) or draws: what a
|
||||
/// dispatch writes is not there for a later command without a wait, and
|
||||
/// dispatches the title runs side by side (its tile classes, up to 92 at a
|
||||
/// time) are not held up by waits of ours. Off: whether the title has ways
|
||||
/// to wait that do not pass through its lists' methods is not known.
|
||||
fn batches() -> u8 {
|
||||
static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() {
|
||||
Ok("0") => 0,
|
||||
Ok("2") => 2,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// The records clamped by the pass opened last ([`batches`]).
|
||||
struct Batch {
|
||||
table: crate::indirect::batch::Table,
|
||||
scratch: ID3D12Resource,
|
||||
/// Dispatches since, which may have written arguments
|
||||
/// (`VICTORY_INDIRECT_BATCH=2`).
|
||||
wrote: bool,
|
||||
}
|
||||
|
||||
/// The host copies arguments were read from last: what a batch opens with,
|
||||
/// as the executions after the first may read theirs from another one.
|
||||
static ARGUMENT_COPIES: std::sync::Mutex<Vec<std::sync::Weak<crate::shadow::Shadow>>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// [`ARGUMENT_COPIES`] that live, and `first` put in front of them.
|
||||
fn argument_copies(first: &std::sync::Arc<crate::shadow::Shadow>) -> Vec<(u64, ID3D12Resource)> {
|
||||
let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect();
|
||||
*copies = std::iter::once(first)
|
||||
.chain(&live)
|
||||
.take(crate::indirect::batch::SOURCES)
|
||||
.map(std::sync::Arc::downgrade)
|
||||
.collect();
|
||||
live.iter().map(|s| (s.id(), s.buffer.clone())).collect()
|
||||
}
|
||||
|
||||
/// What one title list has set, and what its host list was last given.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct State {
|
||||
@@ -219,6 +280,9 @@ pub(crate) struct State {
|
||||
/// The indirect records clamped last, if later draws may still read
|
||||
/// them ([`windows`]).
|
||||
window: Option<Window>,
|
||||
/// The records clamped in a batch, if later executions may still read
|
||||
/// them ([`batches`]).
|
||||
batch: Option<Batch>,
|
||||
/// What the host list has: pipeline, root signature, heaps.
|
||||
host_pipeline: usize,
|
||||
/// Graphics, compute.
|
||||
@@ -2166,6 +2230,7 @@ impl State {
|
||||
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { list.list.Dispatch(x, y, z) };
|
||||
self.buffers_written();
|
||||
DISPATCHED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
@@ -2436,6 +2501,7 @@ impl State {
|
||||
self.mesh_scissor(list, true);
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { l6.DispatchMesh(x, 1, 1) };
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
self.mesh_scissor(list, false);
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
true
|
||||
@@ -2837,6 +2903,7 @@ impl State {
|
||||
list.list
|
||||
.DrawInstanced(count, instances, from, first_instance)
|
||||
};
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if !ran {
|
||||
@@ -2938,6 +3005,7 @@ impl State {
|
||||
list.list
|
||||
.DrawIndexedInstanced(indices, instances, first, base, first_instance)
|
||||
};
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if !ran {
|
||||
@@ -2949,6 +3017,65 @@ impl State {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Shaders that can write buffers were recorded: arguments may be others
|
||||
/// from here on.
|
||||
fn buffers_written(&mut self) {
|
||||
match &mut self.batch {
|
||||
Some(batch) if batches() == 2 => batch.wrote = true,
|
||||
batch => *batch = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
|
||||
/// if its shaders can store to buffers).
|
||||
fn drew(&mut self, p: Option<&HostPipeline>) {
|
||||
if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
|
||||
self.batch = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The title waits for earlier work (a barrier or a pipeline sync).
|
||||
pub(crate) fn synced(&mut self) {
|
||||
if self.batch.as_ref().is_some_and(|b| b.wrote) {
|
||||
self.batch = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the clamped record of `kind` at `arguments` of the copy `args`
|
||||
/// is, from the open batch or a new one ([`batches`]). `None` if it
|
||||
/// cannot be clamped in one.
|
||||
fn batched(
|
||||
&mut self,
|
||||
list: &HostList,
|
||||
args: &std::sync::Arc<crate::shadow::Shadow>,
|
||||
arguments: u64,
|
||||
kind: u32,
|
||||
) -> Option<(ID3D12Resource, u64)> {
|
||||
const BATCH_USE: usize = usize::MAX - 0x78;
|
||||
const DISPATCH: u32 = 2;
|
||||
// Another host list, or this one after its reset ([`windows`]).
|
||||
if list.first_use(BATCH_USE) {
|
||||
self.batch = None;
|
||||
}
|
||||
// A draw after dispatches waits for them.
|
||||
if kind != DISPATCH {
|
||||
self.synced();
|
||||
}
|
||||
let (id, offset) = (args.id(), args.offset(arguments));
|
||||
if let Some(b) = &mut self.batch
|
||||
&& let Some(at) = b.table.place(id, offset, kind)
|
||||
{
|
||||
return Some((b.scratch.clone(), at));
|
||||
}
|
||||
self.batch = None;
|
||||
let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
|
||||
self.host_pipeline = 0;
|
||||
self.host_roots[1] = 0;
|
||||
let at = table.place(id, offset, kind)?;
|
||||
self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
|
||||
Some((scratch, at))
|
||||
}
|
||||
|
||||
/// Indirect execution of a one-argument signature of `kind` (PC
|
||||
/// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
|
||||
/// records `stride` bytes apart at title address `arguments`, and the
|
||||
@@ -3040,6 +3167,16 @@ impl State {
|
||||
why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
|
||||
return false;
|
||||
}
|
||||
// One record without a count: clamped in a batch (`batches`).
|
||||
let batch = if batches() > 0 && max == 1 && count.is_none() {
|
||||
args.refresh(list, arguments, len);
|
||||
self.batched(list, &args, arguments, kind)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if batch.is_some() {
|
||||
self.window = None;
|
||||
}
|
||||
// A window of records clamped in one pass (`windows`): for single
|
||||
// records without a count buffer, drawn by shaders that store to no
|
||||
// buffer. Anything else ends the window: it uses the scratch buffer
|
||||
@@ -3063,7 +3200,7 @@ impl State {
|
||||
.filter(|w| same(w) && offset >= w.base)
|
||||
.filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
|
||||
.map(|w| (w.scratch.clone(), offset - w.base));
|
||||
let (bounded, at) = match hit {
|
||||
let (bounded, at) = match batch.or(hit) {
|
||||
Some(hit) => hit,
|
||||
None => {
|
||||
// A record a short step after the last window's last one
|
||||
@@ -3153,6 +3290,11 @@ impl State {
|
||||
if kind == MESH {
|
||||
self.mesh_scissor(list, false);
|
||||
}
|
||||
if kind == DISPATCH {
|
||||
self.buffers_written();
|
||||
} else {
|
||||
self.drew(Some(p));
|
||||
}
|
||||
// The scratch buffer stays readable as arguments: the next draw of
|
||||
// the window reads it with no barrier, and the next clamp moves it
|
||||
// back (`crate::indirect`).
|
||||
|
||||
@@ -226,18 +226,29 @@ mod tests {
|
||||
// origin poll that times out (and starts the frame), then a
|
||||
// blocking flip wait. Each flip takes its own tick.
|
||||
const FLIP: u32 = 2;
|
||||
assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK);
|
||||
// (The ticks are far apart, and it may take a few tries: a busy PC
|
||||
// wakes a wait tens of milliseconds late at times.)
|
||||
assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK);
|
||||
let mut token = 0;
|
||||
let flips: Vec<u64> = (0..4)
|
||||
.map(|_| {
|
||||
let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
|
||||
assert_eq!(
|
||||
wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
|
||||
S_OK
|
||||
);
|
||||
LAST[2].load(Ordering::Relaxed)
|
||||
})
|
||||
.collect();
|
||||
let mut four = || -> Vec<u64> {
|
||||
(0..4)
|
||||
.map(|_| {
|
||||
let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
|
||||
assert_eq!(
|
||||
wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
|
||||
S_OK
|
||||
);
|
||||
LAST[2].load(Ordering::Relaxed)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut flips = four();
|
||||
for _ in 0..10 {
|
||||
if flips.windows(2).all(|w| w[1] == w[0] + 1) {
|
||||
break;
|
||||
}
|
||||
flips = four();
|
||||
}
|
||||
assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
|
||||
// Even when a flip wait begins on the tick another just ended on.
|
||||
let (tick, _) = next_tick(FLIP);
|
||||
|
||||
@@ -767,6 +767,10 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The batches of clamped records in one scratch buffer
|
||||
/// ([`HostList::batch_place`]).
|
||||
const BATCHES: u32 = 8;
|
||||
|
||||
/// A host command list and its allocator, always used together.
|
||||
pub(crate) struct HostList {
|
||||
allocator: ID3D12CommandAllocator,
|
||||
@@ -802,6 +806,9 @@ pub(crate) struct HostList {
|
||||
/// Device-local scratch buffer for clamped indirect arguments (`indirect`),
|
||||
/// grown to the largest indirect execution recorded on the list.
|
||||
indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
|
||||
/// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
|
||||
/// how many batches of this recording have a place in them.
|
||||
batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
|
||||
/// Counts the list in [`ALIVE`] while it lives.
|
||||
_alive: Counted,
|
||||
/// The texts of the markers `note_op` set, in order (for device-removed
|
||||
@@ -3308,6 +3315,7 @@ impl Host {
|
||||
budget: OnceLock::new(),
|
||||
card_budget: OnceLock::new(),
|
||||
indirect_args: Mutex::default(),
|
||||
batch_args: Mutex::default(),
|
||||
_alive: Counted::new(),
|
||||
#[cfg(feature = "diagnostics")]
|
||||
notes: Mutex::default(),
|
||||
@@ -5092,6 +5100,7 @@ impl HostList {
|
||||
if let Some((scratch, _)) = scratch {
|
||||
self.indirect_common(&scratch);
|
||||
}
|
||||
self.batches_common();
|
||||
self.card_budget_out();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some((heap, back)) = self.stamps() {
|
||||
@@ -5821,6 +5830,43 @@ impl HostList {
|
||||
Some(buffer)
|
||||
}
|
||||
|
||||
/// Where the next batch of clamped records goes: a device-local buffer
|
||||
/// the list keeps from recording to recording, the batch's place in it
|
||||
/// and the state the buffer is in. Every batch of a recording has a place
|
||||
/// of its own: the executions before it may still read theirs.
|
||||
pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
|
||||
use crate::indirect::batch::{JOBS, SLOT};
|
||||
let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
|
||||
if buffer == args.0.len() {
|
||||
let size = u64::from(BATCHES * JOBS * SLOT);
|
||||
let made = host()?.uav_buffer(size)?;
|
||||
name(&made, || format!("indirect batches {size:#x}"));
|
||||
args.0.push(made);
|
||||
}
|
||||
args.1 += 1;
|
||||
// (Its first batch finds it as the recording before left it:
|
||||
// `batches_common`.)
|
||||
let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
|
||||
Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
|
||||
}
|
||||
|
||||
/// Before the list closes: the scratch buffers of the batched clamps go
|
||||
/// back to the common state, where the next recording expects them.
|
||||
fn batches_common(&self) {
|
||||
let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
|
||||
let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
|
||||
.iter()
|
||||
.map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
|
||||
.collect();
|
||||
if !barriers.is_empty() {
|
||||
// SAFETY: an open list and live buffers this recording left in
|
||||
// `INDIRECT_ARGUMENT`.
|
||||
unsafe { self.list.ResourceBarrier(&barriers) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves `scratch` back to the common state if a clamp left it readable
|
||||
/// as indirect arguments ([`HostList::indirect_readable`]): where the
|
||||
/// list's first clamp expects it. Done before the list closes and before
|
||||
|
||||
@@ -17,6 +17,10 @@
|
||||
//! execution was followed by a move of the scratch buffer back to the
|
||||
//! common state, which drivers may treat as a full wait.
|
||||
//!
|
||||
//! The executions of one record without a count buffer (all the title's)
|
||||
//! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of
|
||||
//! this is for the others.
|
||||
//!
|
||||
//! When a count buffer is given, threads at or past `min(max, count)` return
|
||||
//! immediately without charging the list's budget or reading uninitialized
|
||||
//! tail slots. Each list has a budget (2^27 vertex instances or threads,
|
||||
@@ -36,6 +40,8 @@ use windows::core::s;
|
||||
|
||||
use crate::host::{HostList, host, transition};
|
||||
|
||||
pub(crate) mod batch;
|
||||
|
||||
const SOURCE: &str = r#"
|
||||
#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
|
||||
cbuffer Record : register(b0) {
|
||||
@@ -478,6 +484,70 @@ fn record_clamp_as(
|
||||
true
|
||||
}
|
||||
|
||||
/// The batched clamp's pipeline ([`batch`]).
|
||||
fn batch_clamp() -> Option<&'static Clamp> {
|
||||
static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
|
||||
CLAMP
|
||||
.get_or_init(|| {
|
||||
let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE));
|
||||
match made {
|
||||
Ok(c) => Some(c),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time");
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Opens a batch in `list` ([`batch`]): a pass that clamps the records of
|
||||
/// the executions recorded after it, of `source` (a host copy's number and
|
||||
/// buffer) and of the `recent` ones after it. The table to add them to,
|
||||
/// and the scratch buffer its places are in. Replaces the list's compute
|
||||
/// root signature and pipeline (callers bind theirs after). `None` if the
|
||||
/// clamp is not available.
|
||||
pub(crate) fn open_batch(
|
||||
list: &HostList,
|
||||
source: (u64, &ID3D12Resource),
|
||||
recent: &[(u64, ID3D12Resource)],
|
||||
) -> Option<(batch::Table, ID3D12Resource)> {
|
||||
let c = batch_clamp()?;
|
||||
let budget = list.budget()?;
|
||||
let (jobs, at) = list.scratch(batch::TABLE)?;
|
||||
let (dst, base, before) = list.batch_place()?;
|
||||
let gpu = |b: &ID3D12Resource| {
|
||||
// SAFETY: a live buffer.
|
||||
Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4))
|
||||
};
|
||||
// A source there is none of is the first again, which no job names.
|
||||
let mut ids = [0u64; batch::SOURCES];
|
||||
let mut sources = [gpu(source.1)?; batch::SOURCES];
|
||||
ids[0] = source.0;
|
||||
let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1);
|
||||
for (i, (id, buffer)) in others.enumerate() {
|
||||
if let Some(at) = gpu(buffer) {
|
||||
// Bound, and read only if a job names it: kept alive like the
|
||||
// copies draws read (`Shadow::refresh`).
|
||||
list.keep(buffer);
|
||||
(ids[i + 1], sources[i + 1]) = (*id, at);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
|
||||
batch::record(c, &list.list, (&dst, before), budget, sources, jobs);
|
||||
// SAFETY: the list's own upload memory of that many bytes, 256-byte
|
||||
// aligned, until it is reset.
|
||||
Some((unsafe { batch::Table::new(at, base, ids) }, dst))
|
||||
}
|
||||
|
||||
/// The batched clamp's root signature and pipeline on `device`, for the
|
||||
/// replayer.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> {
|
||||
make_from(device, batch::SOURCE).map(|c| (c.root, c.pso))
|
||||
}
|
||||
|
||||
fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
|
||||
@@ -491,7 +561,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use windows::Win32::Foundation::HANDLE;
|
||||
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
|
||||
@@ -521,6 +591,19 @@ void main() {
|
||||
event: HANDLE,
|
||||
clamp: Clamp,
|
||||
worker: Clamp,
|
||||
/// Last, so given up last.
|
||||
_turn: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
|
||||
/// The software adapter is one test's at a time. Two tests that compile
|
||||
/// and run shaders on it at once (it is one device for the process) make
|
||||
/// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in
|
||||
/// its own shader compiler, on its own worker threads, in 12% of runs of
|
||||
/// all tests and 3% of runs of these alone on two threads; none in 100
|
||||
/// runs one after the other.
|
||||
pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
TURN.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
impl WarpHarness {
|
||||
@@ -530,6 +613,7 @@ void main() {
|
||||
|
||||
/// On the software adapter, or the first one (for measurements).
|
||||
fn on(software: bool) -> Option<Self> {
|
||||
let turn = warp_turn();
|
||||
// SAFETY: plain DXGI query and D3D12 test harness setup.
|
||||
unsafe {
|
||||
let factory: IDXGIFactory4 =
|
||||
@@ -572,6 +656,7 @@ void main() {
|
||||
event,
|
||||
clamp,
|
||||
worker,
|
||||
_turn: turn,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1716,6 +1801,318 @@ void main() {
|
||||
assert_eq!(hits, expected, "every record of both windows runs once");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command signature of one argument of `kind` on `device`.
|
||||
fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature {
|
||||
let arg = D3D12_INDIRECT_ARGUMENT_DESC {
|
||||
Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_COMMAND_SIGNATURE_DESC {
|
||||
ByteStride: stride,
|
||||
NumArgumentDescs: 1,
|
||||
pArgumentDescs: &arg,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let mut sig: Option<ID3D12CommandSignature> = None;
|
||||
// SAFETY: a valid single-argument command signature description.
|
||||
unsafe {
|
||||
device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap();
|
||||
}
|
||||
sig.unwrap()
|
||||
}
|
||||
|
||||
/// What a batch's table says of records added to it: one job per
|
||||
/// record, charged for every execution that reads it, and none for what
|
||||
/// the pass cannot read.
|
||||
#[test]
|
||||
fn batch_tables() {
|
||||
use batch::{JOBS, SLOT, TABLE, TIMES, Table, job};
|
||||
let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1];
|
||||
// SAFETY: the vector holds the table and outlives its use.
|
||||
let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) };
|
||||
assert_eq!(t.place(7, 64, 10), Some(4096));
|
||||
assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
|
||||
assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record");
|
||||
// The same record again: the same place, charged twice.
|
||||
assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
|
||||
assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]);
|
||||
assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]);
|
||||
assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]);
|
||||
assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16);
|
||||
// Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind.
|
||||
for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] {
|
||||
assert_eq!(t.place(id, offset, kind), None);
|
||||
}
|
||||
// Read more often than one job may be charged for: another job.
|
||||
for _ in 1..TIMES {
|
||||
assert_eq!(t.place(7, 64, 10), Some(4096));
|
||||
}
|
||||
assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
|
||||
assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
|
||||
for i in 4..u64::from(JOBS) {
|
||||
assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT)));
|
||||
}
|
||||
assert_eq!(t.place(7, 1024, 1), None, "full");
|
||||
assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT)));
|
||||
assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff));
|
||||
}
|
||||
|
||||
/// A batch clamps records exactly as the clamp of one execution does, of
|
||||
/// any kind, sensible or not; they are added to its table after the pass
|
||||
/// was recorded; it charges each as often as it is read.
|
||||
#[test]
|
||||
fn warp_batch_clamps_as_the_clamp_of_one_does() {
|
||||
let Some(mut warp) = WarpHarness::new() else {
|
||||
return;
|
||||
};
|
||||
let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
|
||||
let kinds = [0u32, 1, 2, 10];
|
||||
let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX];
|
||||
// Every kind with many records, in two sources.
|
||||
let mut records: Vec<(u32, [u32; 5])> = Vec::new();
|
||||
for kind in kinds {
|
||||
for (i, a) in values.into_iter().enumerate() {
|
||||
for (k, b) in values.into_iter().enumerate() {
|
||||
records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD]));
|
||||
}
|
||||
}
|
||||
}
|
||||
// In passes of so few that the budget holds whatever one asks for,
|
||||
// and one pass of them all, which it does not.
|
||||
let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
|
||||
let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10);
|
||||
for (i, (_, words)) in records.iter().enumerate() {
|
||||
for (w, word) in words.iter().enumerate() {
|
||||
// SAFETY: 400 records of 32 bytes in 64 KiB.
|
||||
unsafe {
|
||||
src_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
|
||||
other_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
|
||||
let (back, back_ptr, _) = warp.shared_buffer(64 << 10);
|
||||
let dst = warp.default_uav(64 << 10);
|
||||
let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
|
||||
for (i, (kind, _)) in records.iter().enumerate().step_by(3) {
|
||||
let offset = i as u64 * 32;
|
||||
let words = batch::words(*kind).unwrap();
|
||||
let stride = words * 4;
|
||||
let read = |p: *mut u8| -> Vec<u32> {
|
||||
// SAFETY: the mapping holds more.
|
||||
(0..words as usize).map(|w| unsafe { p.cast::<u32>().add(w).read_volatile() }).collect()
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
for batched in [false, true] {
|
||||
// SAFETY: mapped buffers; nothing runs.
|
||||
unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) };
|
||||
if batched {
|
||||
batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu);
|
||||
// SAFETY: the mapped table; the list has not run.
|
||||
let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) };
|
||||
assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0));
|
||||
} else {
|
||||
assert!(record_clamp_as(
|
||||
&warp.clamp,
|
||||
&warp.list,
|
||||
(&dst, D3D12_RESOURCE_STATE_COMMON),
|
||||
budget_gpu,
|
||||
(&src, offset),
|
||||
None,
|
||||
(*kind, stride, 1),
|
||||
false,
|
||||
));
|
||||
}
|
||||
// SAFETY: an open list; the records are readable as arguments.
|
||||
unsafe {
|
||||
warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
|
||||
warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride));
|
||||
warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
|
||||
}
|
||||
warp.submit_and_wait();
|
||||
// SAFETY: the list has run; mapped words.
|
||||
let budget: Vec<u32> = (0..3).map(|k| unsafe { budget_ptr.cast::<u32>().add(k).read_volatile() }).collect();
|
||||
seen.push((read(back_ptr), budget));
|
||||
}
|
||||
// (A mesh record that asks for nothing notes nothing.)
|
||||
assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records past the list's budget come out empty, and one read by many
|
||||
/// executions is charged for each.
|
||||
#[test]
|
||||
fn warp_batch_charges_every_execution() {
|
||||
let Some(mut warp) = WarpHarness::new() else {
|
||||
return;
|
||||
};
|
||||
let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
|
||||
const BUDGET: u32 = 1 << 27;
|
||||
// 2^26 vertices each, as much as a draw is let run: two fill it.
|
||||
for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] {
|
||||
let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
|
||||
let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
|
||||
let (back, back_ptr, _) = warp.shared_buffer(1024);
|
||||
let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
|
||||
let dst = warp.default_uav(64 << 10);
|
||||
batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
|
||||
// SAFETY: mapped buffers, which the list has not read yet.
|
||||
let mut table = unsafe {
|
||||
std::ptr::write_bytes(budget_ptr, 0, 256);
|
||||
for r in 0..records {
|
||||
for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() {
|
||||
src_ptr.cast::<u32>().add(r as usize * 4 + w).write_volatile(word);
|
||||
}
|
||||
}
|
||||
batch::Table::new(table_ptr, 0, [1, 0, 0, 0])
|
||||
};
|
||||
for _ in 0..times {
|
||||
for r in 0..records {
|
||||
assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT)));
|
||||
}
|
||||
}
|
||||
// SAFETY: an open list; the records are readable as arguments.
|
||||
unsafe {
|
||||
warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
|
||||
warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256);
|
||||
}
|
||||
warp.submit_and_wait();
|
||||
// SAFETY: the list has run; mapped words.
|
||||
let (spent, out): (u32, Vec<u32>) = unsafe {
|
||||
(
|
||||
budget_ptr.cast::<u32>().read_volatile(),
|
||||
(0..records as usize).map(|r| back_ptr.cast::<u32>().add(r * batch::SLOT as usize / 4).read_volatile()).collect(),
|
||||
)
|
||||
};
|
||||
assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}");
|
||||
assert!(out.iter().all(|&v| v == 0 || v == 1 << 24));
|
||||
assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32));
|
||||
}
|
||||
}
|
||||
|
||||
/// Two batches through a host list, twice (the second recording finds
|
||||
/// the scratch buffer as the first one's end left it): executions with
|
||||
/// nothing between them read what they asked for, of two source buffers,
|
||||
/// the second batch while the first one's places are still read. With
|
||||
/// the debug layer on no barrier names a state the buffer is not in.
|
||||
#[test]
|
||||
fn host_list_batches() {
|
||||
let Some(host) = super::host() else {
|
||||
return;
|
||||
};
|
||||
let _ = host.log_messages();
|
||||
let Ok(list) = host.new_list() else {
|
||||
return;
|
||||
};
|
||||
let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
|
||||
let signature = one_argument(&host.device, 2, 12);
|
||||
let mut sources = Vec::new();
|
||||
for first in [1u32, 100] {
|
||||
let Some((buffer, ptr)) = host.shared_buffer(1024) else {
|
||||
return;
|
||||
};
|
||||
for i in 0..16u32 {
|
||||
for (w, word) in [first + i, 1, 1].into_iter().enumerate() {
|
||||
// SAFETY: inside the mapping.
|
||||
unsafe { ptr.cast::<u32>().add(i as usize * 8 + w).write_volatile(word) };
|
||||
}
|
||||
}
|
||||
sources.push(buffer);
|
||||
}
|
||||
let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: a live buffer.
|
||||
let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
|
||||
for _ in 0..2 {
|
||||
// SAFETY: the mapping holds 256 bytes; nothing runs.
|
||||
unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
|
||||
let mut expected = 0;
|
||||
// More batches than one scratch buffer holds.
|
||||
for k in 0..12u32 {
|
||||
let (mut table, scratch) =
|
||||
open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap();
|
||||
// SAFETY: an open list; the worker's root signature and
|
||||
// pipeline; buffers the test holds until the list has run.
|
||||
unsafe {
|
||||
list.list.SetComputeRootSignature(&worker.root);
|
||||
list.list.SetPipelineState(&worker.pso);
|
||||
list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
|
||||
}
|
||||
for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] {
|
||||
let at = table.place(id, u64::from(record) * 32, 2).unwrap();
|
||||
// SAFETY: as above.
|
||||
unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) };
|
||||
expected += record + if id == 1 { 1 } else { 100 };
|
||||
}
|
||||
}
|
||||
list.close();
|
||||
assert_eq!(host.log_messages(), None, "the debug layer found an error");
|
||||
host.execute(&[&list]);
|
||||
list.reset();
|
||||
// SAFETY: the list has run; a mapped buffer.
|
||||
let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
|
||||
assert_eq!(hits, expected, "every execution runs what it asked for");
|
||||
}
|
||||
}
|
||||
|
||||
/// What clamps of a frame cost on the card one by one and in batches
|
||||
/// (ignored: a measurement): 2,355 executions of an empty dispatch, in
|
||||
/// 49 lists' worth of runs, as in the captured frame.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn batch_costs() {
|
||||
let Some(mut gpu) = WarpHarness::on(false) else {
|
||||
return;
|
||||
};
|
||||
const EXECUTIONS: u32 = 2355;
|
||||
let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
|
||||
let sig = gpu.signature(2, 12);
|
||||
let groups: Vec<u32> = vec![1; 2048];
|
||||
let src = dispatch_records(&gpu, &groups, 32);
|
||||
// SAFETY: a live buffer.
|
||||
let src_gpu = unsafe { src.GetGPUVirtualAddress() };
|
||||
let budget = gpu.default_uav(256);
|
||||
let hits = gpu.default_uav(256);
|
||||
// SAFETY: live buffers.
|
||||
let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) };
|
||||
let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400);
|
||||
let dst = gpu.default_uav(4 << 20);
|
||||
for run in [0u32, 2355 / 49, 5, 1] {
|
||||
let mut best = f64::MAX;
|
||||
for _ in 0..6 {
|
||||
let mut state = D3D12_RESOURCE_STATE_COMMON;
|
||||
let mut table = batch::Table::default();
|
||||
for i in 0..EXECUTIONS {
|
||||
if run == 0 {
|
||||
assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false));
|
||||
} else if i % run == 0 {
|
||||
let k = u64::from(i / run) * batch::TABLE;
|
||||
batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k);
|
||||
// SAFETY: the mapped table; the list has not run.
|
||||
table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) };
|
||||
}
|
||||
state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
|
||||
let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() };
|
||||
// SAFETY: an open list; live buffers.
|
||||
unsafe {
|
||||
if run == 0 || i % run == 0 {
|
||||
gpu.list.SetComputeRootSignature(&gpu.worker.root);
|
||||
gpu.list.SetPipelineState(&gpu.worker.pso);
|
||||
gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
|
||||
}
|
||||
gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0);
|
||||
}
|
||||
}
|
||||
let t = std::time::Instant::now();
|
||||
gpu.submit_and_wait();
|
||||
best = best.min(t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") };
|
||||
println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The benchmark of the clamp and its barriers (ignored by default).
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Clamps of many executions in one pass: the arguments of every indirect
|
||||
//! execution between two points where they may change are bounded together,
|
||||
//! at the first of them.
|
||||
//!
|
||||
//! The executions that come after it are not known yet when the pass is
|
||||
//! recorded, so it reads what to clamp from a table of jobs in upload
|
||||
//! memory, which the CPU goes on filling while the list is recorded: the
|
||||
//! pass is as wide as the table and its threads past the count do nothing.
|
||||
//! An execution that asks for a record already in the table (the title's
|
||||
//! tile classes) reads the same clamped one.
|
||||
//!
|
||||
//! What the records charge the list's budget is as for records clamped
|
||||
//! alone, times the executions that read them.
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use super::{Clamp, uav_barrier};
|
||||
use crate::host::transition;
|
||||
|
||||
/// The jobs of one pass.
|
||||
pub(crate) const JOBS: u32 = 256;
|
||||
/// The bytes of its table in upload memory: the count, then the jobs.
|
||||
pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64;
|
||||
/// The bytes of a clamped record's place in the scratch buffer.
|
||||
pub(crate) const SLOT: u32 = 32;
|
||||
/// The source buffers a pass can read.
|
||||
pub(crate) const SOURCES: usize = 4;
|
||||
/// The most executions charged by one job: the most a record costs (2^26)
|
||||
/// as often still fits 32 bits.
|
||||
pub(crate) const TIMES: u32 = 31;
|
||||
|
||||
pub(crate) const SOURCE: &str = r#"
|
||||
#define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)"
|
||||
ByteAddressBuffer src0 : register(t0);
|
||||
ByteAddressBuffer src1 : register(t1);
|
||||
ByteAddressBuffer src2 : register(t2);
|
||||
ByteAddressBuffer src3 : register(t3);
|
||||
// The count, 12 bytes of nothing, then per job: source (bits 0-1), kind
|
||||
// (4-7), words (8-11) and the executions that read it (16-31); the
|
||||
// record's offset in the source; its place in the scratch buffer; nothing.
|
||||
ByteAddressBuffer jobs : register(t4);
|
||||
RWByteAddressBuffer dst_args : register(u0);
|
||||
RWByteAddressBuffer budget : register(u1);
|
||||
static const uint BUDGET = 1u << 27;
|
||||
static const uint GROUPS = 1u << 20;
|
||||
groupshared uint costs[64];
|
||||
groupshared uint fits[64];
|
||||
groupshared uint largest_asked;
|
||||
groupshared uint all_asked;
|
||||
uint load(uint source, uint at) {
|
||||
if (source == 0) return src0.Load(at);
|
||||
if (source == 1) return src1.Load(at);
|
||||
if (source == 2) return src2.Load(at);
|
||||
return src3.Load(at);
|
||||
}
|
||||
[RootSignature(RS)]
|
||||
[numthreads(64, 1, 1)]
|
||||
void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
uint count = jobs.Load(0);
|
||||
bool active = id.x < count;
|
||||
uint4 job = uint4(0, 0, 0, 0);
|
||||
uint record[5] = {0, 0, 0, 0, 0};
|
||||
uint cost = 0;
|
||||
uint asked = 0;
|
||||
uint kind = 0;
|
||||
uint words = 0;
|
||||
if (gi == 0) {
|
||||
largest_asked = 0;
|
||||
all_asked = 0;
|
||||
}
|
||||
// As the clamp of one execution (`super::SOURCE`) bounds them.
|
||||
if (active) {
|
||||
job = jobs.Load4(16 + id.x * 16);
|
||||
kind = (job.x >> 4) & 15;
|
||||
words = min((job.x >> 8) & 15, 5);
|
||||
for (uint w = 0; w < words; w++) {
|
||||
record[w] = load(job.x & 3, job.y + w * 4);
|
||||
}
|
||||
if (kind <= 1) {
|
||||
record[0] = min(record[0], 1u << 24);
|
||||
record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
|
||||
cost = record[0] * record[1];
|
||||
} else if (kind == 2) {
|
||||
uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u));
|
||||
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
|
||||
g = uint3(0, 0, 0);
|
||||
}
|
||||
cost = g.x * g.y * g.z * 64u;
|
||||
record[0] = g.x;
|
||||
record[1] = g.y;
|
||||
record[2] = g.z;
|
||||
} else {
|
||||
asked = record[0];
|
||||
record[0] = min(record[0], 65535u);
|
||||
record[1] = min(record[1], 1u);
|
||||
record[2] = min(record[2], 1u);
|
||||
cost = record[0] * record[1] * record[2] * 128u;
|
||||
}
|
||||
cost *= job.x >> 16;
|
||||
}
|
||||
costs[gi] = cost;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
if (active && kind > 2) {
|
||||
uint was;
|
||||
InterlockedMax(largest_asked, asked, was);
|
||||
InterlockedAdd(all_asked, min(asked, 1u << 24), was);
|
||||
}
|
||||
uint first = id.x - gi;
|
||||
uint n = count > first ? min(64u, count - first) : 0u;
|
||||
if (gi == 0 && n > 0) {
|
||||
uint before;
|
||||
budget.InterlockedOr(0, 0, before);
|
||||
[allow_uav_condition]
|
||||
while (before < BUDGET) {
|
||||
uint next = before;
|
||||
for (uint j = 0; j < n; j++) {
|
||||
uint c = costs[j];
|
||||
if (c > 0 && next < BUDGET) {
|
||||
next = (BUDGET - next <= c) ? BUDGET : (next + c);
|
||||
}
|
||||
}
|
||||
if (next == before) break;
|
||||
uint prev;
|
||||
budget.InterlockedCompareExchange(0, before, next, prev);
|
||||
if (prev == before) break;
|
||||
before = prev;
|
||||
}
|
||||
uint at = before;
|
||||
for (uint k = 0; k < n; k++) {
|
||||
uint c = costs[k];
|
||||
uint fit = 1;
|
||||
if (c > 0) {
|
||||
fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
|
||||
at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
|
||||
}
|
||||
fits[k] = fit;
|
||||
}
|
||||
}
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
if (gi == 0 && n > 0 && all_asked > 0) {
|
||||
uint was;
|
||||
budget.InterlockedMax(4, largest_asked, was);
|
||||
budget.InterlockedAdd(8, all_asked, was);
|
||||
}
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
if (fits[gi] == 0) {
|
||||
record[0] = 0;
|
||||
record[1] = 0;
|
||||
if (kind > 1) {
|
||||
record[2] = 0;
|
||||
}
|
||||
}
|
||||
for (uint s = 0; s < words; s++) {
|
||||
dst_args.Store(job.z + s * 4, record[s]);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The words of a record of `kind` (PC argument numbering).
|
||||
pub(crate) fn words(kind: u32) -> Option<u32> {
|
||||
super::min_stride(kind).map(|bytes| bytes / 4)
|
||||
}
|
||||
|
||||
/// A job's first word.
|
||||
pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 {
|
||||
source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16)
|
||||
}
|
||||
|
||||
/// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it
|
||||
/// keeps which record is where.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Table {
|
||||
/// The table in upload memory ([`TABLE`] bytes).
|
||||
at: usize,
|
||||
/// The place of the first clamped record in the scratch buffer.
|
||||
base: u32,
|
||||
/// The host copies it can read, by number ([`crate::shadow::Shadow::id`];
|
||||
/// 0: none).
|
||||
sources: [u64; SOURCES],
|
||||
/// How many executions each job is charged for so far.
|
||||
times: Vec<u32>,
|
||||
/// The job of a record (source, offset, kind).
|
||||
known: std::collections::HashMap<(u32, u32, u32), u32>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// A table at `at`, with no job yet.
|
||||
///
|
||||
/// # Safety
|
||||
/// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that
|
||||
/// live until the list that reads them is recorded and is not run
|
||||
/// before.
|
||||
pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { at.cast::<u32>().write_volatile(0) };
|
||||
Table { at: at as usize, base, sources, ..Table::default() }
|
||||
}
|
||||
|
||||
/// The place in the scratch buffer of the record of `kind` at `offset`
|
||||
/// of the host copy `id`, once the pass has run: a job of it is added if
|
||||
/// there is none. `None` if the pass cannot read that copy or has no
|
||||
/// room for another job.
|
||||
pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> {
|
||||
let source = self.sources.iter().position(|&s| s == id)? as u32;
|
||||
let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?;
|
||||
offset.checked_add(words(kind)? * 4)?;
|
||||
let key = (source, offset, kind);
|
||||
let table = self.at as *mut u32;
|
||||
let place = |i: u32| u64::from(self.base + i * SLOT);
|
||||
if let Some(&i) = self.known.get(&key)
|
||||
&& self.times[i as usize] < TIMES
|
||||
{
|
||||
self.times[i as usize] += 1;
|
||||
// SAFETY: the job's own word of the table ([`Table::new`]).
|
||||
unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) };
|
||||
return Some(place(i));
|
||||
}
|
||||
let i = self.times.len() as u32;
|
||||
if i == JOBS {
|
||||
return None;
|
||||
}
|
||||
self.times.push(1);
|
||||
self.known.insert(key, i);
|
||||
// SAFETY: inside the table: fewer than [`JOBS`] jobs before it.
|
||||
unsafe {
|
||||
let to = table.add(4 + 4 * i as usize);
|
||||
to.write_volatile(job(source, kind, 1));
|
||||
to.add(1).write_volatile(offset);
|
||||
to.add(2).write_volatile(self.base + i * SLOT);
|
||||
to.add(3).write_volatile(0);
|
||||
table.write_volatile(i + 1);
|
||||
}
|
||||
Some(place(i))
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the pass over the table at `jobs` (a host address) into `dst`,
|
||||
/// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every
|
||||
/// earlier shader write (the title's argument passes), before what reads
|
||||
/// the clamped records.
|
||||
pub(super) fn record(
|
||||
c: &Clamp,
|
||||
l: &ID3D12GraphicsCommandList,
|
||||
(dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
|
||||
budget: u64,
|
||||
sources: [u64; SOURCES],
|
||||
jobs: u64,
|
||||
) {
|
||||
let after = transition(
|
||||
dst,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
|
||||
);
|
||||
// SAFETY: an open list; our root signature and pipeline; live buffers:
|
||||
// the sources and the table are read in the common state (promoted).
|
||||
unsafe {
|
||||
l.ResourceBarrier(&[
|
||||
uav_barrier(),
|
||||
transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
|
||||
]);
|
||||
l.SetComputeRootSignature(&c.root);
|
||||
l.SetPipelineState(&c.pso);
|
||||
for (i, source) in sources.into_iter().enumerate() {
|
||||
l.SetComputeRootShaderResourceView(i as u32, source);
|
||||
}
|
||||
l.SetComputeRootShaderResourceView(SOURCES as u32, jobs);
|
||||
l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress());
|
||||
l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget);
|
||||
l.Dispatch(JOBS.div_ceil(64), 1, 1);
|
||||
// Nothing else the pass writes is read before the next full wait
|
||||
// (the budget, by the next pass): only the records have to be there.
|
||||
l.ResourceBarrier(&[after]);
|
||||
}
|
||||
}
|
||||
@@ -1151,6 +1151,7 @@ mod tests {
|
||||
/// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds.
|
||||
#[test]
|
||||
fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() {
|
||||
let _turn = crate::indirect::tests::warp_turn();
|
||||
let Some(device) = warp() else { return };
|
||||
if device.cast::<ID3D12Device13>().is_err() {
|
||||
eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened");
|
||||
@@ -1174,6 +1175,7 @@ mod tests {
|
||||
/// whole is turned down without asking the host.
|
||||
#[test]
|
||||
fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() {
|
||||
let _turn = crate::indirect::tests::warp_turn();
|
||||
let Some(device) = warp() else { return };
|
||||
if device.cast::<ID3D12Device13>().is_err() {
|
||||
return;
|
||||
@@ -1194,7 +1196,16 @@ mod tests {
|
||||
assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address");
|
||||
drop(placed);
|
||||
// Half of it decommitted: turned down, the host not asked.
|
||||
assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0);
|
||||
// The heap lets go of the pages a moment after its last
|
||||
// reference, if the adapter is busy with other tests' work.
|
||||
let gone = (0..500).any(|_| {
|
||||
let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
|
||||
if !done {
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
done
|
||||
});
|
||||
assert!(gone, "the heap keeps the pages");
|
||||
assert!(matches!(place_part(&device, start, len), Err(None)));
|
||||
mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
|
||||
}
|
||||
|
||||
@@ -70,5 +70,6 @@ pub use host::on_failure;
|
||||
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
|
||||
#[cfg(windows)]
|
||||
pub use watch::{
|
||||
title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write,
|
||||
title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
|
||||
writing as kernel_will_write,
|
||||
};
|
||||
@@ -742,6 +742,9 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
|
||||
if let Some(list) = host_list(this)
|
||||
&& !barriers.is_null()
|
||||
{
|
||||
if count > 0 {
|
||||
with_state(this, |_, state| state.synced());
|
||||
}
|
||||
// SAFETY: the title passes `count` barriers.
|
||||
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
|
||||
let mut host: Vec<Barrier> = barriers
|
||||
@@ -1396,7 +1399,14 @@ extern "system" fn set_pipeline(this: This, pipeline: This) {
|
||||
/// bottom of the pipe `(flags, control, address, size)`. Host lists order
|
||||
/// their own work and every submission is waited for, so there is nothing
|
||||
/// to do.
|
||||
extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
|
||||
/// (Arguments may be what earlier shaders wrote from here on:
|
||||
/// `State::synced`.)
|
||||
extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) {
|
||||
#[cfg(windows)]
|
||||
with_state(this, |_, state| state.synced());
|
||||
#[cfg(not(windows))]
|
||||
let _ = this;
|
||||
}
|
||||
|
||||
/// Reset with console flags `(allocator, pipeline, flags)`; the flags only
|
||||
/// tune the console's command memory.
|
||||
@@ -1943,6 +1953,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
|
||||
&& let Some(list) = host_list(this)
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
|
||||
with_state(this, |_, state| state.synced());
|
||||
// SAFETY: the same layout; no resource named.
|
||||
let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
|
||||
// SAFETY: an open list.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::wire::{ALL, Barrier, Cmd, NONE, Va};
|
||||
use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot};
|
||||
|
||||
/// The buffer the clamped arguments of all clamp passes lie in, in lists
|
||||
/// edited by [`clamps`].
|
||||
@@ -298,6 +298,276 @@ pub fn skip_clamps(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The root signature, pipeline and table of the batched clamp
|
||||
/// (`crate::indirect::batch`), and the scratch buffer it writes in the
|
||||
/// first list of the frame (the next lists' are the ids before it), in lists
|
||||
/// edited by [`batch_clamps`].
|
||||
pub const BATCH_ROOT: u32 = u32::MAX - 2;
|
||||
pub const BATCH: u32 = u32::MAX - 3;
|
||||
pub const BATCH_JOBS: u32 = u32::MAX - 4;
|
||||
pub const BATCH_SCRATCH: u32 = u32::MAX - 16;
|
||||
|
||||
/// What [`batch_clamps`] did to a list.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Batched {
|
||||
/// Clamp passes before; after; the records the latter clamp.
|
||||
pub clamps: u32,
|
||||
pub batches: u32,
|
||||
pub jobs: u32,
|
||||
/// The bytes of the scratch buffer.
|
||||
pub scratch: u64,
|
||||
}
|
||||
|
||||
/// A clamp batch being filled by [`batch_clamps`].
|
||||
struct Batch {
|
||||
/// Where its table is in the jobs, and its root views in the list.
|
||||
table: usize,
|
||||
at: usize,
|
||||
sources: Vec<u32>,
|
||||
/// By source, offset and kind: the job, and how often it is read.
|
||||
known: HashMap<(u32, u64, u32), (u32, u32)>,
|
||||
n: u32,
|
||||
base: u64,
|
||||
}
|
||||
|
||||
/// The list with its clamps done in batches, as `crate::draw` does with
|
||||
/// `VICTORY_INDIRECT_BATCH`: one pass at the first execution after a
|
||||
/// point where arguments may have changed (a wait for shader writes, with
|
||||
/// dispatches since the batch before it; or a draw, with dispatches since
|
||||
/// the last wait). `careful`: before indirect dispatches too, with
|
||||
/// dispatches since the last wait. `compute`: the pipelines that are compute
|
||||
/// ones. The tables go to `jobs` (the contents of [`BATCH_JOBS`]).
|
||||
pub fn batch_clamps(
|
||||
cmds: Vec<Cmd>,
|
||||
psos: &HashSet<u32>,
|
||||
compute: &HashSet<u32>,
|
||||
scratch: u32,
|
||||
careful: bool,
|
||||
jobs: &mut Vec<u8>,
|
||||
) -> (Vec<Cmd>, Batched) {
|
||||
use crate::indirect::batch::{JOBS, SLOT, SOURCES, TIMES, job};
|
||||
const DISPATCH: u32 = 2;
|
||||
let mut done = Batched::default();
|
||||
let scratches: HashSet<u32> = {
|
||||
let mut next = 0;
|
||||
let found = find_clamps(&cmds, psos, &mut next);
|
||||
found.iter().map(|c| c.scratch).collect()
|
||||
};
|
||||
if scratches.is_empty() {
|
||||
return (cmds, done);
|
||||
}
|
||||
let of_clamp =
|
||||
|b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res));
|
||||
let moved = |before, after| Barrier::Transition {
|
||||
flags: 0,
|
||||
res: scratch,
|
||||
sub: ALL,
|
||||
before,
|
||||
after,
|
||||
};
|
||||
// What the last clamp into a scratch buffer clamped: source, offset,
|
||||
// kind.
|
||||
let mut clamps: HashMap<u32, (u32, u64, u32)> = HashMap::new();
|
||||
let (mut bound, mut constants, mut views) = (NONE, [0u32; 6], [(NONE, 0u64); 5]);
|
||||
let mut out: Vec<Cmd> = Vec::with_capacity(cmds.len());
|
||||
let mut open: Option<Batch> = None;
|
||||
let (mut written, mut dirty, mut readable) = (true, true, false);
|
||||
let mut cmds = cmds.into_iter().peekable();
|
||||
while let Some(c) = cmds.next() {
|
||||
match &c {
|
||||
// A clamp's own commands: its root signature and all it sets.
|
||||
Cmd::RootSignature {
|
||||
graphics: false, ..
|
||||
} if matches!(cmds.peek(), Some(Cmd::Pipeline { pso }) if psos.contains(pso)) => {}
|
||||
Cmd::Pipeline { pso } => {
|
||||
bound = *pso;
|
||||
if !psos.contains(pso) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Cmd::Constants {
|
||||
graphics: false,
|
||||
values,
|
||||
offset,
|
||||
..
|
||||
} if psos.contains(&bound) => {
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
if let Some(c) = constants.get_mut(*offset as usize + i) {
|
||||
*c = *v;
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::RootView {
|
||||
graphics: false,
|
||||
param,
|
||||
va: Va::At { res, offset },
|
||||
..
|
||||
} if psos.contains(&bound) => {
|
||||
if let Some(v) = views.get_mut(*param as usize) {
|
||||
*v = (*res, *offset);
|
||||
}
|
||||
}
|
||||
Cmd::Dispatch { .. } if psos.contains(&bound) => {
|
||||
done.clamps += 1;
|
||||
let (source, offset) = views[1];
|
||||
clamps.insert(
|
||||
views[3].0,
|
||||
(source, offset + u64::from(constants[3]), constants[0]),
|
||||
);
|
||||
// What it was clamped for follows: a batch is open by then.
|
||||
let full =
|
||||
|o: &Batch| !o.sources.contains(&source) && o.sources.len() == SOURCES;
|
||||
if dirty && (constants[0] != DISPATCH || careful) || open.as_ref().is_some_and(full)
|
||||
{
|
||||
open = None;
|
||||
}
|
||||
if open.is_some() {
|
||||
continue;
|
||||
}
|
||||
done.batches += 1;
|
||||
let table = jobs.len();
|
||||
jobs.resize(table + 16 + 16 * 2048, 0);
|
||||
out.push(Cmd::Barriers {
|
||||
all: vec![
|
||||
Barrier::Uav {
|
||||
flags: 0,
|
||||
res: NONE,
|
||||
},
|
||||
moved(if readable { INDIRECT_ARGUMENT } else { 0 }, UNORDERED_ACCESS),
|
||||
],
|
||||
});
|
||||
readable = true;
|
||||
out.push(Cmd::RootSignature {
|
||||
graphics: false,
|
||||
root: BATCH_ROOT,
|
||||
});
|
||||
out.push(Cmd::Pipeline { pso: BATCH });
|
||||
let at = out.len();
|
||||
let mut view = |kind, param: usize, res, offset| {
|
||||
out.push(Cmd::RootView {
|
||||
graphics: false,
|
||||
kind,
|
||||
param: param as u32,
|
||||
va: Va::At { res, offset },
|
||||
});
|
||||
};
|
||||
for i in 0..SOURCES {
|
||||
view(slot::SRV, i, source, 0);
|
||||
}
|
||||
view(slot::SRV, SOURCES, BATCH_JOBS, table as u64);
|
||||
view(slot::UAV, SOURCES + 1, scratch, 0);
|
||||
view(slot::UAV, SOURCES + 2, views[4].0, views[4].1);
|
||||
out.push(Cmd::Dispatch {
|
||||
groups: [JOBS.div_ceil(64), 1, 1],
|
||||
});
|
||||
out.push(Cmd::Barriers {
|
||||
all: vec![moved(UNORDERED_ACCESS, INDIRECT_ARGUMENT)],
|
||||
});
|
||||
open = Some(Batch {
|
||||
table,
|
||||
at,
|
||||
sources: Vec::new(),
|
||||
known: HashMap::new(),
|
||||
n: 0,
|
||||
base: done.scratch,
|
||||
});
|
||||
(written, dirty) = (false, false);
|
||||
}
|
||||
Cmd::Barriers { all } => {
|
||||
if all.iter().any(of_clamp) {
|
||||
continue;
|
||||
}
|
||||
let waits = |b: &Barrier| matches!(b, Barrier::Uav { res: NONE, .. });
|
||||
if all.iter().any(waits) {
|
||||
if written {
|
||||
open = None;
|
||||
}
|
||||
dirty = false;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
Cmd::Indirect {
|
||||
signature,
|
||||
most,
|
||||
args,
|
||||
at,
|
||||
count,
|
||||
count_at,
|
||||
} if clamps.contains_key(args) => {
|
||||
let (source, offset, kind) = clamps.get(args).copied().unwrap_or_default();
|
||||
let Some(o) = &mut open else {
|
||||
// Not clamped by any batch: left out, which shows.
|
||||
continue;
|
||||
};
|
||||
let slot = match o.sources.iter().position(|&s| s == source) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
o.sources.push(source);
|
||||
let i = o.sources.len() - 1;
|
||||
if let Some(Cmd::RootView {
|
||||
va: Va::At { res, .. },
|
||||
..
|
||||
}) = out.get_mut(o.at + i)
|
||||
{
|
||||
*res = source;
|
||||
}
|
||||
i
|
||||
}
|
||||
};
|
||||
let offset = offset + at;
|
||||
let entry = o.known.entry((source, offset, kind)).or_insert((o.n, 0));
|
||||
entry.1 += 1;
|
||||
let (i, times) = *entry;
|
||||
if i == o.n {
|
||||
o.n += 1;
|
||||
done.jobs += 1;
|
||||
done.scratch = o.base + u64::from(o.n * SLOT);
|
||||
// Wider than the live pass where its table is longer.
|
||||
if let Some(Cmd::Dispatch { groups }) = out.get_mut(o.at + SOURCES + 3) {
|
||||
groups[0] = groups[0].max(o.n.div_ceil(64));
|
||||
}
|
||||
}
|
||||
let place = o.base + u64::from(i * SLOT);
|
||||
let words = [
|
||||
job(slot as u32, kind, times.min(TIMES)),
|
||||
offset as u32,
|
||||
place as u32,
|
||||
0,
|
||||
];
|
||||
let mut put = |at: usize, w: u32| {
|
||||
jobs[o.table + at..o.table + at + 4].copy_from_slice(&w.to_le_bytes());
|
||||
};
|
||||
for (k, w) in words.into_iter().enumerate() {
|
||||
put(16 + 16 * i as usize + 4 * k, w);
|
||||
}
|
||||
put(0, o.n);
|
||||
out.push(Cmd::Indirect {
|
||||
signature: *signature,
|
||||
most: *most,
|
||||
args: scratch,
|
||||
at: place,
|
||||
count: *count,
|
||||
count_at: *count_at,
|
||||
});
|
||||
if compute.contains(&bound) {
|
||||
(written, dirty) = (true, true);
|
||||
}
|
||||
}
|
||||
Cmd::Dispatch { .. } => {
|
||||
(written, dirty) = (true, true);
|
||||
out.push(c);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
if readable {
|
||||
out.push(Cmd::Barriers {
|
||||
all: vec![moved(INDIRECT_ARGUMENT, 0)],
|
||||
});
|
||||
}
|
||||
(out, done)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -501,4 +771,111 @@ mod tests {
|
||||
[(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_are_batched() {
|
||||
use crate::indirect::batch::job;
|
||||
let clamp = |kind, offset, records, source| {
|
||||
let view = |param, res| Cmd::RootView {
|
||||
graphics: false,
|
||||
kind: 2,
|
||||
param,
|
||||
va: Va::At { res, offset: 0 },
|
||||
};
|
||||
vec![
|
||||
barriers(&[uav(0), moved(5, 0x200, 8)]),
|
||||
Cmd::RootSignature {
|
||||
graphics: false,
|
||||
root: 8,
|
||||
},
|
||||
pso(9),
|
||||
Cmd::Constants {
|
||||
graphics: false,
|
||||
param: 0,
|
||||
offset: 0,
|
||||
values: vec![kind, 32, records, offset, 0, 0],
|
||||
},
|
||||
view(1, source),
|
||||
view(2, source),
|
||||
view(3, 5),
|
||||
view(4, 6),
|
||||
go(),
|
||||
barriers(&[uav(0), moved(5, 8, 0x200)]),
|
||||
]
|
||||
};
|
||||
let run = |at| Cmd::Indirect {
|
||||
signature: 1,
|
||||
most: 1,
|
||||
args: 5,
|
||||
at,
|
||||
count: 0,
|
||||
count_at: 0,
|
||||
};
|
||||
// A dispatch, two indirect ones with a wait of the title's between
|
||||
// them, then draws: a window of two and another buffer's.
|
||||
let mut list = vec![pso(1), go()];
|
||||
list.extend(clamp(2, 0, 1, 70));
|
||||
list.extend([pso(1), run(0)]);
|
||||
list.extend(clamp(2, 64, 1, 70));
|
||||
list.extend([pso(1), run(0), barriers(&[uav(0)])]);
|
||||
list.extend(clamp(2, 64, 1, 70));
|
||||
list.extend([pso(1), run(0)]);
|
||||
list.extend(clamp(10, 128, 2, 70));
|
||||
list.extend([pso(2), run(0), run(32), run(32)]);
|
||||
list.extend(clamp(10, 256, 1, 71));
|
||||
list.extend([pso(2), run(0)]);
|
||||
let (clamps, compute) = (HashSet::from([9]), HashSet::from([1]));
|
||||
let table = 16 + 16 * 2048;
|
||||
for (careful, batches) in [(false, 3), (true, 4)] {
|
||||
let mut jobs = Vec::new();
|
||||
let (out, done) = batch_clamps(list.clone(), &clamps, &compute, 99, careful, &mut jobs);
|
||||
assert_eq!((done.clamps, done.batches, done.jobs), (5, batches, 6), "careful {careful}");
|
||||
assert_eq!(jobs.len(), table * batches as usize);
|
||||
let passes = out.iter().filter(|c| matches!(c, Cmd::Pipeline { pso: BATCH })).count();
|
||||
assert_eq!(passes, batches as usize);
|
||||
// Nothing of the clamps is left; the title's wait is.
|
||||
assert!(!out.contains(&pso(9)) && out.contains(&barriers(&[uav(0)])));
|
||||
let names_5 = |c: &Cmd| matches!(c, Cmd::Barriers { all } if all.iter().any(|b| matches!(b, Barrier::Transition { res: 5, .. })));
|
||||
assert!(!out.iter().any(names_5));
|
||||
let places: Vec<u64> = out
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
Cmd::Indirect { args: 99, at, .. } => Some(*at),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(places, [0, 32, 64, 96, 128, 128, 160]);
|
||||
// The last table: two records, one read twice, then one of the
|
||||
// other buffer.
|
||||
let word = |i: usize| {
|
||||
let at = jobs.len() - table + 4 * i;
|
||||
u32::from_le_bytes(jobs[at..at + 4].try_into().unwrap())
|
||||
};
|
||||
assert_eq!(word(0), 3);
|
||||
let all: Vec<u32> = (4..16).map(word).collect();
|
||||
assert_eq!(
|
||||
all,
|
||||
[
|
||||
[job(0, 10, 1), 128, 96, 0],
|
||||
[job(0, 10, 2), 160, 128, 0],
|
||||
[job(1, 10, 1), 256, 160, 0]
|
||||
]
|
||||
.concat()
|
||||
);
|
||||
let sources: Vec<u32> = out
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
Cmd::RootView { param: 1, va: Va::At { res, .. }, .. } => Some(*res),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(sources.last(), Some(&71));
|
||||
// It ends common, as it began.
|
||||
assert_eq!(out.last(), Some(&barriers(&[moved(99, 0x200, 0)])));
|
||||
}
|
||||
// A list without clamps is left as it is.
|
||||
let plain = vec![pso(1), go(), barriers(&[uav(0)])];
|
||||
let (out, done) = batch_clamps(plain.clone(), &clamps, &compute, 99, false, &mut Vec::new());
|
||||
assert_eq!((out, done), (plain, Batched::default()));
|
||||
}
|
||||
}
|
||||
@@ -65,9 +65,13 @@ pub struct Options {
|
||||
/// Where the picture goes (default: `replay.png` in the capture).
|
||||
pub image: Option<PathBuf>,
|
||||
pub buffers: Buffers,
|
||||
/// Of those, only the ones all of these match ([`chosen`]).
|
||||
pub only_buffers: Vec<String>,
|
||||
pub no_barriers: bool,
|
||||
pub merge_barriers: bool,
|
||||
pub skip_clamps: bool,
|
||||
/// The clamps in batches (`edit::batch_clamps`); 2: carefully.
|
||||
pub batch_clamps: u32,
|
||||
pub skip_hash_passes: bool,
|
||||
pub one_submit: bool,
|
||||
/// Copies of what the CPU wrote leave alone what the card wrote in this
|
||||
@@ -97,9 +101,11 @@ impl Default for Options {
|
||||
top: 20,
|
||||
image: None,
|
||||
buffers: Buffers::AsRecorded,
|
||||
only_buffers: Vec::new(),
|
||||
no_barriers: false,
|
||||
merge_barriers: false,
|
||||
skip_clamps: false,
|
||||
batch_clamps: 0,
|
||||
skip_hash_passes: false,
|
||||
one_submit: false,
|
||||
merge: true,
|
||||
@@ -118,6 +124,7 @@ impl Options {
|
||||
self.no_barriers
|
||||
|| self.merge_barriers
|
||||
|| self.skip_clamps
|
||||
|| self.batch_clamps > 0
|
||||
|| self.skip_hash_passes
|
||||
|| self.one_submit
|
||||
|| self.wait_all
|
||||
@@ -132,6 +139,7 @@ impl Options {
|
||||
no_barriers: false,
|
||||
merge_barriers: false,
|
||||
skip_clamps: false,
|
||||
batch_clamps: 0,
|
||||
skip_hash_passes: false,
|
||||
one_submit: false,
|
||||
wait_all: false,
|
||||
@@ -245,6 +253,32 @@ impl Report {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `--only-buffers` means a buffer: all of `only` match it.
|
||||
/// `name=<text in its name>`, `min=<bytes>`, `max=<bytes>`,
|
||||
/// `seen=<how the CPU saw it>`, `id=<a>..<b>`; with `!` in front: that does not.
|
||||
fn chosen(r: &wire::Resource, only: &[String]) -> bool {
|
||||
only.iter().all(|f| {
|
||||
let (no, f) = match f.strip_prefix('!') {
|
||||
Some(f) => (true, f),
|
||||
None => (false, f.as_str()),
|
||||
};
|
||||
let (key, value) = f.split_once('=').unwrap_or(("name", f));
|
||||
let number = value.parse().unwrap_or(0u64);
|
||||
let is = match key {
|
||||
"min" => r.desc.width >= number,
|
||||
"max" => r.desc.width <= number,
|
||||
"seen" => {
|
||||
matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value))
|
||||
}
|
||||
"id" => value.split_once("..").is_some_and(|(a, b)| {
|
||||
(a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id)
|
||||
}),
|
||||
_ => r.name.contains(value),
|
||||
};
|
||||
is != no
|
||||
})
|
||||
}
|
||||
|
||||
fn median(v: &[f64]) -> f64 {
|
||||
let mut v = v.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
@@ -311,20 +345,65 @@ pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes, one line each, the commands of lists (by their place in the
|
||||
/// frame), and before them the frame's buffers: `--listing`.
|
||||
pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> {
|
||||
let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
|
||||
let pipelines: HashMap<u32, &str> =
|
||||
frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect();
|
||||
for r in &frame.resources {
|
||||
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
|
||||
let place = match &r.place {
|
||||
Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)),
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
|
||||
}
|
||||
}
|
||||
let mut place = 0;
|
||||
for (i, s) in frame.submits.iter().enumerate() {
|
||||
for &l in s.lists.iter().filter(|&&l| l != MISSING) {
|
||||
let here = place;
|
||||
place += 1;
|
||||
if here < lists.0 || here > lists.1 {
|
||||
continue;
|
||||
}
|
||||
line(&format!("list {here} of submission {i}"));
|
||||
for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() {
|
||||
match c {
|
||||
Cmd::Pipeline { pso } => {
|
||||
line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default()));
|
||||
}
|
||||
c => line(&format!("{n} {c:?}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads a capture and runs it: the whole of `victory replay`. The reports,
|
||||
/// with what each is of.
|
||||
pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
|
||||
let mut player = Player::load(folder, options)?;
|
||||
let mut out = Vec::new();
|
||||
if options.compare && options.edited() {
|
||||
// Turn by turn: what else the machine does falls on both.
|
||||
let image = Some(player.folder.join("replay-unchanged.png"));
|
||||
out.push((
|
||||
"unchanged".into(),
|
||||
player.run(&Options {
|
||||
image,
|
||||
..options.plain()
|
||||
})?,
|
||||
));
|
||||
let plain = Options {
|
||||
image,
|
||||
..options.plain()
|
||||
};
|
||||
let mut a = player.prepare(&plain)?;
|
||||
let mut b = player.prepare(options)?;
|
||||
let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new());
|
||||
for _ in 0..options.loops.max(1) {
|
||||
stamps_a = player.once(&plain, &mut a)?;
|
||||
stamps_b = player.once(options, &mut b)?;
|
||||
}
|
||||
out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?));
|
||||
out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?));
|
||||
return Ok(out);
|
||||
}
|
||||
let what = if options.edited() {
|
||||
"with the experiments"
|
||||
@@ -468,7 +547,7 @@ impl Player {
|
||||
*at = Instant::now();
|
||||
};
|
||||
let mut at = Instant::now();
|
||||
player.make_resources(options.buffers)?;
|
||||
player.make_resources(options.buffers, &options.only_buffers)?;
|
||||
step("resources", &mut at);
|
||||
player.make_pipelines()?;
|
||||
step("pipelines", &mut at);
|
||||
@@ -558,7 +637,7 @@ impl Player {
|
||||
}
|
||||
}
|
||||
|
||||
fn make_resources(&mut self, buffers: Buffers) -> Result<()> {
|
||||
fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> {
|
||||
// A heap of memory the CPU sees becomes one the card may write too:
|
||||
// what the CPU wrote is put back by the card.
|
||||
let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES {
|
||||
@@ -602,7 +681,7 @@ impl Player {
|
||||
for h in &self.frame.heaps {
|
||||
let desc = D3D12_HEAP_DESC {
|
||||
SizeInBytes: h.size,
|
||||
Properties: props(&h.props, used_by_buffers_only.contains(&h.id)),
|
||||
Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)),
|
||||
Alignment: h.alignment,
|
||||
Flags: D3D12_HEAP_FLAGS(h.flags & !DROP),
|
||||
};
|
||||
@@ -613,8 +692,15 @@ impl Player {
|
||||
self._heaps.extend(heap.map(|heap| (h.id, heap)));
|
||||
}
|
||||
let mut failed = 0;
|
||||
let mut moves: BTreeMap<String, (u32, u64)> = BTreeMap::new();
|
||||
for (index, r) in self.frame.resources.iter().enumerate() {
|
||||
let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
|
||||
let moved = is_buffer && chosen(r, only);
|
||||
if moved && let Place::Committed { props, .. } = &r.place {
|
||||
let seen = gpu::seen(props);
|
||||
let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64));
|
||||
*m = (m.0 + 1, m.1 + r.desc.width);
|
||||
}
|
||||
let desc = gpu::to_desc(&r.desc);
|
||||
let mut made: Option<ID3D12Resource> = None;
|
||||
let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
|
||||
@@ -637,7 +723,7 @@ impl Player {
|
||||
None => Err(windows::core::Error::empty()),
|
||||
},
|
||||
Place::Committed { props: p, flags } => {
|
||||
let p = props(p, is_buffer);
|
||||
let p = props(p, moved);
|
||||
let state = if p.Type == D3D12_HEAP_TYPE_READBACK {
|
||||
D3D12_RESOURCE_STATE_COPY_DEST
|
||||
} else {
|
||||
@@ -700,6 +786,11 @@ impl Player {
|
||||
if failed > 0 {
|
||||
self.note(format!("{failed} resources could not be made again"));
|
||||
}
|
||||
if buffers != Buffers::AsRecorded {
|
||||
self.notes.push(format!(
|
||||
"--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1800,6 +1891,17 @@ impl Player {
|
||||
.push(format!("{} pipelines match --skip-shader", skip.len()));
|
||||
}
|
||||
let hash = self.pipelines_named(COMPARE);
|
||||
let clamp = self.pipelines_named(CLAMP);
|
||||
let compute: HashSet<u32> = self
|
||||
.frame
|
||||
.pipelines
|
||||
.iter()
|
||||
.filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0)))
|
||||
.map(|p| p.id)
|
||||
.collect();
|
||||
let mut batched = edit::Batched::default();
|
||||
let mut jobs = Vec::new();
|
||||
let mut scratches = Vec::new();
|
||||
let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0);
|
||||
let mut place = 0;
|
||||
let mut out = Vec::new();
|
||||
@@ -1818,6 +1920,24 @@ impl Player {
|
||||
{
|
||||
cmds = edit::skip_clamps(cmds, c);
|
||||
}
|
||||
if o.batch_clamps > 0 {
|
||||
let scratch = edit::BATCH_SCRATCH - here;
|
||||
let done;
|
||||
(cmds, done) = edit::batch_clamps(
|
||||
cmds,
|
||||
&clamp,
|
||||
&compute,
|
||||
scratch,
|
||||
o.batch_clamps > 1,
|
||||
&mut jobs,
|
||||
);
|
||||
batched.clamps += done.clamps;
|
||||
batched.batches += done.batches;
|
||||
batched.jobs += done.jobs;
|
||||
if done.scratch > 0 {
|
||||
scratches.push((scratch, done.scratch));
|
||||
}
|
||||
}
|
||||
let mut n;
|
||||
if !skip.is_empty() {
|
||||
(cmds, n) = edit::skip_pipelines(cmds, &skip);
|
||||
@@ -1839,6 +1959,15 @@ impl Player {
|
||||
}
|
||||
out.push(lists);
|
||||
}
|
||||
if o.batch_clamps > 0 {
|
||||
report.notes.push(format!(
|
||||
"--batch-clamps: {} clamp passes became {}, of {} records",
|
||||
batched.clamps, batched.batches, batched.jobs
|
||||
));
|
||||
if let Err(e) = self.make_batches(&jobs, &scratches) {
|
||||
report.notes.push(format!("--batch-clamps failed: {e:#}"));
|
||||
}
|
||||
}
|
||||
if !skip.is_empty() {
|
||||
report
|
||||
.notes
|
||||
@@ -1862,6 +1991,44 @@ impl Player {
|
||||
out
|
||||
}
|
||||
|
||||
/// What lists edited by [`edit::batch_clamps`] name: the pass, its
|
||||
/// tables and scratch buffers.
|
||||
fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> {
|
||||
let (root, pso) = crate::indirect::batch_for(&self.device)?;
|
||||
self.roots.insert(edit::BATCH_ROOT, root);
|
||||
self.pipelines.insert(edit::BATCH, pso);
|
||||
let (table, data) = gpu::buffer(
|
||||
&self.device,
|
||||
D3D12_HEAP_TYPE_UPLOAD,
|
||||
jobs.len().max(4) as u64,
|
||||
D3D12_RESOURCE_FLAG_NONE,
|
||||
)?;
|
||||
// SAFETY: a mapping of as many bytes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) };
|
||||
let mut all = vec![(edit::BATCH_JOBS, table)];
|
||||
for &(id, bytes) in scratches {
|
||||
let (scratch, _) = gpu::buffer(
|
||||
&self.device,
|
||||
D3D12_HEAP_TYPE_DEFAULT,
|
||||
bytes.next_multiple_of(64 << 10),
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
|
||||
)?;
|
||||
all.push((id, scratch));
|
||||
}
|
||||
for (id, res) in all {
|
||||
// SAFETY: a live buffer.
|
||||
let va = unsafe { res.GetGPUVirtualAddress() };
|
||||
let object = Object {
|
||||
res,
|
||||
va,
|
||||
index: 0,
|
||||
subs: 1,
|
||||
};
|
||||
self.objects.insert(id, object);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The clamp passes of each list of the frame, in order, and their
|
||||
/// results in [`RESULTS`] (by a run that keeps them).
|
||||
fn clamp_results(&mut self, report: &mut Report) -> Result<Vec<Vec<Clamp>>> {
|
||||
@@ -2126,7 +2293,8 @@ impl Player {
|
||||
wait: bool,
|
||||
) -> Vec<Stamp> {
|
||||
let version = self.version_of.get(submit).copied().unwrap_or(0);
|
||||
let clamps = self.pipelines_named(CLAMP);
|
||||
let mut clamps = self.pipelines_named(CLAMP);
|
||||
clamps.insert(edit::BATCH);
|
||||
let compares = self.pipelines_named(COMPARE);
|
||||
let mesh: HashSet<u32> = self
|
||||
.frame
|
||||
@@ -2713,6 +2881,16 @@ impl Player {
|
||||
|
||||
/// Runs the frame as the options say.
|
||||
pub fn run(&mut self, o: &Options) -> Result<Report> {
|
||||
let mut made = self.prepare(o)?;
|
||||
let mut stamps = Vec::new();
|
||||
for _ in 0..o.loops.max(1) {
|
||||
stamps = self.once(o, &mut made)?;
|
||||
}
|
||||
self.finish(o, made, &stamps)
|
||||
}
|
||||
|
||||
/// The lists for a run as the options say.
|
||||
fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> {
|
||||
let mut report = Report {
|
||||
notes: self.notes.clone(),
|
||||
..Default::default()
|
||||
@@ -2724,45 +2902,51 @@ impl Player {
|
||||
Vec::new()
|
||||
};
|
||||
let submits = self.edited(o, &mut report, &clamps);
|
||||
let built = self.build(&submits, o)?;
|
||||
let mut stamps = Vec::new();
|
||||
for _ in 0..o.loops.max(1) {
|
||||
self.restore(o.restore)?;
|
||||
self.fresh = false;
|
||||
stamps = self.send(&built, o)?;
|
||||
if let Some((db, _, hash, _)) = self.picture_now()? {
|
||||
report.pictures.push((db, hash));
|
||||
}
|
||||
let ms = |a: u32, b: u32| {
|
||||
stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
|
||||
};
|
||||
let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
|
||||
let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
|
||||
bail!("no lists to run");
|
||||
};
|
||||
let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
|
||||
report.delta_ms.push(
|
||||
delta
|
||||
.filter(|d| d.first > first.first)
|
||||
.map(|d| ms(d.first, d.last))
|
||||
.sum(),
|
||||
);
|
||||
report.frame_ms.push(ms(first.first, last.last));
|
||||
let each = |l: &[Built]| match (l.first(), l.last()) {
|
||||
(Some(a), Some(b)) => ms(a.first, b.last),
|
||||
_ => 0.0,
|
||||
};
|
||||
report.submits = built
|
||||
.steps
|
||||
.iter()
|
||||
.map(|(_, l)| (l.len(), each(l)))
|
||||
.collect();
|
||||
report
|
||||
.busy_ms
|
||||
.push(report.submits.iter().map(|s| s.1).sum());
|
||||
Ok((self.build(&submits, o)?, report))
|
||||
}
|
||||
|
||||
/// One run of the frame, noted in the report; its timestamps.
|
||||
fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result<Vec<u64>> {
|
||||
self.restore(o.restore)?;
|
||||
self.fresh = false;
|
||||
let stamps = self.send(built, o)?;
|
||||
if let Some((db, _, hash, _)) = self.picture_now()? {
|
||||
report.pictures.push((db, hash));
|
||||
}
|
||||
let ms = |a: u32, b: u32| {
|
||||
stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
|
||||
};
|
||||
let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
|
||||
let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
|
||||
bail!("no lists to run");
|
||||
};
|
||||
let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
|
||||
report.delta_ms.push(
|
||||
delta
|
||||
.filter(|d| d.first > first.first)
|
||||
.map(|d| ms(d.first, d.last))
|
||||
.sum(),
|
||||
);
|
||||
report.frame_ms.push(ms(first.first, last.last));
|
||||
let each = |l: &[Built]| match (l.first(), l.last()) {
|
||||
(Some(a), Some(b)) => ms(a.first, b.last),
|
||||
_ => 0.0,
|
||||
};
|
||||
report.submits = built
|
||||
.steps
|
||||
.iter()
|
||||
.map(|(_, l)| (l.len(), each(l)))
|
||||
.collect();
|
||||
report
|
||||
.busy_ms
|
||||
.push(report.submits.iter().map(|s| s.1).sum());
|
||||
Ok(stamps)
|
||||
}
|
||||
|
||||
/// The report after the last run.
|
||||
fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result<Report> {
|
||||
if o.detailed {
|
||||
self.detail(&built, &stamps, o, &mut report);
|
||||
self.detail(&built, stamps, o, &mut report);
|
||||
}
|
||||
if self.merging {
|
||||
let notes = self.merge_notes(o.loops)?;
|
||||
|
||||
+128
-18
@@ -1010,10 +1010,39 @@ pub fn title_memory_reading_now() -> Option<Reading> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
|
||||
/// shows is new and read-write, so it is no longer guarded (nor known
|
||||
/// unmapped).
|
||||
/// The runtime mapped title memory `[at, at + len)`: what it shows is new,
|
||||
/// so it is no longer guarded (nor known unmapped), and read-write.
|
||||
///
|
||||
/// The view is there before we are told of it, and a copy's refresh on
|
||||
/// another thread may have guarded its blocks in between (it finds blocks
|
||||
/// it knew absent committed, and holds [`GUARDS`], which we wait for).
|
||||
/// Forgetting such a block and leaving it read-only would make the title's
|
||||
/// next write to it an access violation nobody takes (`on_write` finds it
|
||||
/// neither guarded nor writable) and a kernel read into it fail, so the
|
||||
/// write access is given back.
|
||||
pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
open(&mut title_memory_changed(at, len), at, at.saturating_add(len));
|
||||
}
|
||||
|
||||
/// The runtime is about to unmap title memory `[at, at + len)`: it is
|
||||
/// nothing of ours any more. Its protection goes with it.
|
||||
pub fn title_memory_unmapping(at: usize, len: usize) {
|
||||
let mut g = title_memory_changed(at, len);
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
|
||||
.copied()
|
||||
.collect();
|
||||
for block in blocks {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells what keeps track of what title memory shows; the guards, with no
|
||||
/// block of the range known unmapped.
|
||||
fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> {
|
||||
// A placed texture there arrives, goes or changes with no descriptor
|
||||
// written.
|
||||
crate::descriptor::host::remapped(at, len);
|
||||
@@ -1023,16 +1052,11 @@ pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
crate::inplace::title_memory_freeing(at, len);
|
||||
let mut g = guards();
|
||||
let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
|
||||
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
|
||||
let absent: Vec<usize> = g.absent.range(range).copied().collect();
|
||||
for block in absent {
|
||||
g.absent.remove(&block);
|
||||
}
|
||||
let blocks: Vec<usize> = g.protected.range(range).copied().collect();
|
||||
for block in blocks {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// Registers the handler that takes writes to guarded blocks, once, ahead
|
||||
@@ -1122,16 +1146,18 @@ mod tests {
|
||||
} as usize;
|
||||
assert_ne!(p, 0);
|
||||
let (start, end) = (p, p + 4 * PAGE);
|
||||
let (_, before) = writes(start, end, false).expect("watched");
|
||||
assert!(before.is_empty());
|
||||
// The journal may hold pages of another test's memory that was here.
|
||||
let (none, before) = writes(start, end, false).expect("watched");
|
||||
assert!(before.iter().all(|&(_, w)| w < none), "{before:?}");
|
||||
// SAFETY: committed pages of ours.
|
||||
unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
|
||||
let (now, after) = writes(start, end, false).expect("watched");
|
||||
assert_eq!(after, [(p / PAGE + 1, now)]);
|
||||
let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::<Vec<_>>();
|
||||
assert_eq!(new(after), [(p / PAGE + 1, now)]);
|
||||
// Another asker after the kernel's bit was cleared still sees it.
|
||||
let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
|
||||
assert!(later > now);
|
||||
assert_eq!(again, [(p / PAGE + 1, now)]);
|
||||
assert_eq!(new(again), [(p / PAGE + 1, now)]);
|
||||
let mut plain = vec![0u8; PAGE];
|
||||
assert!(
|
||||
writes(
|
||||
@@ -1190,6 +1216,9 @@ mod tests {
|
||||
guard(view, view + 2 * BLOCK),
|
||||
Some((view / PAGE..view / PAGE + 1).collect())
|
||||
);
|
||||
// Before the view goes, as the runtime does: the address may be
|
||||
// another test's the moment it is free.
|
||||
title_memory_unmapping(view, 2 * BLOCK);
|
||||
// SAFETY: our view.
|
||||
unsafe {
|
||||
UnmapViewOfFile(
|
||||
@@ -1198,7 +1227,52 @@ mod tests {
|
||||
},
|
||||
)
|
||||
};
|
||||
title_memory_remapped(view, 2 * BLOCK);
|
||||
}
|
||||
|
||||
/// The runtime maps a view and then tells us; a copy's refresh on another
|
||||
/// thread can guard it in between. Told, it is the title's to write: a
|
||||
/// block left read-only and forgotten would be an access violation in
|
||||
/// title code.
|
||||
#[test]
|
||||
fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() {
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
|
||||
};
|
||||
// SAFETY: a pagefile section of two blocks, mapped read-write; the
|
||||
// view holds it.
|
||||
let view = unsafe {
|
||||
let section = CreateFileMappingW(
|
||||
INVALID_HANDLE_VALUE,
|
||||
std::ptr::null(),
|
||||
PAGE_READWRITE,
|
||||
0,
|
||||
(2 * BLOCK) as u32,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!section.is_null());
|
||||
let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK);
|
||||
CloseHandle(section);
|
||||
view
|
||||
};
|
||||
let at = view.Value as usize;
|
||||
assert_ne!(at, 0);
|
||||
// The refresh, then the runtime's word.
|
||||
assert!(guard(at, at + 2 * BLOCK).is_some());
|
||||
assert!(!writable(at) && !writable(at + BLOCK));
|
||||
title_memory_remapped(at, 2 * BLOCK);
|
||||
assert!(writable(at) && writable(at + BLOCK));
|
||||
// SAFETY: inside the view; a fault would end the process.
|
||||
unsafe { ((at + 8) as *mut u8).write_volatile(1) };
|
||||
// Looked at again as new, and guarded again.
|
||||
assert_eq!(
|
||||
guard(at, at + 2 * BLOCK),
|
||||
Some((at / PAGE..at / PAGE + 2).collect())
|
||||
);
|
||||
assert!(!writable(at));
|
||||
title_memory_unmapping(at, 2 * BLOCK);
|
||||
// SAFETY: our view.
|
||||
unsafe { UnmapViewOfFile(view) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1213,7 +1287,7 @@ mod tests {
|
||||
struct View(MEMORY_MAPPED_VIEW_ADDRESS);
|
||||
impl Drop for View {
|
||||
fn drop(&mut self) {
|
||||
title_memory_remapped(self.0.Value as usize, SIZE);
|
||||
title_memory_unmapping(self.0.Value as usize, SIZE);
|
||||
// SAFETY: our view is still mapped.
|
||||
unsafe { UnmapViewOfFile(self.0) };
|
||||
}
|
||||
@@ -1339,6 +1413,7 @@ mod tests {
|
||||
let mut local = [0u8; 16];
|
||||
let at = local.as_mut_ptr() as usize;
|
||||
assert!(!is_view(at, at + local.len()));
|
||||
title_memory_unmapping(p, 3 * BLOCK);
|
||||
// SAFETY: our views and placeholder.
|
||||
unsafe {
|
||||
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
|
||||
@@ -1348,7 +1423,6 @@ mod tests {
|
||||
}
|
||||
windows_sys::Win32::Foundation::CloseHandle(section);
|
||||
}
|
||||
title_memory_remapped(p, 3 * BLOCK);
|
||||
}
|
||||
|
||||
/// Blocks of a placeholder between views are reported once, then not
|
||||
@@ -1423,6 +1497,7 @@ mod tests {
|
||||
title_memory_remapped(p + BLOCK, BLOCK);
|
||||
assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
|
||||
assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
|
||||
title_memory_unmapping(p, 3 * BLOCK);
|
||||
// SAFETY: our views and placeholder.
|
||||
unsafe {
|
||||
UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
|
||||
@@ -1432,7 +1507,6 @@ mod tests {
|
||||
}
|
||||
windows_sys::Win32::Foundation::CloseHandle(section);
|
||||
}
|
||||
title_memory_remapped(p, 3 * BLOCK);
|
||||
}
|
||||
|
||||
/// A write or mapping that runs past the end of the address space (a
|
||||
@@ -1630,6 +1704,42 @@ mod many_askers_tests {
|
||||
// of these writes.)
|
||||
}
|
||||
|
||||
/// A block's bit goes with everything that makes it the title's to write,
|
||||
/// or forgets it.
|
||||
#[test]
|
||||
fn bits_go_with_the_guard() {
|
||||
// SAFETY: a view of a section of our own, which stays.
|
||||
let at = unsafe {
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (2 * PAGE) as u32, std::ptr::null());
|
||||
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * PAGE).Value as usize
|
||||
};
|
||||
let end = at + 2 * PAGE;
|
||||
let takes: [&dyn Fn(); 4] = [
|
||||
&|| super::title_memory_remapped(at, PAGE),
|
||||
// SAFETY: the view.
|
||||
&|| unsafe { ((at + 8) as *mut u8).write_volatile(1) },
|
||||
&|| super::writing(at, 1),
|
||||
// (Told again, as of a view mapped there next: it is read-only.)
|
||||
&|| {
|
||||
super::title_memory_unmapping(at, PAGE);
|
||||
assert!(!super::published(at, end), "forgotten");
|
||||
super::title_memory_remapped(at, PAGE);
|
||||
let mut old = 0;
|
||||
// SAFETY: the view.
|
||||
unsafe { VirtualProtect(at as *const _, PAGE, PAGE_READWRITE, &mut old) };
|
||||
},
|
||||
];
|
||||
for (i, take) in takes.iter().enumerate() {
|
||||
writes(at, end, true).expect("a view");
|
||||
assert!(super::published(at, end), "{i}");
|
||||
take();
|
||||
assert!(!super::published(at, end), "{i}");
|
||||
assert!(super::published(at + PAGE, end), "{i}: the other block");
|
||||
}
|
||||
super::title_memory_unmapping(at, 2 * PAGE);
|
||||
}
|
||||
|
||||
/// A range's bits are all of its blocks', whatever lies beside them.
|
||||
#[test]
|
||||
fn bits_of_ranges() {
|
||||
|
||||
@@ -1029,7 +1029,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) {
|
||||
continue;
|
||||
};
|
||||
physical.forget_view(at, size, &slice);
|
||||
victory_gpu::title_memory_remapped(at, size);
|
||||
victory_gpu::title_memory_unmapping(at, size);
|
||||
// SAFETY: a view we mapped; it becomes a placeholder again.
|
||||
unsafe {
|
||||
UnmapViewOfFile2(
|
||||
|
||||
@@ -63,6 +63,8 @@ pub const ALL: u32 = MODULE | FIRST;
|
||||
pub(crate) struct Usage {
|
||||
/// A wave or quad operation.
|
||||
pub wave_ops: bool,
|
||||
/// A rasterizer ordered view.
|
||||
pub rovs: bool,
|
||||
/// A 64-bit integer, as a result or an operand.
|
||||
pub int64: bool,
|
||||
/// A typed load of several components from a UAV.
|
||||
@@ -388,7 +390,7 @@ impl Module {
|
||||
}
|
||||
|
||||
/// An integer constant's width and value (the bits of that width).
|
||||
fn int_k(&self, v: V) -> Option<(u32, u64)> {
|
||||
pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> {
|
||||
let V::Const(i) = v else { return None };
|
||||
let (ty, Const::Int(x)) = &self.consts[i as usize] else {
|
||||
return None;
|
||||
@@ -1009,6 +1011,8 @@ impl Module {
|
||||
Some((_, 0)) => u.heap_views = true,
|
||||
_ => u.heap_samplers = true,
|
||||
}
|
||||
} else if name == "annotateHandle" {
|
||||
u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0);
|
||||
} else if name.starts_with("atomic") && name.ends_with(".i64") {
|
||||
u.atomic64 = true;
|
||||
} else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") {
|
||||
|
||||
@@ -107,6 +107,64 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
|
||||
const TWO_PI: f32 = std::f32::consts::TAU;
|
||||
/// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
|
||||
const GS_ALLOC_REQ: u16 = 9;
|
||||
/// `s_sendmsg` id that ends a pixel wave's ordered section.
|
||||
const ORDERED_PS_DONE: u16 = 7;
|
||||
/// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
|
||||
/// before it waits for the waves it overlaps.
|
||||
const POPS_PACKER: u16 = 25;
|
||||
/// The operand `src_pops_exiting_wave_id`.
|
||||
const POPS_EXITING: u8 = 239;
|
||||
|
||||
/// The instructions inside a pixel program's ordered section
|
||||
/// (primitive-ordered pixel shading, which the console compiler makes of
|
||||
/// rasterizer ordered views): from the write of `POPS_PACKER`, along every
|
||||
/// path, to the message that ends the section or the program's end. The
|
||||
/// console waits there until the waves holding earlier primitives' samples
|
||||
/// of the same pixels have left their sections; a host's rasterizer ordered
|
||||
/// views wait by themselves, at their first access. Empty for a program
|
||||
/// without such a section.
|
||||
fn ordered_section(p: &Program) -> HashSet<Site> {
|
||||
let starts = |i: &Inst| {
|
||||
i.name() == "s_setreg_b32"
|
||||
&& matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
|
||||
};
|
||||
let ends = |i: &Inst| {
|
||||
i.name() == "s_sendmsg"
|
||||
&& matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
|
||||
};
|
||||
let mut section = HashSet::new();
|
||||
let mut entered = vec![false; p.blocks.len()];
|
||||
let mut work: Vec<Site> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
(0..block.insts.len())
|
||||
.filter(|&i| starts(&block.insts[i]))
|
||||
.map(move |i| (b, i))
|
||||
})
|
||||
.collect();
|
||||
while let Some((b, from)) = work.pop() {
|
||||
let block = &p.blocks[b];
|
||||
let mut done = false;
|
||||
for i in from..block.insts.len() {
|
||||
if ends(&block.insts[i]) {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
section.insert((b, i));
|
||||
}
|
||||
if done {
|
||||
continue;
|
||||
}
|
||||
for (t, next) in p.blocks.iter().enumerate() {
|
||||
if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
|
||||
work.push((t, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
|
||||
/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
|
||||
@@ -194,6 +252,13 @@ struct Lower<'a> {
|
||||
/// Descriptor dwords with no host value (addresses, formats, all of a constant
|
||||
/// buffer's): no program reads them as numbers ([`Self::dead`]).
|
||||
stale: HashSet<Value>,
|
||||
/// See [`ordered_section`] (pixel programs).
|
||||
ordered: HashSet<Site>,
|
||||
/// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
|
||||
/// wave's cache (GLC): other groups write what it waits for. On the host
|
||||
/// they are globally coherent; a load in a loop that only waits would
|
||||
/// be made once otherwise.
|
||||
coherent: HashSet<(usize, u32)>,
|
||||
mask_phis: HashMap<Value, V>,
|
||||
pending_masks: Vec<(V, usize, usize)>,
|
||||
data_phis: Vec<(V, usize, usize)>,
|
||||
@@ -1486,6 +1551,12 @@ impl<'a> Lower<'a> {
|
||||
data_phis: Vec::new(),
|
||||
read_phis: HashSet::new(),
|
||||
stale: HashSet::new(),
|
||||
coherent: HashSet::new(),
|
||||
ordered: if x.native.stage == HwStage::Ps {
|
||||
ordered_section(p)
|
||||
} else {
|
||||
HashSet::new()
|
||||
},
|
||||
params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
|
||||
user_data: None,
|
||||
user_reads: BTreeMap::new(),
|
||||
@@ -2064,9 +2135,12 @@ impl<'a> Lower<'a> {
|
||||
/// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
|
||||
/// their halves' sums for the last addition. The high half of the result is lane 0's,
|
||||
/// which no `v_add_f16` writes.
|
||||
/// That needs every lane of a full wave there to be read: refused where not every lane
|
||||
/// runs, in a thread group that does not fill its waves, and for each half-wave on its
|
||||
/// own (half a sum is no sum).
|
||||
/// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
|
||||
/// count as the console's do (it masks them to +0): a partner's partial sum is read from
|
||||
/// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
|
||||
/// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
|
||||
/// group that does not fill its waves, and for each half-wave on its own (half a sum is
|
||||
/// no sum).
|
||||
fn half_sum(&mut self, x: V) -> Result<V, Why> {
|
||||
const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
|
||||
let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
|
||||
@@ -2087,24 +2161,54 @@ impl<'a> Lower<'a> {
|
||||
} else {
|
||||
all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
|
||||
};
|
||||
if !every {
|
||||
if halves {
|
||||
need(self.cur_ir);
|
||||
}
|
||||
if !every && halves {
|
||||
need(self.cur_ir);
|
||||
return Err(WHERE);
|
||||
}
|
||||
let c = self.cur;
|
||||
let i32t = self.s.t.i32;
|
||||
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
|
||||
let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
|
||||
// the lanes that are here, when not all are
|
||||
let here = (!every).then(|| {
|
||||
self.s.flags |= flags::WAVE_OPS;
|
||||
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
|
||||
let yes = self.s.m.bool(true);
|
||||
let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
|
||||
(self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
|
||||
});
|
||||
// `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
|
||||
let first_of = |l: &mut Self, v: V, base: V, n: u32| {
|
||||
let Some((lo, hi)) = here else {
|
||||
return l.read_lane(v, base);
|
||||
};
|
||||
let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
|
||||
let lower = l.s.m.cmp(c, pred::IULT, base, k32);
|
||||
let word = l.s.m.select(c, lower, lo, hi);
|
||||
let shift = l.s.m.bin(c, Bin::And, base, k31);
|
||||
let word = l.s.m.bin(c, Bin::LShr, word, shift);
|
||||
let run = l.s.m.i32(u32::MAX >> (32 - n));
|
||||
let word = l.s.m.bin(c, Bin::And, word, run);
|
||||
let any = l.s.m.cmp(c, pred::NE, word, zero);
|
||||
let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
|
||||
let from = l.s.m.bin(c, Bin::Add, base, nth);
|
||||
// (no lane there: this one, which is here; the read is not used)
|
||||
let from = l.s.m.select(c, any, from, lane);
|
||||
let got = l.read_lane(v, from);
|
||||
l.s.m.select(c, any, got, zero)
|
||||
};
|
||||
let mut sum = x;
|
||||
for step in 0..if halves { 5 } else { 6 } {
|
||||
let bit = self.s.m.i32(1 << step);
|
||||
let partner = self.s.m.bin(c, Bin::Xor, lane, bit);
|
||||
let theirs = self.read_lane(sum, partner);
|
||||
let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
|
||||
if !every {
|
||||
let run = self.s.m.i32(!((1 << step) - 1));
|
||||
partner = self.s.m.bin(c, Bin::And, partner, run);
|
||||
}
|
||||
let theirs = first_of(self, sum, partner, 1 << step);
|
||||
sum = self.add_halves(sum, theirs);
|
||||
}
|
||||
let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
|
||||
let first = self.read_lane(x, zero);
|
||||
let first = first_of(self, x, zero, 1);
|
||||
let first = self.s.m.bin(c, Bin::And, first, high);
|
||||
let sum = self.s.m.bin(c, Bin::And, sum, low);
|
||||
let mine = self.s.m.bin(c, Bin::Or, first, sum);
|
||||
@@ -2121,6 +2225,7 @@ impl<'a> Lower<'a> {
|
||||
|
||||
fn run(mut self) -> Result<Lowered, Stop> {
|
||||
let p = self.x.p;
|
||||
self.find_coherent();
|
||||
let order = crate::ir::reverse_postorder(&p.blocks);
|
||||
for (n, &b) in order.iter().enumerate() {
|
||||
self.rpo[b] = n;
|
||||
@@ -2258,6 +2363,8 @@ impl<'a> Lower<'a> {
|
||||
// paths only seem to allow it before any save: the lane of a VGPR
|
||||
// nobody wrote, and VGPRs nobody set read as zero.
|
||||
None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
|
||||
// No wave overlaps this one (see `ordered_section`).
|
||||
None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
|
||||
None => Val::Missing("a hardware SGPR input"),
|
||||
},
|
||||
Reg::Scc => Val::Missing("SCC on entry"),
|
||||
@@ -2273,6 +2380,36 @@ impl<'a> Lower<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the input SGPR `v` is the POPS collision wave id: a program
|
||||
/// with an ordered section only takes its fields apart (bit 31 says
|
||||
/// that the wave overlaps another, the others which packer and waves).
|
||||
fn pops_collision(&self, v: Value) -> bool {
|
||||
if self.ordered.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut packer = false;
|
||||
for block in &self.x.p.blocks {
|
||||
if block.phis.iter().any(|p| p.args.contains(&v)) {
|
||||
return false;
|
||||
}
|
||||
for i in &block.insts {
|
||||
if !i.reads.iter().any(|r| r.1 == v) {
|
||||
continue;
|
||||
}
|
||||
let Fields::Sop { src, .. } = &i.fields else {
|
||||
return false;
|
||||
};
|
||||
match (i.name(), src.get(1)) {
|
||||
// bits 28 and 29: the packer
|
||||
("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
|
||||
("s_bfe_u32" | "s_lshr_b32", _) => {}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
packer
|
||||
}
|
||||
|
||||
fn input(&mut self, input: Input) -> Val {
|
||||
let (kind, col) = match input {
|
||||
Input::VertexId => (1, 0),
|
||||
@@ -2632,6 +2769,18 @@ impl<'a> Lower<'a> {
|
||||
self.s.m.extract(entry, r, index % 4)
|
||||
}
|
||||
|
||||
/// Whether some instruction reads `v` as a number (or may, through a
|
||||
/// join), rather than in a descriptor operand.
|
||||
fn read_as_number(&self, v: Value) -> bool {
|
||||
self.x.p.blocks.iter().any(|b| {
|
||||
b.phis.iter().any(|p| p.args.contains(&v))
|
||||
|| b.insts.iter().any(|i| {
|
||||
matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
|
||||
&& i.reads.iter().any(|r| r.1 == v)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether some instruction computes with `v` (scalar or vector
|
||||
/// arithmetic), rather than only naming it in a descriptor operand,
|
||||
/// moving it (at most `depth` moves are followed) or comparing it: a
|
||||
@@ -2665,6 +2814,112 @@ impl<'a> Lower<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the image `src` names is one of 32-bit integers (one channel):
|
||||
/// the program has an integer atomic on the same table entry, which
|
||||
/// takes no other view.
|
||||
fn is_counter(&self, src: &Source) -> bool {
|
||||
let Some(this) = self.entry(src) else {
|
||||
return false;
|
||||
};
|
||||
self.x.res.descriptors.iter().any(|d| {
|
||||
let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
|
||||
d.role == Role::Resource
|
||||
&& matches!(i.fields, Fields::Image { dmask: 1, .. })
|
||||
&& matches!(
|
||||
i.name(),
|
||||
"image_atomic_add"
|
||||
| "image_atomic_sub"
|
||||
| "image_atomic_and"
|
||||
| "image_atomic_or"
|
||||
| "image_atomic_xor"
|
||||
| "image_atomic_smin"
|
||||
| "image_atomic_smax"
|
||||
| "image_atomic_umin"
|
||||
| "image_atomic_umax"
|
||||
)
|
||||
&& self.entry(&d.source) == Some(this)
|
||||
})
|
||||
}
|
||||
|
||||
/// Which table entry `src` is loaded from: its root parameter and byte.
|
||||
fn entry(&self, src: &Source) -> Option<(usize, u32)> {
|
||||
let Source::Loaded { load, first } = src else {
|
||||
return None;
|
||||
};
|
||||
let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
|
||||
Some((a.param, a.offset + 4 * u32::from(*first)))
|
||||
}
|
||||
|
||||
/// See [`Lower::coherent`].
|
||||
fn find_coherent(&mut self) {
|
||||
let found: Vec<_> = self
|
||||
.x
|
||||
.res
|
||||
.descriptors
|
||||
.iter()
|
||||
.filter(|d| {
|
||||
let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
|
||||
matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
|
||||
&& i.name().starts_with("buffer_load_dword")
|
||||
&& self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
|
||||
})
|
||||
.filter_map(|d| self.entry(&d.source))
|
||||
.collect();
|
||||
self.coherent.extend(found);
|
||||
}
|
||||
|
||||
/// The kind of a view no instruction uses (in this program, or through
|
||||
/// another load of its address), by what the code reads of the
|
||||
/// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
|
||||
/// `Some(true)` for a 2D image, read only for its size, `Some(false)`
|
||||
/// for a structured buffer, read only for its record count.
|
||||
///
|
||||
/// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
|
||||
/// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
|
||||
/// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
|
||||
/// a cube or a volume also dword 4.
|
||||
/// - Four dwords at a table entry the used resources list as an SRV or
|
||||
/// UAV are a buffer's. A stride above 4 bytes there is an element's
|
||||
/// (a typed or raw view has at most 4): a test for a null view reads
|
||||
/// the record count, nothing else.
|
||||
fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
|
||||
let dword = |k: u8| inst.write(Reg::S(code + k));
|
||||
let read = |v: Value| {
|
||||
self.x.p.blocks.iter().any(|b| {
|
||||
b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
|
||||
|| b.phis.iter().any(|p| p.args.contains(&v))
|
||||
})
|
||||
};
|
||||
let only = |allowed: &[u8]| {
|
||||
(0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
|
||||
};
|
||||
match count {
|
||||
8 => {
|
||||
const HEIGHT: u32 = 16 << 16 | 14;
|
||||
let v = dword(2)?;
|
||||
let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
|
||||
i.name() == "s_bfe_u32"
|
||||
&& i.reads.iter().any(|r| r.1 == v)
|
||||
&& matches!(&i.fields, Fields::Sop { src, .. }
|
||||
if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
|
||||
});
|
||||
(height && only(&[1, 2, 3])).then_some(true)
|
||||
}
|
||||
4 => {
|
||||
let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
|
||||
let a = self.scalar.get(&site)?;
|
||||
let buffer = used.dwords == 4
|
||||
&& a.dynamic.is_none()
|
||||
&& used.table_offset_dwords == a.offset / 4
|
||||
&& matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
|
||||
&& used.stride > 4
|
||||
&& used.stride.is_multiple_of(4);
|
||||
(buffer && only(&[2])).then_some(false)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The title address (low dword, bits from 32 up) of the buffer view
|
||||
/// whose descriptor the scalar load at `site` reads from the start of
|
||||
/// a table entry, as the host tells it when it binds (`shader.rs`
|
||||
@@ -3116,6 +3371,8 @@ impl<'a> Lower<'a> {
|
||||
let bit = self.scc_in(inst)?;
|
||||
Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
|
||||
}
|
||||
// Nothing to wait for (see `ordered_section`).
|
||||
Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
|
||||
Operand::Const(c) => crate::resource::inline(c)
|
||||
.map(|x| self.s.m.i32(x))
|
||||
.ok_or("a special operand (vccz, execz, scc, lds_direct)"),
|
||||
@@ -5400,12 +5657,30 @@ impl<'a> Lower<'a> {
|
||||
|
||||
fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
|
||||
let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
|
||||
match self.get(v)? {
|
||||
Val::Bit(x) => Ok(x),
|
||||
_ => Err("SCC without a value"),
|
||||
match self.get(v) {
|
||||
Ok(Val::Bit(x)) => Ok(x),
|
||||
Ok(_) => Err("SCC without a value"),
|
||||
// Of a mask operation whose result lies within EXEC: whether
|
||||
// some lane is left.
|
||||
Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
|
||||
Err(why) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the mask operation that sets the SCC value `scc` gives no
|
||||
/// lane outside EXEC a bit.
|
||||
fn within_exec(&self, scc: Value) -> bool {
|
||||
let Some(&b) = self.def_block.get(&scc) else {
|
||||
return false;
|
||||
};
|
||||
let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
|
||||
by.is_some_and(|i| {
|
||||
i.write(Reg::S(EXEC)).is_some()
|
||||
|| matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
|
||||
if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
|
||||
})
|
||||
}
|
||||
|
||||
fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
|
||||
let Fields::Smem {
|
||||
data,
|
||||
@@ -5653,7 +5928,12 @@ impl<'a> Lower<'a> {
|
||||
.find_map(|(s, _)| use_of(*s))
|
||||
};
|
||||
let use_at = use_of(site).or_else(twin);
|
||||
let Some((at, first)) = use_at else {
|
||||
// A view whose kind no use tells, but what is read of it does.
|
||||
let sized = match use_at {
|
||||
Some(_) => None,
|
||||
None => self.sized_view(inst, site, code, count),
|
||||
};
|
||||
let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
|
||||
// A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
|
||||
// copies its dwords and compares them, lane against first lane, and every load
|
||||
// that reaches those lanes reads one address. Each dword stands in as its place
|
||||
@@ -5721,6 +6001,8 @@ impl<'a> Lower<'a> {
|
||||
|| used.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let u = if uav { 0x1000 } else { 0 };
|
||||
let (props, image) = match &ui.fields {
|
||||
_ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
|
||||
_ if sized.is_some() => ((11 | u, 0), None),
|
||||
// A ray-tracing structure in a buffer of the host: read raw.
|
||||
Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
|
||||
Fields::Image { dim, .. } => {
|
||||
@@ -5736,13 +6018,25 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
Fields::Buffer { idxen, format, .. } => {
|
||||
let stride = used.map_or(0, |u| u.stride);
|
||||
let counted = inst
|
||||
.write(Reg::S(code + first + 2))
|
||||
.is_some_and(|v| self.read_as_number(v));
|
||||
let props = if un.starts_with("buffer_load_format")
|
||||
|| un.starts_with("buffer_store_format")
|
||||
{
|
||||
(10 | u, 0x409)
|
||||
} else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
|
||||
} else if !counted
|
||||
&& *idxen
|
||||
&& format.is_none()
|
||||
&& stride >= 4
|
||||
&& stride.is_multiple_of(4)
|
||||
{
|
||||
// Nothing reads the count: the query is cleaned up.
|
||||
(12 | u, stride)
|
||||
} else {
|
||||
// Structured ones too: the host's views of them are raw
|
||||
// (see `buffer`), which count bytes, and a size asked
|
||||
// for as a structured view's is that count on AMD.
|
||||
(11 | u, 0)
|
||||
};
|
||||
if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
|
||||
@@ -5816,9 +6110,20 @@ impl<'a> Lower<'a> {
|
||||
// A raw view counts bytes; the descriptor's record count is in elements.
|
||||
let n = field(self, 0);
|
||||
let stride = used.map_or(0, |u| u.stride);
|
||||
let counted = inst
|
||||
.write(Reg::S(code + first + 2))
|
||||
.is_some_and(|v| self.read_as_number(v));
|
||||
let n = if props.0 & 0xFF == 11 && stride > 1 {
|
||||
let k = self.s.m.i32(stride);
|
||||
self.s.m.bin(c, Bin::UDiv, n, k)
|
||||
} else if props.0 & 0xFF == 11
|
||||
&& counted
|
||||
&& let Some(stride) = self.slot_stride(&src)?
|
||||
{
|
||||
// Picked from the heap: the host's table has the stride.
|
||||
let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
|
||||
let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
|
||||
self.s.m.bin(c, Bin::UDiv, n, k)
|
||||
} else {
|
||||
n
|
||||
};
|
||||
@@ -6610,6 +6915,17 @@ impl<'a> Lower<'a> {
|
||||
self.lane(inst, Some(true));
|
||||
return Ok(());
|
||||
}
|
||||
// One lane of a VGPR a whole-wave section left.
|
||||
if name == "v_readlane_b32"
|
||||
&& let Some(&(_, w)) = inst.writes.first()
|
||||
&& let Some(sh) = self.sections.get(&b).and_then(|s| {
|
||||
s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
|
||||
})
|
||||
{
|
||||
let x = self.shape(sh, false)?;
|
||||
self.vals.insert(w, Val::I32(x));
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
|
||||
let r = if v.dpp.is_some() {
|
||||
Err("a compare with DPP")
|
||||
@@ -9549,7 +9865,13 @@ impl<'a> Lower<'a> {
|
||||
|| self
|
||||
.used_kind(src)
|
||||
.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
|
||||
// A UAV inside an ordered section is a rasterizer ordered view.
|
||||
let ordered = uav && self.ordered.contains(&site);
|
||||
if ordered {
|
||||
self.s.flags |= flags::ROVS;
|
||||
}
|
||||
let rov = if ordered { 0x2000 } else { 0 };
|
||||
let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
|
||||
if let Some(op) = name.strip_prefix("image_atomic_") {
|
||||
// GLC returns the old value. DXIL implements subtraction by adding
|
||||
// the two's complement of the operand at the same width.
|
||||
@@ -9607,7 +9929,7 @@ impl<'a> Lower<'a> {
|
||||
} else {
|
||||
original
|
||||
};
|
||||
let h = self.handle(site, src, false, (kind | 0x1000, component))?;
|
||||
let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
|
||||
let mut args = vec![h];
|
||||
let (intrinsic, opcode) = if compare {
|
||||
let comparand = if wide {
|
||||
@@ -9660,7 +9982,9 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
// shortcut: stores are taken to write all four channels of a
|
||||
// float format (the console converts by the view's format).
|
||||
if *dmask != 0xF {
|
||||
// One channel goes into a view the program also counts in.
|
||||
let counter = *dmask == 1 && self.is_counter(src);
|
||||
if *dmask != 0xF && !counter {
|
||||
return Err("an image store of some channels");
|
||||
}
|
||||
let iu = self.s.m.undef(self.s.t.i32);
|
||||
@@ -9671,6 +9995,34 @@ impl<'a> Lower<'a> {
|
||||
let Operand::Vector { reg, .. } = *data else {
|
||||
return Err("image store data");
|
||||
};
|
||||
if counter {
|
||||
let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
|
||||
let x = self.i32_of(v)?;
|
||||
// A 16-bit integer, extended by the view's sign: the same
|
||||
// number either way only if it is known to be small.
|
||||
if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
|
||||
return Err("a 16-bit image store of one channel");
|
||||
}
|
||||
let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
|
||||
let at = self.begin_guarded(guard);
|
||||
// All four channels are written (the validator wants them
|
||||
// all): the view has the first alone.
|
||||
let mut args = vec![h];
|
||||
args.extend(cs);
|
||||
args.extend([x; 4]);
|
||||
args.push(self.s.m.i8(0xF));
|
||||
let void = self.s.t.void;
|
||||
self.s.op(
|
||||
self.cur,
|
||||
"textureStore.i32",
|
||||
Attr::NoUnwind,
|
||||
void,
|
||||
67,
|
||||
&args,
|
||||
);
|
||||
self.end_guarded(at, &[]);
|
||||
return Ok(());
|
||||
}
|
||||
let mut vals = Vec::new();
|
||||
for k in 0..4u8 {
|
||||
// d16: two f16 channels per VGPR, low half first.
|
||||
@@ -10445,7 +10797,10 @@ impl<'a> Lower<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let u = if uav { 0x1000 } else { 0 };
|
||||
let mut u = if uav { 0x1000 } else { 0 };
|
||||
if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
|
||||
u |= 0x4000;
|
||||
}
|
||||
let iu = self.s.m.undef(self.s.t.i32);
|
||||
if let Some((bits, signed)) = narrow {
|
||||
// Below a dword: raw buffers are read and written in dwords on
|
||||
|
||||
@@ -99,6 +99,8 @@ mod threading;
|
||||
#[cfg(windows)]
|
||||
pub mod validator;
|
||||
#[cfg(all(test, windows))]
|
||||
mod size_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod valu_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod waterfall_tests;
|
||||
@@ -859,6 +861,134 @@ mod tests {
|
||||
assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
|
||||
}
|
||||
|
||||
/// A pixel program with an ordered section, as the console compiler
|
||||
/// makes one of rasterizer ordered views (the title's hair cards keep
|
||||
/// their nearest layers that way): the wait for overlapped waves is
|
||||
/// skipped, the views inside the section are the host's ordered ones,
|
||||
/// the one after it is not.
|
||||
#[test]
|
||||
fn an_ordered_section_uses_rasterizer_ordered_views() {
|
||||
let section = [
|
||||
0xBE82_0300u32, // s_mov_b32 s2, s0
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0
|
||||
0xFA00_0000,
|
||||
0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c
|
||||
0x0002_001C,
|
||||
0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000
|
||||
0x000A_0000,
|
||||
0x8F10_8110, // s_lshl_b32 s16, s16, 1
|
||||
0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010
|
||||
0x000A_0010,
|
||||
0xBE91_0711, // s_not_b32 s17, s17
|
||||
0x9013_9F01, // s_lshr_b32 s19, s1, 31
|
||||
0x8810_8110, // s_or_b32 s16, s16, 1
|
||||
0x8112_1112, // s_add_i32 s18, s18, s17
|
||||
0xBF06_8013, // s_cmp_eq_u32 s19, 0
|
||||
0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16
|
||||
0x8514_807E, // s_cselect_b32 s20, exec_lo, 0
|
||||
0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
|
||||
0xBF08_1215, // s_cmp_gt_u32 s21, s18
|
||||
0x8516_807E, // s_cselect_b32 s22, exec_lo, 0
|
||||
0x8814_1614, // s_or_b32 s20, s20, s22
|
||||
0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20
|
||||
0xBF87_0004, // s_cbranch_vccnz past the wait
|
||||
0xBF8E_FFFF, // s_sleep 0xffff
|
||||
0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
|
||||
0xBF0A_1512, // s_cmp_lt_u32 s18, s21
|
||||
0xBF84_FFFC, // s_cbranch_scc0 back to the sleep
|
||||
0x7E00_0280, // v_mov_b32 v0, 0
|
||||
0x7E02_0280, // v_mov_b32 v1, 0
|
||||
0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc
|
||||
0x0002_0200,
|
||||
0x0604_04F2, // v_add_f32 v2, 1.0, v2
|
||||
0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc
|
||||
0x0002_0200,
|
||||
0xBEFC_0380, // s_mov_b32 m0, 0
|
||||
0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE)
|
||||
];
|
||||
let end = [
|
||||
0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm
|
||||
0x0202_0202,
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
// A store after the section, through an ordinary view.
|
||||
let after = [0xF020_3F08u32, 0x0002_0200];
|
||||
let lower = |words: Vec<u32>| {
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![crate::native::RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![crate::native::UsedResource {
|
||||
kind: crate::native::ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 8,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
io: StageIo::Ps {
|
||||
inputs: vec![],
|
||||
input_addr: 0,
|
||||
db_shader_control: 0,
|
||||
patches: vec![],
|
||||
},
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let target = SigElement {
|
||||
name: "SV_Target".into(),
|
||||
index: 0,
|
||||
kind: 16,
|
||||
comp: 9,
|
||||
interp: 0,
|
||||
row: Some(0),
|
||||
col: 0,
|
||||
cols: 4,
|
||||
usage: 15,
|
||||
half: false,
|
||||
};
|
||||
let osg1 = container::signature(&[target], false);
|
||||
let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let out = emit(&c, &native, &p, &st, &io, &res)?;
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::validator::Validator::load(
|
||||
super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut out.dxil.clone()).unwrap();
|
||||
}
|
||||
let host = Container::parse(&out.dxil).unwrap();
|
||||
let sfi0 = host.part(FourCC::SFI0).unwrap().data;
|
||||
Ok::<u64, ShaderError>(u64::from_le_bytes(sfi0.try_into().unwrap()))
|
||||
};
|
||||
// D3D_SHADER_REQUIRES_ROVS
|
||||
let features = lower([§ion[..], &end].concat()).unwrap();
|
||||
assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs");
|
||||
lower([§ion[..], &after, &end].concat()).unwrap();
|
||||
// The same accesses outside a section: ordinary views, no feature.
|
||||
let plain = [§ion[..4], §ion[28..35], &end].concat();
|
||||
let features = lower(plain).unwrap();
|
||||
assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs");
|
||||
// Without the section's start the wait stays unknown.
|
||||
let mut unmarked = [§ion[..], &end].concat();
|
||||
unmarked.remove(16);
|
||||
assert!(lower(unmarked).is_err());
|
||||
}
|
||||
|
||||
/// A wave64 compute program that writes only EXEC's high dword
|
||||
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
|
||||
/// opaque and keyed by the unchanged low dword, so building its lane bit
|
||||
|
||||
@@ -76,6 +76,7 @@ pub(crate) mod flags {
|
||||
pub const DOUBLES: u64 = 1 << 2;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const ROVS: u64 = 1 << 18;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
@@ -455,6 +456,7 @@ impl Shader {
|
||||
self.m.optimise(passes);
|
||||
let used = self.m.usage();
|
||||
for (flag, used) in [
|
||||
(flags::ROVS, used.rovs),
|
||||
(flags::WAVE_OPS, used.wave_ops),
|
||||
(flags::INT64, used.int64),
|
||||
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
|
||||
@@ -787,6 +789,9 @@ impl Shader {
|
||||
if self.flags & flags::TYPED_UAV_LOADS != 0 {
|
||||
features |= 0x800;
|
||||
}
|
||||
if self.flags & flags::ROVS != 0 {
|
||||
features |= 0x1000;
|
||||
}
|
||||
if self.flags & flags::WAVE_OPS != 0 {
|
||||
features |= 0x4000;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
//! End-to-end tests of what a program tells about a view by how it uses it:
|
||||
//! descriptors read for sizes (the dwords of a view no instruction uses) and
|
||||
//! counters, lowered to DXIL, validated by `dxil.dll` when present, and run
|
||||
//! on the host GPU and WARP.
|
||||
|
||||
use super::host::{Stride, View};
|
||||
use super::waterfall_tests::run;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Lowers a wave32 compute program of one thread with the table of views at
|
||||
/// s0 and the view heap at s1; `srv`: the dwords and the stride of the used
|
||||
/// resource at the table's first entry (the third is a raw UAV).
|
||||
fn build(words: &[u32], srv: (u8, u32)) -> Result<HostShader, ShaderError> {
|
||||
let param = |root, user_data| RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot: 0,
|
||||
};
|
||||
let range = |kind, table_offset_dwords, dwords, stride| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride,
|
||||
dwords,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
};
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![param(RootType::Table, 0), param(RootType::ResourceHeap, 1)],
|
||||
used: vec![
|
||||
range(ResourceType::Srv, 0, srv.0, srv.1),
|
||||
range(ResourceType::Uav, 16, 4, 0),
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
.expect("DXIL validation failed");
|
||||
} else {
|
||||
eprintln!("no dxil.dll; validation skipped");
|
||||
}
|
||||
Ok(shader)
|
||||
}
|
||||
|
||||
/// The table at s[2:3], its raw UAV's descriptor in s[20:23].
|
||||
const TABLE: &[u32] = &[
|
||||
0xBE82_0300, // s_mov_b32 s2, s0
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
0xF408_0501, // s_load_dwordx4 s[20:23], s[2:3], 64
|
||||
0xFA00_0040,
|
||||
];
|
||||
|
||||
/// Stores s4 and s5 at bytes 0 and 4 of the UAV.
|
||||
const STORE: &[u32] = &[
|
||||
0x7E08_0204, // v_mov_b32 v4, s4
|
||||
0x7E0A_0205, // v_mov_b32 v5, s5
|
||||
0xE070_0000, // buffer_store_dword v4, off, s[20:23], 0
|
||||
0x8005_0400,
|
||||
0xE070_0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4
|
||||
0x8005_0500,
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
|
||||
/// `GetDimensions` of a texture as the console compiler expands it, from
|
||||
/// the descriptor in s[8:15]: width in s4, height in s5, base level in s6.
|
||||
const SIZES: &[u32] = &[
|
||||
0x9004_9E09, // s_lshr_b32 s4, s9, 30
|
||||
0x8F05_820A, // s_lshl_b32 s5, s10, 2
|
||||
0x8804_0504, // s_or_b32 s4, s4, s5
|
||||
0x8704_FF04, // s_and_b32 s4, s4, 0xffff
|
||||
0x0000_FFFF,
|
||||
0x9385_FF0A, // s_bfe_u32 s5, s10, 0x10000e
|
||||
0x0010_000E,
|
||||
0x9386_FF0B, // s_bfe_u32 s6, s11, 0x4000c
|
||||
0x0004_000C,
|
||||
0x8104_8104, // s_add_i32 s4, s4, 1
|
||||
0x8105_8105, // s_add_i32 s5, s5, 1
|
||||
0x9004_0604, // s_lshr_b32 s4, s4, s6
|
||||
0x9005_0605, // s_lshr_b32 s5, s5, s6
|
||||
];
|
||||
|
||||
/// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap.
|
||||
const FROM_HEAP: &[u32] = &[
|
||||
0xBE86_0301, // s_mov_b32 s6, s1
|
||||
0xBE87_0380, // s_mov_b32 s7, 0
|
||||
0xBE8C_03A0, // s_mov_b32 s12, 32
|
||||
0xF40C_0203,
|
||||
0x1800_0000,
|
||||
];
|
||||
|
||||
/// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0
|
||||
/// in s5.
|
||||
const COUNT: &[u32] = &[
|
||||
0xF408_0201,
|
||||
0xFA00_0000,
|
||||
0xBE84_030A, // s_mov_b32 s4, s10
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
|
||||
/// A puddle pass of the title picks three textures from the view heap,
|
||||
/// reads the first one's size and samples the other two.
|
||||
#[test]
|
||||
fn the_size_of_a_heap_texture_nothing_reads() {
|
||||
let words = [TABLE, FROM_HEAP, SIZES, STORE].concat();
|
||||
let shader = build(&words, (8, 0)).expect("translates");
|
||||
let (one, texels) = ([[0.0; 4]; 1], [[0.0; 4]; 15]);
|
||||
let views = [
|
||||
View::Texture(1, 1, &one),
|
||||
View::Texture(5, 3, &texels),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [5, 3], "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Without the height nothing tells a 2D texture from the others, and a
|
||||
/// volume's depth or an array's layers are no 2D texture's.
|
||||
#[test]
|
||||
fn sizes_of_unknown_dimensions_stay_untranslated() {
|
||||
let width = [
|
||||
0x9004_9E09, // s_lshr_b32 s4, s9, 30
|
||||
0x8F05_820A, // s_lshl_b32 s5, s10, 2
|
||||
0x8804_0504, // s_or_b32 s4, s4, s5
|
||||
];
|
||||
let words = [TABLE, FROM_HEAP, &width, STORE].concat();
|
||||
assert!(build(&words, (8, 0)).is_err());
|
||||
let depth = [
|
||||
0x8805_0C05, // s_or_b32 s5, s5, s12
|
||||
];
|
||||
let words = [TABLE, FROM_HEAP, SIZES, &depth, STORE].concat();
|
||||
assert!(build(&words, (8, 0)).is_err());
|
||||
}
|
||||
|
||||
/// A water simulation step runs only while a structured buffer is bound:
|
||||
/// it tests the record count of a view it never reads.
|
||||
#[test]
|
||||
fn the_record_count_of_a_structured_buffer_nothing_reads() {
|
||||
let words = [TABLE, COUNT, STORE].concat();
|
||||
let shader = build(&words, (4, 16)).expect("translates");
|
||||
let (data, texel) = ([0u32; 12], [[0.0; 4]; 1]);
|
||||
// The runtime makes structured views raw.
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [3, 0], "{label}");
|
||||
}
|
||||
// A stride of 4 or less may be a typed view's component count.
|
||||
assert!(build(&words, (4, 4)).is_err());
|
||||
assert!(build(&words, (4, 0)).is_err());
|
||||
}
|
||||
|
||||
/// As [`the_record_count_of_a_structured_buffer_nothing_reads`], of one the
|
||||
/// program also reads by index.
|
||||
#[test]
|
||||
fn the_record_count_of_a_structured_buffer_read_by_index() {
|
||||
let load = [
|
||||
0x7E06_0280, // v_mov_b32 v3, 0
|
||||
0xE030_2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen
|
||||
0x8002_0503,
|
||||
0x7E0A_0505, // v_readfirstlane_b32 s5, v5
|
||||
];
|
||||
let words = [TABLE, COUNT, &load, STORE].concat();
|
||||
let shader = build(&words, (4, 16)).expect("translates");
|
||||
let (mut data, texel) = ([0u32; 12], [[0.0; 4]; 1]);
|
||||
data[0] = 77;
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [3, 77], "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An upscaler counts its groups in a texture with atomics and sets the
|
||||
/// counter back with a store of one channel, 16 bits wide.
|
||||
#[test]
|
||||
fn a_counter_texture_is_set_by_a_store_of_one_channel() {
|
||||
let program = |store: [u32; 2], value: u32| {
|
||||
let words = [
|
||||
0xF40C_0201u32, // s_load_dwordx8 s[8:15], s[2:3], 0
|
||||
0xFA00_0000,
|
||||
0x7E00_0280, // v_mov_b32 v0, 0
|
||||
0x7E02_0280, // v_mov_b32 v1, 0
|
||||
0x7E04_0283, // v_mov_b32 v2, 3
|
||||
0xF044_3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc
|
||||
0x0002_0200,
|
||||
value, // v_mov_b32 v3, ..
|
||||
store[0],
|
||||
store[1],
|
||||
0x7E08_0281, // v_mov_b32 v4, 1
|
||||
0xF044_3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc
|
||||
0x0002_0400,
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
build(&[TABLE, &words, STORE].concat(), (8, 0))
|
||||
};
|
||||
// image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16
|
||||
for store in [[0xF020_1108, 0x0002_0300], [0xF020_1108, 0x8002_0300]] {
|
||||
let shader = program(store, 0x7E06_0289).expect("translates"); // v3 = 9
|
||||
let texel = [[0.0; 4]; 1];
|
||||
let views = [
|
||||
View::UintTextureUav(1, 1),
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[0], 10, "{label}");
|
||||
}
|
||||
}
|
||||
// Sixteen bits of a number only the card knows may be signed.
|
||||
assert!(program([0xF020_1108, 0x8002_0300], 0x7E06_0302).is_err()); // v3 = v2
|
||||
// A store of two channels says nothing about the view.
|
||||
assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err());
|
||||
}
|
||||
|
||||
/// A load past the wave's cache (GLC) of a buffer other groups write: its
|
||||
/// view is globally coherent on the host, as is every access to it.
|
||||
#[test]
|
||||
fn a_buffer_loaded_past_the_cache_is_coherent() {
|
||||
let program = |load: u32| {
|
||||
let words = [
|
||||
0x7E04_028Bu32, // v_mov_b32 v2, 11
|
||||
0xE070_0008, // buffer_store_dword v2, off, s[20:23], 0 offset:8
|
||||
0x8005_0200,
|
||||
load, // buffer_load_dword v3, off, s[20:23], 0 offset:8
|
||||
0x8005_0300,
|
||||
0x7E08_0503, // v_readfirstlane_b32 s4, v3
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
build(&[TABLE, &words, STORE].concat(), (8, 0)).expect("translates")
|
||||
};
|
||||
let (plain, coherent) = (program(0xE030_0008), program(0xE030_C008));
|
||||
// the annotations of the store's and the load's handles
|
||||
assert_ne!(plain.dxil, coherent.dxil);
|
||||
let texel = [[0.0; 4]; 1];
|
||||
let views = [
|
||||
View::Texture(1, 1, &texel),
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(3),
|
||||
];
|
||||
for shader in [&plain, &coherent] {
|
||||
for (label, got) in run(shader, &views) {
|
||||
assert_eq!(got[..3], [11, 0, 11], "{label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
|
||||
/// hardware GPU and on WARP (each skipped without a device) and returns,
|
||||
/// per one that ran, the UAV's 32 dwords.
|
||||
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
let samplers = [D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
|
||||
@@ -143,6 +143,10 @@ pub(crate) enum Shape {
|
||||
pub(crate) struct Section {
|
||||
pub end: usize,
|
||||
pub shapes: HashMap<Value, Shape>,
|
||||
/// What a `v_readlane_b32` of one lane takes, later in the block, from a
|
||||
/// VGPR the section leaves (by the scalar it writes): the last lanes of
|
||||
/// a reduction hold it before the first do.
|
||||
pub reads: HashMap<Value, Shape>,
|
||||
}
|
||||
|
||||
/// Every whole-wave section of `block`, by start index.
|
||||
@@ -180,8 +184,25 @@ pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> {
|
||||
let Some(end) = end else {
|
||||
break;
|
||||
};
|
||||
let shapes = simulate(&insts[i + 1..end], wave, saved);
|
||||
out.insert(i, Section { end, shapes });
|
||||
let (vec, uni) = simulate(&insts[i + 1..end], wave, saved);
|
||||
let mut reads = HashMap::new();
|
||||
for later in insts[end + 1..].iter().filter(|i| i.name() == "v_readlane_b32") {
|
||||
if let Fields::Valu(v) = &later.fields
|
||||
&& let (Some(Operand::Scalar { code, .. }), [Operand::Vector { reg, .. }, lane]) =
|
||||
(v.dst, &v.src[..])
|
||||
&& let Some(left) = later.read(Reg::V(*reg)).and_then(|x| vec.get(&x))
|
||||
&& let Some(w) = later.write(Reg::S(code))
|
||||
&& let Some(l) = lane_number(lane)
|
||||
&& let Some(&sym) = left.get(l as usize)
|
||||
// (a lane's own value stays a lane read)
|
||||
&& !matches!(sym, Sym::Own(_))
|
||||
&& let Some(shape) = single(sym, wave)
|
||||
{
|
||||
reads.insert(w, shape);
|
||||
}
|
||||
}
|
||||
let shapes = shapes(vec, uni, wave);
|
||||
out.insert(i, Section { end, shapes, reads });
|
||||
i = end + 1;
|
||||
}
|
||||
out
|
||||
@@ -268,7 +289,19 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym {
|
||||
}
|
||||
}
|
||||
|
||||
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
/// The lane a `v_readlane_b32` names.
|
||||
fn lane_number(op: &Operand) -> Option<u32> {
|
||||
match *op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(x) => Some(x),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lanes' values of the VGPRs the section writes, and its scalars.
|
||||
type Left = (HashMap<Value, Vec<Sym>>, HashMap<Value, Sym>);
|
||||
|
||||
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
@@ -289,7 +322,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.then(|| constant(inst))
|
||||
.flatten();
|
||||
let Some(k) = lo else {
|
||||
return shapes(vec, uni, wave);
|
||||
return (vec, uni);
|
||||
};
|
||||
exec = (if name == "s_mov_b64" {
|
||||
k
|
||||
@@ -304,7 +337,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.then(|| constant(inst))
|
||||
.flatten()
|
||||
else {
|
||||
return shapes(vec, uni, wave);
|
||||
return (vec, uni);
|
||||
};
|
||||
exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all;
|
||||
continue;
|
||||
@@ -371,11 +404,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let l = match *lane {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(x) => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
let l = lane_number(lane);
|
||||
let x = lanes(src, &vec, &uni);
|
||||
if let Some(w) = inst.write(Reg::S(code)) {
|
||||
let s = l
|
||||
@@ -664,7 +693,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.collect();
|
||||
vec.insert(dst, merged);
|
||||
}
|
||||
shapes(vec, uni, wave)
|
||||
(vec, uni)
|
||||
}
|
||||
|
||||
fn constant(inst: &Inst) -> Option<u64> {
|
||||
@@ -688,19 +717,10 @@ fn constant(inst: &Inst) -> Option<u64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of each value, where every lane agrees on one.
|
||||
fn shapes(
|
||||
vec: HashMap<Value, Vec<Sym>>,
|
||||
uni: HashMap<Value, Sym>,
|
||||
wave: u32,
|
||||
) -> HashMap<Value, Shape> {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
u64::from(u32::MAX)
|
||||
};
|
||||
let mut out = HashMap::new();
|
||||
let single = |s: Sym| match s {
|
||||
/// The shape of a scalar.
|
||||
fn single(s: Sym, wave: u32) -> Option<Shape> {
|
||||
let all = u64::MAX >> (64 - wave);
|
||||
match s {
|
||||
Sym::K(k) => Some(Shape::K(k)),
|
||||
Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)),
|
||||
Sym::Red {
|
||||
@@ -718,9 +738,19 @@ fn shapes(
|
||||
high,
|
||||
} if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of each value, where every lane agrees on one.
|
||||
fn shapes(
|
||||
vec: HashMap<Value, Vec<Sym>>,
|
||||
uni: HashMap<Value, Sym>,
|
||||
wave: u32,
|
||||
) -> HashMap<Value, Shape> {
|
||||
let all = u64::MAX >> (64 - wave);
|
||||
let mut out = HashMap::new();
|
||||
for (v, s) in uni {
|
||||
if let Some(sh) = single(s) {
|
||||
if let Some(sh) = single(s, wave) {
|
||||
out.insert(v, sh);
|
||||
}
|
||||
}
|
||||
@@ -1074,6 +1104,40 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wave OR whose last step stays in the section's VGPR: the lower
|
||||
/// lanes add the first half's to themselves, so only the upper ones
|
||||
/// hold the whole, and the last lane is read after the section (an
|
||||
/// upscaler's programs).
|
||||
#[test]
|
||||
fn one_lane_of_what_a_section_leaves_is_read_after_it() {
|
||||
let words = |lane: u32| {
|
||||
let mut w = WAVE_OR_V7_TO_S7[..14].to_vec(); // .. v_or_b32 v1, v2, v1
|
||||
w.extend([
|
||||
0xD760_0007,
|
||||
0x0001_0101, // v_readlane_b32 s7, v1, 0
|
||||
0x3802_0207, // v_or_b32 v1, s7, v1
|
||||
0xBEFE_0404, // s_mov_b64 exec, s[4:5]
|
||||
0xD760_0006,
|
||||
0x0001_0101 | lane << 9, // v_readlane_b32 s6, v1, lane
|
||||
S_ENDPGM,
|
||||
]);
|
||||
w
|
||||
};
|
||||
let read = |lane: u32| {
|
||||
let p = build(&words(lane), true);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let saved = insts[0].write(Reg::S(4)).unwrap();
|
||||
let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap();
|
||||
let got = insts[insts.len() - 2].write(Reg::S(6)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
(sec.reads.get(&got).copied(), Shape::Active(Op::Or, v7, saved, 0))
|
||||
};
|
||||
let (found, whole) = read(63);
|
||||
assert_eq!(found, Some(whole));
|
||||
// Lane 0 has the first half's alone: still a lane read.
|
||||
assert_eq!(read(0).0, None);
|
||||
}
|
||||
|
||||
/// `WaveActiveSum` of 16-bit floats, as compiled in
|
||||
/// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the
|
||||
/// lowering reproduces. A tree in another order is not followed.
|
||||
|
||||
@@ -199,6 +199,162 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
|
||||
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
|
||||
}
|
||||
|
||||
/// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for
|
||||
/// other groups in a loop that ends when every lane saw its flag, or after enough rounds:
|
||||
/// both tests become -1 or 0 and SCC of `timeout | ~waiting` ends it.
|
||||
#[test]
|
||||
fn some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() {
|
||||
let native = native(&[
|
||||
0xD765_0001,
|
||||
0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0
|
||||
0xD766_0001,
|
||||
0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1
|
||||
0x7D84_0200, // v_cmp_eq_u32 vcc, s0, v1
|
||||
0x8792_7E6A, // s_and_b64 s[18:19], vcc, exec
|
||||
0x8592_80C1, // s_cselect_b64 s[18:19], -1, 0
|
||||
0xBF09_8501, // s_cmp_ge_u32 s1, 5
|
||||
0x8594_80C1, // s_cselect_b64 s[20:21], -1, 0
|
||||
0x8B92_1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19]
|
||||
0x8506_8081, // s_cselect_b32 s6, 1, 0
|
||||
0x7E04_0206, // v_mov_b32 v2, s6
|
||||
0xE070_0000,
|
||||
0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0
|
||||
]);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = on_64_lanes(&native, &p);
|
||||
// (lane s0 waits, if there is one; s1 rounds)
|
||||
for (wait, rounds, done) in [(0, 0, 0), (37, 4, 0), (63, 4, 0), (64, 0, 1), (37, 5, 1), (64, 9, 1)] {
|
||||
let Some(out) = dispatched(&shader, &[wait, rounds]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(out, done, "lane {wait} after {rounds} rounds");
|
||||
}
|
||||
}
|
||||
|
||||
/// `native` for a host of 64-lane waves.
|
||||
fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader {
|
||||
let st = structure::structure(p).expect("structure");
|
||||
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
|
||||
let io = io::raise(p, native).expect("io::raise");
|
||||
let was = lower::TEST_HOST_WAVE.replace(Some(64));
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
lower::TEST_HOST_WAVE.set(was);
|
||||
let lowered = lowered.expect("lower");
|
||||
assert_eq!(lowered.wave_size, Some(64));
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
shader
|
||||
}
|
||||
|
||||
/// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a
|
||||
/// device that takes it.
|
||||
fn dispatched(shader: &HostShader, constants: &[u32]) -> Option<u32> {
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return None;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 64?): {e}; not run");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if u.root == RootType::Constants {
|
||||
ud[u.index as usize] = constants.get(u.dword as usize).copied().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
Some(out[0][0])
|
||||
}
|
||||
|
||||
/// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0
|
||||
/// are elsewhere, and count as +0 in the console's tree.
|
||||
#[test]
|
||||
fn a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() {
|
||||
let mut words = vec![
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
0x7D86_0000, // v_cmp_le_u32 vcc, s0, v0
|
||||
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
|
||||
0xBF88_0000 | 23, // s_cbranch_execz to the restore of EXEC
|
||||
];
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
|
||||
]);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = on_64_lanes(&native, &p);
|
||||
let wide = |h: u16| match h {
|
||||
0 => 0.0,
|
||||
h => f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13),
|
||||
};
|
||||
let narrow = |f: f32| {
|
||||
if f == 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
for from in [0u32, 1, 5, 31, 32, 37, 63] {
|
||||
let mut tree: Vec<u16> = (0..64u16).map(|t| if u32::from(t) < from { 0 } else { 0x3C00 + 37 * t }).collect();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| narrow(wide(c[0]) + wide(c[1]))).collect();
|
||||
}
|
||||
let Some(out) = dispatched(&shader, &[from]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(out, u32::from(tree[0]), "lanes from {from}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
|
||||
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
|
||||
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
|
||||
|
||||
+193
-57
@@ -15,6 +15,8 @@
|
||||
//! operand's whole possible range: from the encoded register up to the
|
||||
//! program's VGPR count, all read (and all written, for a destination).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
|
||||
|
||||
@@ -149,7 +151,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
}
|
||||
leaders.sort_unstable();
|
||||
leaders.dedup();
|
||||
let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs);
|
||||
let parked = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs);
|
||||
let block_at = |offset: usize| {
|
||||
leaders
|
||||
.binary_search(&offset)
|
||||
@@ -242,12 +244,21 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
/// is left of a cross-lane operation, which a console wave run as two host
|
||||
/// waves could not do where not every lane runs (the lane may be in the other
|
||||
/// wave, or not running).
|
||||
/// A VGPR of other uses is such a store too from its first save on, when every
|
||||
/// use from there is one of the two forms, in one block, and saves a lane
|
||||
/// before it restores it (a register free again after a wave reduction).
|
||||
/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit
|
||||
/// address) moves as a pair (`s_mov_b64`) when every save and every restore
|
||||
/// of the two lanes come together, so a parked lane mask comes back as the
|
||||
/// mask it is; otherwise its halves come back as two scalars.
|
||||
///
|
||||
/// The compiler reuses a lane once what it held is dead, for a pair first and
|
||||
/// a scalar later, say. Where that keeps a pair from being one, each life of a
|
||||
/// lane (the saves that reach a restore in common, and those restores) is a
|
||||
/// store of its own.
|
||||
fn unspill(
|
||||
list: &mut [gfx10::Instruction],
|
||||
flows: &[Flow],
|
||||
leaders: &[usize],
|
||||
wave64: bool,
|
||||
lanes: u8,
|
||||
@@ -276,7 +287,7 @@ fn unspill(
|
||||
// VGPRs used by parking alone, the scalar codes the program uses, and
|
||||
// per instruction the scalar codes it writes.
|
||||
let mut stores = [false; 256];
|
||||
let mut other = [false; 256];
|
||||
let mut other: [Option<usize>; 256] = [None; 256]; // the last such use
|
||||
let mut used = [false; 128];
|
||||
let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
|
||||
let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
|
||||
@@ -314,7 +325,7 @@ fn unspill(
|
||||
match reg {
|
||||
Reg::S(c) => used[usize::from(c)] = true,
|
||||
Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true,
|
||||
Reg::V(r) => other[usize::from(r)] = true,
|
||||
Reg::V(r) => other[usize::from(r)] = Some(parks.len()),
|
||||
Reg::Scc => {}
|
||||
}
|
||||
}
|
||||
@@ -323,16 +334,33 @@ fn unspill(
|
||||
written.push(codes);
|
||||
read.push(from);
|
||||
}
|
||||
for (i, park) in parks.iter_mut().enumerate() {
|
||||
if park.is_some_and(|p| other[usize::from(p.1)]) {
|
||||
*park = None;
|
||||
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
|
||||
for reg in 0..256 {
|
||||
let Some(last) = other[reg] else { continue };
|
||||
let of = |p: &Option<(bool, u8, u8, u32)>| p.filter(|p| usize::from(p.1) == reg);
|
||||
let first = parks.iter().position(|p| of(p).is_some_and(|p| p.0));
|
||||
let late = first.is_some_and(|first| {
|
||||
let end = parks.iter().rposition(|p| of(p).is_some()).unwrap_or(first);
|
||||
let mut saved = Vec::new();
|
||||
last < first
|
||||
&& !(first + 1..=end).any(leader)
|
||||
&& parks[first..=end].iter().filter_map(of).all(|(save, _, _, lane)| {
|
||||
if save {
|
||||
saved.push(lane);
|
||||
}
|
||||
saved.contains(&lane)
|
||||
})
|
||||
});
|
||||
let from = if late { first.unwrap_or(0) } else { parks.len() };
|
||||
for park in &mut parks[..from] {
|
||||
if of(park).is_some() {
|
||||
*park = None;
|
||||
}
|
||||
}
|
||||
let _ = i;
|
||||
}
|
||||
if parks.iter().all(Option::is_none) {
|
||||
return Vec::new();
|
||||
}
|
||||
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
|
||||
// Lane pairs (register, lower lane) that always move together: each
|
||||
// save of the lower lane is followed, in the same block and before its
|
||||
// register changes, by the save of the next register into the next
|
||||
@@ -342,9 +370,6 @@ fn unspill(
|
||||
// compiler puts loads and constants between the two: five instructions later
|
||||
// in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask
|
||||
// is one dword, and a pair move of it with its neighbour would hide it.
|
||||
let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect();
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
// instruction -> the instruction that completes its pair
|
||||
let partner = |i: usize| -> Option<usize> {
|
||||
let (save, reg, code, lane) = parks[i]?;
|
||||
@@ -385,52 +410,163 @@ fn unspill(
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut pairs: Vec<(u8, u32)> = Vec::new();
|
||||
for &(reg, lane) in &slots {
|
||||
if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) {
|
||||
continue;
|
||||
// The store each parking instruction uses, and what the stores are lanes
|
||||
// of: one per (VGPR, lane), or (`split`) one per life of it.
|
||||
let stores_of = |split: bool| -> (Vec<usize>, Vec<(u8, u32)>) {
|
||||
let slot = |i: usize| parks[i].map(|p| (p.1, p.3));
|
||||
// Instructions of one store, by the first of them.
|
||||
let mut first: Vec<usize> = (0..list.len()).collect();
|
||||
if split {
|
||||
fn root(first: &mut [usize], mut i: usize) -> usize {
|
||||
while first[i] != i {
|
||||
first[i] = first[first[i]];
|
||||
i = first[i];
|
||||
}
|
||||
i
|
||||
}
|
||||
let at = |offset: usize| list.partition_point(|i| i.offset < offset);
|
||||
for save in (0..list.len()).filter(|&i| parks[i].is_some_and(|p| p.0)) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut work = vec![save + 1];
|
||||
while let Some(from) = work.pop() {
|
||||
for i in from..list.len() {
|
||||
if slot(i).is_some() && slot(i) == slot(save) {
|
||||
if parks[i].is_some_and(|p| p.0) {
|
||||
break;
|
||||
}
|
||||
let (a, b) = (root(&mut first, save), root(&mut first, i));
|
||||
first[a.max(b)] = a.min(b);
|
||||
}
|
||||
let mut go = |to: usize| {
|
||||
if seen.insert(to) {
|
||||
work.push(to);
|
||||
}
|
||||
};
|
||||
match flows[i] {
|
||||
Flow::Next if i + 1 < list.len() && leader(i + 1) => go(i + 1),
|
||||
Flow::Next => continue,
|
||||
Flow::Stop => {}
|
||||
Flow::Jump(t) => go(at(t)),
|
||||
Flow::Branch(t) => {
|
||||
go(at(t));
|
||||
go(i + 1);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..list.len() {
|
||||
first[i] = root(&mut first, i);
|
||||
}
|
||||
} else {
|
||||
let mut of: HashMap<(u8, u32), usize> = HashMap::new();
|
||||
for i in 0..list.len() {
|
||||
if let Some(s) = slot(i) {
|
||||
first[i] = *of.entry(s).or_insert(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect();
|
||||
let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count();
|
||||
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
|
||||
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() {
|
||||
pairs.push((reg, lane));
|
||||
let mut stores: Vec<((u8, u32), usize)> = (0..list.len())
|
||||
.filter(|&i| first[i] == i)
|
||||
.filter_map(|i| Some((slot(i)?, i)))
|
||||
.collect();
|
||||
stores.sort_unstable();
|
||||
let number = |i: usize| stores.iter().position(|s| s.1 == first[i]);
|
||||
let of = (0..list.len())
|
||||
.map(|i| parks[i].and_then(|_| number(i)).unwrap_or(usize::MAX))
|
||||
.collect();
|
||||
(of, stores.into_iter().map(|s| s.0).collect())
|
||||
};
|
||||
// The stores that move as pairs (lower, upper) and every store's code;
|
||||
// none if the spare codes do not suffice.
|
||||
let plan = |split: bool| -> Option<(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)> {
|
||||
let (mut of, stores) = stores_of(split);
|
||||
let mut pairs: Vec<(usize, usize)> = Vec::new();
|
||||
for (n, &(reg, lane)) in stores.iter().enumerate() {
|
||||
if !wave64 || pairs.iter().any(|&(_, upper)| upper == n) {
|
||||
continue;
|
||||
}
|
||||
let lower: Vec<usize> = (0..list.len()).filter(|&i| of[i] == n).collect();
|
||||
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
|
||||
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
let Some(upper) = distinct.first().map(|&j| of[j]) else {
|
||||
continue;
|
||||
};
|
||||
if stores[upper] == (reg, lane + 1)
|
||||
&& partners.iter().all(Option::is_some)
|
||||
&& distinct.len() == lower.len()
|
||||
&& distinct.iter().all(|&j| of[j] == upper)
|
||||
&& of.iter().filter(|&&o| o == upper).count() == lower.len()
|
||||
{
|
||||
pairs.push((n, upper));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Codes for the parked scalars: the trap temporaries (108..=123), then
|
||||
// user SGPRs the program never names, from the top, then the codes past
|
||||
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
|
||||
// parked one always exists). A material resolve program parks up to 63
|
||||
// scalars and leaves about 20 machine codes unused.
|
||||
let past = usize::from(PARKED);
|
||||
let mut free = [false; 256];
|
||||
for c in (0..105).chain(108..=123) {
|
||||
free[c] = !used[c];
|
||||
}
|
||||
free[past..255].fill(true);
|
||||
let mut codes: Vec<((u8, u32), u8)> = Vec::new();
|
||||
for &(reg, lane) in &pairs {
|
||||
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
|
||||
// Not enough spare codes: leave the program as it is.
|
||||
let Some(c) = at else { return Vec::new() };
|
||||
(free[c], free[c + 1]) = (false, false);
|
||||
codes.push(((reg, lane), c as u8));
|
||||
codes.push(((reg, lane + 1), c as u8 + 1));
|
||||
}
|
||||
for &slot in &slots {
|
||||
if codes.iter().any(|c| c.0 == slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else {
|
||||
return Vec::new();
|
||||
// Lives of one lane that move alike share a code, as they share the lane.
|
||||
let role = |n: usize| {
|
||||
let (lower, upper) = (pairs.iter().any(|p| p.0 == n), pairs.iter().any(|p| p.1 == n));
|
||||
(stores[n], u8::from(lower) + 2 * u8::from(upper))
|
||||
};
|
||||
free[c] = false;
|
||||
codes.push((slot, c as u8));
|
||||
let mut shared: Vec<_> = (0..stores.len()).map(role).collect();
|
||||
let place: Vec<usize> = {
|
||||
let all = shared.clone();
|
||||
shared.sort_unstable();
|
||||
shared.dedup();
|
||||
all.iter().filter_map(|r| shared.binary_search(r).ok()).collect()
|
||||
};
|
||||
for o in of.iter_mut().filter(|o| **o != usize::MAX) {
|
||||
*o = place[*o];
|
||||
}
|
||||
for p in &mut pairs {
|
||||
*p = (place[p.0], place[p.1]);
|
||||
}
|
||||
pairs.sort_unstable();
|
||||
pairs.dedup();
|
||||
// Codes for the parked scalars: the trap temporaries (108..=123), then
|
||||
// user SGPRs the program never names, from the top, then the codes past
|
||||
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
|
||||
// parked one always exists). A material resolve program parks up to 63
|
||||
// scalars and leaves about 20 machine codes unused.
|
||||
let past = usize::from(PARKED);
|
||||
let mut free = [false; 256];
|
||||
for c in (0..105).chain(108..=123) {
|
||||
free[c] = !used[c];
|
||||
}
|
||||
free[past..255].fill(true);
|
||||
let mut codes: Vec<Option<u8>> = vec![None; shared.len()];
|
||||
for &(lower, upper) in &pairs {
|
||||
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
|
||||
// Not enough spare codes: leave the program as it is.
|
||||
let c = at?;
|
||||
(free[c], free[c + 1]) = (false, false);
|
||||
codes[lower] = Some(c as u8);
|
||||
codes[upper] = Some(c as u8 + 1);
|
||||
}
|
||||
for code in codes.iter_mut().filter(|c| c.is_none()) {
|
||||
let c = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c])?;
|
||||
free[c] = false;
|
||||
*code = Some(c as u8);
|
||||
}
|
||||
Some((of, pairs, codes.into_iter().flatten().collect()))
|
||||
};
|
||||
let Some(mut chosen) = plan(false) else { return Vec::new() };
|
||||
let lonely = |(of, pairs, _): &(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)| {
|
||||
(0..list.len()).any(|i| {
|
||||
parks[i].is_some_and(|p| p.0)
|
||||
&& partner(i).is_some()
|
||||
&& !pairs.iter().any(|&(lower, upper)| of[i] == lower || of[i] == upper)
|
||||
})
|
||||
};
|
||||
if wave64
|
||||
&& lonely(&chosen)
|
||||
&& let Some(split) = plan(true)
|
||||
&& split.1.len() > chosen.1.len()
|
||||
{
|
||||
chosen = split;
|
||||
}
|
||||
let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1);
|
||||
let (store, pairs, codes) = chosen;
|
||||
let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
|
||||
list[i] = gfx10::Instruction {
|
||||
offset: list[i].offset,
|
||||
@@ -446,11 +582,11 @@ fn unspill(
|
||||
const NOP: u32 = 0xBF80_0000;
|
||||
let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new();
|
||||
for i in 0..list.len() {
|
||||
let Some((save, reg, code, lane)) = parks[i] else {
|
||||
let Some((save, _, code, _)) = parks[i] else {
|
||||
continue;
|
||||
};
|
||||
let Some(slot) = code_of(reg, lane) else { return Vec::new() };
|
||||
if pairs.contains(&(reg, lane)) {
|
||||
let slot = codes[store[i]];
|
||||
if pairs.iter().any(|p| p.0 == store[i]) {
|
||||
let Some(j) = partner(i) else { return Vec::new() };
|
||||
// A save moves the pair where its second half is saved; a
|
||||
// restore where its first half is restored.
|
||||
@@ -458,7 +594,7 @@ fn unspill(
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
edits.push((at, Some((true, dst, src))));
|
||||
edits.push((gone, None));
|
||||
} else if lane > 0 && pairs.contains(&(reg, lane - 1)) {
|
||||
} else if pairs.iter().any(|p| p.1 == store[i]) {
|
||||
// the upper half of a pair: moved with the lower
|
||||
} else {
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
|
||||
@@ -2611,6 +2611,94 @@ pub(crate) mod tests {
|
||||
assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]);
|
||||
}
|
||||
|
||||
/// A VGPR a wave reduction used is free again after it: from the first
|
||||
/// save on it holds parked scalars alone (an upscaler program parks a
|
||||
/// constant buffer's descriptor that way).
|
||||
#[test]
|
||||
fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() {
|
||||
let before = [
|
||||
0x7E00_0281, // v_mov_b32 v0, 1
|
||||
0x7E02_0300, // v_mov_b32 v1, v0
|
||||
];
|
||||
let park = [
|
||||
0xD761_0000,
|
||||
0x0001_0609, // v_writelane_b32 v0, s9, 3
|
||||
0xD760_0002,
|
||||
0x0001_0700, // v_readlane_b32 s2, v0, 3
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
];
|
||||
let load = [
|
||||
0xF40C_0001,
|
||||
0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20
|
||||
S_ENDPGM,
|
||||
];
|
||||
let words = [&before[..], &park, &load].concat();
|
||||
let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps);
|
||||
assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]);
|
||||
// Still lane reads: a lane restored before it is saved, and a
|
||||
// register with an ordinary use after the first save.
|
||||
let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat();
|
||||
let used_after = [&before[..], &park, &before[1..], &load].concat();
|
||||
for words in [restored_first, used_after] {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let insts = p.blocks.iter().flat_map(|b| &b.insts);
|
||||
assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two lanes hold a pair (a lane mask, say) and later one of them a
|
||||
/// scalar, as in a water volume program that parks more than the lanes
|
||||
/// of one VGPR hold: the pair still moves as one.
|
||||
#[test]
|
||||
fn a_lane_spilled_to_again_later_does_not_split_an_earlier_pair() {
|
||||
let pair = [
|
||||
0xD761_0000u32,
|
||||
0x0001_0004, // v_writelane_b32 v0, s4, 0
|
||||
0xD761_0000,
|
||||
0x0001_0205, // v_writelane_b32 v0, s5, 1
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xD760_0004,
|
||||
0x0001_0100, // v_readlane_b32 s4, v0, 0
|
||||
0xD760_0005,
|
||||
0x0001_0300, // v_readlane_b32 s5, v0, 1
|
||||
];
|
||||
let scalar = [
|
||||
0xD761_0000u32,
|
||||
0x0001_0006, // v_writelane_b32 v0, s6, 0
|
||||
0xBE86_0380, // s_mov_b32 s6, 0
|
||||
0xD760_0006,
|
||||
0x0001_0100, // v_readlane_b32 s6, v0, 0
|
||||
S_ENDPGM,
|
||||
];
|
||||
let moves = |words: &[u32]| {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let names: Vec<_> = p.blocks[0].insts.iter().map(|i| i.name()).collect();
|
||||
assert!(!names.iter().any(|n| n.contains("lane")));
|
||||
names.iter().filter(|n| **n == "s_mov_b64").count()
|
||||
};
|
||||
assert_eq!(moves(&[&pair[..], &scalar].concat()), 2);
|
||||
// A restore both saves reach keeps the lane one scalar.
|
||||
let joined = [
|
||||
&pair[..4],
|
||||
&[0xBF84_0002], // s_cbranch_scc0 past the second save
|
||||
&scalar[..2],
|
||||
&pair[4..],
|
||||
&scalar[2..],
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(moves_anywhere(&joined), 0);
|
||||
}
|
||||
|
||||
fn moves_anywhere(words: &[u32]) -> usize {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let insts = p.blocks.iter().flat_map(|b| &b.insts);
|
||||
insts.filter(|i| i.name() == "s_mov_b64").count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptors_joined_by_control_flow_are_traced_per_edge() {
|
||||
let r = track_words(
|
||||
|
||||
+4
-1
@@ -56,12 +56,15 @@ with the presented one.
|
||||
|
||||
| switch | does |
|
||||
|---|---|
|
||||
| `--compare` | runs the frame unchanged first and prints the difference |
|
||||
| `--compare` | runs the frame unchanged and with the experiments turn by turn, and prints the difference |
|
||||
| `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run |
|
||||
| `--batch-clamps` / `--batch-clamps 2` | argument clamps in batches, as `VICTORY_INDIRECT_BATCH=2` / `=1` does |
|
||||
| `--skip-hash-passes` | no compare/rehash passes over card buffers |
|
||||
| `--no-barriers` | no unordered-access barriers |
|
||||
| `--merge-barriers` | joins barrier calls with no work between them |
|
||||
| `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory |
|
||||
| `--only-buffers <what>` | with `--buffers`: only the buffers all of these match: `name=<text>`, `min=<bytes>`, `max=<bytes>`, `seen=No`, `Cached` or `Combined`, `id=<a>..<b>`, or `!` and one of them (repeatable) |
|
||||
| `--listing 3..7` | only writes the frame's buffers and those lists' commands |
|
||||
| `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones |
|
||||
| `--only 3..7` | runs these lists; of the others only barriers |
|
||||
| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
|
||||
|
||||
Reference in new issue
Block a user