translator: an argument buffer's texture index is masked to the set-1 image arrays

What: under the identity domains (Device::from_queries' profile alone; Device::new never takes
them, so its modules are unchanged), the handle of a texture whose resource ID an argument buffer
holds is the ID's low word masked to its low 16 bits (IDENTITY_TEXTURES - 1, the two image
arrays' 65,536 elements, a power of two the compiler checks): one OpBitwiseAnd a handle. A bad ID
reads the element at index & 0xFFFF, never one outside the arrays. Nothing else changes: a slot's
index is the runtime's own push (SlotGuestBase), a constexpr sampler's too (ConstexprSampler), and
an argument buffer's sampler is not lowered under these domains, so the sampler arrays stay at
4,000 with no mask. docs/API.md, where that sampler's refusal is listed, and RESOURCE-ID.md say
the change that first lowers one masks its index the same way. The new runtime's README records,
among the known gaps of memory blocks, that a shader uses a buffer's gpuAddress unchecked, so a
stale one can still fault the device. SEMANTICS_VERSION 2178: from_queries' translations of such a
texture change (2177 is the unlanded float-array branch's).

The feedback elements (index + 65,536 in the sampled array, where the device reads attachments):
only a draw's push of a texture slot's index reaches them. The render encoder builds no
useResource: or useHeap:, so no draw makes an argument buffer's texture resident, and Metal reads
an argument buffer's texture only once it is resident; the mask keeps every argument-buffer index
below 65,536 besides. So an argument-buffer texture that is also the pass's attachment is never
offset to its feedback element: the shader reads element index, as before, a read Metal leaves
undefined while the texture is not made resident (only the compute encoder has use_resource and
use_heap).

Why: the ID is the program's word, and an index past the arrays fetches a descriptor outside
them.

Verified:
- Check 46942 (msi) at this change on 98efd4de50: clippy, all features, 0; clippy under
  m2v_gpu 0; the identity, golden, old render key, resource ID and public fixture tests 86 of 87,
  the one failure the old render key, pinned here at 64b84e0f... from that run (SEMANTICS 2178).
- Final check 47056 (msi) at this tree (as 5794117bcb): clippy, all features, 0; clippy under
  m2v_gpu 0; the same tests 87 of 87, the old render key at its pin among them.
- Words per identity texture kernel (base d392d453d6, 46865 -> this change, 46942): without an
  argument buffer 829 -> 829; with one 1172 -> 1191; without robustImageAccess2 942 -> 942 and
  1368 -> 1387.
- Negative control 46864: with the mask taken out, the identity test of IDs 65,536 past the
  arrays fails (rc 100); with it, passes.
- The rt device test, ID 0x1_0005 reading element 5 (index 5 and 5 + 0x1_0000 both answer
  7 x 3 and the texel): RX 550 46854, XTX 46855, RTX 3090 46856, Iris Xe 46857, all pass.
- Harness module hashes, every compute row, the mask (8d9317bef0) against its base (d392d453d6),
  the same harness: XTX 46951 19 of 19 equal; RTX 3090 46952 19 of 19 equal.
This commit is contained in:
Anees Iqbal committed 2026-11-18 09:37:25 -08:00
1 parent e38d800b23
commit a47fc3e69d
9 files changed
+200 -19

No files matched your search

+6
View File
@@ -236,6 +236,8 @@ after a quiesce.
### Known gaps of memory blocks
- A shader uses a buffer's `gpuAddress` directly, unchecked: a stale one, of a released buffer, can
still fault the device.
- A dispatch whose indirect arguments, or an indexed draw whose indices, start at a byte of their
block that is not a multiple of 4, or of the index size, is refused (`Refusal::ArgumentPlace`).
Metal's offset rules keep both at that multiple of the buffer's start, so only a buffer that
@@ -273,6 +275,10 @@ made, with no lock, and never rewritten for layouts.
with no storage view); on a device without the loop it is the texture's view of its image's
shadow (Render encoders), written at the first draw that reads through it where the texture
still owns index `i`. It is a null descriptor otherwise, and no grant reaches it.
- A shader masks the index of a texture ID it reads from an argument buffer to its low 16 bits,
so a bad ID there reads the element at `index & 0xFFFF`, never one outside the arrays. A slot's
index is the runtime's own push, unmasked, and no argument buffer's ID reaches the feedback
elements.
- Every element no object owns is defined. A texture element is a null descriptor
(`nullDescriptor`): it reads zeros, sizes 0 and drops writes, as Metal's nil texture does. A
sampler element is its array's default sampler, nearest and clamped to the edge; the
@@ -1901,4 +1901,146 @@ mod on_device {
println!("{name}: loads and stores up to 2 GiB landed at their own words");
});
}
/// A kernel that reads, through the argument buffer at buffer 0 (one `texture2d<float, read>`
/// member, its 8-byte resource ID), the texture's width, height and texel `(0, 0)`'s red bits
/// into words 0 to 2 of `out` (buffer 1).
const ARGUMENT_TEXTURE: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
%struct.T = type { ptr addrspace(1) }
%struct.R = type { %struct.T }
define void @argument_texture(ptr addrspace(2) %r, ptr addrspace(1) noundef "air-buffer-no-alias" %out) {
entry:
%pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0
%t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8
%s = tail call ptr addrspace(2) @air.get_read_sampler()
%r0 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1)
%v = extractvalue { <4 x float>, i8 } %r0, 0
%red = extractelement <4 x float> %v, i64 0
%rb = bitcast float %red to i32
%w = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0)
%h = tail call i32 @air.get_height_texture_2d(ptr addrspace(1) %t, i32 0)
store i32 %w, ptr addrspace(1) %out, align 4
%o1 = getelementptr inbounds i32, ptr addrspace(1) %out, i64 1
store i32 %h, ptr addrspace(1) %o1, align 4
%o2 = getelementptr inbounds i32, ptr addrspace(1) %out, i64 2
store i32 %rb, ptr addrspace(1) %o2, align 4
ret void
}
declare ptr addrspace(2) @air.get_read_sampler()
declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)
declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32)
declare i32 @air.get_height_texture_2d(ptr addrspace(1), i32)
!air.kernel = !{!0}
!air.version = !{!7}
!air.language_version = !{!8}
!0 = !{ptr @argument_texture, !1, !2}
!1 = !{}
!2 = !{!3, !5}
!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"}
!4 = !{i32 0, i32 8, i32 0, !"texture2d<float, read>", !"t", !"air.indirect_argument", !6}
!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
!6 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d<float, read>", !"air.arg_name", !"t"}
!7 = !{i32 2, i32 8, i32 0}
!8 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// An argument buffer's texture ID is the program's word, so the shader masks its index to
/// the set-1 image arrays: an ID whose index is 65,536 past texture 5's reads texture 5, as
/// its own ID does, and never an element outside the arrays.
#[test]
fn every_device_reads_an_argument_buffer_texture_at_its_index_masked_to_the_arrays() {
use crate::{
IndexClass, PixelFormat, Region, Resource, ResourceUsage, TextureDescriptor,
TextureType, TextureUsage,
};
let bitcode = match metal2vulkan_devtools::llvm_assemble_text(ARGUMENT_TEXTURE) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(error) => panic!("argument_texture: {error:?}"),
};
let library = Library::from_air(&bitcode).expect("the library");
let function = library.function("argument_texture").expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
each_device("compute_argument_texture_masked", |name, _, device| {
let _grant = device
.grant_indices(IndexClass::Texture, 1, 8)
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (width, height) = (7u32, 3u32);
let mut d = TextureDescriptor::new(
TextureType::Type2D,
PixelFormat::RGBA32Float,
width,
height,
);
d.usage = TextureUsage::SHADER_READ;
let texture = device
.new_texture(&d, Some(5))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let texel = [0.75f32, 0.0, 0.0, 1.0];
let bytes: Vec<u8> = (0..width * height)
.flat_map(|_| texel.iter().flat_map(|c| c.to_le_bytes()))
.collect();
let row = u64::from(width) * 16;
texture
.replace_region(
Region {
origin: [0, 0, 0],
size: [width, height, 1],
},
0,
0,
&bytes,
row,
row * u64::from(height),
)
.unwrap_or_else(|error| panic!("{name}: {error}"));
let id = texture.gpu_resource_id();
assert_eq!(id.index, 5, "{name}");
let state = state(name, &device, &descriptor);
let mut buffers = Buffers::new(&device, 1 << 16);
let queue = device.new_command_queue(4).expect("a queue");
for index in [id.index, id.index + 0x1_0000] {
let argument = buffers.buffer(8);
write(
&argument,
0,
&(u64::from(index) | u64::from(id.word) << 32).to_le_bytes(),
);
let out = buffers.buffer(16);
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = command_buffer
.compute_command_encoder(DispatchType::Serial)
.expect("an encoder");
encoder.set_compute_pipeline_state(&state).expect("a state");
encoder.set_buffer(Some(&argument), 0, 0).expect("a buffer");
encoder.set_buffer(Some(&out), 0, 1).expect("a buffer");
encoder
.use_resource(Resource::Texture(&texture), ResourceUsage::READ)
.expect("a resident texture");
encoder
.dispatch_threadgroups([1, 1, 1], [1, 1, 1])
.expect("a dispatch");
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
assert_eq!(
words(&out, 0, 3),
[width, height, 0.75f32.to_bits()],
"{name}: an ID of index {index:#x}"
);
}
println!("{name}: index 5 and index 0x10005 both read texture 5");
});
}
}
+1 -1
View File
@@ -61,7 +61,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 = 2176;
pub const SEMANTICS_VERSION: u32 = 2178;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -980,11 +980,13 @@ pub fn emit(
}
/// Under the identity domains, the handle of a texture whose resource ID `id` (`uvec2`, low word
/// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the id's index, the
/// element of the set-1 arrays (0, nil, the null descriptor), with the word's missing-alpha bit
/// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the id's index masked
/// below the set-1 image arrays' length (`pipeline::link::IDENTITY_TEXTURES`, a power of two), the
/// element of those arrays (0, nil, the null descriptor), with the word's missing-alpha bit
/// (`TextureWord::OUT_OF_BOUNDS_ALPHA_ONE`) moved to `HANDLE_ALPHA_ONE` where the function's
/// handles carry it (`memory::handles::Lookup::Flagged`'s `alpha`). The admission allows no other
/// form (`select::identity_admits`).
/// handles carry it (`memory::handles::Lookup::Flagged`'s `alpha`). The program writes the ID, so
/// the mask keeps any value it holds inside the arrays: a bad ID reads the element at its masked
/// index. The admission allows no other form (`select::identity_admits`).
fn emit_identity_handle(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -992,7 +994,9 @@ fn emit_identity_handle(
id: SValue,
) -> BResult<()> {
use crate::metal::resource_word::TextureWord;
let index = fb.composite_extract(id, &[0])?;
let low = fb.composite_extract(id, &[0])?;
let mask = k32(fb, crate::pipeline::link::IDENTITY_TEXTURES - 1)?;
let index = fb.binary(BinOp::BitwiseAnd, low, mask)?;
let h = match cx.plan.families.access.lookup() {
handles::Lookup::Element => index,
handles::Lookup::Flagged { alpha: true, .. } => {
@@ -1274,7 +1274,7 @@ fn the_old_render_descriptor_key_keeps_its_value() {
let key = device("moltenvk-m3").render_descriptor_key(&d);
let hex: String = key.digest().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex, "eeff468606512cc27447cb56b4dc3a5e4ee7f5e18b45873a95f48a9825480798",
hex, "64b84e0f84f29d6744821b2ffb58baf8f1e57b44f4c49e7787c26a42019d8de7",
"the old runtime's key of the descriptor"
);
}
+4 -2
View File
@@ -1262,8 +1262,10 @@ fn heap_set(
/// Each image array of the identity domains' set 1, the sampled-image array (binding 0) and the
/// storage-image array (binding 1): one element per index a texture's resource ID may hold, the
/// same index in both (`docs/RESOURCE-ID.md`).
const IDENTITY_TEXTURES: u32 = 65_536;
/// same index in both (`docs/RESOURCE-ID.md`). A power of two, so an argument buffer's texture
/// index masked below it (`lower::access::handle`) is an element of both.
pub(crate) const IDENTITY_TEXTURES: u32 = 65_536;
const _: () = assert!(IDENTITY_TEXTURES.is_power_of_two());
/// Each sampler array of the identity domains' set 1: bindings 2, 3 and 4, one element per index a
/// sampler's resource ID may hold (`docs/RESOURCE-ID.md`).
@@ -37,7 +37,8 @@
//! bounds from the word, as `tests/resource_words.tsv` gives it.
//! - The same kernel with its textures in an argument buffer (`tex` with `ab`) reads their
//! resource IDs from the buffer's members, at its pushed address, and answers the same at the
//! same elements, with no handle table and no descriptor.
//! same elements, with no handle table and no descriptor; IDs whose indices are 65,536 past
//! the arrays read the elements at their low 16 bits.
//! - A kernel's slots that nothing writes (`read_only`, generated: an unaliased `device` buffer it
//! only reads and a `constant` one) are loaded through `NonWritable` device-address places; a
//! written slot, and a `device` slot the AIR does not declare unaliased, are not. It passes L3
@@ -792,7 +793,7 @@ fn texture_slots_are_the_set_1_elements_their_pushed_resource_ids_name() {
/// An argument buffer's textures under the identity domains are the same elements, at the
/// indices of the resource IDs its members hold, with no handle table and no descriptor of the
/// argument buffer's own.
/// argument buffer's own, and an ID's index past the arrays is masked to its low 16 bits.
#[test]
fn argument_buffer_textures_are_the_set_1_elements_their_resource_ids_name() {
textures_at_their_resource_ids(true);
@@ -801,6 +802,10 @@ fn argument_buffer_textures_are_the_set_1_elements_their_resource_ids_name() {
/// The address of the argument buffer of [`texture_kernel`]`(true)`.
const AB: u64 = 0x4_0000_0100;
/// An index past the set-1 image arrays by their length: masked to its low 16 bits, index `i +
/// PAST` is element `i`.
const PAST: u32 = 0x1_0000;
/// [`texture_kernel`]`(ab)` under the identity domains, on the CPU interpreter: its textures are
/// the set-1 elements their resource IDs name, pushed or, with `ab`, in the argument buffer.
fn textures_at_their_resource_ids(ab: bool) {
@@ -900,11 +905,22 @@ fn textures_at_their_resource_ids(ab: bool) {
};
let (sampled, storage) = (class(0), class(1));
// Two dispatches: `src` of a format without alpha and `other` nil, then `src` with alpha
// and `other` bound.
for (word, other, alpha) in [(red, 0, 1.0f32), (rgba, resource_id(1, rgba), 0.0)] {
// and `other` bound. With `ab`, a third holds the second's IDs with their indices
// `PAST` higher, past the arrays: the shader masks an argument buffer's index to its low
// 16 bits, so they read the same elements.
let dispatches = [(red, 0, 1.0f32, 0), (rgba, 1, 0.0, 0), (rgba, 1, 0.0, PAST)];
for &(word, other, alpha, past) in &dispatches[..2 + usize::from(ab)] {
let oob = [0, 0, 0, f(alpha)];
let robust = (!checked).then_some(oob);
let ids = [resource_id(SRC, word), resource_id(DST, rgba), other];
let other = match other {
0 => 0,
index => resource_id(index + past, rgba),
};
let ids = [
resource_id(SRC + past, word),
resource_id(DST + past, rgba),
other,
];
let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
let mut fields = Vec::new();
for field in &plan.push.fields {
@@ -969,13 +985,19 @@ fn textures_at_their_resource_ids(ab: bool) {
}
}
want.extend_from_slice(&[0; 4]);
assert_eq!(got.buffers[0], want, "{stem}: out, alpha {alpha}");
assert_eq!(
got.buffers[0], want,
"{stem}: out, alpha {alpha}, indices {past:#x} past"
);
let dst = &images[(SRC + 1 + DST) as usize];
let written: Vec<[u32; 4]> = (0..2)
.flat_map(|y| (0..5).map(move |x| (x, y)))
.map(|(x, y)| read(x, y))
.collect();
assert_eq!(dst.texels, written, "{stem}: dst, alpha {alpha}");
assert_eq!(
dst.texels, written,
"{stem}: dst, alpha {alpha}, indices {past:#x} past"
);
}
}
}
+3
View File
@@ -166,6 +166,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
argument buffer's texture, emulates a sampler's anisotropy or bicubic filter, uses a texture buffer, a slot's levels or swizzle, a
two-plane, extended-range or sRGB-twin form, reads an argument buffer's texture through another
numeric type or as raw texels, or uses any other state of a texture or sampler beyond its ID.
An argument buffer's texture reads the element at its ID's index masked to its low 16 bits,
so a bad ID reads an element of the arrays ([RESOURCE-ID.md](RESOURCE-ID.md)); the change that
first lowers an argument buffer's sampler masks its index the same way.
- **The model's linear sample of planes read in place** (`YCbCrInPlacePolicy::Model`, the
default; changes emitted code). On an integrated GPU or a CPU device a function that only
samples, gathers or sizes a `YCBCR8_420_2P` or `YCBCR10_420_2P` texture reads its planes' codes
+5 -3
View File
@@ -59,7 +59,9 @@ A shader takes a texture slot's ID from the slot's push field (`PushField::SlotG
argument buffer's texture's ID from the member's 8 bytes, with no table between. It indexes the
arrays with the low word, answers `is_null_texture` by whether the index is 0, and,
where it checks a `read` itself (a device without `robustImageAccess2`), takes an out-of-bounds
alpha of 1 from bit 12 of the word.
alpha of 1 from bit 12 of the word. 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.
Element `i` of each sampler array is a device sampler made of the sampler whose ID holds index `i`,
one per use, which the shader picks by the instruction and the texture's numeric type: binding 2
@@ -74,8 +76,8 @@ A constexpr sampler has no ID: the consumer places a device sampler of it (the f
`PushField::ConstexprSampler` names it and its use, and `CombinedSampler::constexpr_sampler`
describes it) at an index of the use's array and pushes that index as a `u32`. Its coordinates
are normalized; the shader scales a pixel sampler's coordinate itself. It samples with its own
address modes. An argument buffer's
sampler is not lowered under these domains yet.
address modes. An argument buffer's sampler is not lowered under these domains yet; the change
that first lowers it masks its index as an argument buffer's texture's is masked.
## The texture word