Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion crates/metal2vulkan-runtime/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,11 @@ pub(crate) struct Gpu {
/// boxed from its make. `None` where the type is host-coherent: one pointer, as each hand-off
/// moves the command buffer by value.
pub(crate) coherence: Option<Box<coherence::Recorded>>,
/// Images whose very first use in segment 0 of this command buffer is a full-extent
/// `LoadAction::Clear` or `LoadAction::DontCare` render pass transitioning from `UNDEFINED`.
/// When the submit thread sees no earlier command in the same batch reading the image, it
/// skips the eager `Upload::home` clear and marks the image homed (`Image::claim_homed`).
pub(crate) first_overwrites: Vec<Arc<Image>>,
}

/// Whether `segments` hold nothing for the GPU: no commands, wait or signal ([`Gpu::is_empty`]).
Expand Down Expand Up @@ -568,6 +573,7 @@ impl CommandBuffer {
queries: Queries::default(),
sets: crate::bound::Sets::default(),
coherence,
first_overwrites: Vec::new(),
},
handlers: Handlers {
scheduled: Vec::new(),
Expand Down Expand Up @@ -1705,6 +1711,33 @@ impl Building {
self.gpu.coherence.as_deref_mut()
}

/// Whether the encoder is still recording into the command buffer's first segment (segment 0).
pub(crate) fn is_first_segment(&self) -> bool {
self.gpu.segments.len() == 1
}

/// Whether any earlier command in this command buffer has already referenced `image`.
pub(crate) fn keeps_image(&self, image: &Arc<Image>) -> bool {
self.gpu
.kept
.textures
.iter()
.any(|texture| texture.image_of().is_some_and(|held| Arc::ptr_eq(held, image)))
|| self.gpu.images.iter().any(|held| Arc::ptr_eq(held, image))
}

/// Records `image` as fully overwritten before any prior use in segment 0 of this command buffer.
pub(crate) fn record_first_overwrite(&mut self, image: Arc<Image>) {
if !self
.gpu
.first_overwrites
.iter()
.any(|held| Arc::ptr_eq(held, &image))
{
self.gpu.first_overwrites.push(image);
}
}

/// A dispatch wrote: an indirect dispatch after it needs a barrier that reaches its
/// argument read.
pub(crate) fn wrote(&mut self) {
Expand Down Expand Up @@ -2429,12 +2462,13 @@ pub(crate) fn retire(
queries,
sets,
coherence: _,
first_overwrites,
} = gpu;
if let Some(recorder) = recorder {
core.recorders.give_back(core, recorder);
}
ring.give_back(core);
drop((segments, blocks, images, fences, executed));
drop((segments, blocks, images, fences, executed, first_overwrites));
queries.give_back(core);
sets.give_back(core);
kept.clear();
Expand Down
5 changes: 5 additions & 0 deletions crates/metal2vulkan-runtime/src/pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,11 @@ impl Target {
self.layout != self.attachment.home
}

/// The Vulkan load operation recorded for this attachment on the pass's first begin.
pub(crate) fn load_op(&self) -> vk::AttachmentLoadOp {
self.load
}

/// The colour the pass clears it to, as its rendering's load clears it: `None` for an
/// attachment the pass loads or does not care for, and for the stencil attachment.
pub(crate) fn clear_color(&self) -> Option<vk::ClearColorValue> {
Expand Down
149 changes: 139 additions & 10 deletions crates/metal2vulkan-runtime/src/render_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,7 @@ impl CommandBuffer {
let mut scratch = building.take_render_scratch();
let colors = std::mem::take(&mut scratch.colors);
match begin(&mut building, &core, descriptor, colors) {
Ok((pass, command, visibility)) => {
Ok((pass, command, visibility, pre_moved)) => {
let [width, height] = pass.area;
let raster = Raster {
positions: pass.positions.is_some(),
Expand Down Expand Up @@ -1094,7 +1094,7 @@ impl CommandBuffer {
drew: false,
pass_drew: false,
owed: false,
moved: Vec::new(),
moved: pre_moved,
shadowed: Vec::new(),
shadow_slots: Vec::new(),
facts,
Expand Down Expand Up @@ -1123,8 +1123,125 @@ fn begin(
core: &Arc<Core>,
descriptor: &RenderPassDescriptor,
colors: Vec<Option<Target>>,
) -> Result<(Pass, vk::CommandBuffer, Option<Visibility>), Error> {
let pass = Pass::check(core, descriptor, colors)?;
) -> Result<(Pass, vk::CommandBuffer, Option<Visibility>, Vec<Moved>), Error> {
let mut pass = Pass::check(core, descriptor, colors)?;
// P3-1: Single-mip, single-layer 2D non-storage color render targets previously moved into the
// feedback layout (`Image.feedback_hint`) begin directly in `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`
// so the first feedback draw in subsequent passes needs no mid-pass `vkCmdEndRendering`.
let mut pre_moved = Vec::new();
if core.attachment_reads && core.feedback_loop {
let looped = vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT;
let eligible: Vec<u32> = pass
.colors
.iter()
.flatten()
.filter_map(|t| {
let hazard = t.texture.hazard_id();
let eligible = t.stand_in.is_none()
&& t.texture.looped()
&& t.texture.attachment_reads()
&& t.texture.feedback_hint()
&& !t.texture.has_storage()
&& t.texture.is_single_2d()
&& t.attachment.home != looped
&& pass
.targets()
.filter(|other| other.texture.hazard_id() == hazard)
.count()
== 1
&& (!pass.resolving
|| !pass
.resolves()
.any(|r| r.texture.hazard_id() == hazard));
eligible.then_some(hazard)
})
.collect();
for t in pass.colors.iter_mut().flatten() {
let hazard = t.texture.hazard_id();
if eligible.contains(&hazard) {
t.layout = looped;
pre_moved.push(Moved {
hazard,
image: t.attachment.image,
whole: t.texture.whole(),
home: t.attachment.home,
});
}
}
}
// P3-3: Newly created single-mip/single-layer 2D textures whose very first use in segment 0 is
// a full-extent `CLEAR` or `DONT_CARE` pass covering all aspects transition directly from
// `UNDEFINED` here, letting `WorkState::close` skip their eager `Upload::home` clear.
let mut elided_zero: Vec<usize> = Vec::new();
if building.is_first_segment() && pass.layers == 1 {
let overwrites = |load: vk::AttachmentLoadOp| {
matches!(load, vk::AttachmentLoadOp::CLEAR | vk::AttachmentLoadOp::DONT_CARE)
};
let mut try_elide = |t: &Target, expected_aspects: vk::ImageAspectFlags| {
if t.stand_in.is_some()
|| !t.texture.has_zero()
|| t.texture.is_homed()
|| !t.texture.is_single_2d()
|| t.texture.image_aspects() != expected_aspects
|| pass.area != t.attachment.extent
|| pass.reach != t.attachment.extent
{
return;
}
let Some(image) = t.texture.image_arc() else {
return;
};
if building.keeps_image(image) {
return;
}
let key = Arc::as_ptr(image) as usize;
let unique_target = pass
.targets()
.filter(|other| {
other
.texture
.image_arc()
.is_some_and(|held| Arc::as_ptr(held) as usize == key)
})
.count()
== 1;
let unique_resolve = !pass.resolving
|| !pass.resolves().any(|r| {
r.texture
.image_arc()
.is_some_and(|held| Arc::as_ptr(held) as usize == key)
});
if unique_target && unique_resolve && !elided_zero.contains(&key) {
elided_zero.push(key);
building.record_first_overwrite(Arc::clone(image));
}
};
for t in pass.colors.iter().flatten() {
if overwrites(t.load_op()) {
try_elide(t, vk::ImageAspectFlags::COLOR);
}
}
match (&pass.depth, &pass.stencil) {
(Some(d), Some(s))
if d.texture
.image_arc()
.zip(s.texture.image_arc())
.is_some_and(|(di, si)| Arc::ptr_eq(di, si)) =>
{
if overwrites(d.load_op()) && overwrites(s.load_op()) {
try_elide(d, vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL);
}
}
(depth, stencil) => {
if let Some(d) = depth.as_ref().filter(|d| overwrites(d.load_op())) {
try_elide(d, vk::ImageAspectFlags::DEPTH);
}
if let Some(s) = stencil.as_ref().filter(|s| overwrites(s.load_op())) {
try_elide(s, vk::ImageAspectFlags::STENCIL);
}
}
}
}
// The attachments, and where the pass resolves the resolve textures, which the pass writes:
// a pass that resolves nothing walks no resolve.
let resolves = || {
Expand Down Expand Up @@ -1195,11 +1312,22 @@ fn begin(
building.overs_after(overs(), false);
building.count(Metric::Passes);
let mut away = building.take_pass_barriers();
away.extend(
(pass.targets())
.filter(|t| t.moves())
.map(|t| t.barrier(t.attachment.home, t.layout)),
);
for t in pass.targets() {
let elided = t
.texture
.image_arc()
.is_some_and(|image| elided_zero.contains(&(Arc::as_ptr(image) as usize)));
if elided {
away.push(layout_barrier(
t.attachment.image,
t.texture.whole(),
vk::ImageLayout::UNDEFINED,
t.layout,
));
} else if t.moves() {
away.push(t.barrier(t.attachment.home, t.layout));
}
}
if pass.resolving {
away.extend(
(pass.resolves())
Expand Down Expand Up @@ -1263,7 +1391,7 @@ fn begin(
if let Some(id) = first_discard {
building.cancel_first_discard_lean(id);
}
Ok((pass, command, visibility))
Ok((pass, command, visibility, pre_moved))
}

impl RenderCommandEncoder {
Expand Down Expand Up @@ -2293,6 +2421,7 @@ impl RenderCommandEncoder {
for t in self.pass.colors.iter_mut().flatten() {
if (moves.iter()).any(|m| m.moved.hazard == t.texture.hazard_id()) {
t.layout = looped;
t.texture.mark_feedback_hint();
}
}
// A read declaration that covers an attachment now held out of its home layout.
Expand Down
31 changes: 28 additions & 3 deletions crates/metal2vulkan-runtime/src/submit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ use crate::staging::{At, Oldest, Region, Stage, Staging, REGION_LEN};
use crate::texture::{Homing, Image, OverCopy, TextureInner, TextureObject, Zeroing};
use crate::times;
use ash::vk;
use std::collections::VecDeque;
use std::collections::{HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};

Expand Down Expand Up @@ -614,6 +614,11 @@ struct Batch {
/// The first failed call recording a command buffer of moves that leads a segment of it
/// (`crate::alias::stage`), which loses the device.
lost: Option<DeviceLoss>,
/// Images already referenced by earlier segments staged into this batch (`Arc::as_ptr` as `usize`).
seen_images: HashSet<usize>,
/// Un-homed images whose first use in this batch is a full-extent `Clear`/`DontCare` pass
/// transitioning from `UNDEFINED`, allowing `take_uploads` to skip their eager upload clear.
elided_homes: HashSet<usize>,
}

/// What a batch flushes before it is submitted, where the Shared type is not host-coherent
Expand Down Expand Up @@ -1632,6 +1637,7 @@ impl WorkState {
released: &AtomicU64,
value: u64,
through: u64,
elided_homes: Option<&HashSet<usize>>,
) -> Vec<Upload> {
let within = (self.sealed.iter())
.take_while(|upload| upload.number <= through)
Expand Down Expand Up @@ -1661,6 +1667,10 @@ impl WorkState {
}
}
for image in upload.homes.drain(..).filter_map(|home| home.upgrade()) {
if elided_homes.is_some_and(|set| set.contains(&(Arc::as_ptr(&image) as usize))) {
image.claim_homed();
continue;
}
// One an upload copied to or from was moved before its copy, and is held.
if let Some(homing) = image.homing() {
homes.push(homing);
Expand Down Expand Up @@ -2040,6 +2050,8 @@ impl WorkState {
handed: Vec::new(),
flushes: None,
lost: None,
seen_images: HashSet::new(),
elided_homes: HashSet::new(),
});
if leads {
group.run = group.run.saturating_add(run.unwrap_or(u64::MAX));
Expand All @@ -2050,6 +2062,17 @@ impl WorkState {
group.unseen = 0;
}
group.unseen += 1;
for image in &pending.gpu.first_overwrites {
let key = Arc::as_ptr(image) as usize;
if !group.seen_images.contains(&key) {
group.elided_homes.insert(key);
}
}
}
for texture in pending.gpu.kept.textures.iter() {
if let Some(image) = texture.image_of() {
group.seen_images.insert(Arc::as_ptr(image) as usize);
}
}
group.leans.join(&segment.overs);
if let Some(coherence::Recorded {
Expand Down Expand Up @@ -2263,7 +2286,7 @@ impl WorkState {
.extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, pending.value)));
(self.carried)
.extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, pending.value)));
let uploads = self.take_uploads(core, released, value, through);
let uploads = self.take_uploads(core, released, value, through, Some(&batch.elided_homes));
Some((value, uploads, batch))
}

Expand Down Expand Up @@ -2586,7 +2609,7 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard<
}
if state.flush > 0 && !sent {
let value = state.progress + 1;
let uploads = state.take_uploads(core, &work.released, value, 0);
let uploads = state.take_uploads(core, &work.released, value, 0, None);
if !uploads.is_empty() {
state.progress = value;
drop(state);
Expand Down Expand Up @@ -2658,6 +2681,8 @@ impl Batch {
handed: Vec::new(),
flushes: None,
lost: None,
seen_images: HashSet::new(),
elided_homes: HashSet::new(),
}
}
}
Expand Down
Loading
Loading