Tests: an OpenCL-mode kernel's 1D images read their 2D textures under the identity domains

Red first for L61. Every kernel of OpenCL mode that takes a 1D image (image1d_t or
image1d_array_t) is refused when its pipeline is made: Unsupported{IdentityDomains} naming
RuntimeFact::OpenClLineTexture, the fact by which the table domains read a 1D texture bound
there in a variant. Apple's OpenCL binds a 2D texture of height 1 for an image1d_t and a 2D array
of that height for an image1d_array_t, and the M3 Max and the Radeon Pro 5300M read those as the
1D image's row 0. These tests now ask for that answer.

- engine_opencl_mode: __entry_lr (read_imagef of an image1d_t at 2 and of an image1d_array_t at
  (1, 1)) compiles in OpenCL mode and passes L3 on every profile the identity domains derive. It
  states OpenClMode and no OpenClLineTexture, and its images are elements of the sampled float 2D
  and 2D-array classes. On the CPU interpreter, over a 4 x 1 2D texture and a 4 x 1 2D array of two
  layers, it reads texel 2 of the first and texel 1 of the second's layer 1.
- runtime opencl_lines (device cfg, under the validation layer): __entry_ol, with its hidden
  buffers bound as Apple's OpenCL binds them, reads a 4 x 1 2D texture at x and a 2D array at
  (x, 1). It writes their sum to a third 2D texture and the array's texel to o[x]; both are
  checked.
This commit is contained in:
Anees Iqbal committed 2026-12-02 07:25:18 -08:00
1 parent 5806b10c13
commit 283d8d8f50
4 files changed
+399 -7

No files matched your search

