diff --git a/crates/metal2vulkan-air/src/canon/async_copy.rs b/crates/metal2vulkan-air/src/canon/async_copy.rs index 066ddb32b..f09c460ba 100644 --- a/crates/metal2vulkan-air/src/canon/async_copy.rs +++ b/crates/metal2vulkan-air/src/canon/async_copy.rs @@ -213,49 +213,15 @@ pub(super) fn expand( m.release(plans.capacity() * std::mem::size_of::<(InstId, Lowered)>()); drop(plans); - // The calls rewritten in place to the functions built for them, then inlined. - let mut body = body; - for &(id, f) in &calls { - m.tick(1)?; - let inst = body - .insts - .get_mut(id) - .ok_or_else(|| invariant("a planned call out of range"))?; - let InstKind::Call(call) = &mut inst.kind else { - return Err(invariant("a planned call is not a call")); - }; - let lowered = Call { - callee: Callee::Direct(f), - args: call.args.clone(), - fmf: FastMath::NONE, - tail: TailKind::None, - attrs: None, - range: None, - }; - m.charge(lowered.heap_bytes())?; - m.release(call.heap_bytes()); - **call = lowered; - } - m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); - drop(calls); - let func = ep.func; - if let Some(replaced) = parts - .funcs - .get_mut(func) - .ok_or_else(|| invariant("entry out of range"))? - .body - .replace(body) - { - replaced.release(m); - } - inline::inline( - &parts.funcs, - (&parts.types, &parts.symbols), - &mut parts.consts, - func, + // The calls made calls of the functions built for them, then inlined. + inline::inline_calls( + body, + parts, + ep.func, + calls, + "an expanded asynchronous copy was not inlined", m, - )? - .ok_or_else(|| invariant("an expanded asynchronous copy was not inlined")) + ) } /// The function `lowered` of the callee type `ty`: its parameters are the call's operands. diff --git a/crates/metal2vulkan-air/src/canon/block_read.rs b/crates/metal2vulkan-air/src/canon/block_read.rs index 2c9d07443..327e0e480 100644 --- a/crates/metal2vulkan-air/src/canon/block_read.rs +++ b/crates/metal2vulkan-air/src/canon/block_read.rs @@ -206,48 +206,15 @@ pub(super) fn expand( m.release(plans.capacity() * std::mem::size_of::<(InstId, Lowered, FuncId)>()); drop(plans); - // The calls rewritten in place to the functions built for them, then inlined. - let mut body = body; - for &(id, f) in &calls { - m.tick(1)?; - let inst = body - .insts - .get_mut(id) - .ok_or_else(|| invariant("a planned call out of range"))?; - let InstKind::Call(call) = &mut inst.kind else { - return Err(invariant("a planned call is not a call")); - }; - let lowered = Call { - callee: Callee::Direct(f), - args: call.args.clone(), - fmf: FastMath::NONE, - tail: TailKind::None, - attrs: None, - range: None, - }; - m.charge(lowered.heap_bytes())?; - m.release(call.heap_bytes()); - **call = lowered; - } - m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); - drop(calls); - if let Some(replaced) = parts - .funcs - .get_mut(func) - .ok_or_else(|| invariant("entry out of range"))? - .body - .replace(body) - { - replaced.release(m); - } - inline::inline( - &parts.funcs, - (&parts.types, &parts.symbols), - &mut parts.consts, + // The calls made calls of the functions built for them, then inlined. + inline::inline_calls( + body, + parts, func, + calls, + "an expanded block read was not inlined", m, - )? - .ok_or_else(|| invariant("an expanded block read was not inlined")) + ) } /// The function `lowered` of the block read declared by `decl`: its parameters are the call's diff --git a/crates/metal2vulkan-air/src/canon/inline.rs b/crates/metal2vulkan-air/src/canon/inline.rs index 93cf14796..95039d78c 100644 --- a/crates/metal2vulkan-air/src/canon/inline.rs +++ b/crates/metal2vulkan-air/src/canon/inline.rs @@ -32,8 +32,8 @@ use crate::budget::Meter; use crate::error::{DiagName, Location}; use crate::error::{Error, Feature, Limit, Unsupported}; -use crate::ir::Value; use crate::ir::{Arena, Block, BlockId, Body, Callee, Const, ConstTable, Constant, FuncId}; +use crate::ir::{Call, FastMath, ModuleParts, TailKind, Value}; use crate::ir::{Function, Idx, Inst, InstId, InstKind, Symbols, Type, TypeId, TypeTable}; use super::rewrite::{filled, invariant, scoped}; @@ -70,6 +70,60 @@ pub(super) fn inline( }) } +/// The entry `func`'s `body` with each call of `calls` (its instruction, and the function an +/// expansion built for it, whose parameters are the call's operands) made a direct call of that +/// function, then inlined: the entry's new body. `calls` was charged to `m` by its capacity; +/// `what` names the expansion in an invariant's error. +pub(super) fn inline_calls( + mut body: Body, + parts: &mut ModuleParts, + func: FuncId, + calls: Vec<(InstId, FuncId)>, + what: &'static str, + m: &mut Meter, +) -> Result { + for &(id, f) in &calls { + m.tick(1)?; + let inst = body + .insts + .get_mut(id) + .ok_or_else(|| invariant("a planned call out of range"))?; + let InstKind::Call(call) = &mut inst.kind else { + return Err(invariant("a planned call is not a call")); + }; + let direct = Call { + callee: Callee::Direct(f), + args: call.args.clone(), + fmf: FastMath::NONE, + tail: TailKind::None, + attrs: None, + range: None, + }; + m.charge(direct.heap_bytes())?; + m.release(call.heap_bytes()); + **call = direct; + } + m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); + drop(calls); + if let Some(replaced) = parts + .funcs + .get_mut(func) + .ok_or_else(|| invariant("entry out of range"))? + .body + .replace(body) + { + replaced.release(m); + } + inline( + &parts.funcs, + (&parts.types, &parts.symbols), + &mut parts.consts, + func, + m, + )? + .ok_or_else(|| invariant(what)) +} + /// The body of a defined function, or `None`. fn body_of(funcs: &Arena, f: FuncId) -> Option<&Body> { funcs.get(f).and_then(|f| f.body.as_ref()) diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index a685b0dcb..a4ed4b78e 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -40,7 +40,8 @@ //! constant that survives is `Error::NeedsInput(FunctionConstant)`. **Unrolling**: a loop whose //! trip count SCCP made constant, and whose counter decides a branch of its body, is unrolled //! within fixed ceilings, and SCCP runs again over the copies; the result is kept where it is -//! no larger than the loops it replaces (`unroll`). +//! no larger than the loops it replaces (`unroll`). Before SCCP, in OpenCL mode, each operation +//! of a 1D image becomes the 2D texture's that Apple's OpenCL binds for it (`opencl_1d`). //! 8. **Post-check**: no unknown or unbound intrinsic, indirect call, or call to an undefined //! non-intrinsic function survives, and no reachable branch tests `undef`. A table call's refused candidate, //! a table call no linked function answers, and a function pointer used as a value are refused @@ -65,8 +66,8 @@ //! (`aggregates`). **Global built-in //! variables**: each `air.get_*` read of a program-scope built-in becomes a read of a built-in //! parameter appended to the entry (`global_builtin`); in OpenCL mode, first, the entry takes -//! the three hidden buffers and each OpenCL C work-item read becomes a read of its built-in or -//! of the first buffer ([`opencl`]). +//! the three hidden buffers, each OpenCL C work-item read becomes a read of its built-in or of +//! the first buffer, and each image format query a read of the third ([`opencl`]). //! 10. **ABI resolution and pruning**: predicate-gated parameters and outputs that are off //! disappear from the entry point, a read of an absent argument takes its absent value (the //! null reference of a resource argument) or is refused, global-valued ABI integers become @@ -105,6 +106,7 @@ mod link; mod link_tests; mod matmul2d; pub mod opencl; +mod opencl_1d; mod out; mod pieces; mod prune; @@ -610,6 +612,12 @@ pub fn specialize_dynamic( let body = async_copy::expand(body, &mut parts, ep, m)?; // Metal 4.1's block reads are the reads of their texels. let body = block_read::expand(body, &mut parts, ep.func, m)?; + // OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it. + let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { + opencl_1d::expand(body, &mut parts, ep.func, m)? + } else { + body + }; // SCCP. The body it read is freed as soon as it has run. let solved = solve(&body, &mut parts, &fcs, &name, m)?; @@ -692,10 +700,12 @@ pub fn specialize_dynamic( } else { body }; - // OpenCL mode: the three hidden buffers appended to the entry, and each OpenCL work-item read - // a read of its built-in or of the first buffer, which the global built-ins below take. + // OpenCL mode: the three hidden buffers appended to the entry, each OpenCL work-item read a + // read of its built-in or of the first buffer, which the global built-ins below take, and each + // image format query a read of the third. let (body, hidden) = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { - let (body, first) = opencl::expand(body, &mut parts, func, m)?; + let images = opencl::Images::of(ep, m)?; + let (body, first) = opencl::expand(body, &mut parts, (func, images), m)?; (body, Some(first)) } else { (body, None) diff --git a/crates/metal2vulkan-air/src/canon/opencl.rs b/crates/metal2vulkan-air/src/canon/opencl.rs index 1214eb0ec..431107348 100644 --- a/crates/metal2vulkan-air/src/canon/opencl.rs +++ b/crates/metal2vulkan-air/src/canon/opencl.rs @@ -24,6 +24,17 @@ //! by 2 at offset (3, 5), of two dimensions, answers each value of every thread, for constant //! dimensions and for a dimension the kernel is given. //! +//! - **Image formats.** `get_image_channel_order(image)` is `air.get_channel_order_texture_` +//! and `get_image_channel_data_type(image)` `air.get_channel_data_type_texture_` +//! ([`Query::ChannelOrder`], [`Query::ChannelDataType`]), each of the image argument. The third +//! hidden buffer holds two words per texture index: of the image at texture index `t`, word +//! `2t` is its data type and word `2t + 1` its order, read as they are. Measured on an M3 Max +//! (macOS 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) with the buffer's word `i` set to +//! `i * 0x10000 + 0x1234`, over one image of each kind beside a 2D image at index 0. Two +//! queries of one kind's wrapper (`get_image_channel_order` of two read-only 2D images) answer +//! the same word on both, the M3 Max's and the 5300M's of different calls; here each query +//! answers its own image's. +//! //! `expand` runs after SCCP, whose constants name each read's dimension, and before the global //! built-ins (`global_builtin`) take the reads it leaves. It appends the three buffers to the entry //! and rewrites each read of a dimension `c` below 3: `get_global_id(c)` becomes the built-in's @@ -31,7 +42,9 @@ //! `get_work_dim()` word 3. A read of a dimension past 2 is OpenCL's answer for it, 0 for an id //! or an offset and 1 for a size or a count (the M3 Max leaves the store of such a value //! unwritten). A read of a dimension no constant names selects among its reads of the three lanes, -//! with OpenCL's answer past them. [`entry`] then moves the entry's buffer-indexed arguments 3 on +//! with OpenCL's answer past them. Each image format query of an image argument at a constant +//! texture index becomes the load of its word of the third buffer; one of any other texture is +//! left, and lowering refuses it. [`entry`] then moves the entry's buffer-indexed arguments 3 on //! and adds the three buffers' bindings. use crate::abi::{ @@ -39,7 +52,7 @@ use crate::abi::{ }; use crate::budget::Meter; use crate::error::{DiagName, Error}; -use crate::intrinsics::{AirIntrinsic, Elem, GlobalBuiltin, GlobalVar, WorkItem}; +use crate::intrinsics::{AirIntrinsic, Elem, GlobalBuiltin, GlobalVar, Query, TexOp, WorkItem}; use crate::ir::{ AddrSpace, Align, ArgIdx, BinOp, Block, Body, Call, Callee, CastOp, Const, Constant, FastMath, FuncId, Idx, Inst, InstId, InstKind, IntFlags, IntPredicate, ModuleParts, Type, TypeId, Value, @@ -80,6 +93,47 @@ const BUFFERS: [(&str, &str, u32, Access, AddrSpace); 3] = [ /// The word of the first hidden buffer that holds the dispatch's dimension count. const WORK_DIM_WORD: u64 = 3; +/// The hidden buffer that holds the images' formats, after the first. +const TABLE: u32 = 2; + +/// The entry's image arguments: each parameter bound at a constant texture index, with that +/// index. +#[derive(Debug, Default)] +pub(super) struct Images(Vec<(u32, u32)>); + +impl Images { + /// The image arguments of entry `ep`. + pub(super) fn of(ep: &EntryPoint, m: &mut Meter) -> Result { + let mut images = Vec::new(); + for p in &ep.params { + m.tick(1)?; + if let ParamRole::Texture(t) = &p.role { + if let (AbiInt::Const(index), AbiInt::Const(1)) = + (t.location.index, t.location.count) + { + m.reserve(&mut images, 1)?; + images.push((p.param, index)); + } + } + } + Ok(Images(images)) + } + + /// The texture index of the image `v` is, where it is an image argument. + fn index(&self, v: Value) -> Option { + let Value::Arg(a) = v else { + return None; + }; + let param = u32::try_from(a.index()).ok()?; + self.0.iter().find(|(p, _)| *p == param).map(|&(_, t)| t) + } + + /// The bytes [`Images::of`] charged. + fn release(self, m: &mut Meter) { + m.release(self.0.capacity() * std::mem::size_of::<(u32, u32)>()); + } +} + /// An OpenCL work-item read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Read { @@ -89,6 +143,9 @@ enum Read { Offset, /// `get_work_dim()`. WorkDim, + /// `get_image_channel_order` or `get_image_channel_data_type` of an image argument: word + /// `word` of the third hidden buffer. + Format { word: u64 }, } impl Read { @@ -96,7 +153,7 @@ impl Read { fn elem(self) -> Elem { match self { Read::Builtin(g) => g.ty, - Read::Offset | Read::WorkDim => Elem::I32, + Read::Offset | Read::WorkDim | Read::Format { .. } => Elem::I32, } } @@ -116,13 +173,13 @@ impl Read { /// Whether the read takes a dimension. fn dimensioned(self) -> bool { - self != Read::WorkDim + matches!(self, Read::Builtin(_) | Read::Offset) } } -/// The OpenCL work-item read `kind` is, with its call: a read of one of the six built-ins OpenCL C -/// names, `get_global_offset` or `get_work_dim`. -fn read(kind: &InstKind) -> Option<(Read, &Call)> { +/// The OpenCL read `kind` is, with its call: a read of one of the six built-ins OpenCL C names, +/// `get_global_offset`, `get_work_dim`, or an image format query of one of `images`. +fn read<'k>(kind: &'k InstKind, images: &Images) -> Option<(Read, &'k Call)> { let InstKind::Call(call) = kind else { return None; }; @@ -144,6 +201,17 @@ fn read(kind: &InstKind) -> Option<(Read, &Call)> { ) => Read::Builtin(g), AirIntrinsic::WorkItem(WorkItem::GlobalOffset) => Read::Offset, AirIntrinsic::WorkItem(WorkItem::WorkDim) => Read::WorkDim, + AirIntrinsic::Texture(t) => { + let order = match t.op { + TexOp::Query(Query::ChannelOrder) => 1, + TexOp::Query(Query::ChannelDataType) => 0, + _ => return None, + }; + let index = images.index(*call.args.first()?)?; + Read::Format { + word: 2 * u64::from(index) + order, + } + } _ => return None, }; Some((read, call)) @@ -156,11 +224,13 @@ enum Dim { Value(Value), } -/// The dimension call `call` of `r` names (`Const(WORK_DIM_WORD)` for `get_work_dim`, which -/// names none). +/// The dimension call `call` of `r` names (`Const(WORK_DIM_WORD)` for `get_work_dim` and an image +/// format's word for its query, which name none). fn dim(parts: &ModuleParts, r: Read, call: &Call) -> Result { - if !r.dimensioned() { - return Ok(Dim::Const(WORK_DIM_WORD)); + match r { + Read::WorkDim => return Ok(Dim::Const(WORK_DIM_WORD)), + Read::Format { word } => return Ok(Dim::Const(word)), + Read::Builtin(_) | Read::Offset => {} } let [v] = call.args.as_ref() else { return Err(invariant("a work-item read without its dimension")); @@ -180,6 +250,8 @@ struct Sink<'a> { parts: &'a mut ModuleParts, /// The first hidden buffer's parameter. offsets: Value, + /// The third hidden buffer's parameter. + table: Value, } impl Sink<'_> { @@ -212,8 +284,8 @@ impl Sink<'_> { Ok(Value::Inst(id)) } - /// Word `w` of the first hidden buffer, in `e`. - fn word(&mut self, w: u64, e: Elem, m: &mut Meter) -> Result { + /// Word `w` of the hidden buffer `base`, in `e`. + fn word(&mut self, base: Value, w: u64, e: Elem, m: &mut Meter) -> Result { let i32t = self.elem_ty(Elem::I32, m)?; let ptr = self.ty( Type::Ptr { @@ -226,7 +298,7 @@ impl Sink<'_> { ptr, InstKind::Gep { src_ty: i32t, - base: self.offsets, + base, indices: Box::new([index]), inbounds: true, }, @@ -271,7 +343,8 @@ impl Sink<'_> { return self.int(e, r.past(), m); } match r { - Read::Offset | Read::WorkDim => self.word(c, e, m), + Read::Offset | Read::WorkDim => self.word(self.offsets, c, e, m), + Read::Format { .. } => self.word(self.table, c, e, m), Read::Builtin(g) => { let lane = self.int(e, c, m)?; let mut lane_read = call.clone(); @@ -280,7 +353,7 @@ impl Sink<'_> { if g.var != GlobalVar::ThreadPositionInGrid { return Ok(v); } - let offset = self.word(c, e, m)?; + let offset = self.word(self.offsets, c, e, m)?; self.push( ty, InstKind::BinOp { @@ -365,7 +438,7 @@ struct Expansion { /// emitting it into a scratch body. fn measure( parts: &mut ModuleParts, - offsets: Value, + (offsets, table): (Value, Value), (r, call, ty, d): (Read, &Call, TypeId, Dim), m: &mut Meter, ) -> Result { @@ -374,6 +447,7 @@ fn measure( out: &mut scratch, parts, offsets, + table, }; let v = s.emit(r, call, ty, d, m)?; let len = u32::try_from(scratch.insts.len()).map_err(|_| invariant("expansion length"))?; @@ -385,12 +459,26 @@ fn measure( } /// Append the three hidden buffers to the entry `func` and make each OpenCL work-item read of its -/// solved `body` a read of a built-in or of the first buffer (see the module), returning the new -/// body and the first buffer's parameter index. +/// solved `body` a read of a built-in or of the first buffer, and each image format query of one +/// of its `images` a read of the third (see the module), returning the new body and the first +/// buffer's parameter index. pub(super) fn expand( + body: Body, + parts: &mut ModuleParts, + (func, images): (FuncId, Images), + m: &mut Meter, +) -> Result<(Body, u32), Error> { + let out = rewrite(body, parts, func, &images, m); + images.release(m); + out +} + +/// [`expand`] over `images`. +fn rewrite( body: Body, parts: &mut ModuleParts, func: FuncId, + images: &Images, m: &mut Meter, ) -> Result<(Body, u32), Error> { let [a, b, c] = BUFFERS.map(|(.., space)| Type::Ptr { space }); @@ -401,7 +489,17 @@ pub(super) fn expand( ]; let first = append_params(parts, func, &tys, m)?; let offsets = Value::Arg(ArgIdx::new(first)); - if !body.insts.iter().any(|(_, i)| read(&i.kind).is_some()) { + let table = Value::Arg(ArgIdx::new( + first + .checked_add(TABLE) + .ok_or_else(|| invariant("parameter indices"))?, + )); + let buffers = (offsets, table); + if !body + .insts + .iter() + .any(|(_, i)| read(&i.kind, images).is_some()) + { return Ok((body, first)); } // Each old instruction's value in the output: an expansion's last instruction, or its @@ -411,10 +509,10 @@ pub(super) fn expand( let mut next = 0u32; for (_, inst) in body.insts.iter() { m.tick(1)?; - let e = match read(&inst.kind) { + let e = match read(&inst.kind, images) { Some((r, call)) => { let d = dim(parts, r, call)?; - measure(parts, offsets, (r, call, inst.ty, d), m)? + measure(parts, buffers, (r, call, inst.ty, d), m)? } None => Expansion { len: 1, @@ -458,7 +556,7 @@ pub(super) fn expand( if let Some(e) = failed { return Err(e); } - let found = read(&kind).map(|(r, call)| (r, call.clone())); + let found = read(&kind, images).map(|(r, call)| (r, call.clone())); let value = match found { Some((r, call)) => { let d = dim(parts, r, &call)?; @@ -466,6 +564,7 @@ pub(super) fn expand( out: &mut out, parts, offsets, + table, }; s.emit(r, &call, inst.ty, d, m)? } diff --git a/crates/metal2vulkan-air/src/canon/opencl_1d.rs b/crates/metal2vulkan-air/src/canon/opencl_1d.rs new file mode 100644 index 000000000..b8f0e979b --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/opencl_1d.rs @@ -0,0 +1,295 @@ +//! OpenCL mode's 1D images as the textures Apple's OpenCL binds for them. +//! +//! Apple's OpenCL compiler declares an `image1d_t` argument `texture1d` and an `image1d_array_t` +//! `texture1d_array`, and its OpenCL binds a 2D texture of height 1 for the first and a 2D array +//! texture of height 1 for the second. A pipeline of OpenCL mode reads those textures as the +//! kernel's 1D images: row 0, of the layer an array access names. Measured on an M3 Max (macOS +//! 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1): the reflection states the two arguments +//! `MTLTextureType2D` and `MTLTextureType2DArray`; over 2D textures of height 1 bound there, a read +//! with and without a sampler, a sample at integer, unnormalized and normalized coordinates (a +//! linear filter at a border-clamped edge answers the texel, blending in no row of the border), a +//! write, `get_image_width` and `get_image_array_size` answer the 1D image's values. With 1D +//! textures bound, the M3 Max reads texel 0 at every coordinate. +//! +//! [`expand`] makes each such call of a 1D texture in a kernel of OpenCL mode a call of a function +//! built here, and inlines it: the same operation of a 2D texture, or a 2D array texture for a 1D +//! array, its coordinate `(x, 0)`, a sampled coordinate `(x, 0.5)` (the row's centre in +//! normalized and unnormalized coordinates alike), its offset `(o, 0)` or, where the 1D form has +//! none, `(0, 0)`. Lowering then declares the slot, and the binder binds it, as the 2D texture +//! Metal's OpenCL binds. Not rewritten: `get_num_mip_levels`, whose 1D answer (0) a 2D texture's is +//! not, and the image format queries, which read a hidden buffer whatever the shape +//! (`canon::opencl`); neither is OpenCL C's. + +use crate::budget::Meter; +use crate::error::Error; +use crate::intrinsics::{AirIntrinsic, ImageDim, ImageShape, Query, TexOp, TexRole, Texture}; +use crate::ir::{ + ArgIdx, Body, Call, CallConv, Callee, Const, FnAttrs, FuncId, Function, InstId, InstKind, + Linkage, ModuleParts, Param, ParamAttrs, Type, TypeId, UnnamedAddr, Value, Visibility, +}; + +use super::inline; +use super::out::Out; +use super::rewrite::invariant; + +/// The 2D operation that reads 1D operation `t`'s texture as Metal's OpenCL binds it, where `t` +/// is one [`expand`] rewrites. +fn widened(t: Texture) -> Option { + if t.image.dim != ImageDim::D1 { + return None; + } + match t.op { + TexOp::Read + | TexOp::Sample { .. } + | TexOp::Write + | TexOp::Query(Query::Width | Query::ArraySize) => Some(Texture { + image: ImageShape { + dim: ImageDim::D2, + ..t.image + }, + ..t + }), + _ => None, + } +} + +/// The 1D texture operation `kind` calls that [`expand`] rewrites, with its declaration and call. +fn site(kind: &InstKind) -> Option<(Texture, FuncId, &Call)> { + let InstKind::Call(call) = kind else { + return None; + }; + match call.callee { + Callee::Air { + decl, + op: AirIntrinsic::Texture(t), + } if widened(t).is_some() => Some((t, decl, call)), + _ => None, + } +} + +/// Whether `parts` declares a 1D texture operation [`expand`] rewrites. Every site calls one, so +/// a module that declares none has none, and [`expand`] need not read its instructions. +fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result { + for f in parts.funcs.values() { + m.tick(1)?; + if f.body.is_some() { + continue; + } + let air = parts + .symbols + .get(f.name) + .and_then(|n| std::str::from_utf8(n).ok()) + .and_then(AirIntrinsic::parse); + if matches!(air, Some(AirIntrinsic::Texture(t)) if widened(t).is_some()) { + return Ok(true); + } + } + Ok(false) +} + +/// Make each 1D texture operation of the entry `func`'s inlined `body` that the module doc lists +/// a call of a function built for it, and inline the result. +pub(super) fn expand( + body: Body, + parts: &mut ModuleParts, + func: FuncId, + m: &mut Meter, +) -> Result { + if !declares_sites(parts, m)? { + return Ok(body); + } + // One function per operation and declaration, and each call's. + let mut made: Vec<((Texture, FuncId), FuncId)> = Vec::new(); + let mut calls: Vec<(InstId, FuncId)> = Vec::new(); + for (id, inst) in body.insts.iter() { + m.tick(1)?; + let Some((t, decl, call)) = site(&inst.kind) else { + continue; + }; + let f = match made.iter().find(|(k, _)| *k == (t, decl)) { + Some(&(_, f)) => f, + None => { + let f = function(parts, (t, decl), &call.args, m)?; + m.reserve(&mut made, 1)?; + made.push(((t, decl), f)); + f + } + }; + m.reserve(&mut calls, 1)?; + calls.push((id, f)); + } + m.release(made.capacity() * std::mem::size_of::<((Texture, FuncId), FuncId)>()); + drop(made); + if calls.is_empty() { + m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); + return Ok(body); + } + inline::inline_calls( + body, + parts, + func, + calls, + "a widened 1D texture operation was not inlined", + m, + ) +} + +/// The function of 1D operation `t` declared by `decl`, whose parameters are the call's operands: +/// it calls the 2D operation [`widened`] names. `args`, a call's operands, give the immediates +/// (`t` binds them: every call of `t` passes the same). +fn function( + parts: &mut ModuleParts, + (t, decl): (Texture, FuncId), + args: &[Value], + m: &mut Meter, +) -> Result { + let (ty, name) = parts + .funcs + .get(decl) + .map(|f| (f.ty, f.name)) + .ok_or_else(|| invariant("a declaration out of range"))?; + let name = parts + .symbols + .get(name) + .and_then(|n| std::str::from_utf8(n).ok()) + .ok_or_else(|| invariant("a 1D texture operation's name"))?; + // The dimension token of the name: `texture_1d[_array]` to `texture_2d[_array]`. + let wide_name = match name.split_once("_texture_1d") { + Some((head, tail)) => format!("{head}_texture_2d{tail}"), + None => return Err(invariant("a 1D texture operation's name")), + }; + let (ret, params): (TypeId, Vec) = match parts.types.get(ty) { + Some(Type::Function { + ret, + params, + vararg: false, + }) => (*ret, params.to_vec()), + _ => return Err(invariant("a 1D texture operation is not a function")), + }; + let wide = widened(t).ok_or_else(|| invariant("a 1D texture operation's 2D form"))?; + let narrow = t.layout(); + let at = |role| -> Result<(usize, TypeId), Error> { + let i = narrow + .index(role) + .ok_or_else(|| invariant("a 1D texture operation's operand"))?; + let ty = *params + .get(i) + .ok_or_else(|| invariant("a 1D texture operation's parameters"))?; + Ok((i, ty)) + }; + let param = |i: usize| -> Result { + let i = u32::try_from(i).map_err(|_| invariant("parameters"))?; + Ok(Value::Arg(ArgIdx::new(i))) + }; + let void = matches!(parts.types.get(ret), Some(Type::Void)); + let mut out = Out::new(parts); + out.open(None)?; + let mut tys = Vec::new(); + let mut wide_args = Vec::new(); + for (role, _) in wide.layout().positions() { + let (v, ty) = match role { + // The row's centre for a sampled coordinate, row 0 for an integer one. + TexRole::Coord => { + let (i, ty) = at(role)?; + let float = matches!(out.parts.types.get(ty), Some(Type::Float)); + pair(&mut out, param(i)?, ty, float.then_some(0.5), m)? + } + TexRole::Offset => match narrow.index(role) { + Some(_) => { + let (i, ty) = at(role)?; + pair(&mut out, param(i)?, ty, None, m)? + } + // A read's 2D offset, of its coordinate's lane type, which the 1D form has not. + None => { + let (_, ty) = at(TexRole::Coord)?; + let pair_ty = out.ty(Type::Vector { elem: ty, len: 2 }, m)?; + (out.constant(pair_ty, Const::Null, m)?, pair_ty) + } + }, + // The immediates, which the 2D call must state as constants. + TexRole::Access | TexRole::LodMode | TexRole::OffsetFlag | TexRole::Component => { + let (i, ty) = at(role)?; + let v = *args + .get(i) + .ok_or_else(|| invariant("a 1D texture operation's operands"))?; + if !matches!(v, Value::Const(_)) { + return Err(invariant("a bound immediate is not a constant")); + } + (v, ty) + } + _ => { + let (i, ty) = at(role)?; + (param(i)?, ty) + } + }; + tys.push(ty); + wide_args.push(v); + } + let result = out.intrinsic(&wide_name, ret, &tys, &wide_args, m)?; + // The declaration decodes as the 2D operation meant, its immediates bound alike. + let bound = match result { + Value::Inst(id) => out.body.insts.get(id).map(|i| &i.kind), + _ => None, + }; + let meant = + |c: &Call| matches!(c.callee, Callee::Air { op, .. } if op == AirIntrinsic::Texture(wide)); + if !matches!(bound, Some(InstKind::Call(c)) if meant(c)) { + return Err(invariant("a 1D texture operation's 2D form")); + } + out.ret((!void).then_some(result), m)?; + let Out { body, parts, .. } = out; + let name = format!("__m2v.opencl_1d.{}", parts.funcs.len()); + let name = parts.symbols.intern(name.as_bytes(), m)?; + let mut ps = Vec::new(); + m.reserve(&mut ps, params.len())?; + ps.resize(params.len(), Param::default()); + let f = Function { + name, + ty, + linkage: Linkage::Internal, + visibility: Visibility::Default, + unnamed_addr: UnnamedAddr::Significant, + cconv: CallConv::C, + attrs: FnAttrs::default(), + ret_attrs: ParamAttrs::default(), + params: ps.into_boxed_slice(), + body: Some(body), + section: None, + align: None, + }; + parts.funcs.push(f, m) +} + +/// `v`, a lane of type `ty`, as lane 0 of a pair whose lane 1 is the `float` `y` where `Some`, +/// else zero: the pair and its type. +fn pair( + out: &mut Out<'_>, + v: Value, + ty: TypeId, + y: Option, + m: &mut Meter, +) -> Result<(Value, TypeId), Error> { + let pair_ty = out.ty(Type::Vector { elem: ty, len: 2 }, m)?; + let base = match y { + Some(y) => { + let lane = |v| match v { + Value::Const(c) => Ok(c), + _ => Err(invariant("a constant is not one")), + }; + let lanes = Box::new([lane(out.f32k(0.0, m)?)?, lane(out.f32k(y, m)?)?]); + out.constant(pair_ty, Const::Aggregate(lanes), m)? + } + None => out.constant(pair_ty, Const::Null, m)?, + }; + let idx = out.k32(0, m)?; + let v = out.push( + pair_ty, + InstKind::InsertElement { + vec: base, + elt: v, + idx, + }, + m, + )?; + Ok((v, pair_ty)) +} diff --git a/crates/metal2vulkan-air/src/canon/tests/opencl.rs b/crates/metal2vulkan-air/src/canon/tests/opencl.rs index 9dde7be37..d93ff5680 100644 --- a/crates/metal2vulkan-air/src/canon/tests/opencl.rs +++ b/crates/metal2vulkan-air/src/canon/tests/opencl.rs @@ -258,3 +258,273 @@ fn opencl_work_item_reads_become_built_ins_and_the_first_hidden_buffer() { .collect(); assert_eq!(left, [WorkItem::GlobalOffset, WorkItem::WorkDim]); } + +/// `@img(texture2d a [[texture(0)]], texture1d b [[texture(1)]], texture1d_array c +/// [[texture(2)]], texture1d d [[texture(3)]], sampler s [[sampler(0)]], device int *o +/// [[buffer(0)]], device float4 *f [[buffer(1)]])` as Apple's OpenCL compiler writes OpenCL C's +/// image functions (macOS 27.0.1, through internal wrappers where it uses one): `o[0..6]` take +/// `get_image_channel_order(b)`, `get_image_channel_data_type(c)`, the order of `a`, the data +/// type of `d`, `get_image_width(b)` and `get_image_array_size(c)`; `f[0]` reads `b` at `x`, `f[1]` +/// samples layer 1 of `c` at `x`, and `d` takes `f[1]`'s texel at `x`. +const IMAGES: &str = "define void @img(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c, ptr addrspace(1) %d, ptr addrspace(2) %s, ptr addrspace(1) %o, ptr addrspace(1) %f) #0 {\n\ + %x = tail call i32 @air.get_global_id.i32(i32 0)\n\ + %ob = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %b)\n\ + store i32 %ob, ptr addrspace(1) %o, align 4\n\ + %dc = tail call i32 @air.get_channel_data_type_texture_1d_array(ptr addrspace(1) %c)\n\ + %o1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 1\n\ + store i32 %dc, ptr addrspace(1) %o1, align 4\n\ + %oa = tail call i32 @air.get_channel_order_texture_2d(ptr addrspace(1) %a)\n\ + %o2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 2\n\ + store i32 %oa, ptr addrspace(1) %o2, align 4\n\ + %da = tail call i32 @air.get_channel_data_type_texture_1d(ptr addrspace(1) %d)\n\ + %o3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 3\n\ + store i32 %da, ptr addrspace(1) %o3, align 4\n\ + %wb = tail call i32 @air.get_width_texture_1d(ptr addrspace(1) %b, i32 0)\n\ + %o4 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 4\n\ + store i32 %wb, ptr addrspace(1) %o4, align 4\n\ + %nc = tail call i32 @air.get_array_size_texture_1d_array(ptr addrspace(1) %c)\n\ + %o5 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 5\n\ + store i32 %nc, ptr addrspace(1) %o5, align 4\n\ + %rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\ + %rb = tail call { <4 x float>, i8 } @air.read_texture_1d.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %rs, i32 %x, i32 0, i32 1)\n\ + %tb = extractvalue { <4 x float>, i8 } %rb, 0\n\ + store <4 x float> %tb, ptr addrspace(1) %f, align 16\n\ + %fx = sitofp i32 %x to float\n\ + %sc = tail call { <4 x float>, i8 } @air.sample_texture_1d_array.v4f32(ptr addrspace(1) %c, ptr addrspace(2) %s, float %fx, i32 1, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\ + %tc = extractvalue { <4 x float>, i8 } %sc, 0\n\ + %f1 = getelementptr inbounds <4 x float>, ptr addrspace(1) %f, i64 1\n\ + store <4 x float> %tc, ptr addrspace(1) %f1, align 16\n\ + tail call void @air.write_texture_1d.v4f32(ptr addrspace(1) %d, i32 %x, <4 x float> %tc, i32 0, i32 2)\n\ + ret void\n}\n\ +define internal fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %0) #1 {\n\ + %2 = tail call i32 @air.get_channel_order_texture_1d(ptr addrspace(1) %0) #2\n\ + ret i32 %2\n}\n\ +declare i32 @air.get_global_id.i32(i32) #2\n\ +declare i32 @air.get_channel_order_texture_1d(ptr addrspace(1)) #2\n\ +declare i32 @air.get_channel_data_type_texture_1d_array(ptr addrspace(1)) #2\n\ +declare i32 @air.get_channel_order_texture_2d(ptr addrspace(1)) #2\n\ +declare i32 @air.get_channel_data_type_texture_1d(ptr addrspace(1)) #2\n\ +declare i32 @air.get_width_texture_1d(ptr addrspace(1), i32) #2\n\ +declare i32 @air.get_array_size_texture_1d_array(ptr addrspace(1)) #2\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.sample_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), float, i32, i1, i32, i1, float, float, i32) #2\n\ +declare void @air.write_texture_1d.v4f32(ptr addrspace(1), i32, <4 x float>, i32, i32) #3\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { nounwind optsize }\n\ +attributes #2 = { nounwind readonly willreturn }\n\ +attributes #3 = { nounwind willreturn }\n\ +!air.kernel = !{!0}\n\ +!air.version = !{!10}\n\ +!air.language_version = !{!11}\n\ +!0 = !{ptr @img, !1, !2}\n\ +!1 = !{}\n\ +!2 = !{!3, !4, !5, !6, !7, !8, !9}\n\ +!3 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"a\"}\n\ +!4 = !{i32 1, !\"air.texture\", !\"air.location_index\", i32 1, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture1d\", !\"air.arg_name\", !\"b\"}\n\ +!5 = !{i32 2, !\"air.texture\", !\"air.location_index\", i32 2, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture1d_array\", !\"air.arg_name\", !\"c\"}\n\ +!6 = !{i32 3, !\"air.texture\", !\"air.location_index\", i32 3, i32 1, !\"air.write\", !\"air.arg_type_name\", !\"texture1d\", !\"air.arg_name\", !\"d\"}\n\ +!7 = !{i32 4, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}\n\ +!8 = !{i32 5, !\"air.buffer\", !\"air.location_index\", i32 0, 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\", !\"int\", !\"air.arg_name\", !\"o\"}\n\ +!9 = !{i32 6, !\"air.buffer\", !\"air.location_index\", i32 1, 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\", !\"f\"}\n\ +!10 = !{i32 2, i32 9, i32 0}\n\ +!11 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; + +/// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`; `None` without `llvm-as`. +fn images(test: &str, open_cl_mode: bool) -> Option { + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{IMAGES}")) { + Ok(b) => b, + Err(e) => { + eprintln!("SKIP {test}: {e:?}"); + return None; + } + }; + let d = crate::bitcode::decode(&bitcode, &mut meter()).expect("decoded"); + let req = SpecRequest { + entry: "img".into(), + open_cl_mode, + ..SpecRequest::default() + }; + Some(specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized")) +} + +/// The texture operations the entry's body calls: each one's operation and texture shape. +fn texture_ops(e: &Entry) -> Vec<(TexOp, crate::intrinsics::ImageDim, bool)> { + body(e) + .insts + .values() + .filter_map(|i| match &i.kind { + InstKind::Call(c) => match c.callee { + Callee::Air { + op: AirIntrinsic::Texture(t), + .. + } => Some((t.op, t.image.dim, t.image.array)), + _ => None, + }, + _ => None, + }) + .collect() +} + +#[test] +fn opencl_image_formats_read_their_words_of_the_third_hidden_buffer() { + use crate::intrinsics::{ImageDim, Query}; + let test = "opencl_image_formats_read_their_words_of_the_third_hidden_buffer"; + let (Some(plain), Some(cl)) = (images(test, false), images(test, true)) else { + return; + }; + let format = |op: &(TexOp, ImageDim, bool)| { + matches!( + op.0, + TexOp::Query(Query::ChannelOrder | Query::ChannelDataType) + ) + }; + // As Metal AIR the four queries stay, for lowering to refuse. + assert_eq!(texture_ops(&plain).iter().filter(|o| format(o)).count(), 4); + // In OpenCL mode none is left: each is a load of a word of the third hidden buffer, the + // seven parameters' ninth, at `2t + 1` for an order and `2t` for a data type, `t` the image's + // texture index: the order of texture 1, the data type of texture 2, the order of texture 0 + // and the data type of texture 3. + assert!( + !texture_ops(&cl).iter().any(format), + "{}", + print(&cl.module) + ); + let consts = cl.module.consts(); + let words: Vec = body(&cl) + .insts + .values() + .filter_map(|i| match &i.kind { + InstKind::Gep { + base: Value::Arg(a), + indices, + .. + } if a.index() == 9 => match indices.as_ref() { + [Value::Const(c)] => match consts.get(*c).map(|k| &k.value) { + Some(Const::Int(w)) => Some(*w), + other => panic!("{other:?}"), + }, + other => panic!("{other:?}"), + }, + _ => None, + }) + .collect(); + assert_eq!(words, [3, 4, 1, 6]); + let table = cl + .ep + .params + .iter() + .find(|p| p.param == 9) + .expect("the table"); + assert_eq!( + table.name.as_ref().map(ToString::to_string).as_deref(), + Some("__image_order_data_type_table") + ); +} + +#[test] +fn opencl_1d_images_are_read_written_and_queried_as_2d_textures() { + use crate::intrinsics::{ImageDim, Query}; + let test = "opencl_1d_images_are_read_written_and_queried_as_2d_textures"; + let (Some(plain), Some(cl)) = (images(test, false), images(test, true)) else { + return; + }; + let ops = |e: &Entry| { + let mut v: Vec<_> = texture_ops(e) + .into_iter() + .filter(|(op, ..)| { + !matches!( + op, + TexOp::Query(Query::ChannelOrder | Query::ChannelDataType) + ) + }) + .map(|(op, dim, array)| { + let op = match op { + TexOp::Read => "read", + TexOp::Sample { .. } => "sample", + TexOp::Write => "write", + TexOp::Query(Query::Width) => "width", + TexOp::Query(Query::ArraySize) => "array_size", + other => panic!("{other:?}"), + }; + (op, dim, array) + }) + .collect(); + v.sort(); + v + }; + // As Metal AIR the operations stay those of 1D textures. + assert_eq!( + ops(&plain), + [ + ("array_size", ImageDim::D1, true), + ("read", ImageDim::D1, false), + ("sample", ImageDim::D1, true), + ("width", ImageDim::D1, false), + ("write", ImageDim::D1, false), + ] + ); + // In OpenCL mode each is the 2D texture's, or the 2D array texture's, Apple's OpenCL binds. + assert_eq!( + ops(&cl), + [ + ("array_size", ImageDim::D2, true), + ("read", ImageDim::D2, false), + ("sample", ImageDim::D2, true), + ("width", ImageDim::D2, false), + ("write", ImageDim::D2, false), + ], + "{}", + print(&cl.module) + ); + // The sampled coordinate is `(x, 0.5)`, the integer ones `(x, 0)`: each built by inserting + // `x` into lane 0 of a constant pair. + let pairs: Vec = body(&cl) + .insts + .values() + .filter_map(|i| match &i.kind { + InstKind::InsertElement { + vec: Value::Const(c), + .. + } => cl.module.consts().get(*c).map(|k| k.value.clone()), + _ => None, + }) + .collect(); + let half = Const::Float(u64::from(0.5f32.to_bits())); + let sampled = pairs.iter().filter(|c| match c { + Const::Aggregate(lanes) => { + lanes.len() == 2 && cl.module.consts().get(lanes[1]).map(|k| &k.value) == Some(&half) + } + _ => false, + }); + assert_eq!(sampled.count(), 1, "{}", print(&cl.module)); + // The read's and the write's coordinates from zero. + assert!( + pairs.iter().filter(|c| matches!(c, Const::Null)).count() >= 2, + "{}", + print(&cl.module) + ); +} + +#[test] +fn opencl_image_formats_of_buffer_and_depth_images_stay_undecoded() { + // Metal makes no pipeline of OpenCL mode that queries their formats (M3 Max, macOS 27.0.1; + // Radeon Pro 5300M, macOS 26.7.1): the names stay unknown, and are refused as such. + for name in [ + "air.get_channel_order_texture_buffer_1d", + "air.get_channel_data_type_texture_buffer_1d", + "air.get_channel_order_depth_2d", + "air.get_channel_data_type_depth_2d_array", + ] { + assert_eq!(AirIntrinsic::parse(name), None, "{name}"); + } + for name in [ + "air.get_channel_order_texture_1d", + "air.get_channel_data_type_texture_1d_array", + "air.get_channel_order_texture_2d", + "air.get_channel_data_type_texture_2d_array", + "air.get_channel_order_texture_3d", + ] { + assert!(AirIntrinsic::parse(name).is_some(), "{name}"); + } +} diff --git a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs index 9b62e1e1b..06f500d1b 100644 --- a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs @@ -492,6 +492,10 @@ const OBSERVED: &[(&str, &str)] = &[ ("air.get_height_depth_cube_array", "i32 (p1, i32)"), ("air.is_null_texture_1d", "i1 (p1)"), ("air.get_null_texture_3d", "p1 ()"), + // OpenCL C's image format queries (Apple's OpenCL compiler, macOS 27.0.1 and 26.7.1). + ("air.get_channel_order_texture_2d", "i32 (p1)"), + ("air.get_channel_data_type_texture_1d_array", "i32 (p1)"), + ("air.get_channel_order_texture_3d", "i32 (p1)"), ("air.get_read_sampler", "p2 ()"), // Derivatives and boolean reductions. ("air.dfdx.v3f16", "v3f16 (v3f16)"), diff --git a/crates/metal2vulkan-air/src/intrinsics/texture.rs b/crates/metal2vulkan-air/src/intrinsics/texture.rs index ad9d29553..af91e1372 100644 --- a/crates/metal2vulkan-air/src/intrinsics/texture.rs +++ b/crates/metal2vulkan-air/src/intrinsics/texture.rs @@ -142,6 +142,15 @@ pub enum Query { NumMipLevels, /// `get_num_samples`: a multisampled texture's samples per texel. NumSamples, + /// `get_channel_order`: OpenCL C's `get_image_channel_order`, as Apple's OpenCL compiler + /// writes it (`i32 (tex)`, macOS 27.0.1 and 26.7.1). A pipeline of OpenCL mode reads it from + /// its third hidden buffer (`canon::opencl`); lowering refuses one any other pipeline keeps. + /// Metal makes no pipeline of OpenCL mode that queries a texture buffer or a depth texture + /// (measured on an M3 Max and a Radeon Pro 5300M), so those kinds stay undecoded. + ChannelOrder, + /// `get_channel_data_type`: OpenCL C's `get_image_channel_data_type`, as + /// [`Query::ChannelOrder`]. + ChannelDataType, } /// A texture operation. The bound immediates live in the variant. @@ -377,6 +386,9 @@ pub(super) const OPS: &[(&str, OpName, &[&str], &[&str])] = { const LOD_D: &[&str] = &["2d", "2d_array", "cube", "cube_array"]; // The textures Metal's atomics take (Apple's metal 32023.921 declares no cube one). const ATOMIC_T: &[&str] = &["1d", "1d_array", "2d", "2d_array", "3d", "buffer_1d"]; + // The images whose format a pipeline of OpenCL mode answers (OpenCL C's image types but the + // buffer and depth ones, whose queries Metal refuses). + const CL_T: &[&str] = &["1d", "1d_array", "2d", "2d_array", "3d"]; &[ ( "sample", @@ -582,6 +594,19 @@ pub(super) const OPS: &[(&str, OpName, &[&str], &[&str])] = { &["2d_ms", "2d_ms_array"], &["2d_ms", "2d_ms_array"], ), + // OpenCL C's image format queries (Apple's OpenCL compiler, macOS 27.0.1 and 26.7.1). + ( + "get_channel_order", + Query(super::texture::Query::ChannelOrder), + CL_T, + &[], + ), + ( + "get_channel_data_type", + Query(super::texture::Query::ChannelDataType), + CL_T, + &[], + ), ("is_null", IsNull, ALL_T, ALL_D), ("get_null", GetNull, ALL_T, ALL_D), ( diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 9ff9b426c..de3964a6e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -347,6 +347,8 @@ mod noted_apart; mod notice_command_buffers; mod numbered_samplers; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod opencl_images; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_kernels; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_mode; diff --git a/crates/metal2vulkan-runtime/src/tests/opencl_images.rs b/crates/metal2vulkan-runtime/src/tests/opencl_images.rs new file mode 100644 index 000000000..c17c8bcb6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/opencl_images.rs @@ -0,0 +1,433 @@ +//! Images in compute pipelines of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`), +//! each kernel in the shape Apple's OpenCL compiler writes OpenCL C's image functions, run with the +//! textures, samplers and hidden buffers bound as Apple's OpenCL binds them, and compared with what +//! an M3 Max (macOS 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) compute for kernels of the same +//! shapes over the same data: +//! +//! - **formats**: `get_image_channel_order` and `get_image_channel_data_type` answer the words of +//! the third hidden buffer (`__image_order_data_type_table`) of the image's texture index `t`: +//! `2t + 1` for the order, `2t` for the data type. With the buffer's word `i` holding +//! `i * 0x10000 + 0x1234`: the order of the 1D image at texture 1 is `0x31234`, the data type of +//! the 2D array image at 2 `0x41234`, and the 2D image at 0 answers `0x11234` and `0x1234`. +//! - **lines**: a 1D image bound as a 2D texture of height 1 and a 1D array image as a 2D array +//! texture of height 1, as Apple's OpenCL binds them, read with and without a sampler and +//! queried: each read answers the 1D image's texel (row 0, of the layer an array read names; +//! a linear filter at a border-clamped edge blends in no row of the border), and the width and +//! layer count are the image's. +//! - **wlines**: writes to the same two bindings land in row 0, of the layer named. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The modules are LLVM text written here +//! (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use super::opencl_mode::{buffer, floats, floats_buffer, kernel_list, state, words, words_buffer}; +use crate::{ + Buffer, ComputePipelineState, Device, Region, ResourceOptions, SamplerState, Size, Texture, + TextureDescriptor, +}; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::{ + PixelFormat, SamplerAddressMode, SamplerMinMagFilter, TextureType, TextureUsage, +}; + +/// The 1D images' width, in texels, and the threads that read or write them. +const WIDTH: u64 = 16; + +/// The node of argument `n`, a texture at `index` of the MSL type `ty` (`texture1d`), 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}\"}}" + ) +} + +/// The node of argument `n`, a sampler at `index`. +fn sampler_node(n: u32, index: u32, name: &str) -> String { + format!( + "!{{i32 {n}, !\"air.sampler\", !\"air.location_index\", i32 {index}, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"{name}\"}}" + ) +} + +/// The node of argument `n`, a read-write `float4` buffer at `index`. +fn float4s(n: u32, index: u32, name: &str) -> String { + format!( + "!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, 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\", !\"{name}\"}}" + ) +} + +/// `__kernel void formats(__read_only image2d_t a, __read_only image1d_t b, __read_only +/// image2d_array_t c, __global int *o)`: `o[0..4]` take the order of `b`, the data type of `c`, and +/// the order and the data type of `a`. +fn formats() -> String { + let body = "define void @__entry_formats(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\ +entry:\n\ + tail call fastcc void @formats(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 @formats(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c, ptr addrspace(1) %o) #1 {\n\ +entry:\n\ + %ob = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %b)\n\ + store i32 %ob, ptr addrspace(1) %o, align 4\n\ + %dc = tail call fastcc i32 @_Z27get_image_channel_data_type20ocl_image2d_array_ro(ptr addrspace(1) %c)\n\ + %o1 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 1\n\ + store i32 %dc, ptr addrspace(1) %o1, align 4\n\ + %oa = tail call fastcc i32 @_Z23get_image_channel_order14ocl_image2d_ro(ptr addrspace(1) %a)\n\ + %o2 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 2\n\ + store i32 %oa, ptr addrspace(1) %o2, align 4\n\ + %da = tail call fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_ro(ptr addrspace(1) %a)\n\ + %o3 = getelementptr inbounds i32, ptr addrspace(1) %o, i64 3\n\ + store i32 %da, ptr addrspace(1) %o3, align 4\n\ + ret void\n}\n\ +define internal fastcc i32 @_Z23get_image_channel_order14ocl_image1d_ro(ptr addrspace(1) %0) #2 {\n\ + %2 = tail call i32 @air.get_channel_order_texture_1d(ptr addrspace(1) %0) #0\n\ + ret i32 %2\n}\n\ +define internal fastcc i32 @_Z27get_image_channel_data_type20ocl_image2d_array_ro(ptr addrspace(1) %0) #2 {\n\ + %2 = tail call i32 @air.get_channel_data_type_texture_2d_array(ptr addrspace(1) %0) #0\n\ + ret i32 %2\n}\n\ +define internal fastcc i32 @_Z23get_image_channel_order14ocl_image2d_ro(ptr addrspace(1) %0) #2 {\n\ + %2 = tail call i32 @air.get_channel_order_texture_2d(ptr addrspace(1) %0) #0\n\ + ret i32 %2\n}\n\ +define internal fastcc i32 @_Z27get_image_channel_data_type14ocl_image2d_ro(ptr addrspace(1) %0) #2 {\n\ + %2 = tail call i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1) %0) #0\n\ + ret i32 %2\n}\n\ +declare i32 @air.get_channel_order_texture_1d(ptr addrspace(1)) #0\n\ +declare i32 @air.get_channel_data_type_texture_2d_array(ptr addrspace(1)) #0\n\ +declare i32 @air.get_channel_order_texture_2d(ptr addrspace(1)) #0\n\ +declare i32 @air.get_channel_data_type_texture_2d(ptr addrspace(1)) #0\n"; + let args = [ + image(0, 0, "sample", "texture2d", "a"), + image(1, 1, "sample", "texture1d", "b"), + image(2, 2, "sample", "texture2d_array", "c"), + buffer(3, 0, "read_write", 1, "int", "o"), + ]; + format!("{body}{}", kernel_list("__entry_formats", &args)) +} + +/// `__kernel void lines(__read_only image1d_t a, __read_only image1d_array_t b, sampler_t s, +/// sampler_t l, __global float4 *o)`: at `x = get_global_id(0)`, `o[6x..6x + 6]` take `a` read at +/// `x`, sampled through `s` at `x` and through `l` at `(x + 0.5) / 16`, layer 1 of `b` read at `x` +/// and sampled through `l` at `(x + 0.5) / 16`, and `(width(a), width(b), array_size(b), 0)`. +fn lines() -> String { + let body = "define void @__entry_lines(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(2) %2, ptr addrspace(2) %3, ptr addrspace(1) %4) #0 {\n\ +entry:\n\ + tail call fastcc void @lines(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(2) %2, ptr addrspace(2) %3, ptr addrspace(1) %4)\n\ + ret void\n}\n\ +define internal fastcc void @lines(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(2) %s, ptr addrspace(2) %l, 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\ + %base = mul i64 %g, 6\n\ + %fx = sitofp i32 %x to float\n\ + %h = fadd float %fx, 5.000000e-01\n\ + %nx = fmul float %h, 6.250000e-02\n\ + %rs = tail call ptr addrspace(2) @air.get_read_sampler()\n\ + %r0 = 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\ + %t0 = extractvalue { <4 x float>, i8 } %r0, 0\n\ + %p0 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %base\n\ + store <4 x float> %t0, ptr addrspace(1) %p0, align 16\n\ + %r1 = tail call { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %s, float %fx, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\ + %t1 = extractvalue { <4 x float>, i8 } %r1, 0\n\ + %i1 = add i64 %base, 1\n\ + %p1 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i1\n\ + store <4 x float> %t1, ptr addrspace(1) %p1, align 16\n\ + %r2 = tail call { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1) %a, ptr addrspace(2) %l, float %nx, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\ + %t2 = extractvalue { <4 x float>, i8 } %r2, 0\n\ + %i2 = add i64 %base, 2\n\ + %p2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i2\n\ + store <4 x float> %t2, ptr addrspace(1) %p2, align 16\n\ + %r3 = 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\ + %t3 = extractvalue { <4 x float>, i8 } %r3, 0\n\ + %i3 = add i64 %base, 3\n\ + %p3 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i3\n\ + store <4 x float> %t3, ptr addrspace(1) %p3, align 16\n\ + %r4 = tail call { <4 x float>, i8 } @air.sample_texture_1d_array.v4f32(ptr addrspace(1) %b, ptr addrspace(2) %l, float %nx, i32 1, i1 false, i32 0, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n\ + %t4 = extractvalue { <4 x float>, i8 } %r4, 0\n\ + %i4 = add i64 %base, 4\n\ + %p4 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i4\n\ + store <4 x float> %t4, ptr addrspace(1) %p4, align 16\n\ + %wa = tail call i32 @air.get_width_texture_1d(ptr addrspace(1) %a, i32 0)\n\ + %wb = tail call i32 @air.get_width_texture_1d_array(ptr addrspace(1) %b, i32 0)\n\ + %nb = tail call i32 @air.get_array_size_texture_1d_array(ptr addrspace(1) %b)\n\ + %fwa = sitofp i32 %wa to float\n\ + %fwb = sitofp i32 %wb to float\n\ + %fnb = uitofp i32 %nb to float\n\ + %v0 = insertelement <4 x float> , float %fwa, i64 0\n\ + %v1 = insertelement <4 x float> %v0, float %fwb, i64 1\n\ + %v2 = insertelement <4 x float> %v1, float %fnb, i64 2\n\ + %i5 = add i64 %base, 5\n\ + %p5 = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i64 %i5\n\ + store <4 x float> %v2, ptr addrspace(1) %p5, 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 { <4 x float>, i8 } @air.sample_texture_1d.v4f32(ptr addrspace(1), ptr addrspace(2), float, i1, i32, i1, float, float, i32) #0\n\ +declare { <4 x float>, i8 } @air.sample_texture_1d_array.v4f32(ptr addrspace(1), ptr addrspace(2), float, i32, i1, i32, i1, float, float, i32) #0\n\ +declare i32 @air.get_width_texture_1d(ptr addrspace(1), i32) #0\n\ +declare i32 @air.get_width_texture_1d_array(ptr addrspace(1), i32) #0\n\ +declare i32 @air.get_array_size_texture_1d_array(ptr addrspace(1)) #0\n"; + let args = [ + image(0, 0, "sample", "texture1d", "a"), + image(1, 1, "sample", "texture1d_array", "b"), + sampler_node(2, 0, "s"), + sampler_node(3, 1, "l"), + float4s(4, 0, "o"), + ]; + format!("{body}{}", kernel_list("__entry_lines", &args)) +} + +/// `__kernel void wlines(__write_only image1d_t a, __write_only image1d_array_t b)`: at +/// `x = get_global_id(0)`, `a` takes `(x, 1, 2, 3)` at `x` and layer 1 of `b` `(x, 4, 5, 6)`. +fn wlines() -> String { + let body = "define void @__entry_wlines(ptr addrspace(1) %0, ptr addrspace(1) %1) #0 {\n\ +entry:\n\ + tail call fastcc void @wlines(ptr addrspace(1) %0, ptr addrspace(1) %1)\n\ + ret void\n}\n\ +define internal fastcc void @wlines(ptr addrspace(1) %a, ptr addrspace(1) %b) #1 {\n\ +entry:\n\ + %g = tail call fastcc i64 @_Z13get_global_idj(i32 0)\n\ + %x = trunc i64 %g to i32\n\ + %fx = sitofp i32 %x to float\n\ + %ta = insertelement <4 x float> , float %fx, i64 0\n\ + tail call void @air.write_texture_1d.v4f32(ptr addrspace(1) %a, i32 %x, <4 x float> %ta, i32 0, i32 2)\n\ + %tb = insertelement <4 x float> , float %fx, i64 0\n\ + tail call void @air.write_texture_1d_array.v4f32(ptr addrspace(1) %b, i32 %x, i32 1, <4 x float> %tb, i32 0, i32 2)\n\ + ret void\n}\n\ +declare void @air.write_texture_1d.v4f32(ptr addrspace(1), i32, <4 x float>, i32, i32) #0\n\ +declare void @air.write_texture_1d_array.v4f32(ptr addrspace(1), i32, i32, <4 x float>, i32, i32) #0\n"; + let args = [ + image(0, 0, "write", "texture1d", "a"), + image(1, 1, "write", "texture1d_array", "b"), + ]; + format!("{body}{}", kernel_list("__entry_wlines", &args)) +} + +/// A shared `RGBA32Float` texture of `texture_type`, `width` by `height`, of `layers` layers, each +/// of `texels` where given. +fn texture( + device: &Device, + texture_type: TextureType, + (width, height, layers): (u64, u64, u64), + texels: Option<&[f32]>, +) -> Texture { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA32Float, width, height, false); + descriptor.texture_type = texture_type; + descriptor.array_length = layers; + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let image = (width * height * 4) as usize; + if let Some(texels) = texels { + for (layer, texels) in (0u64..).zip(texels.chunks(image)) { + let bytes: Vec = texels.iter().flat_map(|f| f.to_le_bytes()).collect(); + texture + .replace_region( + Region::new_2d(0, 0, width, height), + 0, + layer, + &bytes, + 16 * width, + 0, + ) + .unwrap(); + } + } + texture +} + +/// Row 0 of layer `layer` of `texture`, `WIDTH` texels wide, as floats. +fn row(texture: &Texture, layer: u64) -> Vec { + let mut bytes = vec![0u8; (16 * WIDTH) as usize]; + texture + .get_bytes( + &mut bytes, + 16 * WIDTH, + 0, + Region::new_2d(0, 0, WIDTH, 1), + 0, + layer, + ) + .unwrap(); + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|w| f32::from_le_bytes(*w)) + .collect() +} + +/// A sampler of `filter`, `address` and `normalized` coordinates. +fn sampler( + device: &Device, + filter: SamplerMinMagFilter, + address: SamplerAddressMode, + normalized: bool, +) -> SamplerState { + let mut descriptor = SamplerDescriptor::new(); + descriptor.min_filter = filter; + descriptor.mag_filter = filter; + descriptor.s_address_mode = address; + descriptor.t_address_mode = address; + descriptor.r_address_mode = address; + descriptor.normalized_coordinates = normalized; + device.new_sampler_state(&descriptor).unwrap() +} + +/// What `state` binds besides its hidden buffers. +struct Bound<'a> { + textures: &'a [&'a Texture], + samplers: &'a [&'a SamplerState], + /// The kernel's own buffer at 3 (its index 0), if any. + out: Option<&'a Buffer>, +} + +/// `state` dispatched over `threads` threads, one dimension, its hidden buffers bound as Apple's +/// OpenCL binds them (the third holding word `i` as `i * 0x10000 + 0x1234`), and `bound`'s textures, +/// samplers and buffer at their indices. +fn run(device: &Device, state: &ComputePipelineState, threads: u64, bound: &Bound<'_>) { + let table: Vec = (0..64).map(|i| i * 0x10000 + 0x1234).collect(); + let hidden = [ + words_buffer(device, &[0, 0, 0, 1]), + words_buffer(device, &[0; 16]), + words_buffer(device, &table), + ]; + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + for (index, b) in (0u32..).zip(&hidden) { + encoder.set_buffer(Some(b), 0, index).unwrap(); + } + if let Some(out) = bound.out { + encoder.set_buffer(Some(out), 0, 3).unwrap(); + } + for (index, t) in (0u32..).zip(bound.textures) { + encoder.set_texture(Some(t), index).unwrap(); + } + for (index, s) in (0u32..).zip(bound.samplers) { + encoder.set_sampler_state(Some(s), index).unwrap(); + } + encoder + .dispatch_threads(Size::new(threads, 1, 1), Size::new(threads, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); +} + +/// The 1D image's texels: lane `i` of the row is `10 + i`. +fn line() -> Vec { + (0..WIDTH * 4).map(|i| 10.0 + i as f32).collect() +} + +/// The 1D array image's texels: lane `i` of its two layers is `1000 + i`. +fn layers() -> Vec { + (0..2 * WIDTH * 4).map(|i| 1000.0 + i as f32).collect() +} + +#[test] +fn opencl_mode_image_formats_read_the_third_hidden_buffer() { + let scratch = Scratch::new("opencl-images-formats"); + let device = device(&scratch.0); + let formats = state(&device, &formats(), "__entry_formats"); + let a = texture(&device, TextureType::Type2D, (8, 4, 1), None); + let b = texture(&device, TextureType::Type2D, (WIDTH, 1, 1), None); + let c = texture(&device, TextureType::Type2DArray, (8, 4, 3), None); + let o = words_buffer(&device, &[0xeeee_eeee; 4]); + run( + &device, + &formats, + 1, + &Bound { + textures: &[&a, &b, &c], + samplers: &[], + out: Some(&o), + }, + ); + assert_eq!(words(&o), [0x31234, 0x41234, 0x11234, 0x1234]); +} + +#[test] +fn opencl_mode_1d_images_read_their_2d_bindings_row_0() { + let scratch = Scratch::new("opencl-images-lines"); + let device = device(&scratch.0); + let lines = state(&device, &lines(), "__entry_lines"); + let (line, layers) = (line(), layers()); + let a = texture(&device, TextureType::Type2D, (WIDTH, 1, 1), Some(&line)); + let b = texture( + &device, + TextureType::Type2DArray, + (WIDTH, 1, 2), + Some(&layers), + ); + let s = sampler( + &device, + SamplerMinMagFilter::Nearest, + SamplerAddressMode::ClampToEdge, + false, + ); + let l = sampler( + &device, + SamplerMinMagFilter::Linear, + SamplerAddressMode::ClampToZero, + true, + ); + let o = floats_buffer(&device, &vec![-1.0; (WIDTH * 6 * 4) as usize]); + run( + &device, + &lines, + WIDTH, + &Bound { + textures: &[&a, &b], + samplers: &[&s, &l], + out: Some(&o), + }, + ); + let got = floats(&o); + for x in 0..WIDTH as usize { + let at = |column: usize| &got[(6 * x + column) * 4..(6 * x + column + 1) * 4]; + let texel = &line[4 * x..4 * x + 4]; + let layer1 = &layers[(WIDTH as usize + x) * 4..(WIDTH as usize + x + 1) * 4]; + assert_eq!(at(0), texel, "read of a at {x}"); + assert_eq!(at(1), texel, "sample of a through s at {x}"); + assert_eq!(at(2), texel, "sample of a through l at {x}"); + assert_eq!(at(3), layer1, "read of b's layer 1 at {x}"); + assert_eq!(at(4), layer1, "sample of b's layer 1 through l at {x}"); + assert_eq!(at(5), [16.0, 16.0, 2.0, 0.0], "sizes at {x}"); + } +} + +#[test] +fn opencl_mode_1d_images_write_their_2d_bindings_row_0() { + let scratch = Scratch::new("opencl-images-wlines"); + let device = device(&scratch.0); + let wlines = state(&device, &wlines(), "__entry_wlines"); + let zeros = vec![0.0; (2 * WIDTH * 4) as usize]; + let a = texture(&device, TextureType::Type2D, (WIDTH, 1, 1), Some(&zeros)); + let b = texture( + &device, + TextureType::Type2DArray, + (WIDTH, 1, 2), + Some(&zeros), + ); + run( + &device, + &wlines, + WIDTH, + &Bound { + textures: &[&a, &b], + samplers: &[], + out: None, + }, + ); + let texels = |lanes: [f32; 3]| -> Vec { + (0..WIDTH) + .flat_map(|x| [x as f32, lanes[0], lanes[1], lanes[2]]) + .collect() + }; + assert_eq!(row(&a, 0), texels([1.0, 2.0, 3.0])); + assert_eq!(row(&b, 0), vec![0.0; (WIDTH * 4) as usize]); + assert_eq!(row(&b, 1), texels([4.0, 5.0, 6.0])); +} diff --git a/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs index a712dd02f..c2a480600 100644 --- a/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs +++ b/crates/metal2vulkan-runtime/src/tests/opencl_mode.rs @@ -89,7 +89,7 @@ attributes #5 = { convergent nounwind willreturn }\n\ /// The node of argument `n`, a buffer at `index` of address space `space` holding `ty`, `access` /// one of `read`, `read_write`. -fn buffer(n: u32, index: u32, access: &str, space: u32, ty: &str, name: &str) -> String { +pub(super) fn buffer(n: u32, index: u32, access: &str, space: u32, ty: &str, name: &str) -> String { format!( "!{{i32 {n}, !\"air.buffer\", !\"air.location_index\", i32 {index}, i32 1, !\"air.{access}\", !\"air.address_space\", i32 {space}, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"{ty}\", !\"air.arg_name\", !\"{name}\"}}" ) @@ -107,7 +107,7 @@ fn constant(n: u32, index: u32, size: u32, ty: &str, name: &str, layout: Option< } /// The kernel list of `entry` with argument nodes `args`. -fn kernel_list(entry: &str, args: &[String]) -> String { +pub(super) fn kernel_list(entry: &str, args: &[String]) -> String { kernel_list_with(entry, args, "") } @@ -403,7 +403,7 @@ entry:\n\ } /// The state of `entry` of the module `text` (after [`HEAD`]), of OpenCL mode. -fn state(device: &Device, text: &str, entry: &str) -> ComputePipelineState { +pub(super) fn state(device: &Device, text: &str, entry: &str) -> ComputePipelineState { let air = metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{text}")).unwrap(); let library = metal2vulkan::library::Library::from_air(&air).unwrap(); let function = device @@ -419,7 +419,7 @@ fn state(device: &Device, text: &str, entry: &str) -> ComputePipelineState { } /// A shared buffer of `words`. -fn words_buffer(device: &Device, words: &[u32]) -> Buffer { +pub(super) fn words_buffer(device: &Device, words: &[u32]) -> Buffer { let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); device .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) @@ -427,7 +427,7 @@ fn words_buffer(device: &Device, words: &[u32]) -> Buffer { } /// A shared buffer of `floats`. -fn floats_buffer(device: &Device, floats: &[f32]) -> Buffer { +pub(super) fn floats_buffer(device: &Device, floats: &[f32]) -> Buffer { words_buffer( device, &floats.iter().map(|f| f.to_bits()).collect::>(), @@ -435,7 +435,7 @@ fn floats_buffer(device: &Device, floats: &[f32]) -> Buffer { } /// The words of `buffer`, which no command uses now. -fn words(buffer: &Buffer) -> Vec { +pub(super) fn words(buffer: &Buffer) -> Vec { let contents = buffer.contents().unwrap(); // SAFETY: the buffer's bytes, which no command uses now. let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }; @@ -448,7 +448,7 @@ fn words(buffer: &Buffer) -> Vec { } /// The floats of `buffer`, which no command uses now. -fn floats(buffer: &Buffer) -> Vec { +pub(super) fn floats(buffer: &Buffer) -> Vec { words(buffer).into_iter().map(f32::from_bits).collect() } diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 7a37bfcd7..04c8d65b6 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -3758,6 +3758,10 @@ fn select_query( } Query::NumMipLevels => QueryKind::Levels, Query::NumSamples => QueryKind::Samples, + // Canonicalization reads each from the third hidden buffer of a kernel compiled in OpenCL + // mode (`air::canon::opencl`); no other pipeline has the table, and Metal makes no other + // pipeline of a function that queries it. + Query::ChannelOrder | Query::ChannelDataType => return Err(refuse()), }; // A size query at a level that is not the constant 0 answers from the image's first level // (`emit::level_extent`), as Metal does at every level: it queries no level the image may diff --git a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs index c4acfc865..77b364856 100644 --- a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs +++ b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs @@ -172,6 +172,52 @@ attributes #2 = { nounwind readnone willreturn }\n\ !5 = !{i32 2, i32 9, i32 0}\n\ !6 = !{!\"Metal\", i32 1, i32 1, i32 0}\n"; +/// `__kernel void lines(__read_only image1d_t a, __read_only image1d_array_t b, __write_only +/// image1d_t w, __global int *o)`: `w` takes `read_imagef(a, x) + read_imagef(b, (int2)(x, 1))` at +/// `x = get_global_id(0)`, and `o[0]` `get_image_channel_order(a)`, in the shape the OpenCL +/// compiler writes them (macOS 27.0.1). +const LINES: &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_lines(ptr addrspace(1) %0, ptr addrspace(1) %1, ptr addrspace(1) %2, ptr addrspace(1) %3) #0 {\n\ +entry:\n\ + tail call fastcc void @lines(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 @lines(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %w, ptr addrspace(1) %o) #1 {\n\ +entry:\n\ + %x = tail call i32 @air.get_global_id.i32(i32 0) #2\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 %x, 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 %x, i32 1, i32 0, i32 1) #2\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) #3\n\ + %ord = tail call i32 @air.get_channel_order_texture_1d(ptr addrspace(1) %a) #2\n\ + store i32 %ord, ptr addrspace(1) %o, align 4\n\ + ret void\n}\n\ +declare i32 @air.get_global_id.i32(i32) #2\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\ +declare void @air.write_texture_1d.v4f32(ptr addrspace(1), i32, <4 x float>, i32, i32) #3\n\ +declare i32 @air.get_channel_order_texture_1d(ptr addrspace(1)) #2\n\ +attributes #0 = { nounwind }\n\ +attributes #1 = { convergent nounwind }\n\ +attributes #2 = { nounwind readonly willreturn }\n\ +attributes #3 = { nounwind willreturn }\n\ +!air.kernel = !{!0}\n\ +!air.version = !{!7}\n\ +!air.language_version = !{!8}\n\ +!0 = !{ptr @__entry_lines, !1, !2}\n\ +!1 = !{}\n\ +!2 = !{!3, !4, !5, !6}\n\ +!3 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture1d\", !\"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\", !\"air.arg_name\", !\"b\"}\n\ +!5 = !{i32 2, !\"air.texture\", !\"air.location_index\", i32 2, i32 1, !\"air.write\", !\"air.arg_type_name\", !\"texture1d\", !\"air.arg_name\", !\"w\"}\n\ +!6 = !{i32 3, !\"air.buffer\", !\"air.location_index\", i32 0, 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\", !\"int\", !\"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 { function(MODULE, "__entry_k") @@ -444,3 +490,48 @@ fn a_required_work_group_size_caps_the_threadgroup() { assert_eq!(maxima(wg), (64, 64)); assert_eq!(maxima(k), (1024, 1024)); } + +/// In OpenCL mode a 1D image's slot is the 2D texture Apple's OpenCL binds for it, and an image +/// array's the 2D array texture (as the M3 Max's and the Radeon Pro 5300M's reflections state +/// them), so a 2D texture of height 1 binds there; `get_image_channel_order` reads the third hidden +/// buffer. Without the mode the query has no table to read, and the compile refuses it, as Metal +/// refuses a plain pipeline of the kernel. +#[test] +fn an_opencl_mode_kernel_binds_its_1d_images_as_2d_textures() { + use crate::metal::TextureType; + use crate::pipeline::interface::SlotInterface; + let Some(k) = function(LINES, "__entry_lines") else { + return; + }; + let dev = device("moltenvk-m3"); + let b = Budget::standard(); + let p = dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k.clone()), true), &b) + .expect("an OpenCL-mode pipeline"); + let textures: Vec<_> = p + .interface + .slots + .iter() + .filter_map(|(slot, s)| match s { + SlotInterface::Texture(t) => Some((slot.index, t.texture_type, t.access.write)), + _ => None, + }) + .collect(); + assert_eq!( + textures, + [ + (0, TextureType::Type2D, false), + (1, TextureType::Type2DArray, false), + (2, TextureType::Type2D, true), + ] + ); + match dev + .compile_compute_pipeline(&descriptor(StageSource::Function(k), false), &b) + .map(|_| ()) + { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::Lowering(LowerFamily::Texture), "{u:?}"); + } + other => panic!("{other:?}"), + } +}