Storage-form color inputs are read once, before the body

What. A fragment function that fetches a color in the storage form (the
ordered pixel interlock's storage image of the attachment) reads that image
once per invocation, in its entry hook before the body (fragment::emit_entry,
EmitCx::fetched), and every use of the color input takes that texel. Before,
each use read the image again at the use.

Why. The coverage chain's discarding fill (dsx_coverage_chain's
chain_color_discarding) tests its fetched coverage for its discard, then
multiplies its color by it: two uses, so the body read the raster-ordered
image, branched on it, then fenced and read it again. On MoltenVK on the M3
Max (MoltenVK 1.4.2, macOS 27.0.1), while other work ran on the GPU, Apple's
GPU lost the color the function wrote through its output in whole 8x4 blocks:
runtime_lane::framebuffer_fetch::coverage_chain failed 4 of 60 runs (and 9 of
90, 12 of 90 in earlier batches). With one read, 0 of 60, whether the discard
demotes or is predicated; a form that read the image twice with no branch
between the reads also lost nothing (0 of 150). Metal hands the function one
value of the attachment, so one read is its semantics, and it keeps the
image's accesses in the interlock to that read and the writes at the returns.

Test. tests::engine_fragment::a_fetched_color_is_read_once_before_the_body:
chain_color_discarding reads the coverage's image once, in the first block,
on every committed profile that orders fetch through the interlock (two reads
without the change).

(cherry picked from commit 3917662cbbb5d214ceb7a4f8c8631a71679a2849)
This commit is contained in:
Anees Iqbal committed 2026-11-09 00:56:11 -08:00
1 parent b60bab13e4
commit 0c3eb77a5d
5 files changed
+119 -20

No files matched your search

