Translator: a texture buffer held as words is read through a sampler by the words

A read through a sampler (MSL 4.1's read(sampler, coord)) of a texture buffer took the texture's
own view alone, and where the device held the bound format as words the runtime refused the
draw or dispatch (Gap::TexelBufferOwnView). The words now build it: the site reads the
sampler's state (through::state), addresses the index against the words' width the way the own
view's read addresses it against its size (through::buffer_index, which address() now calls for
a texture buffer: the first texel outside, the nearest where a runtime slot sampler's s mode is
clamp_to_edge, the border where the t mode is clamp_to_zero or clamp_to_border), calls the read
routine at the addressed index, and where it reads the border hands back the border texel of
the format the word's code names (words::border_texels), the alpha 1 of a format without alpha
included. Such a read no longer records RuntimeFact::TexelBufferOwnView; the remaining own-view
accesses are a read that observes residency, a read or write of another numeric class, a read of
an sRGB texture's codes and a write of fewer than four lanes.

The site's word estimate adds the sampler's addressing again and THROUGH_WORDS (the view's size,
the width, the border texels by code).

Tests: engine_identity's read-through test now asserts no own-view fact and a words routine
where the profile holds formats as words. The runtime test reads rt_buffer (mirrored_repeat),
rt_buffer_ow (clamp_to_border, opaque white) and rt_arg_buffer through three runtime sampler
states (clamp_to_edge; t clamp_to_zero; t clamp_to_border opaque black) over six formats in
either form, against Metal's texel in bounds and outside.

Docs: words.rs module docs, the fact's and the gap's docs and Display, the runtime README's known
gap, RESOURCE-ID.md; REFUSALS.md regenerated.

Verified at the hand-over tip 355c902082, with (b), on development 8a2acc84fb: clippy in the
three configurations and the translator's tests (gate m3-max-82186; the read-through and words
tests 120 passed, m3-max-82186's focused step); on lavapipe the runtime's texture buffer tests 13
passed and the stream test passed, and the runtime's whole suite 972 passed, 4 skipped; the
read-through test over the three sampler states and six formats on an Iris Xe (m3-max-82187), an
RTX 3090 (m3-max-82193) and an RX 7900 XTX and a 780M (RADV, m3-max-82282), each format in its
form there (B5G6R5Unorm as words on the 3090, the XTX and the 780M); the read-through-buffer
conformance replay on lavapipe, base 8a2acc84fb against the tip, 0 of 1 cases differ
(m3-max-82188).
This commit is contained in:
Anees Iqbal committed 2026-12-02 23:05:54 -08:00
1 parent 13d511cfe9
commit c56000f9e4
11 files changed
+369 -226

No files matched your search