@@ -94,6 +94,7 @@ mod opencl_barriers;
mod opencl_data;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_kernels;
mod opencl_lines;
mod opencl_local;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_mode;
@@ -0,0 +1,212 @@
//! 1D images of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`), under a device cfg
//! on every device of the cfg's kind and under the validation layer. Apple's OpenCL binds an
//! `image1d_t` as a 2D texture of height 1 and an `image1d_array_t` as a 2D array texture of that
//! height, and a kernel of the mode reads, and writes, each as that texture at row 0, as an M3 Max
//! (macOS 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) answer: `__entry_ol` over 2D textures of
//! 4 × 1 reads `a` at its thread's `x`, the array `b` at `(x, 1)`, writes their sum to `w` and
//! `b`'s texel to `o[x]`.
//!
//! The module is LLVM text written here; `llvm-as` assembles it, and without it the test skips
//! visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::opencl_mode::{
floats, floats_buffer, kernel_list, library, state, words_buffer,
};
use crate::{
ComputePipelineState, Device, DispatchType, Error, IndexClass, PixelFormat, Region,
StorageMode, Texture, TextureDescriptor, TextureType, TextureUsage,
};
/// The images' width, and the threads: thread `x` takes texel `x`.
const W: u32 = 4;
/// The node of argument `n`, a texture at `index` of the MSL type `ty`, its access `access`
/// (`sample` or `write`).
fn image(n: u32, index: u32, access: &str, ty: &str, name: &str) -> String {
format!(
"!{{i32 {n}, !\"air.texture\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}"
)
}
/// `__kernel void ol(__read_only image1d_t a, __read_only image1d_array_t b, __write_only
/// image1d_t w, __global float4 *o)`: `write_imagef(w, x, read_imagef(a, x) + read_imagef(b,
/// (int2)(x, 1)))` and `o[x] = read_imagef(b, (int2)(x, 1))` for `x = get_global_id(0)`, in the
/// shape the OpenCL compiler writes them.
fn lines() -> String {
let body = "define void @__entry_ol(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\
entry:\n\
tail call fastcc void @ol(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3)\n\
ret void\n}\n\
define internal fastcc void @ol(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %w, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\
%x = trunc i64 %g to i32\n\
%rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\
%ra = tail call { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %rs, i32 %x, i32 0, i32 1)\n\
%ta = extractvalue { <4 x float>, i8 } %ra, 0\n\
%rb = tail call { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %rs, i32 %x, i32 1, i32 0, i32 1)\n\
%tb = extractvalue { <4 x float>, i8 } %rb, 0\n\
%t = fadd <4 x float> %ta, %tb\n\
tail call void @air.write_texture_1d.v4f32(ptr addrspace(1) %w, i32 %x, <4 x float> %t, i32 0, i32 2)\n\
%q = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %g\n\
store <4 x float> %tb, ptr addrspace(1) %q, align 16\n\
ret void\n}\n\
declare ptr addrspace(2) @air.get_read_sampler() #0\n\
declare { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32) #0\n\
declare { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32, i32) #0\n\
declare void @air.write_texture_1d.v4f32(ptr addrspace(1), i32, <4 x float>, i32, i32) #0\n";
let args = [
image(0, 0, "sample", "texture1d<unknown, read>", "a"),
image(1, 1, "sample", "texture1d_array<unknown, read>", "b"),
image(2, 2, "write", "texture1d<unknown, write>", "w"),
"!{i32 3, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"o\"}".to_owned(),
];
format!("{body}{}", kernel_list("__entry_ol", &args))
}
/// Texel `x` of layer `layer` of the images the test fills.
fn texel(layer: u32, x: u32) -> [f32; 4] {
[
100.0 * layer as f32 + x as f32 + 0.5,
10.0 + x as f32,
-2.0 * layer as f32,
1.0,
]
}
/// A Shared `RGBA32Float` texture of `texture_type`, `W` wide and of height 1, of `layers`
/// layers, at index `index`, layer `l` filled with [`texel`]`(l, x)` (zero for a written one).
fn texture(
name: &str,
device: &Device,
(texture_type, layers, write): (TextureType, u32, bool),
index: u32,
) -> Texture {
let mut d = TextureDescriptor::new(texture_type, PixelFormat::RGBA32Float, W, 1);
d.array_length = layers;
d.usage = match write {
true => TextureUsage::SHADER_WRITE,
false => TextureUsage::SHADER_READ,
};
d.storage_mode = StorageMode::Shared;
let texture = (device.new_texture(&d, Some(index)))
.unwrap_or_else(|error| panic!("{name}: {texture_type:?}: {error}"));
for layer in 0..layers {
let values: Vec<f32> = match write {
true => vec![0.0; 4 * W as usize],
false => (0..W).flat_map(|x| texel(layer, x)).collect(),
};
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
(texture.replace_region(
row(),
0,
layer,
crate::HostBytes::from(&bytes[..]),
u64::from(W * 16),
u64::from(W * 16),
))
.unwrap_or_else(|error| panic!("{name}: {texture_type:?}: {error}"));
}
texture
}
/// Row 0 of an image `W` wide.
fn row() -> Region {
Region {
origin: [0; 3],
size: [W, 1, 1],
}
}
/// `state` dispatched on `device` over `W` threads, its hidden buffers bound as Apple's OpenCL
/// binds them (the first's bytes at index 0: no offset, one dimension), `textures` at 0, 1 and
/// 2 and `out` at 3: the dispatch's answer, the command buffer committed and finished without
/// an error where it is `Ok`.
fn dispatch(
name: &str,
device: &Device,
state: &ComputePipelineState,
textures: [&Texture; 3],
out: &crate::Buffer,
) -> Result<(), Error> {
let first: Vec<u8> = [0u32, 0, 0, 1]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let hidden = [
words_buffer(device, &[0; 16]),
words_buffer(device, &[0; 64]),
];
let queue = device.new_command_queue(1).expect("a queue");
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("the state");
encoder
.set_bytes(&first, 0)
.expect("the first hidden buffer");
for (index, b) in (1u32..).zip(&hidden) {
(encoder.set_buffer(Some(b), 0, index)).expect("a hidden buffer");
}
encoder
.set_buffer(Some(out), 0, 3)
.expect("the kernel's buffer");
for (index, t) in (0u32..).zip(textures) {
(encoder.set_texture(Some(t), index))
.unwrap_or_else(|error| panic!("{name}: texture {index}: {error}"));
}
let answer = encoder.dispatch_threads([W, 1, 1], [W, 1, 1]);
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
answer
}
/// Over 2D textures of height 1 the kernel reads row 0 of each and writes row 0 of `w`.
#[test]
fn every_device_reads_an_opencl_1d_image_as_its_2d_texture() {
let Some(library) = library(&lines()) else {
return;
};
each_device("opencl_lines", |name, _, device| {
let _textures = (device.grant_indices(IndexClass::Texture, 1, 3))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let state = state(&device, &library, "__entry_ol");
let a = texture(name, &device, (TextureType::Type2D, 1, false), 1);
let b = texture(name, &device, (TextureType::Type2DArray, 2, false), 2);
let w = texture(name, &device, (TextureType::Type2D, 1, true), 3);
let out = floats_buffer(&device, &[-7.0; 4 * W as usize]);
(dispatch(name, &device, &state, [&a, &b, &w], &out))
.unwrap_or_else(|error| panic!("{name}: the dispatch: {error}"));
let want: Vec<f32> = (0..W).flat_map(|x| texel(1, x)).collect();
assert_eq!(floats(&out), want, "{name}: o, b's layer 1");
let mut bytes = vec![0u8; (W * 16) as usize];
(w.get_bytes(
&mut bytes,
u64::from(W * 16),
u64::from(W * 16),
row(),
0,
0,
))
.unwrap_or_else(|error| panic!("{name}: w: {error}"));
let written: Vec<f32> = (bytes.chunks_exact(4))
.map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect();
let sums: Vec<f32> = (0..W)
.flat_map(|x| {
let (p, q) = (texel(0, x), texel(1, x));
[p[0] + q[0], p[1] + q[1], p[2] + q[2], p[3] + q[3]]
})
.collect();
assert_eq!(written, sums, "{name}: w, a + b");
println!("{name}: OpenCL 1D images read as 2D textures");
});
}
}
@@ -29,13 +29,8 @@
//! toward zero, up and down; `float` to integers of 8 to 64 bits to nearest even, up and down;
//! and `.sat` between integers.
//!
//! Not run here: a kernel of OpenCL mode that takes a 1D image (`image1d_t` or `image1d_array_t`,
//! which Apple's OpenCL binds as a 2D texture of height 1 or a 2D array of that height), whose
//! channel queries, reads, samples and writes the M3 Max and the Radeon Pro 5300M answer. The
//! runtime refuses each such kernel's pipeline state at its making: "the translator made no
//! pipeline of __entry_<name>: unsupported: IdentityDomains (state of a bound texture or sampler
//! beyond its resource ID (OpenClLineTexture { slot: SlotRef { stage: Kernel, class: Texture,
//! index: <i> } })); needs NotImplemented" (the runtime's README, Known gaps of pipeline states).
//! A kernel of OpenCL mode that takes a 1D image (`image1d_t` or `image1d_array_t`, which Apple's
//! OpenCL binds as a 2D texture of height 1 or a 2D array of that height) is `tests::opencl_lines`'.
//!
//! The modules are LLVM text written here; `llvm-as` assembles them, and without it the tests skip
//! visibly.
@@ -218,6 +218,44 @@ attributes #3 = { nounwind willreturn }\n\
!7 = !{i32 2, i32 9, i32 0}\n\
!8 = !{!\"Metal\", i32 1, i32 1, i32 0}\n";
/// `__kernel void lr(__read_only image1d_t a, __read_only image1d_array_t b, __global float4 *o)`:
/// `o[0] = read_imagef(a, 2)` and `o[1] = read_imagef(b, (int2)(1, 1))`, in the shape the OpenCL
/// compiler writes them (macOS 27.0.1).
const LINE_READS: &str = "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\"\n\
target triple = \"air64_v29-apple-macosx27.0.0\"\n\
define void @__entry_lr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2) #0 {\n\
entry:\n\
tail call fastcc void @lr(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2)\n\
ret void\n}\n\
define internal fastcc void @lr(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %o) #1 {\n\
entry:\n\
%rs = tail call ptr addrspace(2) @air.get_read_sampler() #2\n\
%ra = tail call { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %rs, i32 2, i32 0, i32 1) #2\n\
%ta = extractvalue { <4 x float>, i8 } %ra, 0\n\
%rb = tail call { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %rs, i32 1, i32 1, i32 0, i32 1) #2\n\
%tb = extractvalue { <4 x float>, i8 } %rb, 0\n\
store <4 x float> %ta, ptr addrspace(1) %o, align 16\n\
%o1 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 1\n\
store <4 x float> %tb, ptr addrspace(1) %o1, align 16\n\
ret void\n}\n\
declare ptr addrspace(2) @air.get_read_sampler() #2\n\
declare { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32) #2\n\
declare { <4 x float>, i8 } @air.read_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), i32, i32, i32, i32) #2\n\
attributes #0 = { nounwind }\n\
attributes #1 = { nounwind }\n\
attributes #2 = { nounwind readonly willreturn }\n\
!air.kernel = !{!0}\n\
!air.version = !{!7}\n\
!air.language_version = !{!8}\n\
!0 = !{ptr @__entry_lr, !1, !2}\n\
!1 = !{}\n\
!2 = !{!3, !4, !5}\n\
!3 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture1d<unknown, read>\", !\"air.arg_name\", !\"a\"}\n\
!4 = !{i32 1, !\"air.texture\", !\"air.location_index\", i32 1, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture1d_array<unknown, read>\", !\"air.arg_name\", !\"b\"}\n\
!5 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"o\"}\n\
!7 = !{i32 2, i32 9, i32 0}\n\
!8 = !{!\"Metal\", i32 1, i32 1, i32 0}\n";
/// The kernel's function, or `None` (a skip) without `llvm-as`.
fn kernel() -> Option<FunctionDescriptor> {
function(MODULE, "__entry_k")
@@ -660,6 +698,152 @@ fn an_opencl_mode_kernel_binds_its_1d_images_as_2d_textures() {
}
}
/// Under the identity domains a kernel of OpenCL mode reads each 1D image as the 2D texture Apple's
/// OpenCL binds for it, with no `RuntimeFact::OpenClLineTexture` and no variant: `__entry_lr`
/// compiles and passes L3 on every profile the identity domains derive, its images the sampled
/// float 2D and 2D-array classes' elements. On the CPU interpreter, over a 2D texture of 4 × 1 at
/// element 3 and a 2D array of 4 × 1 and two layers at element 5, `o[0]` is texel 2 of the
/// first's row and `o[1]` texel 1 of the second's layer 1. A 1D texture bound there is the
/// consumer's refusal (the runtime's `Gap::OpenClLineTexture`).
#[test]
fn an_opencl_mode_kernels_1d_images_read_their_2d_textures_under_the_identity_domains() {
use super::engine_word_phases::{bounds_word, identity_profiles, slot_word, ZERO_UNMAPPED};
use crate::lower::dispatch::region_bytes;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::link::{link, LinkInputs};
use crate::pipeline::sym::{
HandleClass, ImageAccess, ImageDim, ImageHandleClass, PushField, ResourceKind, SampledType,
SlotClass, StorageFormatClass,
};
use crate::pipeline::testing::{compile_kept_with, link_and_validate};
use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Resources};
const OUT: u64 = 0x2_0000_0000;
const A: u32 = 3;
const B: u32 = 5;
// The output buffer's index, past the three hidden buffers an OpenCL-mode kernel takes first.
const HIDDEN: u32 = 3;
let bitcode = match metal2vulkan_devtools::llvm_assemble_text(LINE_READS) {
Ok(b) => b,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the module: {why}"),
};
let mut inputs = LowerInputs::new();
inputs.open_cl_mode = true;
let profiles = identity_profiles();
assert!(
!profiles.is_empty(),
"no profile the identity domains derive"
);
let class = |arrayed| {
ResourceKind::Heap(HandleClass::Image(ImageHandleClass {
dim: ImageDim::D2,
arrayed,
multisampled: false,
sampled_type: SampledType::Float,
depth_compare: false,
access: ImageAccess::Sampled,
format: StorageFormatClass::NotStorage,
}))
};
let texel = |layer: u32, x: u32| {
[
100.0 * layer as f32 + x as f32 + 0.5,
10.0 + x as f32,
20.0,
-1.0,
]
.map(f32::to_bits)
};
for (stem, p) in profiles {
let (a, plan, module) = compile_kept_with(&bitcode, "__entry_lr", &p, &inputs)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
assert!(a.facts.contains(&RuntimeFact::OpenClMode), "{stem}");
assert!(
!(a.facts.iter()).any(|f| matches!(f, RuntimeFact::OpenClLineTexture { .. })),
"{stem}: {:?}",
a.facts
);
let linked =
link(&[&a], &LinkInputs::standalone(), &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
let mut sampled: Vec<_> = (linked.table.bindings.iter())
.filter(|(_, b)| **b == (1, 0))
.map(|(s, _)| s.kind)
.collect();
sampled.sort();
let mut want = vec![class(false), class(true)];
want.sort();
assert_eq!(sampled, want, "{stem}: the sampled classes");
let (Some(plane), Some(array)) = (
(linked.table.bindings.keys()).find(|s| s.kind == class(false)),
(linked.table.bindings.keys()).find(|s| s.kind == class(true)),
) else {
panic!("{stem}: the classes' slots");
};
let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
for f in &plan.push.fields {
let PushLoc::Push { offset } = f.loc else {
panic!("{stem}: {f:?} spilled");
};
let o = offset as usize;
match f.field {
PushField::SlotGuestBase(s) => {
let word = match (s.class, s.index) {
(SlotClass::Texture, 0) => u64::from(A),
(SlotClass::Texture, 1) => u64::from(B),
(SlotClass::Buffer, HIDDEN) => slot_word(OUT),
_ => panic!("{stem}: unexpected slot {s:?}"),
};
push[o..o + 8].copy_from_slice(&word.to_le_bytes());
}
PushField::SlotBounds(_) => push[o..o + 8].copy_from_slice(&bounds_word(32, 0)),
PushField::ZeroAddress => {
push[o..o + 8].copy_from_slice(&ZERO_UNMAPPED.to_le_bytes())
}
PushField::DispatchRegion => {
let region = region_bytes([0; 3], [1; 3], [1; 3]).expect("packs");
push[o..o + 32].copy_from_slice(&region);
}
other => panic!("{stem}: unexpected push field {other:?}"),
}
}
let mut images: Vec<Image> = (0..A)
.map(|e| Image::new(*plane, [1, 1, 1], 1, 1, 1).at_element(e))
.collect();
let mut line = Image::new(*plane, [4, 1, 1], 1, 1, 1).at_element(A);
line.texels = (0..4).map(|x| texel(0, x)).collect();
images.push(line);
images.extend((0..B).map(|e| Image::new(*array, [1, 1, 1], 1, 1, 1).at_element(e)));
let mut lines = Image::new(*array, [4, 1, 1], 2, 1, 1).at_element(B);
lines.texels = (0..2)
.flat_map(|l| (0..4).map(move |x| texel(l, x)))
.collect();
images.push(lines);
let res = Resources {
buffers: vec![Buffer {
slot: None,
address: Some(OUT),
bytes: vec![0xA5; 32],
}],
push,
spec: std::collections::BTreeMap::from(crate::pipeline::threadgroup_constants([
1, 1, 1,
])),
};
let (got, _) = run_with_images(&module, &Config::default(), res, images)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
let want: Vec<u8> = [texel(0, 2), texel(1, 1)]
.iter()
.flatten()
.flat_map(|w| w.to_le_bytes())
.collect();
assert_eq!(got.buffers[0], want, "{stem}");
}
}
/// `__kernel void vsh(__global const float *a, __global half *o)`: `vstore_half_rtz(a[i], i, o)`,
/// and `__kernel void trunc(__global const float *a, __global half *o)`: `o[i] = (half)a[i]`, for
/// `i = get_global_id(0)`, in the shape the OpenCL compiler writes them.