SEMANTICS 2111 / RUNTIME 2296: indirect command buffer GPU work touches only the bindings a descriptor counts

A record holds 128 buffer bindings (4 stages x 32 slots, 2 KiB) whatever its
descriptor counts. The draw replay's preprocess read all 128 of every command
to refuse a binding set past its stage's count, the compute replay all 128
for its inheritance check, and a GPU reset (air.reset_*_command) wrote all
2248 bytes of the record. On a discrete GPU those reads crossed the link.

A binding past its stage's count is zero in every record: the storage is made
zero, an encoder's write past the count faults and writes nothing, the CPU's
setter refuses one, a compute command has no other stage's setter, and a copy
takes a source of the same descriptor. So:
- the render preprocess reads a binding only below its stage's count and
  writes a slot table entry past it as null, unread;
- the compute replay reads the kernel bindings below the header's count alone
  (clamped to 32) and writes the entries past it null;
- a GPU reset writes the command's words (64 B), the bindings below each
  stage's count (16 B each) and the words past the bindings (136 B).
The replay's check of a binding set past the count goes: it never applies.

Tests: interpreter (metal2vulkan) render and compute cases with garbage past
the counts draw/dispatch as without it, the same garbage in a counted slot is
refused (negative control); a reset clears the command words, counted bindings
and tail and leaves a mark past the counts, where no reset leaves every stale
byte (negative control). Runtime device test: a GPU reset, an encode of the
even commands and an execution leave the odd commands empty and draw the even
cells alone; without the reset every command keeps its earlier draw (control).
icb_reads gains a gpu-reset shape.

Verified: msi m3-max-29281 at the tip: clippy -D warnings (all targets and
features) 0, interpreter tests 72/72, lavapipe ICB/indirect 34/34, m2v_gpu
build 0. 5080 (b5080 entry, at the change before a test-only lint fix): device
ICB/indirect 34/34; icb_reads 8192 commands, GPU us a command, two alternated
rounds: gpu-shared execute 0.0295/0.0171 -> 0.0109/0.0109, gpu-reset encode
0.0143 -> 0.0031 and execute 0.0130 -> 0.0109, gpu-private execute 0.0169 ->
0.0107, cpu-shared unchanged. The 780M A/B follows.
This commit is contained in:
Anees Iqbal committed 2026-11-14 06:48:34 -08:00
1 parent 9c1994c7f5
commit eed5f3d84b
9 files changed
+694 -162

No files matched your search

