Count a pass's tiles only where a count or a clear reads them

A render pass's end worked out two things about the tiles its draws reach at every pass,
whatever read them:

- the count of the 32-pixel tiles its draws' scissors cover against their bounding rectangle
  (`DrawnArea::covered_tiles`), computed at every pass's first instance before `count_colors`
  looked for a shadowed color attachment, where it feeds only
  `shadow_attachment_tiles_covered` and `_bounded`, counted for a shadowed color the pass loads
  within its draws' scissors; and
- the grid of the tiles the draws reach (`DrawnArea::tiles`), made at every pass whose draws
  reach the tiles their primitives touch, where only a `DontCare` load given a clear reads it
  (`ReachClears::plan`); elsewhere only whether it is empty mattered.

Now `count_colors` counts the tiles at the first shadowed color loaded within, once a pass;
the pass end asks whether the rectangles reach any tile with a scan of them
(`DrawnArea::reaches_no_tile`, no grid made) and makes the grid only for a `DontCare` load it
answered. The count itself goes by bands of rows between the rectangles' edges, setting a row's
tiles a word at a time, where it went row by row and tile by tile. The counters keep their
meaning and their values; the commands recorded are the same.

A compositor-shaped command buffer (35 draws in 6 passes, one 3840x2400 framebuffer pass) on
the M3 Max over MoltenVK, release, flat out, cache surfaces (no shadowed attachment), two
interleaved runs of 5000 buffers each:

  end_encoding p50/p95/mean us: before 6.71/33.67/11.36 and 7.75/43.50/13.18,
                                after  5.75/7.79/5.94  and 5.96/7.83/6.05

The count was 49% of `end_encoding`'s CPU samples before. The work counts per buffer are the
same, with surfaces over host pages too (`shadow_attachment_tiles_bounded` 2597, `_covered`
2308 per buffer, as before).

Verified: `clear_reach` unit tests, the count checked against tiles counted one at a time over
200 sets of rectangles, and the scan against the grid; a device test
(`tests/pass_end_tiles.rs`, `--cfg m2v_gpu`, MoltenVK) counts the tile work done on the
encoding thread: none for a pass with no shadowed attachment, loaded or cleared, one grid for a
`DontCare` load, one count for a shadowed attachment it loads. With the eager work put back the
test fails (covered 1, grids 1 for the loaded pass).

(cherry picked from commit 8f62289f04f367e88e369e6351485d3b69819f71)
This commit is contained in:
Anees Iqbal committed 2026-11-02 04:58:15 -08:00
1 parent ddccbfac5a
commit 089bbdfb87
6 files changed
+344 -28

No files matched your search