+5 -4
View File
@@ -2290,10 +2290,11 @@ made, with no lock, and never rewritten for layouts.
against 163.8 us, harness row `texel_buffer_b5g6r5_read`, job m3-max-81336) and 2.1% more on an
RX 7900 XTX (93.1 us against 91.2 us, job m3-max-81364); they write it within 0.4% of those
words on both.
- A texture buffer held as words is read, written and asked its width through the words alone: a
function that reaches one by any other access, a read through a sampler (MSL 4.1's
`read(sampler, coord)`) among them, reads the texture's own view, which such a texture buffer
lacks. Such an access compiles as on a device that holds every format directly
- A texture buffer held as words is read (through a sampler too), written and asked its width
through the words alone: a function that reaches one by any other access (a read that observes
residency, a read or write in another numeric class than the texture's, a read of an sRGB
texture's codes, a write of fewer than four lanes) reads the texture's own view, which such a
texture buffer lacks. Such an access compiles as on a device that holds every format directly
(`RuntimeFact::TexelBufferOwnView`), and a draw or dispatch that binds a texture buffer held as
words where it reaches one is refused (`Gap::TexelBufferOwnView`); through an argument
buffer's texture, any such draw or dispatch while a texture buffer held as words is live on the
+9 -11
View File
@@ -1606,9 +1606,9 @@ pub enum Gap {
/// words where the device holds no texel-buffer view of its format
/// (`metal2vulkan::metal::format::texel_buffer_form`), and the function converts its texels
/// from its bytes; the accesses that take the own view alone
/// (`RuntimeFact::TexelBufferOwnView`) are a read through a sampler (MSL 4.1's
/// `read(sampler, coord)`), a read that observes residency, a read or write in another numeric
/// class than the texture's, and a write of fewer than four lanes.
/// (`RuntimeFact::TexelBufferOwnView`) are a read that observes residency, a read or write in
/// another numeric class than the texture's, a read of an sRGB texture's codes, and a write
/// of fewer than four lanes.
/// With `slot`: a texture buffer held as words bound at that texture slot of a function that
/// reaches it so. Without: a function that reaches a texture buffer so through a handle (an
/// argument buffer's texture), while a texture buffer held as words is live on the device. A
@@ -1616,8 +1616,8 @@ pub enum Gap {
/// on a device that holds every format's texture buffers directly. Metal reads and writes such
/// a texture buffer.
///
/// Basis: ours (the words build a texel's read, its write and the width; a read through a
/// sampler's address mode is the next).
/// Basis: ours (the words build a texel's read, its read through a sampler, its write of four
/// lanes and the width).
TexelBufferOwnView {
/// The function's texture slot, or `None` for one it reaches through a handle.
slot: Option<u32>,
@@ -3348,14 +3348,12 @@ impl fmt::Display for Gap {
pixel_format: Some(pixel_format),
} => write!(
f,
"texture slot {slot}, which a function reads through a sampler or otherwise reaches \
by its own view, bound to a texture buffer of {pixel_format:?} held as words is \
not built"
"texture slot {slot}, which a function reaches by its own view, bound to a texture \
buffer of {pixel_format:?} held as words is not built"
),
Gap::TexelBufferOwnView { .. } => f.write_str(
"a texture buffer a function reads through a sampler or otherwise reaches by its \
own view through a handle, while a texture buffer held as words is live, is not \
built",
"a texture buffer a function reaches by its own view through a handle, while a \
texture buffer held as words is live, is not built",
),
Gap::StorageElement {
slot: Some(slot),
@@ -42,7 +42,8 @@ mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::{
Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DispatchType,
FunctionDescriptor, IndexClass, Library, MemoryClass, PixelFormat, StageSource, Texture,
FunctionDescriptor, IndexClass, Library, MemoryClass, PixelFormat, SamplerAddressMode,
SamplerBorderColor, SamplerDescriptor, SamplerState, StageSource, Texture,
TextureDescriptor, TextureType, TextureUsage,
};
use metal2vulkan::device::FormatUsage;
@@ -454,6 +455,7 @@ mod on_device {
state: &ComputePipelineState,
textures: &[&Texture],
buffers: &[&Buffer],
sampler: Option<&SamplerState>,
) -> Result<(), crate::Error> {
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
@@ -468,6 +470,11 @@ mod on_device {
for (slot, buffer) in (0..).zip(buffers) {
encoder.set_buffer(Some(buffer), 0, slot).expect("a buffer");
}
if let Some(sampler) = sampler {
encoder
.set_sampler_state(Some(sampler), 0)
.expect("a sampler");
}
let threads = u32::try_from(THREADS).expect("threads");
let dispatched = encoder.dispatch_threadgroups([1, 1, 1], [threads, 1, 1]);
encoder.end_encoding();
@@ -632,6 +639,7 @@ mod on_device {
&state,
&[&src, &dst, &rw],
&[&values, &reads, &rw_reads, &widths],
None,
) {
Err(error) if refused && read_write_gap(&error, case.format) => {}
Err(error) => return vec![format!("not dispatched: {error}")],
@@ -729,6 +737,7 @@ mod on_device {
&[],
// Slot 2 is unused by the kernel.
&[&values, &args_reads, &values, &args_widths, &args],
None,
) {
wrong.push(format!("not dispatched through handles: {error}"));
return wrong;
@@ -846,24 +855,32 @@ mod on_device {
}
}
/// `kernel_read_through`'s `rt_buffer_ow` reads a texture buffer slot through a sampler
/// (`clamp_to_border`, opaque white), which the words do not build: it compiles on every
/// device as where no format is held as words, and records `RuntimeFact::TexelBufferOwnView`
/// of its slot where some is. Over each of six formats of four channels or none missing but
/// alpha, by the form the device holds it in:
///
/// - held directly, a dispatch reads each texel in bounds and Metal's border texel, white,
/// past the width: of formats without a word layout (`RGBA32Float`, `RGBA16Float`,
/// `RGBA8Unorm`), whose word holds their border texels, and of formats with one
/// (`BGRA8Unorm`, `RGBA16Unorm`, `B5G6R5Unorm`), whose word holds the layout's fields in
/// their place and whose border texels the function takes from the format's code;
/// - held as words, the dispatch that binds it is `Gap::TexelBufferOwnView` of slot 0 and the
/// format, and the same state's next dispatch, of a format held directly, runs as above.
///
/// Each line names the form; a device that holds none of the six as words prints that the
/// refusal was not reached.
/// What a read through a sampler of a texture buffer reads at an index outside it (MSL 4.1;
/// the `read-through-buffer` conformance case's Metal answers): the first texel, the nearest
/// texel (a runtime sampler whose `s` address mode is `clamp_to_edge`), or the border texel of
/// a border color (the `t` axis's mode `clamp_to_zero` or `clamp_to_border`), each lane `[r,
/// g, b, a]`, the alpha 1 of a format without alpha.
#[derive(Clone, Copy)]
enum Outside {
First,
Nearest,
Border([bool; 4]),
}
/// `kernel_read_through`'s texture buffer reads through a sampler: `rt_buffer`
/// (`mirrored_repeat`), `rt_buffer_ow` (`clamp_to_border`, opaque white) and `rt_arg_buffer`
/// through the runtime sampler at `[[sampler(0)]]`: `clamp_to_edge` on every axis, `repeat`
/// on `s` with `clamp_to_zero` on `t`, and with `clamp_to_border` (opaque black) on `t`. Over
/// each of six formats of four channels or none missing but alpha, in whichever form the
/// device holds it, a dispatch reads each texel in bounds and Metal's texel past the width
/// ([`Outside`]): of formats without a word layout (`RGBA32Float`, `RGBA16Float`,
/// `RGBA8Unorm`), whose word holds their border texels, and of formats with one (`BGRA8Unorm`,
/// `RGBA16Unorm`, `B5G6R5Unorm`), whose word holds the layout's fields in their place and whose
/// border texels the function takes from the format's code; held as words, through the words,
/// addressed by the sampler's state against their width. Each line names the read and the
/// form; a device that holds none of the six as words prints that the words were not reached.
#[test]
fn a_read_through_a_sampler_refuses_a_texture_buffer_held_as_words() {
fn a_read_through_a_sampler_reads_a_texture_buffer_as_metal_in_either_form() {
let name = "kernel_read_through.ll";
let library = match llvm_assemble(&engine_dir().join(name)) {
Ok(bitcode) => Library::from_air(&bitcode).expect("the library"),
@@ -881,22 +898,66 @@ mod on_device {
PixelFormat::RGBA16Unorm,
PixelFormat::B5G6R5Unorm,
];
use SamplerAddressMode as M;
let sampler = |s, t, border| {
let mut d = SamplerDescriptor::new();
(d.s_address_mode, d.t_address_mode, d.border_color) = (s, t, border);
Some(d)
};
let reads: [(&str, &str, Option<SamplerDescriptor>, Outside); 5] = [
("rt_buffer", "mirrored_repeat", None, Outside::First),
(
"rt_buffer_ow",
"clamp_to_border opaque white",
None,
Outside::Border([true; 4]),
),
(
"rt_arg_buffer",
"clamp_to_edge",
sampler(
M::ClampToEdge,
M::ClampToEdge,
SamplerBorderColor::TransparentBlack,
),
Outside::Nearest,
),
(
"rt_arg_buffer",
"repeat, t clamp_to_zero",
sampler(
M::Repeat,
M::ClampToZero,
SamplerBorderColor::TransparentBlack,
),
Outside::Border([false; 4]),
),
(
"rt_arg_buffer",
"repeat, t clamp_to_border opaque black",
sampler(
M::Repeat,
M::ClampToBorderColor,
SamplerBorderColor::OpaqueBlack,
),
Outside::Border([false, false, false, true]),
),
];
// Thread `t` reads index `AT[t]` of a texture buffer of 4 texels: texel `t` is channel
// `c` 1 where bit `c` of `t + 1` is set, never all four; past the width, the border.
// `c` 1 where bit `c` of `t + 1` is set, never all four; past the width, `Outside`'s.
const AT: [i32; THREADS] = [0, 1, 2, 3, 4, -1, 7, 1000];
let texel_of = |t: usize| -> [bool; 4] { std::array::from_fn(|c| (t + 1) >> c & 1 == 1) };
each_device(
"texture buffer read through a sampler",
|name, _, device| {
let _grant = (device.grant_indices(IndexClass::Texture, 1, FORMATS.len() as u32))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let function = library.function("rt_buffer_ow").expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
let state = (device
.new_compute_pipeline_state(&descriptor, |s| Ok(vec![0; s.len()])))
.unwrap_or_else(|error| panic!("{name}: no state: {error}"));
let _grants = [
(IndexClass::Texture, FORMATS.len() as u32),
(IndexClass::Sampler, reads.len() as u32),
]
.map(|(class, n)| {
(device.grant_indices(class, 1, n))
.unwrap_or_else(|error| panic!("{name}: {error}"))
});
let block = (device.take_block(MemoryClass::Shared, 16 << 10)).expect("a block");
let place =
|(at, len)| (device.new_buffer(block.id, at, len, Some(0))).expect("a buffer");
@@ -908,89 +969,97 @@ mod on_device {
.collect();
set_bytes(&at, 0, &ats);
let profile = device.translator().profile();
let textures: Vec<(PixelFormat, &str, Texture)> = (FORMATS.into_iter())
.enumerate()
.map(|(k, format)| {
let words = matches!(
formats::texel_buffer_form(format, profile),
Some(formats::TexelBufferForm::Words(_))
);
let form = if words { "words" } else { "own view" };
let texels: Vec<u8> = (0..4)
.flat_map(|t| ones_texel(format, texel_of(t)))
.collect();
let offset = 512 * k;
set_bytes(&data, offset, &texels);
let mut d =
TextureDescriptor::new(TextureType::TextureBuffer, format, 4, 1);
d.usage = TextureUsage::SHADER_READ;
let index = 1 + u32::try_from(k).expect("an index");
let texture = (data.new_texture(&d, Some(index), offset as u64, 256))
.unwrap_or_else(|error| {
panic!("{name}: {format:?} ({form}) not made: {error}")
});
(format, form, texture)
})
.collect();
let mut failed = Vec::new();
let mut refused = 0;
for (k, format) in FORMATS.into_iter().enumerate() {
let words = matches!(
formats::texel_buffer_form(format, profile),
Some(formats::TexelBufferForm::Words(_))
);
let form = if words { "words" } else { "own view" };
let texels: Vec<u8> = (0..4)
.flat_map(|t| ones_texel(format, texel_of(t)))
.collect();
let offset = 512 * k;
set_bytes(&data, offset, &texels);
set_bytes(&out, 0, &[0; 256]);
let mut d = TextureDescriptor::new(TextureType::TextureBuffer, format, 4, 1);
d.usage = TextureUsage::SHADER_READ;
let index = 1 + u32::try_from(k).expect("an index");
let texture = (data.new_texture(&d, Some(index), offset as u64, 256))
.unwrap_or_else(|error| {
panic!("{name}: {format:?} ({form}) not made: {error}")
});
let dispatched = dispatch(&device, &state, &[&texture], &[&at, &out]);
match (words, dispatched) {
(
true,
Err(crate::Error::Unsupported(crate::Gap::TexelBufferOwnView {
slot: Some(0),
pixel_format: Some(f),
})),
) if f == format => {
refused += 1;
println!(
"{name}: {format:?} ({form}): refused, Gap::TexelBufferOwnView"
);
for (r, (entry, mode, descriptor, outside)) in (1..).zip(&reads) {
let (entry, mode, outside) = (*entry, *mode, *outside);
let function = library.function(entry).expect("the kernel");
let pipeline = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
let state = (device
.new_compute_pipeline_state(&pipeline, |s| Ok(vec![0; s.len()])))
.unwrap_or_else(|error| panic!("{name}: {entry}: no state: {error}"));
let sampler = descriptor.as_ref().map(|d| {
(device.new_sampler_state(d, r))
.unwrap_or_else(|error| panic!("{name}: {mode}: {error}"))
});
for (format, form, texture) in &textures {
let read = format!("{entry} ({mode}), {format:?} ({form})");
set_bytes(&out, 0, &[0; 256]);
let buffers = [&at, &out];
if let Err(error) =
dispatch(&device, &state, &[texture], &buffers, sampler.as_ref())
{
println!("{name}: {read}: {error}");
failed.push(read);
continue;
}
(_, Err(error)) => {
println!("{name}: {format:?} ({form}): {error}");
failed.push(format);
continue;
}
(true, Ok(())) => {
println!("{name}: {format:?} ({form}): dispatched, not refused");
failed.push(format);
continue;
}
(false, Ok(())) => {}
}
let got = floats(&out);
let mut wrong = Vec::new();
for (t, &x) in AT.iter().enumerate() {
let want: [bool; 4] = match usize::try_from(x) {
Ok(i) if i < 4 => {
let mut c = texel_of(i);
c[3] |= format == PixelFormat::B5G6R5Unorm;
c
}
_ => [true; 4],
let alpha = *format == PixelFormat::B5G6R5Unorm;
let texel = |i: usize| {
let mut c = texel_of(i);
c[3] |= alpha;
c
};
let want = want.map(|on| if on { 1.0f32 } else { 0.0 });
if got[4 * t..4 * t + 4] != want {
wrong.push(format!(
"index {x}: {:?}, Metal {want:?}",
&got[4 * t..4 * t + 4]
));
let got = floats(&out);
let mut wrong = Vec::new();
for (t, &x) in AT.iter().enumerate() {
let want: [bool; 4] = match (usize::try_from(x), outside) {
(Ok(i), _) if i < 4 => texel(i),
(_, Outside::First) => texel(0),
(Ok(_), Outside::Nearest) => texel(3),
(Err(_), Outside::Nearest) => texel(0),
(_, Outside::Border(mut b)) => {
b[3] |= alpha;
b
}
};
let want = want.map(|on| if on { 1.0f32 } else { 0.0 });
if got[4 * t..4 * t + 4] != want {
wrong.push(format!(
"index {x}: {:?}, Metal {want:?}",
&got[4 * t..4 * t + 4]
));
}
}
}
match wrong.is_empty() {
true => {
println!("{name}: {format:?} ({form}): every texel and border Metal's")
}
false => {
println!("{name}: {format:?} ({form}): {wrong:?}");
failed.push(format);
match wrong.is_empty() {
true => println!("{name}: {read}: every texel and outside Metal's"),
false => {
println!("{name}: {read}: {wrong:?}");
failed.push(read);
}
}
}
}
if refused == 0 {
if textures.iter().all(|(_, form, _)| *form != "words") {
println!(
"{name}: none of the formats is held as words: the refusal is not reached"
"{name}: none of the formats is held as words: the words are not reached"
);
}
assert!(failed.is_empty(), "{name}: formats that differ: {failed:?}");
assert!(failed.is_empty(), "{name}: reads that differ: {failed:?}");
},
);
}
@@ -24,7 +24,7 @@ use super::{
use super::{NullArm, Prelude, Switch, TextureStrategy, Write};
use crate::memory::handles::{HANDLE_ALPHA_ONE, NEUTRAL_ELEMENT, NULL_HANDLE};
mod through;
pub(super) mod through;
/// Emit strategy `s` of instruction `at` into the open block.
pub fn emit(
@@ -44,7 +44,7 @@ impl Flag {
}
/// The state a read through a sampler addresses by, in the function ([`ReadSampler`]).
pub(super) struct State {
pub(in crate::lower::texture) struct State {
/// Per plane axis (`s`, `t`, `r`): an index outside the level reads the border texel.
border: [Flag; 3],
/// The read reads at its level, not the base level: the sampler has a mip filter.
@@ -60,7 +60,7 @@ pub(super) struct State {
/// The state of `s` in the function: a constexpr sampler's as constants, a runtime one's read from
/// its word (`SamplerWord::READ_STATE`'s fields), a slot's `SamplerState` specialization or an
/// argument buffer's sampler table entry.
pub(super) fn state(
pub(in crate::lower::texture) fn state(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: ReadSampler,
@@ -150,10 +150,9 @@ pub(super) struct Addressed {
/// one) through a sampler of state `s`. Its level, where the image's, is its own under a mip
/// filter, else the base level. Its signed plane coordinate plus its offset is tested lane-wise
/// against the image's size at that level and clamped into `[0, size - 1]`; a lane outside on a
/// border axis reads the border texel, and a texture buffer's index outside reads its first texel,
/// or the border texel where the `t` axis is a border axis, unless the sampler clamps it
/// ([`State::buffer_clamps`]). The layer is composed unclamped
/// ([`compose`]), and tested against the image's layers.
/// border axis reads the border texel. A texture buffer's index is [`buffer_index`]'s against
/// its size. The layer is composed unclamped ([`compose`]), and tested against the image's
/// layers.
pub(super) fn address(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -186,73 +185,56 @@ pub(super) fn address(
Some(l) if sampled => fb.query(ImageQuery::SizeLod(l), img)?,
_ => fb.query(ImageQuery::Size, img)?,
};
let mut plane = cx.operand(fb, at.plane)?;
if let Some(o) = t.offset {
let o = cx.operand(fb, o)?;
plane = fb.binary(BinOp::IAdd, plane, o)?;
}
let n = coord_len(decl);
let lanes = at.lanes;
let extent = if lanes == n {
size
} else if lanes == 1 {
fb.composite_extract(size, &[0])?
} else {
let first: Vec<u32> = (0..u32::from(lanes)).collect();
fb.vector_shuffle(size, size, &first)?
};
let one = u32s(fb, lanes, 1)?;
let top = fb.binary(BinOp::ISub, extent, one)?;
let below = fb.glsl(GlslOp::SMin, &[plane, top])?;
let zero = u32s(fb, lanes, 0)?;
let clamped = fb.glsl(GlslOp::SMax, &[below, zero])?;
let within = fb.binary(BinOp::ULessThan, plane, extent)?;
// A lane outside on a border axis. A texture buffer's index is addressed as the first texel
// of a row outside its one row: the `t` axis's mode says whether that is the border texel, and
// a sampler that clamps the index never reads it (module docs).
let buffer = matches!(decl.dim, Dim::Buffer);
let mut border = None;
for a in 0..lanes {
let inside = match lanes {
1 => within,
_ => fb.composite_extract(within, &[u32::from(a)])?,
};
let outside = fb.unary(UnOp::LogicalNot, inside)?;
let axis = if buffer { 1 } else { usize::from(a) };
let Some(&flag) = s.border.get(axis) else {
return Err(cx.fail("a read's coordinate past the sampler's three axes"));
};
if let Some(out) = flag.and(fb, outside)? {
border = Some(match border {
Some(b) => fb.binary(BinOp::LogicalOr, b, out)?,
None => out,
});
}
}
if buffer {
border = match (border, s.buffer_clamps) {
(_, Flag::Known(true)) | (None, _) => None,
(Some(b), Flag::Known(false)) => Some(b),
(Some(b), Flag::Value(clamps)) => {
let kept = fb.unary(UnOp::LogicalNot, clamps)?;
Some(fb.binary(BinOp::LogicalAnd, b, kept)?)
let (plane, border) = match decl.dim {
Dim::Buffer => buffer_index(cx, fb, r, s, size)?,
_ => {
let mut plane = cx.operand(fb, at.plane)?;
if let Some(o) = t.offset {
let o = cx.operand(fb, o)?;
plane = fb.binary(BinOp::IAdd, plane, o)?;
}
};
}
// A texture buffer's index outside reads its first texel where the sampler does not clamp it.
let plane = match decl.dim {
Dim::Buffer => {
let first = u32s(fb, 1, 0)?;
let unclamped = fb.select(within, clamped, first)?;
s.buffer_clamps.select(fb, clamped, unclamped)?
let n = coord_len(decl);
let lanes = at.lanes;
let extent = if lanes == n {
size
} else if lanes == 1 {
fb.composite_extract(size, &[0])?
} else {
let first: Vec<u32> = (0..u32::from(lanes)).collect();
fb.vector_shuffle(size, size, &first)?
};
let one = u32s(fb, lanes, 1)?;
let top = fb.binary(BinOp::ISub, extent, one)?;
let below = fb.glsl(GlslOp::SMin, &[plane, top])?;
let zero = u32s(fb, lanes, 0)?;
let clamped = fb.glsl(GlslOp::SMax, &[below, zero])?;
let within = fb.binary(BinOp::ULessThan, plane, extent)?;
// A lane outside on a border axis.
let mut border = None;
for a in 0..lanes {
let inside = match lanes {
1 => within,
_ => fb.composite_extract(within, &[u32::from(a)])?,
};
let outside = fb.unary(UnOp::LogicalNot, inside)?;
let Some(&flag) = s.border.get(usize::from(a)) else {
return Err(cx.fail("a read's coordinate past the sampler's three axes"));
};
if let Some(out) = flag.and(fb, outside)? {
border = Some(match border {
Some(b) => fb.binary(BinOp::LogicalOr, b, out)?,
None => out,
});
}
}
(clamped, border)
}
_ => clamped,
};
let coord = compose(cx, fb, decl, at, plane)?;
let layer_ok = match at.layer {
Some(l) => {
let l = cx.operand(fb, l)?;
let layers = fb.composite_extract(size, &[u32::from(lanes)])?;
let layers = fb.composite_extract(size, &[u32::from(at.lanes)])?;
Some(fb.binary(BinOp::ULessThan, l, layers)?)
}
None => None,
@@ -270,6 +252,52 @@ pub(super) fn address(
})
}
/// The index read `r` of a texture buffer of `width` texels (a `u32`) through a sampler of state
/// `s` accesses, and where the read hands back the border texel in place of the texel (`None`:
/// never). Its signed index plus its offset is clamped into `[0, width - 1]`. An index outside the
/// buffer is addressed as the first texel of a row outside its one row: it reads the first texel,
/// or the border texel where the `t` axis is a border axis, unless the sampler clamps the index
/// ([`State::buffer_clamps`]), which then reads the nearest texel. The texture's own view's width
/// is its size; a texture buffer held as words passes the words' (`words`).
pub(in crate::lower::texture) fn buffer_index(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
r: &Read,
s: &State,
width: SValue,
) -> BResult<(SValue, Option<SValue>)> {
let Some(t) = r.through else {
return Err(cx.fail("an addressed index of a read without its sampler"));
};
let mut x = cx.operand(fb, r.at.plane)?;
if let Some(o) = t.offset {
let o = cx.operand(fb, o)?;
x = fb.binary(BinOp::IAdd, x, o)?;
}
let one = u32s(fb, 1, 1)?;
let top = fb.binary(BinOp::ISub, width, one)?;
let below = fb.glsl(GlslOp::SMin, &[x, top])?;
let zero = u32s(fb, 1, 0)?;
let clamped = fb.glsl(GlslOp::SMax, &[below, zero])?;
let within = fb.binary(BinOp::ULessThan, x, width)?;
let outside = fb.unary(UnOp::LogicalNot, within)?;
let Some(&flag) = s.border.get(1) else {
return Err(cx.fail("a sampler state without its t axis"));
};
let border = match (flag.and(fb, outside)?, s.buffer_clamps) {
(None, _) | (_, Flag::Known(true)) => None,
(Some(b), Flag::Known(false)) => Some(b),
(Some(b), Flag::Value(clamps)) => {
let kept = fb.unary(UnOp::LogicalNot, clamps)?;
Some(fb.binary(BinOp::LogicalAnd, b, kept)?)
}
};
let first = u32s(fb, 1, 0)?;
let unclamped = fb.select(within, clamped, first)?;
let index = s.buffer_clamps.select(fb, clamped, unclamped)?;
Ok((index, border))
}
/// `texel`, read `r`'s texel in its result form, with what the read hands back in place of it
/// ([`Addressed`]): the texture's border texel where the plane coordinate is outside on a border
/// axis, and zero in every lane where its level or layer is not the image's; but `texel` itself
@@ -359,7 +387,7 @@ fn border_bits(
/// Metal's border texel of border texels `bits` ([`border_bits`]) for the color of `s`, in the
/// form of `like` (a `float`, `half` or 32-bit integer scalar or vector of up to four lanes): lane
/// `c` is 1 where bit `3c + color` of `bits` is set, else 0.
fn border_texel(
pub(in crate::lower::texture) fn border_texel(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
bits: SValue,
+3 -1
View File
@@ -972,7 +972,9 @@ impl TextureStrategy {
TextureStrategy::ExtendedSample(e) => e.words(),
// The zero, a constant.
TextureStrategy::AbsentArgument(_) => 0,
TextureStrategy::Words(w) => w.native.base_words() + words::SITE_WORDS,
TextureStrategy::Words(w) => {
w.native.base_words() + words::SITE_WORDS + w.through_words()
}
}
}
}
+70 -22
View File
@@ -21,14 +21,16 @@
//! 1 for a format without alpha, bit 12 of the word), a write outside it is dropped, as Metal
//! drops it, the padding of the last word included.
//!
//! A read through a sampler, a read that observes its residency, a read or write in another
//! numeric class than the bound texture's, a read of an sRGB texture's codes and a write of fewer
//! than four lanes are not built for the words: such an access takes the texture's own view alone,
//! as on a profile that holds no format as words, and the stage records
//! `RuntimeFact::TexelBufferOwnView` for its slot or its handles, where the runtime refuses a
//! texture buffer held as words. A texture buffer of a word layout carries its fields in its word's
//! border texels; a slot's read through a sampler of one takes its format's from its code
//! ([`border_texels`]).
//! A read through a sampler (MSL 4.1) is addressed by its sampler's state against the words'
//! width, as the own view's read is against its size (`emit::through::buffer_index`), and where it
//! reads the border it hands back its format's border texel, from its code ([`border_texels`]):
//! a texture buffer of a word layout carries its fields in its word's border texels, so a slot's
//! read through a sampler of its own view takes its format's from its code too. A read that
//! observes its residency, a read or write in another numeric class than the bound texture's, a
//! read of an sRGB texture's codes and a write of fewer than four lanes are not built for the
//! words: such an access takes the texture's own view alone, as on a profile that holds no format
//! as words, and the stage records `RuntimeFact::TexelBufferOwnView` for its slot or its handles,
//! where the runtime refuses a texture buffer held as words.
//!
//! A read converts each channel as Metal reads it: a normalized code `c` of `n` bits to
//! `c / (2^n - 1)` correctly rounded ([`unorm_values`]: the code's repeating binary expansion,
@@ -81,6 +83,7 @@ use crate::spirv::ir::{
ImageUsage, MemAccess, Scope, Semantics, Type as SType, UnOp,
};
use super::emit::through;
use super::{ImageDecl, ImageRef, QueryKind, TexelClass, TexelConv, TextureStrategy};
/// The census name of the routines' words, once per module and routine.
@@ -94,6 +97,10 @@ pub const ROUTINE_WORDS: u64 = 256 + WORD_FORMATS.len() as u64 * 160;
/// call, and a read's held conversion or a width's arithmetic.
pub const SITE_WORDS: u32 = 64;
/// The words a read through a sampler adds to its site past its sampler's state and addressing,
/// which the site takes again: the view's size, the width, and the border texels by code.
pub const THROUGH_WORDS: u32 = 128;
/// A routine of the module's texture buffers held as words. `nonuniform`: its element index may
/// differ between invocations (an argument buffer's texture), so it indexes the array
/// `NonUniform`.
@@ -187,6 +194,15 @@ pub struct Words {
}
impl Words {
/// The words a read through a sampler adds to its site ([`THROUGH_WORDS`] and the sampler's
/// own addressing again).
pub(super) fn through_words(&self) -> u32 {
match &self.native {
TextureStrategy::Read(r) => r.through.map_or(0, |t| t.words() + THROUGH_WORDS),
_ => 0,
}
}
/// The census name.
pub(super) fn name(&self) -> &'static str {
match self.native {
@@ -221,7 +237,7 @@ pub(super) fn wrap(
let class = class.filter(|c| *c != TexelClass::Uint64);
let routine = match (&s, class) {
(TextureStrategy::Read(r), Some(class)) => {
if r.declared.is_some() || r.residency || r.through.is_some() || r.raw {
if r.declared.is_some() || r.residency || r.raw {
return Ok(own_view(cx, image, s));
}
Some(Routine::Read {
@@ -447,9 +463,28 @@ pub(super) fn emit(
let v = super::emit::value(cx, fb, native, None)?;
Ok(ArmEnd::FallThrough(v.into_iter().collect()))
});
let array = match w.storage {
true => cx.decl.families.texture.words.storage,
false => cx.decl.families.texture.words.uniform,
};
let nonuniform = w.image.heap();
let words: ArmFn<'_, EmitCx<'_>> = match (native, routine) {
(TextureStrategy::Read(r), Some(f)) => Box::new(move |fb, cx| {
let x = cx.operand(fb, r.at.plane)?;
// A read through a sampler: its index addressed by the sampler's state against the
// words' width, and the border texel its format's, from its code.
let (x, border) = match r.through {
None => (cx.operand(fb, r.at.plane)?, None),
Some(t) => {
let Some(array) = array else {
return Err(cx.fail("a texture buffer's word array is not declared"));
};
let state = through::state(cx, fb, t.sampler)?;
let size = view_size(fb, (array, nonuniform), element)?;
let width = width(fb, word, size)?;
let (x, out) = through::buffer_index(cx, fb, r, &state, width)?;
(x, out.map(|out| (state, out)))
}
};
let Some(v) = fb.call(f, &[element, word, x])? else {
return Err(cx.fail("a word read without a texel"));
};
@@ -462,6 +497,14 @@ pub(super) fn emit(
_ => TexelClass::Uint,
};
let v = super::emit::held_texel(fb, held, r.texel, v)?;
let v = match border {
Some((state, out)) => {
let bits = border_texels(fb, word)?;
let border = through::border_texel(cx, fb, bits, &state, v)?;
fb.select(out, border, v)?
}
None => v,
};
let v = super::emit::with_word(cx, fb, &r.result, v, None)?;
Ok(ArmEnd::FallThrough(vec![v]))
}),
@@ -485,22 +528,11 @@ pub(super) fn emit(
Ok(ArmEnd::FallThrough(Vec::new()))
}),
(TextureStrategy::Query(_), None) => {
let array = match w.storage {
true => cx.decl.families.texture.words.storage,
false => cx.decl.families.texture.words.uniform,
};
let Some(array) = array else {
return Err(cx.fail("a texture buffer's word array is not declared"));
};
let nonuniform = w.image.heap();
Box::new(move |fb, _| {
let base = fb.module().global_value(array)?;
let p = match nonuniform {
true => fb.access_chain_non_uniform(base, element)?,
false => fb.access_chain(base, &[element])?,
};
let img = fb.load(p, MemAccess::default())?;
let size = fb.query(ImageQuery::Size, img)?;
let size = view_size(fb, (array, nonuniform), element)?;
let v = width(fb, word, size)?;
Ok(ArmEnd::FallThrough(vec![v]))
})
@@ -511,6 +543,22 @@ pub(super) fn emit(
Ok(m.first().copied())
}
/// The words of element `element` of texel-buffer array `array` (indexed `NonUniform` where
/// `nonuniform`): its view's size.
fn view_size(
fb: &mut FunctionBuilder<'_>,
(array, nonuniform): (GlobalId, bool),
element: SValue,
) -> BResult<SValue> {
let base = fb.module().global_value(array)?;
let p = match nonuniform {
true => fb.access_chain_non_uniform(base, element)?,
false => fb.access_chain(base, &[element])?,
};
let img = fb.load(p, MemAccess::default())?;
fb.query(ImageQuery::Size, img)
}
/// The stage's `SpecKey::TexelBufferWords`, a `bool` fixed at pipeline creation (false by
/// default), which gates each site's test and the word bits a handle carries: where it is false
/// they are dead code, and each access is its texture's own view's alone.
+3 -3
View File
@@ -620,9 +620,9 @@ pub enum RuntimeFact {
/// Under the identity domains, on a profile that holds some colour format's texture buffers as
/// words (`metal::format::texel_buffer_form`), the function reaches a texture buffer by an
/// access the words do not build (`lower::texture::words`), which takes the texture's own view
/// alone: a read through a sampler, a read that observes its residency, a read or write in
/// another numeric class than the bound texture's, a read of an sRGB texture's codes, or a
/// write of fewer than four lanes. A texture buffer held as words has no such view. `texture`:
/// alone: a read that observes its residency, a read or write in another numeric class than
/// the bound texture's, a read of an sRGB texture's codes, or a write of fewer than four
/// lanes. A texture buffer held as words has no such view. `texture`:
/// the slot `[[texture(n)]]` of the stage the access reaches, or `None` for a texture buffer it
/// reaches through a handle (an argument buffer's texture). The binder refuses a draw or
/// dispatch that binds a texture buffer held as words at the slot, or, for `None`, one while a
@@ -572,13 +572,13 @@ fn a_texture_buffer_is_the_texel_buffer_element_its_resource_id_names() {
}
/// A read through a sampler of a texture buffer slot (`kernel_read_through`'s `rt_buffer`,
/// `rt_buffer_ow` and `rt_arg_buffer`), which the words of a texture buffer held as words do not
/// build, compiles under the identity domains on each profile and passes L3: it reads the slot's
/// own view, and where the profile holds some format's texture buffers as words it records
/// `RuntimeFact::TexelBufferOwnView` of the slot, where the runtime refuses one held as words; on a
/// profile that holds none so it records nothing of it. One of the profiles holds some so.
/// `rt_buffer_ow` and `rt_arg_buffer`) compiles under the identity domains on each profile, passes
/// L3 and records no `RuntimeFact::TexelBufferOwnView`: where the profile holds some format's
/// texture buffers as words it reads one through the words' read routine, its index addressed by
/// its sampler's state against their width (`lower::texture::words`); on a profile that holds none
/// so it plans no routine. One of the profiles holds some so.
#[test]
fn a_read_through_a_sampler_of_a_texture_buffer_takes_its_own_view() {
fn a_read_through_a_sampler_of_a_texture_buffer_reads_the_words() {
let Some(bc) = assemble("kernel_read_through") else {
return;
};
@@ -591,15 +591,11 @@ fn a_read_through_a_sampler_of_a_texture_buffer_takes_its_own_view() {
let (a, plan, _) =
compile_kept(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}"));
let own: Vec<RuntimeFact> = (plan.facts.iter().copied())
.filter(|f| matches!(f, RuntimeFact::TexelBufferOwnView { .. }))
.collect();
let want = RuntimeFact::TexelBufferOwnView {
stage: Stage::Kernel,
texture: Some(0),
};
let want: Vec<RuntimeFact> = held.then_some(want).into_iter().collect();
assert_eq!(own, want, "{stem} {entry}");
let own =
(plan.facts.iter()).any(|f| matches!(f, RuntimeFact::TexelBufferOwnView { .. }));
assert!(!own, "{stem} {entry}: an own view's fact");
let routines = &plan.families.texture.words.routines;
assert_eq!(!routines.is_empty(), held, "{stem} {entry}: {routines:?}");
}
}
assert!(holding > 0, "no profile holds a format as words");
+1 -1
View File
@@ -378,7 +378,7 @@ Columns:
| `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour, depth and stencil attachments of one sample, with no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 5: `crates/metal2vulkan-runtime/src/render.rs (draw_input)`, `crates/metal2vulkan-runtime/src/render.rs (of)` (+2) | `-` |
| `SwizzledReadWrite` | A draw or dispatch whose function declares `access::read_write` at texture slot `slot` and reads it, where the texture bound there has a swizzle... | every device (a public call's own check of its arguments) | `ours`: built when a replay stream counts one | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` |
| `OpenClLineTexture` | A dispatch of a kernel of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`) whose texture slot `slot` is bound to a 1D or 1D array... | every device (a public call's own check of its arguments) | `ours`: no reading of it is documented Metal | 1: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` | `-` |
| `TexelBufferOwnView` | A draw or dispatch whose function reaches a texture buffer held as words by an access the words do not build, which takes the texture's own view alone | every device (a public call's own check of its arguments) | `ours`: the words build a texel's read, its write and the width; a read through a sampler's address mode is the next | 4: `crates/metal2vulkan-runtime/src/pipeline.rs (own_view_gap, 2 sites)`, `crates/metal2vulkan-runtime/src/render.rs (own_view_gap, 2 sites)` | `-` |
| `TexelBufferOwnView` | A draw or dispatch whose function reaches a texture buffer held as words by an access the words do not build, which takes the texture's own view alone | every device (a public call's own check of its arguments) | `ours`: the words build a texel's read, its read through a sampler, its write of four lanes and the width | 4: `crates/metal2vulkan-runtime/src/pipeline.rs (own_view_gap, 2 sites)`, `crates/metal2vulkan-runtime/src/render.rs (own_view_gap, 2 sites)` | `-` |
| `StorageElement` | A draw or dispatch whose function writes a texture slot, or reads one through its storage image (`access::read_write`), bound to a texture made... | every device (a public call's own check of its arguments) | `ours`: the storage element through a view of the nearest format whose storage Vulkan requires of every device, with the translator's conversion, is the form to build | 4: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch, 2 sites)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find, 2 sites)` | `-` |
| `BicubicTexels` | A dispatch or a draw whose function samples texture slot `slot` through a constexpr sampler with Metal's bicubic filter (`filter::bicubic`), where... | every device (a public call's own check of its arguments) | `ours`: each refused format's treatment is built when a guest binds one | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` |
| `TextureView` | `Texture::new_texture_view` of a kind Metal makes and the runtime does not build | every device (a public call's own check of its arguments) | `ours`: the replay streams' views that compute binds are same-format views of every slice, 2D views of one slice of a 2D array, and level subranges, swizzled or not; each other kind is built when a replay stream binds one | 1: `crates/metal2vulkan-runtime/src/texture.rs (view)` | `-` |
+2 -1
View File
@@ -96,7 +96,8 @@ as words takes its format, its texels per word, whether a texel is two words and
bits 0-10 of its word. A slot's `read` through a sampler (MSL 4.1) takes the border
texel an index outside the level reads on a border axis from bits 0-11 of the word, for the
sampler's border color; a texture buffer's whose word has bit 13 set, from the border texels of
the format its code names. The runtime writes a slot's ID, so its index is an element;
the format its code names, as an argument buffer's texture buffer held as words does from the code
its handle carries. The runtime writes a slot's ID, so its index is an element;
the program writes an argument buffer's, so the shader masks its index to its low 16 bits: a bad
ID reads the element at `index & 0xFFFF`, never one outside the arrays.