Merge a heap half read's class arms as the texel's half bits

What: a half read of a texture an argument buffer holds, whose class arms read a member of
another numeric class (Read::heap_cross), now hands its merge each arm's half bits in u32 lanes
(narrow::to_bits: a sibling's noted bits, its words' low 16; the own arm's texel narrowed by the
device), zero where the handle is null, and widens the merged bits once after the merge
(narrow::from_bits). Before, each arm widened its half and selected it against the null handle's
zero, and the merge carried the texel structs of those floats. emit::read is split into
read_texel (the texel, the handle's liveness, the status word) and the null select and status
word, which read_crossed's half arms apply to the bits instead. The read's word estimate counts
the arms' narrowing and the widening. SEMANTICS_VERSION 1966: the SPIR-V of every such read
changes on every profile.

Why: the stack 28 gate's M3 lane
runtime_lane::cross_class_reads::argument_buffer_cross_class_reads_are_the_native_words, run with
a texel's half rounding counted as measured, answered 0x7e00 where the slot's read keeps an
integer texel's NaN bits (R8Sint, RGBA8Sint, RG16Sint, RGBA16Sint, RGBA32Sint, RGBA16Uint and
RGBA32Uint as half, 66 of 2170 lanes). The module (the lane's held half read, translated through
the CLI on moltenvk-m3 at a1c2a5f52e) merged OpPhi %_struct of
OpSelect(live, OpFConvert(bits as half), 0) from the Sint and Uint arms with the own arm's
texel, then narrowed the extracted float for the store: the merge of a widened half selected
against zero with another widened value that Metal's compiler does not fold back to the bits
(narrow::merges_mixed_selects' measurement: 2045 of 2046 NaNs 0x7E00), which the analysis did
not see through the struct. With the bits merged as integers, the value after the merge is the
slot's shape (the words' low 16 bits widened, then moved and stored), which keeps every NaN's
bits on the M3. The NativeHalfConversion the module recorded for its texel roundings had been
letting the lane accept those NaNs.

Verified: pending in this commit; the next commits' jobs build and run it (the new core test
engine_cross_class::an_argument_buffer_half_read_merges_its_arms_bits: a u32x4 phi and no texel
struct phi for a half read on every committed profile with a sampled heap, a struct phi for a
float read, inside the word estimate, L3).

(cherry picked from commit 3e9fedbf34cb1ff78f7a32c2322fdd67b5fc36db)
This commit is contained in:
Anees Iqbal committed 2026-11-05 04:28:23 -08:00
1 parent 2c6f549f0c
commit bfc5a95e03
4 files changed
+154 -15

No files matched your search