@@ -15,6 +15,8 @@
//! - **`gpu-shared`** and **`gpu-private`**: a buffer of `Shared`, or `Private`, storage whose
//! commands the owned kernel `kernel_icb_encode_render_commands` writes, one thread a command,
//! in one command buffer, and a render pass of another command buffer executes;
//! - **`gpu-reset`**: `gpu-shared` with each thread first resetting its command on the GPU
//! (`air.reset_render_command`), as a kernel that encodes commands anew each frame does;
//! - **`cpu-shared`**: a `Shared` buffer whose commands the CPU writes through each command's
//! setters (its two buffers and its draw), then a render pass executes.
//!
@@ -112,16 +114,23 @@ entry:\n\
#[derive(Clone, Copy, PartialEq)]
enum Shape {
GpuShared,
GpuReset,
GpuPrivate,
CpuShared,
}
impl Shape {
const ALL: [Shape; 3] = [Shape::GpuShared, Shape::GpuPrivate, Shape::CpuShared];
const ALL: [Shape; 4] = [
Shape::GpuShared,
Shape::GpuReset,
Shape::GpuPrivate,
Shape::CpuShared,
];
fn name(self) -> &'static str {
match self {
Shape::GpuShared => "gpu-shared",
Shape::GpuReset => "gpu-reset",
Shape::GpuPrivate => "gpu-private",
Shape::CpuShared => "cpu-shared",
}
@@ -236,6 +245,8 @@ fn gpu_us(command_buffer: &CommandBuffer) -> Result<f64> {
struct Ours<'a> {
device: &'a Device,
writer: ComputePipelineState,
/// The writer with a GPU reset of each command before its writes ([`resetting`]).
resetter: ComputePipelineState,
state: RenderPipelineState,
target: Texture,
/// Three vertices a command: the lower half of its cell.
@@ -258,8 +269,12 @@ impl Ours<'_> {
.new_indirect_command_buffer(&descriptor, self.commands, shape.options())?)
}
/// The kernel's writes of every command of `icb`, committed and waited for: its GPU time.
fn write_on_gpu(&self, icb: &IndirectCommandBuffer) -> Result<f64> {
/// `writer`'s writes of every command of `icb`, committed and waited for: its GPU time.
fn write_on_gpu(
&self,
icb: &IndirectCommandBuffer,
writer: &ComputePipelineState,
) -> Result<f64> {
let arguments = self.device.new_buffer_with_bytes(
&icb.gpu_resource_id().0.to_le_bytes(),
ResourceOptions::shared(),
@@ -267,7 +282,7 @@ impl Ours<'_> {
let queue = self.device.new_command_queue()?;
let command_buffer = queue.command_buffer()?;
let mut encoder = command_buffer.compute_command_encoder()?;
encoder.set_compute_pipeline_state(&self.writer)?;
encoder.set_compute_pipeline_state(writer)?;
encoder.set_buffer(Some(&arguments), 0, 0)?;
encoder.set_buffer(Some(&self.vertices), 0, 1)?;
encoder.set_buffer(Some(&self.out), 0, 2)?;
@@ -369,6 +384,36 @@ impl Ours<'_> {
}
/// The library of the LLVM text `text`, assembled by `llvm-as`.
/// The writer, each thread first resetting its command on the GPU (`air.reset_render_command`),
/// as a kernel that encodes commands anew each frame does.
fn resetting() -> String {
let load = " %7 = bitcast";
let at = WRITER.find(load).expect("the fixture's buffer cast");
let declare = at
+ WRITER[at..]
.find("; Function Attrs")
.expect("the fixture's declarations");
format!(
"{} tail call void @air.reset_render_command(ptr addrspace(1) captures(none) %6, i32 %3) \
#2\n{}declare void @air.reset_render_command(ptr addrspace(1) captures(none), i32) \
local_unnamed_addr #1\n\n{}",
&WRITER[..at],
&WRITER[at..declare],
&WRITER[declare..]
)
}
/// The writer of `text`'s kernel.
fn writer(device: &Device, text: &str) -> Result<ComputePipelineState> {
let writer = library(device, text)?;
let writer = ComputePipelineDescriptor::new(StageSource::Function(
writer
.new_function_with_name("kernel_icb_encode_render_commands")?
.function_descriptor(),
));
Ok(device.new_compute_pipeline_state(&writer, &PipelineOptions::default())?)
}
fn library(device: &Device, text: &str) -> Result<Library> {
let bitcode = tool("llvm-as", &["-o", "-", "-"], text)?;
let library = metal2vulkan::library::Library::from_air(&bitcode)?;
@@ -423,19 +468,13 @@ fn main() -> Result<()> {
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
descriptor.support_indirect_command_buffers = true;
let state = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?;
let writer = library(&device, WRITER)?;
let writer = ComputePipelineDescriptor::new(StageSource::Function(
writer
.new_function_with_name("kernel_icb_encode_render_commands")?
.function_descriptor(),
));
let writer = device.new_compute_pipeline_state(&writer, &PipelineOptions::default())?;
let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false);
target.usage = TextureUsage::RENDER_TARGET;
target.resource_options = ResourceOptions::private();
let ours = Ours {
device: &device,
writer,
writer: writer(&device, WRITER)?,
resetter: writer(&device, &resetting())?,
state,
target: device.new_texture(&target)?,
vertices: private_with(&device, &vertices(args.commands))?,
@@ -472,7 +511,8 @@ fn main() -> Result<()> {
let icb = ours.icb(shape)?;
let (encode, cpu) = match shape {
Shape::CpuShared => (0.0, ours.write_on_cpu(&icb)?.1.as_secs_f64() * 1e6),
_ => (ours.write_on_gpu(&icb)?, 0.0),
Shape::GpuReset => (ours.write_on_gpu(&icb, &ours.resetter)?, 0.0),
_ => (ours.write_on_gpu(&icb, &ours.writer)?, 0.0),
};
let command_buffer = ours.execute(&icb)?;
run(&command_buffer)?;
@@ -5,7 +5,8 @@
//! the GPU wrote them and none where it did not; a `Private` one's never move; any other host
//! access is staged, announced once per device. Elsewhere every buffer's records lie in the host's
//! memory: nothing moves and nothing is staged. On every device the commands draw what was
//! encoded, whoever encoded them, and the getters answer it.
//! encoded, whoever encoded them, and the getters answer it; a GPU reset before an encode leaves
//! nothing of what an earlier encode set (`lower::access::encode`'s `default_record`).
//!
//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind
//! of device the cfg selects. The kernel is the owned fixture
@@ -74,6 +75,51 @@ entry:\n\
/// The fragment function's color, exact in `RGBA8Unorm`.
const TEXEL: [u8; 4] = [255, 0, 255, 255];
/// The owned fixture's kernel, and its file's stem.
const WRITER: &str = "kernel_icb_encode_render_commands";
/// The fixture's kernel with its body replaced: each thread `t`, where `reset`, first resets
/// command `t` on the GPU (`air.reset_render_command`); then an even `t` encodes what the fixture
/// does (its vertex and fragment buffers and its draw), and an odd one nothing.
fn reset_writer_text(reset: bool) -> String {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public")
.join(format!("{WRITER}.ll"));
let text = std::fs::read_to_string(path).unwrap();
let define = text.find(&format!("define void @{WRITER}(")).unwrap();
let open = define + text[define..].find("{\n").unwrap() + 2;
let close = open + text[open..].find("\n}\n").unwrap();
let attributes = text.find("attributes #0").unwrap();
let reset = match reset {
true => {
" tail call void @air.reset_render_command(ptr addrspace(1) captures(none) %6, i32 %3) #2\n"
}
false => "",
};
let body = format!(
" %5 = getelementptr inbounds %struct.Commands, ptr addrspace(1) %0, i64 0, i32 0, i32 0\n\
%6 = load ptr addrspace(1), ptr addrspace(1) %5, align 8\n\
{reset} %odd = and i32 %3, 1\n\
%even = icmp eq i32 %odd, 0\n\
br i1 %even, label %encode, label %done\n\n\
encode:\n\
tail call void @air.set_vertex_buffer_render_command.p1i8(ptr addrspace(1) captures(none) %6, i32 %3, ptr addrspace(1) %1, i64 -1, i32 0) #2\n\
tail call void @air.set_fragment_buffer_render_command.p1i8(ptr addrspace(1) captures(none) %6, i32 %3, ptr addrspace(1) %1, i32 1) #2\n\
%7 = mul i32 %3, 3\n\
tail call void @air.draw_primitives_render_command(ptr addrspace(1) captures(none) %6, i32 %3, i32 3, i32 %7, i32 3, i32 1, i32 0) #2\n\
br label %done\n\n\
done:\n\
ret void"
);
let declare = "declare void @air.reset_render_command(ptr addrspace(1) captures(none), i32) local_unnamed_addr #1\n\n";
format!(
"{}{body}{}{declare}{}",
&text[..open],
&text[close..attributes],
&text[attributes..]
)
}
/// What every test uses, on a device whose notices it hears.
struct Ours {
device: Device,
@@ -161,8 +207,8 @@ impl Ours {
let state = device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
let writer = library(&device, "kernel_icb_encode_render_commands.ll")
.new_function_with_name("kernel_icb_encode_render_commands")
let writer = library(&device, &format!("{WRITER}.ll"))
.new_function_with_name(WRITER)
.unwrap();
let writer =
ComputePipelineDescriptor::new(StageSource::Function(writer.function_descriptor()));
@@ -191,6 +237,20 @@ impl Ours {
}
}
/// A kernel of the fixture's name and arguments, made of LLVM text `text`.
fn writer_of(&self, text: &str) -> ComputePipelineState {
let bitcode = metal2vulkan_devtools::llvm_assemble_text(text).unwrap();
let library = self.device.new_library_with_compile_library(
metal2vulkan::library::Library::from_air(&bitcode).unwrap(),
);
let function = library.new_function_with_name(WRITER).unwrap();
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
self.device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// Whether the device places records by their first use: without unified memory, with a
/// staging queue (`home.rs`).
fn placing(&self) -> bool {
@@ -212,6 +272,11 @@ impl Ours {
/// The kernel's writes of every command of `icb` through an argument buffer that holds it,
/// committed and waited for.
fn encode_on_gpu(&self, icb: &IndirectCommandBuffer) {
self.encode_with(icb, &self.writer);
}
/// [`encode_on_gpu`](Self::encode_on_gpu) by `writer`, a kernel of the fixture's arguments.
fn encode_with(&self, icb: &IndirectCommandBuffer, writer: &ComputePipelineState) {
let arguments = self
.device
.new_buffer_with_bytes(
@@ -222,7 +287,7 @@ impl Ours {
let queue = self.device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&self.writer).unwrap();
encoder.set_compute_pipeline_state(writer).unwrap();
encoder.set_buffer(Some(&arguments), 0, 0).unwrap();
encoder.set_buffer(Some(&self.vertices), 0, 1).unwrap();
encoder.set_buffer(Some(&self.out), 0, 2).unwrap();
@@ -511,3 +576,50 @@ fn a_blit_reset_between_gpu_encodes_keeps_the_records_on_the_device() {
assert_eq!(ours.moved_since(before), [0, 0, 0]);
assert_eq!(ours.staged_notices(), 0);
}
/// A GPU reset clears what a command may have set (`lower::access::encode`'s `default_record`,
/// which writes the command's words, the bindings below each stage's count and the words past the
/// bindings), so a reset, an encode and an execution are exact: after the fixture's encode of every
/// command, a kernel that resets each command and encodes the even ones alone leaves every odd
/// command empty (no draw, no vertex or fragment buffer, as the getters read them) and the even
/// ones the fixture's, and the execution draws the even commands' cells alone. The negative
/// control: the same kernel without the reset leaves the odd commands what the first encode wrote,
/// their draws and buffers, and every cell drawn: the test sees what a reset leaves. Records of
/// both storage modes, wherever they lie.
#[test]
fn a_gpu_reset_then_an_encode_then_an_execution_are_exact() {
let ours = Ours::new("icb-gpu-reset");
let resetting = ours.writer_of(&reset_writer_text(true));
let unresetting = ours.writer_of(&reset_writer_text(false));
let evens: Vec<u64> = every_command().into_iter().filter(|c| c % 2 == 0).collect();
for options in [ResourceOptions::shared(), ResourceOptions::private()] {
for (writer, reset) in [(&resetting, true), (&unresetting, false)] {
let icb = ours.icb(options);
ours.encode_on_gpu(&icb);
ours.encode_with(&icb, writer);
run(&ours.execute(&icb));
let want = match reset {
true => evens.clone(),
false => every_command(),
};
assert_eq!(ours.drawn(), want, "{options:?} reset {reset}");
for index in every_command() {
let command = icb.indirect_render_command_at(index).unwrap();
let empty = reset && index % 2 == 1;
let draw = command.draw().unwrap();
let vertex = command.vertex_buffer(0).unwrap();
let fragment = command.fragment_buffer(1).unwrap();
match empty {
true => assert!(
draw.is_none() && vertex.is_none() && fragment.is_none(),
"{options:?} {index}: {draw:?} {vertex:?} {fragment:?}"
),
false => {
assert_eq!(ours.vertex_start(&icb, index), 3 * index);
assert!(vertex.is_some() && fragment.is_some(), "{index}");
}
}
}
}
}
}
+37 -10
View File
@@ -1521,10 +1521,22 @@ pub fn typed_module(limits: [u32; 3]) -> BResult<TypedModule> {
let bad_state = fb.binary(BinOp::LogicalOr, unknown_state, retained_none)?;
flag(fb, fault, bad_state, ReplayFaults::RECORD.0)?;
// A command that sets any buffer, of any stage, while inheriting buffers: a slot no setter
// set holds an address and a stride of 0.
let all = k32(fb, layout::ALL_BINDINGS as u32)?;
count_loop(fb, t, all, |fb, n| {
// A command that sets any buffer while inheriting buffers: a slot no setter set holds an
// address and a stride of 0. Only its kernel buffers below the descriptor's count are read
// (the header's byte 0, `layout::COUNTS`): every other binding of a compute record is zero,
// as the storage is made zero, an encoder's write past the count faults and writes nothing
// (`lower::access::encode`), the CPU's setter refuses one, a compute command has no other
// stage's setter, and a copy takes a source of the same descriptor. So a command reads the
// bindings its descriptor counts, not the record's 128, 2 KiB.
let counts_at = at(fb, records, layout::COUNTS)?;
let packed = load32(fb, t, counts_at)?;
let byte_mask = k32(fb, 0xff)?;
let kernel_count = fb.binary(BinOp::BitwiseAnd, packed, byte_mask)?;
// At most a stage's slots, whatever the header states: the loop stays in the record.
let most = k32(fb, BINDING_COUNT as u32)?;
let over = fb.binary(BinOp::UGreaterThan, kernel_count, most)?;
let kernel_count = fb.select(over, most, kernel_count)?;
count_loop(fb, t, kernel_count, |fb, n| {
let n64 = wide(fb, t, n)?;
let binding_bytes = k64(fb, layout::BINDING)?;
let rel = fb.binary(BinOp::IMul, n64, binding_bytes)?;
@@ -1597,13 +1609,28 @@ pub fn typed_module(limits: [u32; 3]) -> BResult<TypedModule> {
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
// The record's binding below the descriptor's count; past it, the binding is zero (the
// loop above), whose entry is null, unread.
let own: ArmFn<'_, ()> = Box::new(move |fb, _| {
own_kernel_entry(
fb,
(t, (resident, &view)),
(rec, n64, entry),
(runs_any, fault, misses),
)?;
let below = fb.binary(BinOp::ULessThan, n, kernel_count)?;
let read: ArmFn<'_, ()> = Box::new(move |fb, _| {
own_kernel_entry(
fb,
(t, (resident, &view)),
(rec, n64, entry),
(runs_any, fault, misses),
)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
let null: ArmFn<'_, ()> = Box::new(move |fb, _| {
let zero64 = k64(fb, 0)?;
for field in [roots::HOST, roots::GUEST, roots::SIZE, roots::BIND_OFFSET] {
let a = at(fb, entry, field)?;
store64(fb, t, a, zero64)?;
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), below, read, Some(null))?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), inherit_buffers, inherited, Some(own))?;
+116 -83
View File
@@ -17,8 +17,10 @@
//! [`DrawReplayModule::LOCAL_SIZE`]) reads the command's record, checks it as the host's
//! decode does (`CommandBuffer::decode` and `CommandDescriptor::validate_record`: the
//! producer's sticky encoding fault, an action the descriptor does not hold, a barrier flag
//! other than 0 or 1, a binding past its stage's count or bound with a dynamic stride the
//! descriptor does not allow, a state word no record holds), writes the command's two **slot
//! other than 0 or 1, a binding bound with a dynamic stride the descriptor does not allow, a
//! state word no record holds; it reads only the bindings below each stage's count in the
//! header, as one past it is zero in every record, so the host's refusal of one set there never
//! applies), writes the command's two **slot
//! tables** (vertex, then fragment: the null entry, the sink entry naming the shared resident
//! set, and entry `2 + n` the stage's buffer `n` resolved in the resident set as a compute
//! replay's kernel buffer is, for each `n` below the slots its function reads,
@@ -693,6 +695,24 @@ fn no_binding(_: &Symbol) -> Option<u32> {
/// host's step leaves such a buffer unbound and counts it; an unbound slot holds a nil buffer's
/// address word as its bind offset, so the function sees the offset as the buffer's address, as
/// Metal's does.
/// The binding count of a record's stage `stage` (its words' index: 0 the mesh stage's, 1 the
/// vertex's, 2 the fragment's, 3 the object's) in a render descriptor's packed counts `counts`
/// (`layout::COUNTS`): the stage's byte, 3, 1, 2 or 0.
fn stage_count_of(fb: &mut FunctionBuilder<'_>, counts: Value, stage: Value) -> BResult<Value> {
let mut byte = k32(fb, 0)?;
for (stage_index, header_byte) in [(0u32, 3u32), (1, 1), (2, 2)] {
let k = k32(fb, stage_index)?;
let is = fb.binary(BinOp::IEqual, stage, k)?;
let b = k32(fb, header_byte)?;
byte = fb.select(is, b, byte)?;
}
let eight = k32(fb, 8)?;
let shift = fb.binary(BinOp::IMul, byte, eight)?;
let shifted = fb.binary(BinOp::ShiftRightLogical, counts, shift)?;
let mask = k32(fb, 0xff)?;
fb.binary(BinOp::BitwiseAnd, shifted, mask)
}
fn own_entry(
fb: &mut FunctionBuilder<'_>,
(t, (resident, view)): (Types, (Value, &roots::ResidentView)),
@@ -1098,11 +1118,15 @@ pub fn typed_module() -> BResult<TypedModule> {
let bad_state = fb.binary(BinOp::INotEqual, state, zero32)?;
malformed = fb.binary(BinOp::LogicalOr, malformed, bad_state)?;
// Every binding the record holds, of each of its four stages (mesh, vertex, fragment,
// object): one past its stage's count (the header's byte 3, 1, 2 or 0), or one bound with a
// dynamic stride where the descriptor allows none or the stage takes none (fragment, object),
// is a record the host's validation refuses; one set while the commands inherit buffers
// refuses the command.
// Every binding below its stage's count (the header's byte 3, 1, 2 or 0, of the mesh, vertex,
// fragment and object stages): one bound with a dynamic stride where the descriptor allows
// none or the stage takes none (fragment, object) is a record the host's validation refuses;
// one set while the commands inherit buffers refuses the command. A binding past its stage's
// count is not read. It is zero in every record: the storage is made zero, an encoder's write
// past the count faults and writes nothing (`lower::access::encode`), the CPU's setter refuses
// one, and a copy takes a source of the same descriptor. So the host's refusal of a binding set
// there never applies, and a command's reads of the record's 128 bindings, 2 KiB, shrink to
// those its descriptor counts.
let inherit_bit = k32(fb, INHERIT_BUFFERS)?;
let inherit_bits = fb.binary(BinOp::BitwiseAnd, flags, inherit_bit)?;
let inherit_buffers = fb.binary(BinOp::INotEqual, inherit_bits, zero32)?;
@@ -1115,82 +1139,71 @@ pub fn typed_module() -> BResult<TypedModule> {
let view = roots::resident_view(fb, resident)?;
let all = k32(fb, layout::ALL_BINDINGS as u32)?;
count_loop(fb, t, all, |fb, n| {
let n64 = wide(fb, t, n)?;
let binding_bytes = k64(fb, layout::BINDING)?;
let rel = fb.binary(BinOp::IMul, n64, binding_bytes)?;
let first = k64(fb, layout::buffers(BufferStage::Kernel))?;
let rel = fb.binary(BinOp::IAdd, rel, first)?;
let own = fb.binary(BinOp::IAdd, rec, rel)?;
let address = load64(fb, t, own)?;
let stride_at = at(fb, own, layout::STRIDE)?;
let stride = load64(fb, t, stride_at)?;
let addressed = fb.binary(BinOp::INotEqual, address, zero64)?;
let strided = fb.binary(BinOp::INotEqual, stride, zero64)?;
let set = fb.binary(BinOp::LogicalOr, addressed, strided)?;
let inherited = fb.binary(BinOp::LogicalAnd, inherit_buffers, set)?;
flag(fb, fault, inherited, ReplayFaults::BUFFERS.0)?;
let five = k32(fb, BINDING_COUNT.trailing_zeros())?;
let stage = fb.binary(BinOp::ShiftRightLogical, n, five)?;
let low = k32(fb, BINDING_COUNT as u32 - 1)?;
let slot = fb.binary(BinOp::BitwiseAnd, n, low)?;
// The header's byte of the stage's count: mesh 3, vertex 1, fragment 2, object 0.
let mut byte = k32(fb, 0)?;
for (stage_index, header_byte) in [(0u32, 3u32), (1, 1), (2, 2)] {
let k = k32(fb, stage_index)?;
let is = fb.binary(BinOp::IEqual, stage, k)?;
let b = k32(fb, header_byte)?;
byte = fb.select(is, b, byte)?;
}
let eight = k32(fb, 8)?;
let shift = fb.binary(BinOp::IMul, byte, eight)?;
let shifted = fb.binary(BinOp::ShiftRightLogical, counts, shift)?;
let mask = k32(fb, 0xff)?;
let stage_count = fb.binary(BinOp::BitwiseAnd, shifted, mask)?;
let past = fb.binary(BinOp::UGreaterThanEqual, slot, stage_count)?;
let past = fb.binary(BinOp::LogicalAnd, set, past)?;
let dynamic = fb.binary(BinOp::INotEqual, stride, static_stride)?;
let dynamic = fb.binary(BinOp::LogicalAnd, set, dynamic)?;
let two = k32(fb, 2)?;
let strideless = fb.binary(BinOp::UGreaterThanEqual, stage, two)?;
let refused_stride = fb.unary(UnOp::LogicalNot, dynamic_allowed)?;
let refused_stride = fb.binary(BinOp::LogicalOr, refused_stride, strideless)?;
let bad_stride = fb.binary(BinOp::LogicalAnd, dynamic, refused_stride)?;
let bad = fb.binary(BinOp::LogicalOr, past, bad_stride)?;
flag(fb, bad_bindings, bad, 1)?;
// A buffer of the command's own below its stage's count that no slot table holds (past
// the slots its stage's function reads, or of another stage) is resolved too, so that its
// miss counts as the host step's does.
let first_address = k64(fb, BufferBinding::MIN_BUFFER_ADDRESS)?;
let names = fb.binary(BinOp::UGreaterThanEqual, address, first_address)?;
let stage_count = stage_count_of(fb, counts, stage)?;
let below = fb.binary(BinOp::ULessThan, slot, stage_count)?;
let mut held = [zero64; 2];
for (h, (stage_index, slots)) in held
.iter_mut()
.zip([(1u32, vertex_slots), (2, fragment_slots)])
{
let k = k32(fb, stage_index)?;
let is = fb.binary(BinOp::IEqual, stage, k)?;
let inside = fb.binary(BinOp::ULessThan, slot, slots)?;
*h = fb.binary(BinOp::LogicalAnd, is, inside)?;
}
let covered = fb.binary(BinOp::LogicalOr, held[0], held[1])?;
let uncovered = fb.unary(UnOp::LogicalNot, covered)?;
let own = fb.unary(UnOp::LogicalNot, inherit_buffers)?;
let counted = fb.binary(BinOp::LogicalAnd, names, below)?;
let counted = fb.binary(BinOp::LogicalAnd, counted, uncovered)?;
let counted = fb.binary(BinOp::LogicalAnd, counted, own)?;
let count: ArmFn<'_, ()> = Box::new(move |fb, _| {
let (_, _, hit) = resolved(fb, (resident, &view), address)?;
let missed = fb.unary(UnOp::LogicalNot, hit)?;
let one = k32(fb, 1)?;
let zero = k32(fb, 0)?;
let add = fb.select(missed, one, zero)?;
let u = fb.load(unresolved, MemAccess::default())?;
let u = fb.binary(BinOp::IAdd, u, add)?;
fb.store(unresolved, u, MemAccess::default())?;
let read: ArmFn<'_, ()> = Box::new(move |fb, _| {
let n64 = wide(fb, t, n)?;
let binding_bytes = k64(fb, layout::BINDING)?;
let rel = fb.binary(BinOp::IMul, n64, binding_bytes)?;
let first = k64(fb, layout::buffers(BufferStage::Kernel))?;
let rel = fb.binary(BinOp::IAdd, rel, first)?;
let own = fb.binary(BinOp::IAdd, rec, rel)?;
let address = load64(fb, t, own)?;
let stride_at = at(fb, own, layout::STRIDE)?;
let stride = load64(fb, t, stride_at)?;
let zero64 = k64(fb, 0)?;
let addressed = fb.binary(BinOp::INotEqual, address, zero64)?;
let strided = fb.binary(BinOp::INotEqual, stride, zero64)?;
let set = fb.binary(BinOp::LogicalOr, addressed, strided)?;
let inherited = fb.binary(BinOp::LogicalAnd, inherit_buffers, set)?;
flag(fb, fault, inherited, ReplayFaults::BUFFERS.0)?;
let dynamic = fb.binary(BinOp::INotEqual, stride, static_stride)?;
let dynamic = fb.binary(BinOp::LogicalAnd, set, dynamic)?;
let two = k32(fb, 2)?;
let strideless = fb.binary(BinOp::UGreaterThanEqual, stage, two)?;
let refused_stride = fb.unary(UnOp::LogicalNot, dynamic_allowed)?;
let refused_stride = fb.binary(BinOp::LogicalOr, refused_stride, strideless)?;
let bad_stride = fb.binary(BinOp::LogicalAnd, dynamic, refused_stride)?;
flag(fb, bad_bindings, bad_stride, 1)?;
// A buffer of the command's own that no slot table holds (past the slots its stage's
// function reads, or of another stage) is resolved too, so that its miss counts as
// the host step's does.
let first_address = k64(fb, BufferBinding::MIN_BUFFER_ADDRESS)?;
let names = fb.binary(BinOp::UGreaterThanEqual, address, first_address)?;
let mut held = [zero64; 2];
for (h, (stage_index, slots)) in held
.iter_mut()
.zip([(1u32, vertex_slots), (2, fragment_slots)])
{
let k = k32(fb, stage_index)?;
let is = fb.binary(BinOp::IEqual, stage, k)?;
let inside = fb.binary(BinOp::ULessThan, slot, slots)?;
*h = fb.binary(BinOp::LogicalAnd, is, inside)?;
}
let covered = fb.binary(BinOp::LogicalOr, held[0], held[1])?;
let uncovered = fb.unary(UnOp::LogicalNot, covered)?;
let own = fb.unary(UnOp::LogicalNot, inherit_buffers)?;
let counted = fb.binary(BinOp::LogicalAnd, names, uncovered)?;
let counted = fb.binary(BinOp::LogicalAnd, counted, own)?;
let count: ArmFn<'_, ()> = Box::new(move |fb, _| {
let (_, _, hit) = resolved(fb, (resident, &view), address)?;
let missed = fb.unary(UnOp::LogicalNot, hit)?;
let one = k32(fb, 1)?;
let zero = k32(fb, 0)?;
let add = fb.select(missed, one, zero)?;
let u = fb.load(unresolved, MemAccess::default())?;
let u = fb.binary(BinOp::IAdd, u, add)?;
fb.store(unresolved, u, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), counted, count, None)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), counted, count, None)?;
fb.if_(&mut (), below, read, None)?;
Ok(())
})?;
let bad = fb.load(bad_bindings, MemAccess::default())?;
@@ -1277,15 +1290,18 @@ pub fn typed_module() -> BResult<TypedModule> {
let sink_at = at(fb, resident, sink_entry + roots::HOST)?;
let sink = load64(fb, t, sink_at)?;
let resident_count = view.count;
for (stage, table, slots, parent) in [
// Each stage with its words' index in the record (`layout::buffers`).
for (stage, index, table, slots, parent) in [
(
BufferStage::Vertex,
1u32,
vertex_table,
vertex_slots,
vertex_parent,
),
(
BufferStage::Fragment,
2,
fragment_table,
fragment_slots,
fragment_parent,
@@ -1309,6 +1325,8 @@ pub fn typed_module() -> BResult<TypedModule> {
let a = at(fb, table, sink_entry + field)?;
store64(fb, t, a, v)?;
}
let stage_index = k32(fb, index)?;
let stage_count = stage_count_of(fb, counts, stage_index)?;
count_loop(fb, t, slots, |fb, n| {
let n64 = wide(fb, t, n)?;
let two = k64(fb, 2)?;
@@ -1330,13 +1348,28 @@ pub fn typed_module() -> BResult<TypedModule> {
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
// The record's binding, below the stage's count; past it, the binding is zero (the
// loop over the bindings above), whose entry is null, unread.
let own: ArmFn<'_, ()> = Box::new(move |fb, _| {
own_entry(
fb,
(t, (resident, &view)),
(rec, stage, n64),
(runs, misses, entry),
)?;
let below = fb.binary(BinOp::ULessThan, n, stage_count)?;
let read: ArmFn<'_, ()> = Box::new(move |fb, _| {
own_entry(
fb,
(t, (resident, &view)),
(rec, stage, n64),
(runs, misses, entry),
)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
let null: ArmFn<'_, ()> = Box::new(move |fb, _| {
let zero64 = k64(fb, 0)?;
for field in [roots::HOST, roots::GUEST, roots::SIZE, roots::BIND_OFFSET] {
let a = at(fb, entry, field)?;
store64(fb, t, a, zero64)?;
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), below, read, Some(null))?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), inherit_buffers, inherited, Some(own))?;
@@ -130,12 +130,14 @@ fn word(bytes: &[u8], at: usize) -> u32 {
}
/// The storage header: `capacity`, the fault word, the policy bits of a render descriptor of
/// draws whose commands inherit the pipeline (and the buffers where `inherit_buffers`), and 4
/// vertex buffers and 2 fragment buffers.
/// draws whose commands inherit the pipeline (and the buffers where `inherit_buffers`), and the
/// packed binding counts `counts` (`layout::COUNTS`; [`clean`]'s: 4 vertex buffers and 2
/// fragment buffers).
struct Header {
capacity: u32,
fault: u32,
inherit_buffers: bool,
counts: u32,
}
/// What one preprocess left.
@@ -197,6 +199,18 @@ fn preprocess_in(
records: &[CommandRecord],
header: Header,
range: Option<[u32; 2]>,
) -> Ran {
let records: Vec<Vec<u8>> = records.iter().map(bytes).collect();
preprocess_raw(state, replay, &records, header, range)
}
/// [`preprocess_in`] over records' bytes as given.
fn preprocess_raw(
state: &BindState,
replay: &DrawReplay,
records: &[Vec<u8>],
header: Header,
range: Option<[u32; 2]>,
) -> Ran {
let dev = device();
let pre = draw_replay_preprocess(&dev, state, replay).expect("preprocess");
@@ -207,13 +221,12 @@ fn preprocess_in(
if header.inherit_buffers {
policy |= crate::indirect_commands::INHERIT_BUFFERS;
}
let counts: u32 = (4 << 8) | (2 << 16);
let mut storage = Vec::new();
for w in [header.capacity, header.fault, policy, counts] {
for w in [header.capacity, header.fault, policy, header.counts] {
storage.extend_from_slice(&w.to_le_bytes());
}
for r in records {
storage.extend_from_slice(&bytes(r));
storage.extend_from_slice(r);
}
let l = pre.layout;
let mut scratch = vec![0xEE; l.bytes as usize];
@@ -291,6 +304,7 @@ fn clean(capacity: u32) -> Header {
capacity,
fault: 0,
inherit_buffers: false,
counts: (4 << 8) | (2 << 16),
}
}
@@ -397,10 +411,7 @@ fn a_command_the_replay_cannot_run_draws_nothing_and_says_why() {
),
(barrier, ReplayFaults::BARRIER),
(piped, ReplayFaults::PIPELINE),
(
record(draw(3, 0, 3, [1, 0]), &[(4, A.0)], &[]),
ReplayFaults::RECORD,
),
(dynamic_fragment(1), ReplayFaults::RECORD),
];
for (bad, why) in cases {
let records = [
@@ -419,6 +430,67 @@ fn a_command_the_replay_cannot_run_draws_nothing_and_says_why() {
}
}
/// A draw whose fragment buffer `slot` is bound with a dynamic stride, which a fragment stage
/// takes none of: a record the host's validation refuses.
fn dynamic_fragment(slot: usize) -> CommandRecord {
let mut r = record(draw(3, 0, 3, [1, 0]), &[], &[]);
r.bindings.buffers_mut(BufferStage::Fragment)[slot] = Some(BufferBinding {
address: A.0,
attribute_stride: Some(7),
});
r
}
/// Write into `bytes`, a record's, at binding `slot` of `stage`, what no write of the record's
/// writers puts there: an address no resident allocation holds and a dynamic stride, which no
/// stage of these descriptors takes.
fn garbage(bytes: &mut [u8], stage: BufferStage, slot: usize) {
let at = (layout::buffers(stage) + slot as u64 * layout::BINDING) as usize;
bytes[at..at + 8].copy_from_slice(&0xABAB_ABAB_ABAB_ABABu64.to_le_bytes());
bytes[at + 8..at + 16].copy_from_slice(&7u64.to_le_bytes());
}
/// A command reads the bindings below each stage's count in the header alone: of a descriptor of
/// 2 vertex and 2 fragment buffers, 4 of the record's 128. A binding past its count is zero in
/// every record (the storage is made zero, an encoder's write there faults and writes nothing,
/// the CPU's setter refuses one, a copy takes a source of the same descriptor), so a record with
/// garbage in every such binding draws as one without, its slots null and no miss counted: those
/// bytes are not read. The negative control: the same garbage in a counted binding is a record the
/// host's validation refuses, and the command draws nothing.
#[test]
fn a_command_reads_only_the_bindings_its_descriptor_counts() {
let replay = DrawReplay::new(1, 0, 1, vec![3]);
let header = || Header {
counts: (2 << 8) | (2 << 16),
..clean(1)
};
let drawn = bytes(&record(draw(3, 0, 3, [1, 0]), &[(0, A.0)], &[(1, A.0)]));
let mut past = drawn.clone();
for slot in 0..BINDING_COUNT {
garbage(&mut past, BufferStage::Mesh, slot);
garbage(&mut past, BufferStage::Object, slot);
}
for slot in 2..BINDING_COUNT {
garbage(&mut past, BufferStage::Vertex, slot);
garbage(&mut past, BufferStage::Fragment, slot);
}
let ran = preprocess_raw(&state(), &replay, &[past], header(), None);
assert!(!ran.status.replay_fault, "{:?}", ran.status.replay_faults);
assert!(!ran.status.resident_miss);
assert_eq!(ran.args(0, 0), [3, 1, 0, 0]);
assert_eq!(ran.vertex(0, 0), [A.1, A.0, padded(A.2), 0]);
assert_eq!(ran.fragment(0, 1), [A.1, A.0, padded(A.2), 0]);
for slot in 2..BINDING_COUNT as u64 {
assert_eq!(ran.vertex(0, slot), [0; 4], "vertex {slot}");
assert_eq!(ran.fragment(0, slot), [0; 4], "fragment {slot}");
}
let mut counted = drawn;
garbage(&mut counted, BufferStage::Fragment, 1);
let ran = preprocess_raw(&state(), &replay, &[counted], header(), None);
assert_eq!(ran.status.replay_faults, ReplayFaults::RECORD);
assert_eq!(ran.args(0, 0), [0; 4]);
}
/// An address no resident allocation holds leaves its slot unbound and counts one resident miss
/// per such buffer, and the command still draws.
#[test]
+83 -10
View File
@@ -276,6 +276,27 @@ fn run_preprocess(
records: &[Vec<u8>],
(capacity, fault): (u32, u32),
planned: Option<generated::Planned>,
) -> Ran {
let storage = (capacity, fault, BINDING_COUNT as u32);
run_preprocess_counted(
dev,
limits,
(execution, variants),
records,
storage,
planned,
)
}
/// [`run_preprocess`] with the header's packed binding counts `counts` (`layout::COUNTS`: the
/// kernel buffers in byte 0); [`run_preprocess`]'s count every kernel binding.
fn run_preprocess_counted(
dev: &Device,
limits: [u32; 3],
(execution, variants): (&ReplayExecution, &[ReplayVariant]),
records: &[Vec<u8>],
(capacity, fault, counts): (u32, u32, u32),
planned: Option<generated::Planned>,
) -> Ran {
let pre = match planned {
None => replay_preprocess(dev, &state(), execution, variants),
@@ -285,6 +306,7 @@ fn run_preprocess(
let mut storage = vec![0u8; COMMAND_BUFFER_HEADER_BYTES];
storage[..4].copy_from_slice(&capacity.to_le_bytes());
storage[4..8].copy_from_slice(&fault.to_le_bytes());
storage[12..16].copy_from_slice(&counts.to_le_bytes());
for r in records {
storage.extend_from_slice(r);
}
@@ -495,6 +517,65 @@ fn the_layout_keeps_every_section_apart() {
);
}
/// Write into `bytes`, a record's, at binding `slot` of `stage`, what no write of the record's
/// writers puts there: an address no resident allocation holds and a dynamic stride, which the
/// descriptor does not enable.
fn garbage(bytes: &mut [u8], stage: BufferStage, slot: usize) {
let at = (layout::buffers(stage) + slot as u64 * layout::BINDING) as usize;
bytes[at..at + 8].copy_from_slice(&0xABAB_ABAB_ABAB_ABABu64.to_le_bytes());
bytes[at + 8..at + 16].copy_from_slice(&7u64.to_le_bytes());
}
/// A command reads the kernel bindings below the header's count alone: of a descriptor of 2
/// kernel buffers, 2 of the record's 128 bindings. A binding past the count, or of another stage,
/// is zero in every compute record (the storage is made zero, an encoder's write past the count
/// faults and writes nothing, the CPU's setter refuses one, a compute command has no other
/// stage's setter, a copy takes a source of the same descriptor), so a record with garbage in
/// every such binding dispatches as one without, its slots null and no miss counted: those bytes
/// are not read. The negative control: the same garbage in a counted binding refuses the command.
#[test]
fn a_command_reads_only_the_kernel_bindings_its_descriptor_counts() {
let dev = device();
let variants = [variant(TOKEN, [8, 1, 1], 32)];
let execution = ReplayExecution::new(1, 0, 1);
let limits = dev.profile().fields().limits.max_compute_work_group_count;
let run = |record: Vec<u8>| {
let ev = (&execution, &variants[..]);
run_preprocess_counted(&dev, limits, ev, &[record], (1, 0, 2), None)
};
let dispatched = record(
groups([3, 2, 1], [8, 1, 1]),
Some(TOKEN),
&[(0, A.0), (1, B.0)],
32,
);
let mut past = dispatched.clone();
for stage in [
BufferStage::Vertex,
BufferStage::Fragment,
BufferStage::Object,
] {
for slot in 0..BINDING_COUNT {
garbage(&mut past, stage, slot);
}
}
for slot in 2..BINDING_COUNT {
garbage(&mut past, BufferStage::Kernel, slot);
}
let ran = run(past);
assert_eq!(ran.status.replay_faults, ReplayFaults::default());
assert!(!ran.status.resident_miss);
assert_eq!(ran.args(0, 0), [3, 2, 1]);
for slot in 2..BINDING_COUNT as u64 {
assert_eq!(ran.entry(0, 2 + slot), [0; 4], "kernel {slot}");
}
let mut counted = dispatched;
garbage(&mut counted, BufferStage::Kernel, 1);
let ran = run(counted);
assert_eq!(ran.status.replay_faults, ReplayFaults::BUFFERS);
assert_eq!(ran.args(0, 0), [0; 3]);
}
#[test]
fn a_dispatch_selects_its_variant_and_resolves_its_buffers() {
let dev = device();
@@ -863,14 +944,6 @@ fn a_command_no_variant_replays_dispatches_nothing_and_says_why() {
};
execution.parent_pipeline = Some(token(TOKEN));
let inheriting = || record(groups([2, 1, 1], local), None, &[], 32);
let mut vertex = CommandRecord {
action: groups([2, 1, 1], local),
..CommandRecord::default()
};
vertex.bindings.buffers_mut(BufferStage::Vertex)[5] = bind(B.0);
vertex.threadgroup_memory_lengths = lengths(32);
let mut vertex_bytes = vec![0u8; COMMAND_BYTES];
vertex.encode_into(&mut vertex_bytes).expect("record");
for (name, bad, faults) in [
(
"a pipeline set while inherited",
@@ -878,8 +951,8 @@ fn a_command_no_variant_replays_dispatches_nothing_and_says_why() {
ReplayFaults::PIPELINE.0,
),
(
"a vertex buffer set while inherited",
vertex_bytes,
"a kernel buffer set while inherited",
record(groups([2, 1, 1], local), None, &[(5, B.0)], 32),
ReplayFaults::BUFFERS.0,
),
] {
+2 -2
View File
@@ -61,7 +61,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2110;
pub const SEMANTICS_VERSION: u32 = 2111;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2295;
pub const RUNTIME_VERSION: u32 = 2296;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
+94 -28
View File
@@ -36,8 +36,11 @@
//! where the record keeps it, under its own action; a barrier (of a compute or a render command)
//! its flag (set or cleared); a threadgroup-length setter the length at its binding, as set (a
//! multiple of 16 or not, as Metal keeps it); a stage-in region setter its six words; an imageblock
//! size setter its two `u16`s; and a reset (of a compute or render command) the whole record as
//! `CommandRecord::default` encodes it, in a loop of `u64` stores. A valid operation (a copy too)
//! size setter its two `u16`s; and a reset (of a compute or render command) the record as
//! `CommandRecord::default` encodes it, in loops of `u64` stores over its command words, the
//! bindings below each stage's count in the header and the words past the bindings: a binding
//! past its count is zero in every record, as no write reaches one (`default_record`). A valid
//! operation (a copy too)
//! also stores 1 at its command's written flag past every record
//! (`indirect_commands::written_flag_offset`), contained as its fields are.
//!
@@ -67,8 +70,9 @@ use crate::device::profile::BufferAccess;
use crate::device::requirements::VkFeature;
use crate::error::{Capability, Error, Feature, Unsupported};
use crate::indirect_commands::{
layout, BufferStage, CommandEncoderOperation, Policy, DYNAMIC_STRIDE, INHERIT_BUFFERS,
INHERIT_PIPELINE, RECORDS_ADDRESS_BASE, RECORDS_ADDRESS_SHIFT, WRITTEN_FLAG_BYTES,
layout, BufferStage, CommandEncoderOperation, Policy, BINDING_COUNT, DYNAMIC_STRIDE,
INHERIT_BUFFERS, INHERIT_PIPELINE, RECORDS_ADDRESS_BASE, RECORDS_ADDRESS_SHIFT,
WRITTEN_FLAG_BYTES,
};
use crate::lower::arith::{Form, Held};
use crate::lower::emit::EmitCx;
@@ -206,9 +210,10 @@ impl EncodeStrategy {
/// An upper estimate of the SPIR-V words one use emits: a word load is a leaf access; an
/// operation is a search call, the record's root entry, three header loads and the policy test,
/// and per field a contained store (a reset's loop: its one store and the loop's own words,
/// `RESET_WORDS`; a copy's: its load and store, the loop's words, and the source's search,
/// header loads and tests, `COPY_WORDS`).
/// and per field a contained store (a reset's loops: each its one store and the loop's own
/// words, and its counts' header load and each stage's count, `RESET_WORDS`; a copy's: its
/// load and store, the loop's words, and the source's search, header loads and tests,
/// `COPY_WORDS`).
pub fn words(&self) -> u32 {
match self {
EncodeStrategy::Word(s) => s.words(),
@@ -249,14 +254,18 @@ impl EncodeStrategy {
const COMMAND_WORDS: u32 = dynamic::BASE_WORDS + 40 + 4 * FIELD_WORDS + 160;
/// SPIR-V words of one contained field access.
const FIELD_WORDS: u32 = 72;
/// SPIR-V words of a reset's loop beyond its store: the counter, the exit test, the stride test
/// and its select, the loop's blocks, and a compute reset's retained pipeline (its load, and the
/// tests and selects that keep it).
const RESET_WORDS: u32 = 96 + FIELD_WORDS + 48;
/// SPIR-V words of a loop over a record's `u64`s beyond its store: the counter, the exit test, the
/// stride test and its select, the loop's blocks, and a compute reset's retained pipeline (its
/// load, and the tests and selects that keep it).
const LOOP_WORDS: u32 = 96 + FIELD_WORDS + 48;
/// SPIR-V words of a reset beyond its store: its loops (the command's words, the words past the
/// bindings, and a render command's four stages' bindings), the counts' header load, and each
/// stage's count (its shift, mask, clamp and bounds).
const RESET_WORDS: u32 = 6 * LOOP_WORDS + FIELD_WORDS + 4 * 40;
/// SPIR-V words of a copy beyond its load and store: the source's search call, root entry, four
/// header loads, and its pipeline and state loads, the descriptor and pipeline tests, and the loop
/// with its kept-state test and selection.
const COPY_WORDS: u32 = dynamic::BASE_WORDS + 24 + 6 * FIELD_WORDS + 156 + RESET_WORDS + 64;
const COPY_WORDS: u32 = dynamic::BASE_WORDS + 24 + 6 * FIELD_WORDS + 156 + LOOP_WORDS + 64;
/// Whether `class` is an indirect-command object's.
fn object_class(class: HandleClass) -> bool {
@@ -940,7 +949,10 @@ fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Comma
// A compute command's reset keeps the pipeline it executes with, reported cleared; a
// render command's is unmeasured and clears it.
let retain = matches!(c.op, CommandEncoderOperation::Reset { render: false });
reset = Some((record, retain));
let render = matches!(c.op, CommandEncoderOperation::Reset { render: true });
// The bindings it clears are those the descriptor counts (`default_record`).
let counts = header(cx, fb, b, layout::COUNTS)?;
reset = Some((record, retain, render, counts));
}
Fields::Copy {
source,
@@ -1113,8 +1125,8 @@ fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Comma
for (to, v, leaf) in writes {
dynamic::wide_at(fb, b, Some(to), &leaf, Some(v))?;
}
if let Some((record, retain)) = reset {
default_record(cx, fb, b, record, retain)?;
if let Some((record, retain, render, counts)) = reset {
default_record(cx, fb, b, (record, retain), (render, counts))?;
}
if let Some(from) = copy {
copy_record(cx, fb, b, record, from)?;
@@ -1144,16 +1156,36 @@ fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Comma
/// stride.
const FIRST_BINDING: u32 = (layout::buffers(BufferStage::Kernel) / 8) as u32;
const PAST_BINDINGS: u32 = FIRST_BINDING + (layout::ALL_BINDINGS * layout::BINDING / 8) as u32;
/// The `u64`s of one binding: its address and its stride.
const BINDING_DOUBLES: u32 = (layout::BINDING / 8) as u32;
/// The record's pipeline `u64`, and the one its state word lies alone in.
const PIPELINE_DOUBLE: u32 = (layout::PIPELINE / 8) as u32;
const STATE_DOUBLE: u32 = (layout::STATE / 8) as u32;
/// The `u64`s of a record.
const DOUBLES: u32 = (layout::RECORD / 8) as u32;
/// Emit `each` for every `u64` of a record, its index `j` (a `u32`) counted in a loop.
fn each_double<'c, F>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, each: F) -> BResult<()>
where
F: FnOnce(&mut EmitCx<'c>, &mut FunctionBuilder<'_>, SValue) -> BResult<()>,
{
const DOUBLES: u32 = (layout::RECORD / 8) as u32;
let from = k32(fb, 0)?;
let to = k32(fb, DOUBLES)?;
each_double_in(cx, fb, (from, to), each)
}
/// Emit `each` for the `u64`s of a record from index `from` to `to` (each a `u32`), its index `j`
/// counted in a loop.
fn each_double_in<'c, F>(
cx: &mut EmitCx<'c>,
fb: &mut FunctionBuilder<'_>,
(from, to): (SValue, SValue),
each: F,
) -> BResult<()>
where
F: FnOnce(&mut EmitCx<'c>, &mut FunctionBuilder<'_>, SValue) -> BResult<()>,
{
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
@@ -1166,12 +1198,10 @@ where
let counter = fb.var_ptr(var)?;
// The variable is initialized once, at the function's entry: a loop over a record in a loop
// starts over.
let start = k32(fb, 0)?;
fb.store(counter, start, MemAccess::default())?;
fb.store(counter, from, MemAccess::default())?;
let body: LoopFn<'_, EmitCx<'c>> = Box::new(move |fb, cx, lc| {
let j = fb.load(counter, MemAccess::default())?;
let n = k32(fb, DOUBLES)?;
let done = fb.binary(BinOp::UGreaterThanEqual, j, n)?;
let done = fb.binary(BinOp::UGreaterThanEqual, j, to)?;
let exit: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, _| {
lc.break_(fb)?;
Ok(ArmEnd::Exits)
@@ -1186,16 +1216,25 @@ where
}
/// Write the default record (`CommandRecord::default`'s encoding) at displacement `record` of the
/// record buffer `b`: zero in every `u64` of the record, a buffer binding's address and stride
/// too, as Metal's reset clears them, in a loop. Where `retain`, a compute command's reset, the
/// pipeline word keeps the pipeline the command executes with, and the state word flags it retained
/// when there is one (`layout::RETAINED`).
/// record buffer `b`: zero in every `u64` of the record that a command may have set, a buffer
/// binding's address and stride too, as Metal's reset clears them, in loops: the command's words,
/// the bindings below each stage's count in the header's packed `counts` (`layout::COUNTS`: of a
/// `render` command's mesh, vertex, fragment and object stages, bytes 3, 1, 2 and 0; of a compute
/// command's kernel buffers, byte 0), and the words past the bindings (the threadgroup lengths, an
/// indexed patch draw's control-point indices, the imageblock size and the state word). A binding
/// past its stage's count is zero already, and is not written: the storage is made zero, an
/// encoder's write past the count faults and writes nothing, the CPU's setter refuses one, a
/// compute command has no other stage's setter, and a copy takes a source of the same descriptor.
/// So a reset writes the record's 64-byte head, 136-byte tail and 16 bytes a counted binding,
/// where it wrote all 2248 bytes. Where `retain`, a compute command's reset, the pipeline word
/// keeps the pipeline the command executes with, and the state word flags it retained when there
/// is one (`layout::RETAINED`).
fn default_record(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
b: dynamic::WideBase,
record: SValue,
retain: bool,
(record, retain): (SValue, bool),
(render, counts): (bool, SValue),
) -> BResult<()> {
let retained = if retain {
let field = k64(fb, layout::PIPELINE)?;
@@ -1211,7 +1250,7 @@ fn default_record(
} else {
None
};
each_double(cx, fb, move |_, fb, j| {
let clear = move |fb: &mut FunctionBuilder<'_>, j: SValue| -> BResult<()> {
let mut v = k64(fb, 0)?;
if let Some((token, state)) = retained {
let pipeline = k32(fb, PIPELINE_DOUBLE)?;
@@ -1225,7 +1264,34 @@ fn default_record(
let to = fb.binary(BinOp::IAdd, record, to)?;
dynamic::wide_at(fb, b, Some(to), &DOUBLE, Some(v))?;
Ok(())
})
};
// The command's words, then the words past the bindings.
for (from, to) in [(0, FIRST_BINDING), (PAST_BINDINGS, DOUBLES)] {
let from = k32(fb, from)?;
let to = k32(fb, to)?;
each_double_in(cx, fb, (from, to), move |_, fb, j| clear(fb, j))?;
}
// Each stage's bindings below its count (at most `BINDING_COUNT`), two `u64`s a binding.
let stages: &[(u32, u32)] = match render {
true => &[(0, 3), (1, 1), (2, 2), (3, 0)],
false => &[(0, 0)],
};
for &(stage, byte) in stages {
let shift = k32(fb, 8 * byte)?;
let count = fb.binary(BinOp::ShiftRightLogical, counts, shift)?;
let mask = k32(fb, 0xff)?;
let count = fb.binary(BinOp::BitwiseAnd, count, mask)?;
let most = k32(fb, BINDING_COUNT as u32)?;
let over = fb.binary(BinOp::UGreaterThan, count, most)?;
let count = fb.select(over, most, count)?;
let per = k32(fb, BINDING_DOUBLES)?;
let doubles = fb.binary(BinOp::IMul, count, per)?;
let first = FIRST_BINDING + stage * BINDING_COUNT as u32 * BINDING_DOUBLES;
let from = k32(fb, first)?;
let to = fb.binary(BinOp::IAdd, from, doubles)?;
each_double_in(cx, fb, (from, to), move |_, fb, j| clear(fb, j))?;
}
Ok(())
}
/// Copy the source's record `from` onto the record at displacement `record` of the record buffer
@@ -30,9 +30,9 @@ use crate::device::profile::{BufferAccess, DeviceProfile, GuestIsolation};
use crate::error::{Error, Feature, Needs, Unsupported};
use crate::indirect_commands::written_flag_offset;
use crate::indirect_commands::{
Action, BufferBinding, BufferStage, CommandBuffer, CommandBufferError, CommandDescriptor,
CommandRecord, ComputeDispatch, Inheritance, RenderDraws, StateSource,
COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES, WRITTEN_FLAG_BYTES,
layout, Action, BufferBinding, BufferStage, CommandBuffer, CommandBufferError,
CommandDescriptor, CommandRecord, ComputeDispatch, Inheritance, RenderDraws, StateSource,
BINDING_COUNT, COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES, WRITTEN_FLAG_BYTES,
};
use crate::lower::select::Plan;
use crate::pipeline::interface::PushLoc;
@@ -818,6 +818,115 @@ fn encoded_render_records_round_trip_through_the_host_contract() {
}
}
/// Each thread `t` resets command `t` (`air.reset_render_command`) where `reset`, else reads and
/// writes nothing.
fn render_reset_kernel(reset: bool) -> String {
let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state");
let body = match reset {
true => {
"%pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0
%cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8
call void @air.reset_render_command(ptr addrspace(1) %cmd, i32 %t)"
}
false => "",
};
format!(
r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }}
define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{
entry:
{body}
ret void
}}
declare void @air.reset_render_command(ptr addrspace(1), i32)
{meta}"#
)
}
/// A GPU reset clears what a command may have set and nothing else: its command words, the
/// bindings below each stage's count in the header, and the words past the bindings
/// (`default_record`). Every record starts holding a draw, a barrier, a vertex and a fragment
/// binding below the counts (2 and 2), and threadgroup-length words; each byte of a binding past
/// the counts (vertex 2, fragment 2, every object and mesh one) holds a mark, which no writer of
/// the records puts there. After the reset every byte below the counts and of the words reads zero,
/// and every mark stands: the reset wrote 64 + 4 x 16 + 136 bytes of each record, not 2248. The
/// negative control: the same storage under a kernel that does not reset keeps every stale byte,
/// so the zeros are the reset's.
#[test]
fn a_reset_clears_the_command_words_and_the_counted_bindings_alone() {
let descriptor = CommandDescriptor::Render {
draws: RenderDraws::PRIMITIVES,
max_vertex_buffer_bind_count: 2,
max_fragment_buffer_bind_count: 2,
max_object_buffer_bind_count: 0,
max_mesh_buffer_bind_count: 0,
support_dynamic_attribute_stride: false,
};
const MARK: u8 = 0xab;
let binding = |stage, slot: usize| {
let at = (layout::buffers(stage) + slot as u64 * layout::BINDING) as usize;
at..at + layout::BINDING as usize
};
// Each record's ranges a reset clears, and the marked ones it leaves.
let words = 0..layout::buffers(BufferStage::Kernel) as usize;
let mut cleared = vec![words];
let mut marked = Vec::new();
for slot in 0..BINDING_COUNT {
let below = slot < 2;
for stage in [BufferStage::Vertex, BufferStage::Fragment] {
match below {
true => cleared.push(binding(stage, slot)),
false => marked.push(binding(stage, slot)),
}
}
marked.push(binding(BufferStage::Mesh, slot));
marked.push(binding(BufferStage::Object, slot));
}
cleared.push(layout::THREADGROUP as usize..COMMAND_BYTES);
let mut stale = storage(&descriptor, OWNED);
for t in 0..THREADS as usize {
let record = COMMAND_BUFFER_HEADER_BYTES + t * COMMAND_BYTES;
for range in &cleared {
stale[record + range.start..record + range.end].fill(0x5a);
}
for range in &marked {
stale[record + range.start..record + range.end].fill(MARK);
}
}
for (reset, stem) in [(true, "reset"), (false, "unreset")] {
let Some(runs) = compiled(stem, &render_reset_kernel(reset)) else {
return;
};
for (profile, _, plan, m) in &runs {
let run = run_encoder(plan, m, stale.clone(), &[], true)
.unwrap_or_else(|e| panic!("{profile}: {e}"));
for t in 0..THREADS as usize {
let record = COMMAND_BUFFER_HEADER_BYTES + t * COMMAND_BYTES;
let bytes = &run.records[record..record + COMMAND_BYTES];
for range in &cleared {
let want = match reset {
true => 0,
false => 0x5a,
};
let got = &bytes[range.clone()];
assert!(
got.iter().all(|&b| b == want),
"{profile} {stem} {t} {range:?}"
);
}
for range in &marked {
let got = &bytes[range.clone()];
assert!(
got.iter().all(|&b| b == MARK),
"{profile} {stem} {t} {range:?}"
);
}
}
}
}
}
/// `line` without the `i64` operand of its buffer setter: a declaration's `, i64` or a call's
/// `, i64 <value>`.
fn drop_stride(line: &str) -> String {