Runtime: whether a declaration covers a held attachment is settled as declarations and moves are made, and a draw tests it alone

What: Declarations::held answers whether a read declaration of the encoder covers an attachment
or resolve its pass holds out of its home layout (Pass::held). use_resource sets it for a read
of a held attachment's hazard id (the texture, a view of its image, or the buffer it lies over
in place), use_heap for a new heap a held attachment lies in, and the feedback moves for a
newly held attachment an earlier declaration covers. A draw counts in
Metrics::unslotted_attachment_reads where the answer is set and it may read beyond its slots
(its pipeline reads unbound, or an indirect command buffer's execution), testing the flag first,
in place of the walk of the pass's attachments against the declarations that every draw ran.
The answer only grows within an encoder: declarations are never withdrawn (a re-declaration
merges accesses), an attachment's layout leaves home only through the feedback moves and returns
only at the encoder's end, and a new pass is a new encoder with no declarations, so it equals
the walk's at every draw. The README's encoder-call contract says so.

Why: 78998777a2 moved the check into every draw and cost draw_2000 11.0 user-space instructions
a draw on the encoding thread, though no draw of it reads beyond its slots. Measured with a
probe harness (not landed) that counts the harness thread's instructions over each draw call
alone, 20 runs x 2 rounds per arm, order reversed in the second, RTX 5080 Laptop (NVIDIA
615.71.09, no layer), job m3-max-73399: ec9e2771d0 1,002.8 a draw (runs 1,002.8-1,003.0),
2c95b330e5 1,001.9 (3b76e461a2 alone does not build), 78998777a2 1,012.8, 205c8d2398 1,012.8,
205c8d2398 with 78998777a2 reverted 1,001.9; bind_2000 2,123.2 / 2,131.2 the same way. A
pipeline that reads beyond its slots paid the whole walk on every draw.

Budget: the test every_device_walks_no_attachment_at_a_draw_after_no_change counts the walks of
the pass's attachments (pass::TARGET_WALKS, test builds only) over 64 draws after the first since
a change: none for a pipeline that reads nothing beyond its slots, before and after the target is
declared read, and none for the argument-buffer pipeline, whose 65 draws each count one
unslotted attachment read. Without the change the last 64 draws walk 64 times.

How verified: the job ids of the check, the 5080 instruction arms and the AMD held_loop_reads leg
are in the lane's report to the lander.
This commit is contained in:
Anees Iqbal committed 2026-11-24 01:16:11 -08:00
1 parent 99293cc265
commit 6047a2d8b6
4 files changed
+164 -20

No files matched your search

+5 -3
View File
@@ -5059,9 +5059,11 @@ the pipeline state and the bound resources, and counts into the encoder's own ta
device's counters take once, at the encoder's end. What a draw or a dispatch learns from its
bindings (the vertex buffers it binds, the alignments it checks, whether it reads an attachment,
reaches a Managed buffer's device copy or writes what the host reads) it works out again only
after the pipeline state or a binding changes. On RADV a recorded command lies in write-combining
memory, and a locked instruction between two of them flushes it: a draw took about 490 ns more on
a Radeon RX 7900 XTX with one.
after the pipeline state or a binding changes. Whether a declaration of the encoder covers an
attachment its pass holds out of its home layout (`Metrics::unslotted_attachment_reads`) is
settled as each declaration and each move of an attachment is made, and a draw tests that answer
alone. On RADV a recorded command lies in write-combining memory, and a locked instruction between
two of them flushes it: a draw took about 490 ns more on a Radeon RX 7900 XTX with one.
## Floor
+15
View File
@@ -632,12 +632,16 @@ pub(crate) struct Pass {
thread_local! {
/// The walks of a pass's resolves ([`Pass::resolves`]) on this thread, which a test reads.
pub(crate) static RESOLVE_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// The walks of a pass's attachments ([`Pass::targets`]) on this thread, which a test reads.
pub(crate) static TARGET_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
impl Pass {
/// Every attachment's image once, colors first: the stencil attachment's only where there is
/// no depth attachment, whose image it otherwise is.
pub(crate) fn targets(&self) -> impl Iterator<Item = &Target> {
#[cfg(test)]
TARGET_WALKS.with(|walks| walks.set(walks.get() + 1));
let stencil = self.stencil.as_ref().filter(|_| self.depth.is_none());
(self.colors.iter().flatten())
.chain(&self.depth)
@@ -659,6 +663,17 @@ impl Pass {
.chain(stencil)
}
/// The texture of every attachment and resolve the pass holds out of its home layout: the
/// attachment layout of a shader-read one, or the feedback layout once a draw of the pass read
/// it through a slot. A pass that resolves nothing walks no resolve.
pub(crate) fn held(&self) -> impl Iterator<Item = &Texture> {
let resolves = (self.resolving.then(|| self.resolves()))
.into_iter()
.flatten();
(self.targets().filter(|t| t.moves()).map(|t| &t.texture))
.chain(resolves.filter(|r| r.moves()).map(|r| &r.texture))
}
/// Records `vkCmdBeginRendering` of the pass into `command`; `resumed`, again after the
/// encoder ended it early, loading what it stored.
///
@@ -595,6 +595,13 @@ struct Declarations {
unstored_write: Option<StorageGap>,
/// The heaps' blocks `use_heap` declared, each once.
heaps: Vec<BlockId>,
/// A read declaration covers an attachment the pass holds out of its home layout
/// ([`Pass::held`]): a draw that may read beyond its slots then counts in
/// [`Metrics::unslotted_attachment_reads`](crate::Metrics::unslotted_attachment_reads).
/// Settled as a declaration is made and as an attachment moves to the feedback layout, so a
/// draw tests it alone; once set it holds for the pass, whose declarations and moves last
/// until its end.
held: bool,
}
impl Declarations {
@@ -1747,6 +1754,9 @@ impl RenderCommandEncoder {
t.layout = looped;
}
}
// A read declaration that covers an attachment now held out of its home layout.
let held = (self.pass.held()).any(|attachment| self.declared.reads(attachment));
self.declared.held |= held;
self.moved.extend(moves.into_iter().map(|m| m.moved));
self.push_filled = false;
(self.drew, self.owed) = (false, false);
@@ -1996,7 +2006,12 @@ impl RenderCommandEncoder {
let Some(access) = usage.access() else {
return Ok(());
};
// A read of an attachment the pass holds out of its home layout: of it, of a view of its
// image or of the buffer it lies over in place, all of which name its hazard id.
let held =
access.reads() && (self.pass.held()).any(|attachment| attachment.hazard_id() == id[0]);
let declared = &mut self.declared;
declared.held |= held;
declared.host_write |= access.writes() && host;
if access.writes() && declared.unstored_write.is_none() {
declared.unstored_write = unstored;
@@ -2030,6 +2045,9 @@ impl RenderCommandEncoder {
building.keep_block(&block);
if !self.declared.heaps.contains(&heap) {
self.declared.heaps.push(heap);
// An attachment in the heap that the pass holds out of its home layout.
self.declared.held |= (self.pass.held())
.any(|attachment| TextureObject::object(attachment).heap_block() == Some(heap));
}
Ok(())
}
@@ -2529,7 +2547,6 @@ impl RenderCommandEncoder {
|| arguments.is_some_and(|buffer| buffer.managed_overs().is_some())
|| factors.is_some_and(|(buffer, _)| buffer.managed_overs().is_some())
|| overs;
let unbound = draws.reads_unbound || commands;
self.draw_aliases()?;
match each {
true => self.draw_reaches(reads, [index_buffer, arguments], overs, commands)?,
@@ -2541,20 +2558,15 @@ impl RenderCommandEncoder {
self.overs_after(commands);
}
}
// A draw that may read beyond its slots, while a declared read covers an attachment the
// pass holds out of its home layout once the draw's own moves are recorded: such a read
// names the texture's own element, whose layout is the home one
// (`Metrics::unslotted_attachment_reads`).
let unslotted = unbound && {
let pass = &self.pass;
let resolves = (pass.resolving.then(|| pass.resolves()))
.into_iter()
.flatten();
(pass.targets())
.map(|t| (&t.texture, t.moves()))
.chain(resolves.map(|r| (&r.texture, r.moves())))
.any(|(texture, moved)| moved && self.declared.reads(texture))
};
// A draw that may read beyond its slots while a read declaration covers an attachment the
// pass holds out of its home layout, the draw's own moves included: such a read names the
// texture's own element, whose layout is the home one
// (`Metrics::unslotted_attachment_reads`). The declarations settle the fact as they and
// the moves are made, so a draw tests it alone.
let unslotted = self.declared.held
&& (commands
|| (self.pipeline.as_ref())
.is_some_and(|state| state.inner.compiled.draws.reads_unbound));
let building = (self.building.as_mut())
.expect("an encoder holds its command buffer's recording until it ends");
if unslotted {
@@ -16,6 +16,7 @@
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::pass::TARGET_WALKS;
use crate::tests::blit::on_device::settled;
use crate::tests::command::on_device::each_device;
use crate::tests::draw::on_device::{
@@ -23,10 +24,11 @@ mod on_device {
};
use crate::{
ColorAttachmentDescriptor, FunctionDescriptor, HostBytes, IndexClass, PixelFormat,
PrimitiveType, Region, RenderPipelineDescriptor, Resource, ResourceUsage,
SamplerDescriptor, StageSource,
PrimitiveType, Region, RenderCommandEncoder, RenderPipelineDescriptor, Resource,
ResourceUsage, SamplerDescriptor, StageSource,
};
use metal2vulkan_devtools::engine_dir;
use std::cell::Cell;
/// The attachment's index (the control texture's the next), and the sampler's.
const TEXTURE: u32 = 4096;
@@ -176,4 +178,117 @@ mod on_device {
}
});
}
/// The draws after the first since a change walk none of their pass's attachments
/// (`crate::pass::TARGET_WALKS`): whether a draw counts in
/// `Metrics::unslotted_attachment_reads` is settled as the encoder's declarations and its
/// pass's moves are made, and a draw tests it alone. In a pass over a shader-read render
/// target, which the pass holds in the attachment layout: draws of a pipeline state whose
/// functions read nothing beyond their slots, before the target is declared read and after,
/// count none; draws of the argument-buffer pipeline state, which may read beyond its slots,
/// count one each.
#[test]
fn every_device_walks_no_attachment_at_a_draw_after_no_change() {
const DRAWS: u64 = 64;
let (Some(examples), Some(engine)) =
(examples(), library(&engine_dir().join("resident_draws.ll")))
else {
return;
};
let plain = descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm);
let function = |name| {
StageSource::Function(FunctionDescriptor::new(
engine.function(name).expect("the function"),
))
};
let mut held = RenderPipelineDescriptor::new(function("rd_entry_vertex"));
held.fragment = Some(function("rd_entry_fragment"));
held.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
each_device("held_read_walks", |name, _, device| {
if !device.core().attachment_reads {
println!("{name}: SKIPPED: the device reads no attachment through a texture");
return;
}
let _grants = [
(IndexClass::Texture, TEXTURE, 1),
(IndexClass::Sampler, SAMPLER, 1),
]
.map(|(class, first, count)| {
(device.grant_indices(class, first, count))
.unwrap_or_else(|error| panic!("{name}: {error}"))
});
let plain = state(name, &device, &plain);
let held = state(name, &device, &held);
let color = readable(&device, PixelFormat::RGBA8Unorm, 1, TEXTURE);
let sampler = (device.new_sampler_state(&SamplerDescriptor::new(), SAMPLER))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut buffers = Buffers::new(&device);
let whole = buffers.of(&device, &floats(&[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]));
let colors = buffers.of(&device, &floats(&[0.0; 12]));
let position = buffers.of(&device, &floats(&[0.0, 0.0, 0.0, 1.0]));
let words = [
position.gpu_address(),
color.gpu_resource_id().to_bits(),
sampler.gpu_resource_id().to_bits(),
];
let bytes: Vec<u8> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
let entry = buffers.of(&device, &bytes);
let queue = device.new_command_queue(4).expect("a queue");
// The upload that moves the new target to its home layout, in a submission apart.
let upload = queue.command_buffer().expect("a command buffer");
(upload.record_for_test(&[], |_, _| {})).expect("a command buffer's commands");
run(name, &upload);
let counters = device.counters();
settled(&device);
let before = counters.metrics();
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let draw = |result: Result<(), crate::Error>| {
result.unwrap_or_else(|error| panic!("{name}: {error}"))
};
// A draw, then `DRAWS` more with nothing changed, and the attachment walks of those.
let after_first = |encoder: &mut RenderCommandEncoder| {
draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
let walks = || TARGET_WALKS.with(Cell::get);
let start = walks();
for _ in 0..DRAWS {
draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
}
walks() - start
};
draw(encoder.set_vertex_buffer(Some(&whole), 0, 0));
draw(encoder.set_vertex_buffer(Some(&colors), 0, 1));
draw(encoder.set_render_pipeline_state(&plain));
let undeclared = after_first(&mut encoder);
draw(encoder.use_resource(Resource::Texture(&color), ResourceUsage::READ));
draw(encoder.use_resource(Resource::Buffer(&position), ResourceUsage::READ));
let declared = after_first(&mut encoder);
draw(encoder.set_vertex_buffer(Some(&entry), 0, 0));
draw(encoder.set_fragment_buffer(Some(&entry), 0, 0));
draw(encoder.set_render_pipeline_state(&held));
let unbound = after_first(&mut encoder);
encoder.end_encoding();
run(name, &command_buffer);
let after = counters.metrics();
let unslotted = after.unslotted_attachment_reads - before.unslotted_attachment_reads;
println!(
"held-read-walks: {name}: attachment walks of {DRAWS} draws after the first: \
{undeclared} before the target's read declaration, {declared} after it, \
{unbound} of the argument-buffer pipeline state; unslotted attachment reads \
{unslotted}"
);
assert_eq!(
[undeclared, declared, unbound],
[0; 3],
"{name}: the attachments walked by {DRAWS} draws after the first: before the \
target's read declaration, after it, and of the argument-buffer pipeline state"
);
assert_eq!(
unslotted,
DRAWS + 1,
"{name}: the unslotted attachment reads, one a draw of the argument-buffer state"
);
});
}
}