+1 -1
View File
@@ -60,7 +60,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 = 1965;
pub const SEMANTICS_VERSION: u32 = 1966;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+78 -11
View File
@@ -2273,7 +2273,25 @@ pub(crate) fn with_word(
}
}
/// The texel a read hands the function, before a heap element's null handle zeroes it: the held
/// texel, the heap element's liveness where the image is one, and the sparse arm's status word
/// where the function observes it.
struct ReadTexel {
texel: SValue,
live: Option<SValue>,
word: Option<SValue>,
}
fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<SValue> {
let ReadTexel { texel, live, word } = read_texel(cx, fb, r)?;
let texel = live_or_zero(fb, live, texel)?;
// `{T, i8}`: the status word is the sparse arm's where the function observes it, else 0,
// Metal's for a resident access.
with_word(cx, fb, &r.result, texel, word)
}
/// [`read`]'s texel ([`ReadTexel`]).
fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<ReadTexel> {
// A two-plane 3D texture's read takes its first texel ([`planes_volume`]).
let volume = decl_of(cx, &r.image).is_some_and(|d| planes_volume(&d));
// A storage read's level is its level views'; a sampled read's, its `Lod`.
@@ -2546,10 +2564,7 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<
Some(declared) => reinterpret(fb, r.texel, declared, texel)?,
None => texel,
};
let texel = live_or_zero(fb, live, texel)?;
// `{T, i8}`: the status word is the sparse arm's where the function observes it, else 0,
// Metal's for a resident access.
with_word(cx, fb, &r.result, texel, word)
Ok(ReadTexel { texel, live, word })
}
/// The texel of heap read `r` (`Read::heap_raw`) where its handle's class index names a form a
@@ -2723,6 +2738,17 @@ fn names_class(fb: &mut FunctionBuilder<'_>, index: SValue, class: TexelClass) -
/// the handle's class index names ([`names_class`]), its words handed back as `r`'s, else `r`
/// itself: Metal reads a member of another class in its own class and hands back the words, as
/// at a slot.
///
/// A `half` read's arms hand the merge their texel's `half` bits ([`ArmValue::HalfBits`]), which
/// it carries as integers, and one widening after it reads them as the value (`narrow::from_bits`):
/// a sibling's `half` is its words' low 16 bits widened where the merge ends, as a slot's read of
/// another class widens them (`reinterpret`), so a store of it moves those bits as the slot's
/// does, a NaN's included. Merged as values, each arm's `half` would be the device's widening of
/// its bits, selected against the zero a null handle reads and merged with the other arms'; Metal's
/// compiler does not fold the widening of such a merge back to the bits (`narrow::moves_unfolded`),
/// and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's
/// narrowing (`narrow::to_bits`), the device's conversion of a `half` value, which a store of the
/// merged value took before.
fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<SValue> {
let ImageRef::Heap { handle, .. } = r.image else {
return read(cx, fb, r);
@@ -2732,29 +2758,70 @@ fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) ->
}
let h = cx.operand(fb, handle)?;
let index = heap_class_field(fb, h)?;
read_arms(cx, fb, index, &r.heap_cross, r)
if r.texel.conv != TexelConv::F16 {
return read_arms(cx, fb, index, (&r.heap_cross, r), ArmValue::Read);
}
let half = r.texel.half();
let bits = read_arms(cx, fb, index, (&r.heap_cross, r), ArmValue::HalfBits(half))?;
let texel = narrow::from_bits(fb, half, bits)?;
with_word(cx, fb, &r.result, texel, None)
}
/// The first of `siblings` whose class `index` names, read, else the rest's, else `own`.
/// What each arm of a heap read with siblings hands its merge ([`read_crossed`]).
#[derive(Clone, Copy)]
enum ArmValue {
/// The read's value ([`read`]).
Read,
/// The `half` texel's bits in `u32` lanes, zero-extended, of the texel's form, zero where the
/// handle is null: a `half` read's. A heap read has no status word.
HalfBits(crate::lower::arith::legal::Form),
}
/// Arm `r`'s value for its merge ([`ArmValue`]).
fn arm_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
r: &Read,
what: ArmValue,
) -> BResult<SValue> {
match what {
ArmValue::Read => read(cx, fb, r),
ArmValue::HalfBits(half) => {
let ReadTexel { texel, live, word } = read_texel(cx, fb, r)?;
if word.is_some() {
return Err(cx.fail("a heap read's status word"));
}
let bits = narrow::to_bits(fb, half, texel)?;
live_or_zero(fb, live, bits)
}
}
}
/// The first of `siblings` whose class `index` names, its arm's value ([`arm_value`]), else the
/// rest's, else `own`'s.
fn read_arms(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
index: SValue,
siblings: &[Read],
own: &Read,
(siblings, own): (&[Read], &Read),
what: ArmValue,
) -> BResult<SValue> {
let Some((first, rest)) = siblings.split_first() else {
return read(cx, fb, own);
return arm_value(cx, fb, own, what);
};
let Some(class) = first.heap_class else {
return Err(cx.fail("a heap read's sibling without its class"));
};
let named = names_class(fb, index, class)?;
let then: ArmFn<'_, EmitCx<'_>> =
Box::new(move |fb, cx| Ok(ArmEnd::FallThrough(vec![read(cx, fb, first)?])));
Box::new(move |fb, cx| Ok(ArmEnd::FallThrough(vec![arm_value(cx, fb, first, what)?])));
let other: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
Ok(ArmEnd::FallThrough(vec![read_arms(
cx, fb, index, rest, own,
cx,
fb,
index,
(rest, own),
what,
)?]))
});
let Merged(merged) = fb.if_(cx, named, then, Some(other))?;
+15 -3
View File
@@ -335,7 +335,8 @@ pub struct Read {
/// The read, of a sampled color heap group of one sample, reads a member of another numeric
/// class than its own in that class where the handle's class index names one
/// (`metal::texel_format::heap_numeric_base`, or a float format's own class): one sibling
/// read per other class, the read itself for every other member.
/// read per other class, the read itself for every other member. A `half` read's arms merge
/// the texel's `half` bits, widened once after the merge (`emit::read_crossed`).
pub heap_cross: Vec<Read>,
}
@@ -347,7 +348,7 @@ pub struct Read {
/// clamp-to-edge read's size query, offset, and signed clamp; a `half` texel's call of the
/// conversion routine or exact rounding, or an sRGB texel's raw decode; the lanes Metal reads as
/// constants; the reinterpretation of another class's words; and each sibling of a heap read with
/// its class test and branch.
/// its class test and branch, and a `half` read's merge of its arms' bits.
fn read_words(r: &Read) -> u32 {
let own = 64
+ if r.checked() { 80 } else { 0 }
@@ -382,7 +383,18 @@ fn read_words(r: &Read) -> u32 {
};
let declared = if r.declared.is_some() { 16 } else { 0 };
let siblings: u32 = r.heap_cross.iter().map(|x| read_words(x) + 24).sum();
own + declared + siblings
// A `half` read with siblings merges its arms' bits (`emit::read_crossed`): each arm's
// narrowing (or its noted bits' mask) and null select, and one widening after the merge.
let half_bits = match (r.heap_cross.len() as u32, r.texel.conv) {
(0, _) => 0,
(n, TexelConv::F16) => {
let lanes =
u32::from(r.texel.lanes) * crate::lower::arith::narrow::bits_words(r.texel.half());
(n + 1) * (lanes + 32) + lanes
}
_ => 0,
};
own + declared + siblings + half_bits
}
/// A Metal 4.1 `read(sampler s, ...)` through a constexpr clamp-to-edge sampler (MSL 4.1
@@ -844,6 +844,66 @@ fn a_texture_an_argument_buffer_holds_is_read_in_its_own_class() {
assert!(compiled > 0, "no committed profile has the sampled heap");
}
/// A `half` read of a texture an argument buffer holds merges its class arms as the texel's `half`
/// bits (`emit::read_crossed`), widened once after the merge: on every committed profile with a
/// sampled heap, the module merges a vector of four `u32`s and merges no texel struct, stays inside
/// the plan's word estimate and passes L3. A member of another class then keeps its words' low 16
/// bits wherever the value is stored unchanged, where a merge of each arm's widened `half` selected
/// against a null handle's zero is a move Metal's compiler does not fold back to the bits (on the
/// Apple M3 Max a NaN's bits became `0x7E00`). A `float` read, which widens nothing, still merges
/// its texel structs.
#[test]
fn an_argument_buffer_half_read_merges_its_arms_bits() {
use crate::error::{Error, Feature, Unsupported};
use crate::spirv::ir::Type as SType;
let inputs = LowerInputs::new();
let mut compiled = 0;
for ty in [Ty::Half, Ty::Float] {
let name = format!("held read {ty:?}");
let Some(bc) = assemble(&name, &held_kernel(Held::Read, ty)) else {
return;
};
for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") {
let what = format!("{name} on {stem}");
let m = match typed_module_with(&bc, "k", &p, &inputs) {
Ok((_, m)) => m,
Err(Error::Unsupported(Unsupported {
feature: Feature::ArgumentBufferTextures,
..
})) => continue,
Err(e) => panic!("{what}: {e}"),
};
validate(&bc, &inputs, &p, &what);
let phis: Vec<&SType> = m
.blocks()
.iter()
.flat_map(|b| &b.phis)
.map(|phi| {
let ty = m.value(phi.result).expect("a phi's value").ty;
m.types().get(ty).expect("a phi's type")
})
.collect();
let bits = phis.iter().any(|t| match t {
SType::Vector { elem, len: 4 } => matches!(
m.types().get(*elem),
Ok(SType::Int {
width: 32,
signed: false
})
),
_ => false,
});
let texels = phis.iter().any(|t| matches!(t, SType::Struct { .. }));
match ty {
Ty::Half => assert!(bits && !texels, "{what}: {phis:?}"),
_ => assert!(texels, "{what}: {phis:?}"),
}
compiled += 1;
}
}
assert!(compiled > 0, "no committed profile has the sampled heap");
}
/// A kernel writing the `ty` texel `src[gid.x + 16 gid.y]` (buffer 0) to `access::write` texture
/// slot 0 at its thread's texel `gid`.
fn write_kernel(ty: Ty) -> String {