+7
View File
@@ -210,6 +210,11 @@ pub struct EmitCx<'a> {
/// `stage_io::emit_entry` finds before the body (`stage_io::MergedRead`): defined in the
/// function's straight-line entry, so every later block of the function may read them.
pub(crate) merged_draw: Option<crate::bind::MergedVertex>,
/// The texel of each storage-form color attachment a fragment function reads, by Metal
/// color index, at the invocation's pixel (and sample), which `fragment::emit_entry` reads
/// before the body: defined in the function's straight-line entry, inside the interlock, so
/// every use of the color in a later block takes the one texel (`fragment::fetch::value`).
pub(crate) fetched: Vec<(u32, SValue)>,
}
/// A value that is the same wherever an invocation computes it, so a block computes it once, and
@@ -261,6 +266,7 @@ impl<'a> EmitCx<'a> {
fault: None,
sampling: Default::default(),
merged_draw: None,
fetched: Vec::new(),
}
}
@@ -680,6 +686,7 @@ impl<'a> Emitter<'a> {
fault: None,
sampling: Default::default(),
merged_draw: None,
fetched: Vec::new(),
},
vars: None,
phis,
@@ -437,9 +437,10 @@ fn input_attachment(
mb.resource(slot, StorageClass::UniformConstant, ty)
}
/// The value of color input `c` in its lowered representation, read at each use (the use may
/// sit in a construct whose values do not dominate the rest of the block), at the invocation's
/// sample for a per-sample function.
/// The value of color input `c` in its lowered representation, at the invocation's sample for a
/// per-sample function: an input attachment's read at each use (the use may sit in a construct
/// whose values do not dominate the rest of the block), a storage-form attachment's from the
/// texel the function read before its body (`fetch::value`).
pub(super) fn value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
+29 -13
View File
@@ -6,8 +6,9 @@
//! ([`interlock_orders`]: RADV, ANV, and MoltenVK where measured) orders a fetch instead through
//! the ordered pixel interlock, the mechanism of raster order groups and imageblocks: each color
//! attachment the function reads becomes a storage image of the attachment
//! (`ResourceKind::TileAttachment(n)`), read at the fragment's pixel (the integer part of
//! `FragCoord.xy`) at each use, and, when the function writes that attachment through its first
//! (`ResourceKind::TileAttachment(n)`), read once at the fragment's pixel (the integer part of
//! `FragCoord.xy`) before the body, the texel every use takes, and, when the function writes that
//! attachment through its first
//! (index 0) output, written there at the return in place of the output
//! (`GraphicsState::storage_attachments`; colors it writes but does not read stay ordinary outputs,
//! but those the pipeline's state names: an extended-range attachment it blends, below, and a color
@@ -2607,8 +2608,30 @@ fn as_held(fb: &mut FunctionBuilder<'_>, texel: SValue, numeric: SampledType) ->
fb.convert(ConvOp::Bitcast, texel, uvec4)
}
/// The value of storage-form color input `c` in its lowered representation, read at its pixel
/// (as `color::value` reads an input attachment).
/// The texel the function reads of storage-form attachment `color` at its pixel (and sample):
/// its shadow's, where the instance holds one, else its image's. The function reads it once,
/// before its body (`fragment::emit_entry`), and every use takes it ([`value`]): Metal hands the
/// function one value of the attachment, and one read keeps the image's accesses in the
/// interlock to that read and the writes at the returns.
pub(super) fn texel(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
color: u32,
) -> BResult<SValue> {
let Some(sc) = cx.plan.families.fragment.fetch.get(&color).copied() else {
return Err(cx.fail(format!("attachment {color} is not in the storage form")));
};
match (sc.shadowed, sc.view.extended) {
// The instance's shadow holds the tile value itself.
(true, Some(range)) => shadow_read(cx, fb, color, range),
(true, None) => Err(cx.fail("a shadow of an attachment of another form")),
(false, _) => read_texel(cx, fb, color, &sc),
}
}
/// The value of storage-form color input `c` in its lowered representation, from the texel the
/// function read at its pixel before its body ([`texel`]; as `color::value` reads an input
/// attachment).
pub(super) fn value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -2617,15 +2640,8 @@ pub(super) fn value(
let Some(sc) = cx.plan.families.fragment.fetch.get(&c.color).copied() else {
return Err(cx.fail(format!("attachment {} is not in the storage form", c.color)));
};
let texel = match (sc.shadowed, sc.view.extended) {
// The instance's shadow holds the tile value itself.
(true, Some(range)) => Some(shadow_read(cx, fb, c.color, range)?),
(true, None) => return Err(cx.fail("a shadow of an attachment of another form")),
(false, _) => None,
};
let texel = match texel {
Some(held) => held,
None => read_texel(cx, fb, c.color, &sc)?,
let Some(&(_, texel)) = cx.fetched.iter().find(|&&(color, _)| color == c.color) else {
return Err(cx.fail(format!("attachment {} was not read at entry", c.color)));
};
let texel = match (sc.view.extended, sc.view.uint_view) {
(Some(_), _) if sc.shadowed => texel,
+17 -4
View File
@@ -751,16 +751,29 @@ pub fn writes_outside_interface(cx: &SelectCx<'_>) -> bool {
}
/// The work before the body, in the function's first block: read the imageblock input, place the
/// fragment's tile in the pass's tile memory, and copy the textures read through snapshots
/// (`snapshot`).
/// fragment's tile in the pass's tile memory, copy the textures read through snapshots
/// (`snapshot`), and read the texel of each storage-form color the function reads
/// (`EmitCx::fetched`), which every use of the color then takes.
pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
imageblock::emit_entry(cx, fb)?;
crate::lower::access::tile_memory::emit_entry(cx, fb)?;
snapshot::emit_entry(cx, fb)
snapshot::emit_entry(cx, fb)?;
let fp = &cx.plan.families.fragment;
let read: BTreeSet<u32> = fp
.colors
.iter()
.map(|c| c.color)
.filter(|color| fp.fetch.contains_key(color))
.collect();
for color in read {
let texel = fetch::texel(cx, fb, color)?;
cx.fetched.push((color, texel));
}
Ok(())
}
/// The value of parameter `b` in its lowered representation, read by an instruction or a
/// terminator: a color input's texel, read at each use.
/// terminator: a color input's texel (`color::value`).
pub fn param_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -4927,6 +4927,68 @@ fn an_interlocked_discard_kills_only_in_the_entry() {
}
}
/// A function reads each color it fetches in the storage form once, before its body, and every
/// use takes that texel: the coverage chain's discarding fill (`dsx_coverage_chain`'s
/// `chain_color_discarding`, its coverage fetched, under the lane's attachments) tests the
/// coverage for its discard and multiplies its color by it, two uses in two blocks, and reads
/// the coverage's image once, in the first block of the function that holds the read, on every
/// committed profile that orders fetch through the interlock. Every module passes L3, and on
/// `moltenvk-m3` compiles through SPIRV-Cross to Metal.
#[test]
fn a_fetched_color_is_read_once_before_the_body() {
let Some(chain) = fixture("dsx_coverage_chain") else {
return;
};
let entry = "chain_color_discarding";
let colors = [
PixelFormat::RGBA16Float,
PixelFormat::RG16Float,
PixelFormat::RGBA16Float,
]
.map(|f| Some(ColorAttachmentDescriptor::new(f)));
let mut inputs = LoweringInputs::new();
inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([1], &colors, true, false, 1));
let mut checked = 0;
for (stem, p) in committed_profiles().expect("profiles") {
if !crate::lower::fragment::interlock_orders(&p) {
continue;
}
let what = format!("{entry} on {stem}");
let a = match compile_with(&chain, entry, &p, &inputs) {
Ok(a) => a,
// A device without the attachments' storage formats refuses the form.
Err(Error::Unsupported(_)) => continue,
Err(e) => panic!("{what}: {e}"),
};
let (_, m) =
typed_module_with(&chain, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}"));
// Each image read, with whether it sits in its function's first block.
let reads: Vec<bool> = (m.functions().iter())
.flat_map(|f| {
f.blocks.iter().enumerate().flat_map(|(i, b)| {
(m.blocks()[b.index()].insts.iter())
.filter(|n| matches!(n.inst, Inst::ImageRead { .. }))
.map(move |_| i == 0)
})
})
.collect();
assert_eq!(reads, [true], "{what}: one read, in a first block");
let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
if is_moltenvk_capture(&stem) {
match moltenvk_msl_compile(&words) {
Ok(()) => {}
Err(AssembleError::Missing(why)) => eprintln!("SKIPPED MSL: {why}"),
Err(AssembleError::Rejected(why)) => panic!("{what}: MSL: {why}"),
}
}
checked += 1;
}
assert!(
checked > 0,
"no interlock profile compiled the storage form"
);
}
/// One function the interlock coherence test compiles: its fixture, its entry, the
/// framebuffer-fetch colors it reads (with their formats), and whether it needs the Vulkan
/// memory model.