+134 -17
View File
@@ -278,6 +278,12 @@ pub(super) struct DontCareLoads {
}
impl DontCareLoads {
/// Whether [`dont_care_loads`] gave any attachment's `DontCare` load an answer: the only
/// loads the tiles a pass's draws reach bound ([`ReachClears::plan`]).
pub(super) fn any(&self) -> bool {
!self.colors.is_empty() || self.depth || self.stencil
}
/// Whether [`dont_care_loads`] gave color attachment `index`'s `DontCare` load an answer.
pub(super) fn color(&self, index: usize) -> bool {
self.colors.contains(&index)
@@ -292,10 +298,47 @@ impl DontCareLoads {
/// The most distinct pixel rectangles [`DrawnArea`] keeps; past them it is the whole render area.
const MOST_RECTS: usize = 1024;
/// What [`DrawnArea`] worked out on this thread: its tile counts ([`DrawnArea::covered_tiles`]) and
/// its grids of the tiles a pass's draws reach ([`DrawnArea::tiles`]), which a pass end works out
/// only where a count or a clear reads them (`tests/pass_end_tiles.rs`).
#[cfg(test)]
pub(super) mod made {
use std::cell::Cell;
use std::thread::LocalKey;
thread_local! {
pub(super) static COVERED: Cell<u64> = const { Cell::new(0) };
pub(super) static GRIDS: Cell<u64> = const { Cell::new(0) };
}
/// One more of `what` on this thread.
pub(super) fn note(what: &'static LocalKey<Cell<u64>>) {
what.with(|made| made.set(made.get() + 1));
}
/// The tile counts and the grids worked out on this thread so far.
pub(crate) fn so_far() -> [u64; 2] {
[COVERED.with(Cell::get), GRIDS.with(Cell::get)]
}
}
/// The words of a row of tiles in [`DrawnArea::covered_tiles`]: 512 tiles, the 16384 pixels of
/// the widest render area.
const ROW_WORDS: usize = 8;
/// Set the bits `bits` of `row`, a row of tiles in [`DrawnArea::covered_tiles`], a word at a time.
fn set_bits(row: &mut [u64; ROW_WORDS], bits: std::ops::Range<u32>) {
if bits.is_empty() {
return;
}
for word in bits.start / 64..bits.end.div_ceil(64) {
let first = bits.start.max(word * 64) - word * 64;
let past = bits.end.min(word * 64 + 64) - word * 64;
let ones = u64::MAX >> (64 - (past - first));
row[word as usize] |= ones << first;
}
}
/// The pixels a pass's draws may write, as far as the host bounds them: each draw that draws
/// writes only inside its viewports' pixels within their scissor rectangles
/// (`EncoderState::vk_scissors`), so a tile none of those reaches is one Metal's draws do not,
@@ -393,6 +436,8 @@ impl DrawnArea {
/// `None` where it bounds nothing. A count (`WorkCounts::shadow_attachment_tiles_covered`):
/// what a copy cut to the rectangles' tiles would leave out of one cut to their bounds.
pub(super) fn covered_tiles(&self) -> Option<(u64, u64)> {
#[cfg(test)]
made::note(&made::COVERED);
let [x0, y0, x1, y1] = self.bounds()?;
let (tx0, ty0) = (x0 / TILE, y0 / TILE);
let (tx1, ty1) = (x1.div_ceil(TILE), y1.div_ceil(TILE));
@@ -402,22 +447,31 @@ impl DrawnArea {
if (tx1 - tx0) as usize > ROW_WORDS * 64 {
return Some((bounded, bounded));
}
// Each rectangle's tiles: its columns from the bounds' first, and its rows.
let tiled = |&[rx0, ry0, rx1, ry1]: &[u32; 4]| {
(rx0 < rx1 && ry0 < ry1).then(|| {
let columns = rx0 / TILE - tx0..rx1.div_ceil(TILE) - tx0;
(columns, ry0 / TILE..ry1.div_ceil(TILE))
})
};
// The rows where a rectangle's tiles start or end: every row from one such edge to the
// next is reached by the same rectangles, so one row of tiles counts for them all.
let mut edges: Vec<u32> = (self.rects.iter().filter_map(tiled))
.flat_map(|(_, rows)| [rows.start, rows.end])
.collect();
edges.sort_unstable();
edges.dedup();
let mut covered = 0;
for ty in ty0..ty1 {
let (top, bottom) = (ty * TILE, (ty + 1) * TILE);
for band in edges.windows(2) {
let (top, bottom) = (band[0], band[1]);
let mut row = [0u64; ROW_WORDS];
for &[rx0, ry0, rx1, ry1] in self.rects.iter() {
if rx0 >= rx1 || ry0 >= ry1 || ry0 >= bottom || ry1 <= top {
continue;
}
for tile in rx0 / TILE - tx0..rx1.div_ceil(TILE) - tx0 {
row[(tile / 64) as usize] |= 1 << (tile % 64);
for (columns, rows) in self.rects.iter().filter_map(tiled) {
if rows.contains(&top) {
set_bits(&mut row, columns);
}
}
covered += row
.iter()
.map(|word| u64::from(word.count_ones()))
.sum::<u64>();
let tiles: u64 = row.iter().map(|word| u64::from(word.count_ones())).sum();
covered += u64::from(bottom - top) * tiles;
}
Some((covered, bounded))
}
@@ -450,10 +504,34 @@ impl DrawnArea {
/// `None` where that is every tile of the render area rounded up to whole tiles, the area is
/// not bounded, or the pass's sample count has no measured tile size.
pub(super) fn tiles(&self, layout: &PassLayout) -> Option<DrawnTiles> {
#[cfg(test)]
made::note(&made::GRIDS);
let tile = layout.tile.tile.filter(|_| !self.whole)?;
self.tiles_of(tile, layout.extent)
}
/// Whether [`tiles`](Self::tiles) holds tiles and none is reached: the rectangles reach no
/// tile of `layout`'s pass, which a scan of them answers with no grid made.
pub(super) fn reaches_no_tile(&self, layout: &PassLayout) -> bool {
layout
.tile
.tile
.filter(|_| !self.whole)
.is_some_and(|tile| self.reaches_no_tile_of(tile, layout.extent))
}
/// [`reaches_no_tile`](Self::reaches_no_tile) at `tile` pixels a side of a render area of
/// `extent`: a grid of tiles, none of which a rectangle overlaps, as
/// [`tiles_of`](Self::tiles_of) sets them.
fn reaches_no_tile_of(&self, tile: [u32; 2], extent: [u32; 2]) -> bool {
let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis]));
let overlaps = |&[x0, y0, x1, y1]: &[u32; 4]| {
x0 / tile[0] < x1.div_ceil(tile[0]).min(per_row)
&& y0 / tile[1] < y1.div_ceil(tile[1]).min(rows)
};
per_row != 0 && rows != 0 && !self.rects.iter().any(overlaps)
}
/// The tiles of `tile` pixels a side of a render area of `extent` the rectangles reach:
/// `None` where that is every one ([`tiles`](Self::tiles)).
fn tiles_of(&self, tile: [u32; 2], extent: [u32; 2]) -> Option<DrawnTiles> {
@@ -501,11 +579,6 @@ pub(super) struct DrawnTiles {
}
impl DrawnTiles {
/// Whether no tile is reached.
pub(super) fn is_empty(&self) -> bool {
self.words.iter().all(|&w| w == 0)
}
/// Whether tile `(tx, ty)` is reached: none past the grid.
pub(super) fn contains(&self, tx: u32, ty: u32) -> bool {
let t = (ty as usize) * (self.per_row as usize) + tx as usize;
@@ -879,6 +952,43 @@ mod tests {
assert_eq!(area.covered_tiles(), *expected, "case {case}");
}
assert_eq!(DrawnArea::unbounded().covered_tiles(), None);
// Against the tiles counted one at a time, for rectangles spread over a large area.
let mut seed = 0x2545_f491_u64;
let mut next = |below: u32| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
((seed >> 33) % u64::from(below)) as u32
};
for case in 0..200 {
let rects: Vec<vk::Rect2D> = (0..1 + next(24))
.map(|_| {
rect(
next(3000) as i32,
next(2000) as i32,
1 + next(900),
1 + next(700),
)
})
.collect();
let mut area = DrawnArea::default();
area.add(&rects);
let [x0, y0, x1, y1] = area.bounds().expect("a rectangle");
let (tx0, ty0, tx1, ty1) = (x0 / 32, y0 / 32, x1.div_ceil(32), y1.div_ceil(32));
let mut covered = 0;
for ty in ty0..ty1 {
for tx in tx0..tx1 {
let reached = area.rects.iter().any(|&[rx0, ry0, rx1, ry1]| {
rx0 < (tx + 1) * 32 && tx * 32 < rx1 && ry0 < (ty + 1) * 32 && ty * 32 < ry1
});
covered += u64::from(reached);
}
}
let bounded = u64::from(tx1 - tx0) * u64::from(ty1 - ty0);
assert_eq!(
area.covered_tiles(),
Some((covered, bounded)),
"case {case}"
);
}
}
/// The tiles a pass's rectangles reach are the tiles each overlaps, whether one of them
@@ -905,6 +1015,10 @@ mod tests {
vec![rect(0, 0, 50, 70), rect(50, 0, 50, 70)],
vec![rect(40, 20, 10, 10)],
vec![],
// Past the grid, across and down: no tile.
vec![rect(128, 0, 10, 10)],
vec![rect(0, 80, 10, 10), rect(130, 90, 5, 5)],
vec![rect(96, 64, 4, 6)],
];
for (case, rects) in cases.iter().enumerate() {
let mut area = DrawnArea::default();
@@ -919,6 +1033,9 @@ mod tests {
})
};
let every = (0..rows).all(|ty| (0..per_row).all(|tx| reached(tx, ty)));
// The scan with no grid made answers whether the grid holds none.
let none = (0..rows).all(|ty| (0..per_row).all(|tx| !reached(tx, ty)));
assert_eq!(area.reaches_no_tile_of(tile, extent), none, "case {case}");
match area.tiles_of(tile, extent) {
None => assert!(every, "case {case}"),
Some(tiles) => {
+12 -8
View File
@@ -4332,19 +4332,23 @@ impl RenderLowering {
});
}
let loaded_colors = &loaded[..layout.colors.len()];
let tiles = match reach {
clear_reach::PassReach::Draws => drawn.tiles(&layout),
_ => None,
// A pass whose draws' rectangles reach no tile reaches none.
let reach = match reach {
clear_reach::PassReach::Draws if drawn.reaches_no_tile(&layout) => {
clear_reach::PassReach::Nothing
}
reach => reach,
};
let reach = match &tiles {
Some(tiles) if tiles.is_empty() => clear_reach::PassReach::Nothing,
_ => reach,
};
let tiles = tiles.filter(|tiles| !tiles.is_empty());
// A `DontCare` load of an attachment the pass stores: loaded in a pass whose draws reach
// no tile, else cleared to zero or its clear value, Metal's answer in each tile a draw
// reaches (`clear_reach.rs`), and only in those `tiles` bounds.
let dont_care = clear_reach::dont_care_loads(&mut layout, reach);
// The tiles the draws reach, which only those loads' clears read: none made for a pass
// without one.
let tiles = match reach {
clear_reach::PassReach::Draws if dont_care.any() => drawn.tiles(&layout),
_ => None,
};
if let Some(named) = dont_care.named.clone() {
device.degrade(Degradation::DontCareLoadTiles, || {
(
@@ -638,6 +638,8 @@ fn color_take(
/// Count how a pass of `layout` takes each of its color attachments whose texture is shadowed
/// (`WorkCounts::shadow_attachment_loads_within` and kin), as [`attachment_shadows`] plans them.
/// The tiles `area` covers are counted only for a shadowed color loaded within its draws'
/// scissors, the one count that reads them: a pass with none counts no tile.
fn count_colors(
counts: &Counters,
layout: &PassLayout,
@@ -645,7 +647,7 @@ fn count_colors(
drawn: Option<([u32; 4], &[bool])>,
area: Option<&DrawnArea>,
) {
let tiles = area.and_then(DrawnArea::covered_tiles);
let mut tiles = None;
let colors = layout.colors.iter().enumerate();
for (index, color) in colors.filter_map(|(index, color)| Some((index, color.as_ref()?))) {
let Some(copies) = color.target.texture.shadow() else {
@@ -660,7 +662,11 @@ fn count_colors(
_ => ColorTaken::Loaded,
};
counts.shadow_color_taken(taken);
if let (ColorTaken::LoadedWithin, Some((covered, bounded))) = (taken, tiles) {
if taken != ColorTaken::LoadedWithin {
continue;
}
let tiles = *tiles.get_or_insert_with(|| area.and_then(DrawnArea::covered_tiles));
if let Some((covered, bounded)) = tiles {
counts.shadow_attachment_tiles(covered, bounded);
}
}
@@ -201,6 +201,8 @@ mod owned_kernel_builds;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod owned_pushes;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod pass_end_tiles;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod pending_rebind;
mod pipeline;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
@@ -0,0 +1,187 @@
//! A render pass's end works out the tiles its draws reach only where something reads them
//! (`render/shadows.rs`, `clear_reach.rs`): the count of the tiles its draws' scissors cover
//! against their bounds (`WorkCounts::shadow_attachment_tiles_covered`) only for a shadowed color
//! attachment it loads within those scissors, which the count is of, and the grid of the tiles
//! its draws reach only for a `DontCare` load that clears them. A pass with neither works out
//! neither, whatever else of its shadows it plans: each pass here draws a box that reads its own
//! attachment at its own pixel, through a copy (`texture/attached_reads.rs`), so its end plans
//! that copy (`WorkCounts::attachment_reads_through_copies`) with no shadowed attachment.
//!
//! The assertion is a count of the work done on this thread (`clear_reach::made`), never a time:
//! a pass end that works the tiles out again where nothing reads them turns it red at once.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_rect` and
//! `tob_read` of the owned fixture `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`).
use super::blit_holds::{device, Host, Scratch, WAIT};
use crate::clear_reach::made;
use crate::{
CommandQueue, Device, Error, LoadAction, PipelineOptions, RenderPassDescriptor,
RenderPipelineState, ResourceOptions, ScissorRect, StoreAction, Texture, TextureDescriptor,
};
use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use std::path::Path;
/// The target's side, in pixels: two tiles of 32 each way.
const SIDE: u64 = 64;
/// The fixture's state of `tob_rect` and `tob_read`, one `RGBA8Unorm` target.
fn state(device: &Device) -> RenderPipelineState {
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/engine/tob_renders.ll");
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap();
let library = device.new_library_with_compile_library(library);
let vertex = library.new_function_with_name("tob_rect").unwrap();
let fragment = library.new_function_with_name("tob_read").unwrap();
let mut descriptor =
RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor()));
descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor()));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// The target's descriptor: rendered into and read.
fn descriptor() -> TextureDescriptor {
let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false);
d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
d
}
/// What one pass's end worked out, and the counts it moved.
#[derive(Debug, PartialEq, Eq)]
struct Ended {
/// The tile counts and the grids of reached tiles worked out (`clear_reach::made`).
covered: u64,
grids: u64,
/// `WorkCounts::attachment_reads_through_copies`: the draw's read of its own attachment.
read_copies: u64,
/// `WorkCounts::shadow_attachment_loads_within` and `shadow_attachment_tiles_bounded`.
loads_within: u64,
tiles_bounded: u64,
}
/// A pass over `target`, loaded by `load` and stored: one draw over the whole target that reads
/// the target at its own pixel, inside a scissor of the tile at the origin.
fn end_one_pass(
device: &Device,
queue: &CommandQueue,
state: &RenderPipelineState,
target: &Texture,
load: LoadAction,
) -> Ended {
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = load;
color.store_action = StoreAction::Store;
let before = device.work_counts();
let [covered, grids] = made::so_far();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
encoder.set_render_pipeline_state(state).unwrap();
// The corners of the whole target, in normalized device coordinates.
let corners: Vec<u8> = [-1.0f32, -1.0, 1.0, 1.0]
.iter()
.flat_map(|f| f.to_le_bytes())
.collect();
encoder.set_vertex_bytes(&corners, 0).unwrap();
encoder.set_fragment_texture(Some(target), 0).unwrap();
let scissor = ScissorRect {
x: 8,
y: 8,
width: 8,
height: 8,
};
encoder.set_scissor_rect(scissor).unwrap();
encoder
.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
.unwrap();
encoder.end_encoding().unwrap();
let [covered_after, grids_after] = made::so_far();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
let after = device.work_counts();
Ended {
covered: covered_after - covered,
grids: grids_after - grids,
read_copies: after.attachment_reads_through_copies - before.attachment_reads_through_copies,
loads_within: after.shadow_attachment_loads_within - before.shadow_attachment_loads_within,
tiles_bounded: after.shadow_attachment_tiles_bounded
- before.shadow_attachment_tiles_bounded,
}
}
/// A pass whose color attachment is not shadowed counts no tile, loaded or cleared, and makes
/// the grid of the tiles its draws reach only where a `DontCare` load clears them; a shadowed
/// one it loads counts the tiles once, where the device shadows a texture over host pages.
#[test]
fn a_pass_end_works_out_its_tiles_only_where_they_are_read() {
let scratch = Scratch::new("pass-end-tiles");
let host = Host::new();
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let state = state(&device);
let mut private = descriptor();
private.resource_options = ResourceOptions::private();
let plain = device.new_texture(&private).unwrap();
assert!(
plain.shadow().is_none(),
"a texture of its own is not shadowed"
);
let plain_pass = |load| end_one_pass(&device, &queue, &state, &plain, load);
// Loaded and cleared: the read's copy is planned, and no tile is worked out.
for load in [LoadAction::Load, LoadAction::Clear] {
let ended = plain_pass(load);
let none = Ended {
covered: 0,
grids: 0,
read_copies: 1,
loads_within: 0,
tiles_bounded: 0,
};
assert_eq!(ended, none, "{load:?}");
}
// A `DontCare` load the draw's tiles bound: their grid, once (`clear_reach::ReachClears`).
let ended = plain_pass(LoadAction::DontCare);
assert_eq!((ended.covered, ended.grids, ended.read_copies), (0, 1, 1));
// A texture over host pages, which a device that cannot render into them in place shadows
// (the pass copies it in and back): the count of its tiles, once, of the one tile the
// scissor reaches.
// SAFETY: the memory outlives the buffer (dropped after the device), and only the buffer's
// commands use it while it lives.
let made = unsafe {
let memory = host.memory();
device.new_buffer_with_bytes_no_copy(
memory,
SIDE * SIDE * 4,
ResourceOptions::default(),
None,
)
};
let buffer = match made {
Ok(buffer) => buffer,
Err(Error::Unsupported(gap)) => {
eprintln!("PASS-END-TILES: the device imports no host memory: {gap:?}");
return;
}
Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"),
};
let over_pages = buffer.new_texture(&descriptor(), 0, SIDE * 4).unwrap();
let ended = end_one_pass(&device, &queue, &state, &over_pages, LoadAction::Load);
let counted = u64::from(over_pages.shadow().is_some());
eprintln!("PASS-END-TILES: over host pages, shadowed {counted}: {ended:?}");
let within = Ended {
covered: counted,
grids: 0,
read_copies: 1,
loads_within: counted,
tiles_bounded: counted,
};
assert_eq!(ended, within);
}
@@ -1 +1 @@
3314ddbb7d95976398f75e2ad60298023cdc1deb428b7fe8d0d2206cbafe1e54
f7a3c24de2d546d0f37b2f78994014152eb89cdafada26e02c165caf0db7c0b8