diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 52ae48ec3..6f5ff593c 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -757,7 +757,8 @@ that touch blocks first. - `setBytes` takes up to 64 KiB, one ring chunk (`Limit::BytesLength`). - A dispatch's threadgroup memory, the kernel's own and the lengths set, each rounded up to 16 bytes, is at most the device's `maxComputeSharedMemorySize` (`Limit::ThreadgroupMemory`), where - Metal's is its `maxThreadgroupMemoryLength`. + Metal's is its `maxThreadgroupMemoryLength`. A kernel's access past its threadgroup memory is + undefined, as in Metal, and the runtime does not confine it. ## Compute encoders diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 01bcb9e8c..ff5155c7a 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -2005,6 +2005,163 @@ define internal void @_GLOBAL__sub_I_() section "air.static_init" { }); } + /// A kernel of 256 threads whose every threadgroup access is a whole `float` word, over one + /// `[[threadgroup(0)]]` region of `params[0]` words: each thread stores each of its words' + /// indices, and after a barrier writes, for each of its words `k`, the word `params[0] - 1 - k` + /// to `out[k]`, and for each of its `float4`s `j` the `float4`'s sum to `out[params[0] + j]`. + const FLOAT_ARENA: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +define void @float_arena(ptr addrspace(3) %a, ptr addrspace(1) %out, ptr addrspace(2) %params, i32 %t) { +entry: + %w = load i32, ptr addrspace(2) %params, align 4 + %last = sub i32 %w, 1 + %w4 = lshr i32 %w, 2 + br label %fill + +fill: + %i = phi i32 [ %t, %entry ], [ %i2, %fill ] + %f = uitofp i32 %i to float + %pa = getelementptr inbounds float, ptr addrspace(3) %a, i32 %i + store float %f, ptr addrspace(3) %pa, align 4 + %i2 = add i32 %i, 256 + %more = icmp ult i32 %i2, %w + br i1 %more, label %fill, label %sync + +sync: + tail call void @air.wg.barrier(i32 2, i32 1) + br label %back + +back: + %k = phi i32 [ %t, %sync ], [ %k2, %back ] + %r = sub i32 %last, %k + %q = getelementptr inbounds float, ptr addrspace(3) %a, i32 %r + %x = load float, ptr addrspace(3) %q, align 4 + %xo = fptoui float %x to i32 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %k + store i32 %xo, ptr addrspace(1) %o, align 4 + %k2 = add i32 %k, 256 + %more2 = icmp ult i32 %k2, %w + br i1 %more2, label %back, label %vectors + +vectors: + %j = phi i32 [ %t, %back ], [ %j2, %vectors ] + %j4 = shl i32 %j, 2 + %q4 = getelementptr inbounds float, ptr addrspace(3) %a, i32 %j4 + %y = load <4 x float>, ptr addrspace(3) %q4, align 16 + %y0 = extractelement <4 x float> %y, i32 0 + %y1 = extractelement <4 x float> %y, i32 1 + %y2 = extractelement <4 x float> %y, i32 2 + %y3 = extractelement <4 x float> %y, i32 3 + %ya = fadd float %y0, %y1 + %yb = fadd float %y2, %y3 + %ys = fadd float %ya, %yb + %yo = fptoui float %ys to i32 + %at = add i32 %w, %j + %o4 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %at + store i32 %yo, ptr addrspace(1) %o4, align 4 + %j2 = add i32 %j, 256 + %more3 = icmp ult i32 %j2, %w4 + br i1 %more3, label %vectors, label %done + +done: + ret void +} + +declare void @air.wg.barrier(i32, i32) + +!air.kernel = !{!0} +!air.version = !{!7} +!air.language_version = !{!8} +!0 = !{ptr @float_arena, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5, !6} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"a"} +!4 = !{i32 1, !"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", !"uint", !"air.arg_name", !"out"} +!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"params"} +!6 = !{i32 3, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +!7 = !{i32 2, i32 8, i32 0} +!8 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// [`FLOAT_ARENA`] with its region filling the device's `maxComputeSharedMemorySize` to the + /// byte. The translator holds the arena in `float` words (its accesses are the `.floats` + /// ones), and the array is the limit's words exactly, so the dispatch runs where Metal runs + /// it, and every answer is the program's. + #[test] + fn every_device_runs_a_float_arena_that_fills_the_threadgroup_memory_limit() { + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(FLOAT_ARENA) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("float_arena: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let function = library.function("float_arena").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + each_device("compute_float_arena_at_the_limit", |name, _, device| { + let limit = device.core().limits.max_shared_memory; + let n = limit / 4; + let StageSource::Function(function) = &descriptor.kernel else { + unreachable!("a Function descriptor"); + }; + let lowered = device + .core() + .translator + .compile_function(function, &descriptor.lowering_inputs(), &Budget::standard()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let census = &lowered.strategies().entries; + for strategy in [ + "access.threadgroup.store.floats", + "access.threadgroup.load.floats", + ] { + assert!( + census.contains_key(strategy), + "{name}: {strategy} in {:?}", + census.keys().collect::>() + ); + } + let state = state(name, &device, &descriptor); + let mut buffers = Buffers::new(&device, 1 << 20); + let out = buffers.buffer(5 * u64::from(limit) / 4); + let queue = device.new_command_queue(4).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("a state"); + encoder + .set_threadgroup_memory_length(limit, 0) + .expect("a length"); + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + encoder + .set_bytes(&le_bytes(&[n]), 1) + .expect("the parameters"); + encoder + .dispatch_threadgroups([1, 1, 1], [256, 1, 1]) + .unwrap_or_else(|error| panic!("{name}: a region of {limit} bytes: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let want: Vec = (0..n) + .map(|k| n - 1 - k) + .chain((0..n / 4).map(|j| 16 * j + 6)) + .collect(); + let got = words(&out, 0, want.len()); + let first = got.iter().zip(&want).position(|(got, want)| got != want); + assert_eq!(first, None, "{name}: the first word that differs"); + println!( + "{name}: a float arena of {limit} bytes, the device's limit, answered all {} words", + want.len() + ); + }); + } + /// A kernel that reads, through the argument buffer at buffer 0 (one `texture2d` /// member, its 8-byte resource ID), the texture's width, height and texel `(0, 0)`'s red bits /// into words 0 to 2 of `out` (buffer 1). diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 5680fb78a..82d63364a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2179; +pub const SEMANTICS_VERSION: u32 = 2180; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index b6ebd640b..e697689f6 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -150,6 +150,12 @@ impl DeviceProfile { self.facts.absent_reads } + /// Whether a threadgroup memory access is contained, and how a kernel's threadgroup arena + /// holds its words when every access of it is a whole, aligned `float` word. + pub(crate) fn threadgroup_memory(&self) -> ThreadgroupMemory { + self.facts.threadgroup_memory + } + /// The profile's fields: internal; the profile is opaque to consumers, who compare /// [`DeviceProfile::fingerprint`] and read its facts through the accessors. pub(crate) fn fields(&self) -> &ProfileFields { @@ -600,6 +606,9 @@ pub(crate) struct ProfileFacts { /// What a read of an argument the pipeline's function constants removed does beside taking /// zero. pub(crate) absent_reads: AbsentReads, + /// Whether a threadgroup memory access is contained, and how a kernel's threadgroup arena + /// holds its words when every access of it is a whole, aligned `float` word. + pub(crate) threadgroup_memory: ThreadgroupMemory, } impl ProfileFacts { @@ -616,6 +625,7 @@ impl ProfileFacts { oblivious_edge: ObliviousEdge::Partial, deep_threadgroups: DeepThreadgroups::Axes, absent_reads: AbsentReads::Marked, + threadgroup_memory: ThreadgroupMemory::Contained, }; /// `Device::from_queries`': each fact the same on every device. @@ -631,6 +641,7 @@ impl ProfileFacts { oblivious_edge: ObliviousEdge::Grid, deep_threadgroups: DeepThreadgroups::OneRow, absent_reads: AbsentReads::Nil, + threadgroup_memory: ThreadgroupMemory::Native, }; } @@ -707,6 +718,26 @@ pub(crate) enum AbsentReads { Nil, } +/// Whether an access of threadgroup memory (a threadgroup arena's, `memory::arena`, its atomics, +/// memory intrinsics, pointer cells and imageblock, and a typed threadgroup object's) is contained, +/// and how a kernel's threadgroup arena holds its words when every access of it is a whole, aligned +/// `float` word: a scalar `float`, or a vector of them, at an offset its alignment proves a +/// multiple of its bytes, with no atomic, no memory intrinsic and no access of another type +/// (`lower::access::local`'s `TgWords`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ThreadgroupMemory { + /// Every access contained, as the profile's containment says (`lower::access::local`): a load + /// past the arena reads zero and a store past it is dropped, and a typed object's dynamic index + /// is clamped to its level. Every arena is a `u32` array whose words each access composes: + /// `Device::new`'s profile. + Contained, + /// No access contained: one past the memory is undefined, as in Metal, and reads or writes + /// what the device's access there does. An arena whose every access is a whole, aligned `float` + /// word is a `float` array of its own words, each access one typed load or store per lane at + /// its word index, with no branch and no bitcast: `Device::from_queries`' profile. + Native, +} + /// How a kernel whose workgroup is its threadgroup (`lower::dispatch::LocalSizeForm::Spec`) runs /// a threadgroup deeper than the device's `maxComputeWorkGroupSize[2]`, and so what the device /// reports as Metal's `maxThreadsPerThreadgroup` (`MetalDeviceProperties`). diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index 5a56b229d..ae591a5c4 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -676,6 +676,7 @@ pub fn select( }; let mem = if threadgroup { local::use_arena(cx, Arena::Threadgroup)?; + local::composed(cx, Arena::Threadgroup); super::tile_memory::written(cx)?; AtomicMem::Threadgroup { ptr: local::access_ptr( @@ -684,7 +685,7 @@ pub fn select( Arena::Threadgroup, u64::from(r.elem.bits().div_ceil(8)), )?, - contained: cx.profile.fields().containment != Containment::UnsafeOff, + contained: local::contained(cx, Arena::Threadgroup), } } else if through_root { // A wide pointer reaches every candidate through its root entry's device address, so a @@ -1221,7 +1222,7 @@ pub fn emit( // buffer the whole device reaches: its atomics are `Device`-scope, and order it as device // memory. let tile_base = match a.mem { - AtomicMem::Threadgroup { .. } => local::decl_of(cx, fb, Arena::Threadgroup)?.tile_base, + AtomicMem::Threadgroup { .. } => local::words_decl(cx, fb)?.tile_base, _ => None, }; let (own, scope) = match a.mem { @@ -1301,7 +1302,7 @@ pub fn emit( let result = match &a.mem { AtomicMem::Private(leaf) => on_private(cx, fb, leaf, o, a.float)?, AtomicMem::Threadgroup { ptr, contained } => { - let decl = local::decl_of(cx, fb, Arena::Threadgroup)?; + let decl = local::words_decl(cx, fb)?; let off = match ptr { LocalPtr::Value(v) => cx.operand(fb, *v)?, LocalPtr::Offset(c) => k32(fb, *c)?, diff --git a/crates/metal2vulkan/src/lower/access/copy.rs b/crates/metal2vulkan/src/lower/access/copy.rs index 4f4fe791e..aafa3508f 100644 --- a/crates/metal2vulkan/src/lower/access/copy.rs +++ b/crates/metal2vulkan/src/lower/access/copy.rs @@ -62,7 +62,6 @@ use std::borrow::Cow; use crate::air::intrinsics::LlvmIntrinsic; use crate::air::ir::{Callee, CastOp, Const, Inst, InstId, InstKind, Value, ValueId}; use crate::budget::Meter; -use crate::device::profile::Containment; use crate::error::{Error, LowerFamily}; use crate::lower::arith::{Form, Held}; use crate::lower::emit::EmitCx; @@ -393,6 +392,7 @@ pub fn endpoint( match local::home_of(cx, v) { Some(home @ Home::Arena(arena)) => { local::use_arena(cx, arena)?; + local::composed(cx, arena); if write { local::writable(cx, arena)?; } @@ -405,7 +405,7 @@ pub fn endpoint( ptr, value: None, leaf, - contained: cx.profile.fields().containment != Containment::UnsafeOff, + contained: local::contained(cx, arena), volatile: false, })); } diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 4e5f31bb4..a252358ba 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -89,7 +89,7 @@ use crate::air::ir::{ }; use crate::bind::status::{StatusBits, StatusWord}; use crate::budget::Meter; -use crate::device::profile::{BufferAccess, Containment, GuestIsolation}; +use crate::device::profile::{BufferAccess, GuestIsolation}; use crate::device::requirements::VkFeature; use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; use crate::lower::arith::{Form, Held}; @@ -939,6 +939,7 @@ fn cell(cx: &mut SelectCx<'_>, ptr: Value, leaf: Leaf, write: bool) -> Result, ptr: Value, leaf: Leaf, write: bool) -> Result, cells: CellUse) -> Result, cell_bytes: u32) -> Result<(), Error> { local::use_arena(cx, Arena::Threadgroup)?; + local::composed(cx, Arena::Threadgroup); let limit = crate::lower::mesh::workgroup_limit(cx); let Some(shape) = cx.families.access.local.tg.as_mut() else { return Err(cx.invariant("a used threadgroup arena without a shape")); @@ -290,7 +290,7 @@ pub(crate) fn cell_offset( /// Whether an imageblock access is contained: as every threadgroup arena access. pub(crate) fn contained(cx: &SelectCx<'_>) -> bool { - cx.profile.fields().containment != Containment::UnsafeOff + local::contained(cx, Arena::Threadgroup) } /// Load `leaf` from the threadgroup arena at byte offset `off`, contained when `contained`. diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index 66560a390..3baf22246 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -33,8 +33,20 @@ //! memory model's operands the arena's words take; a volatile one's words carry `Volatile`, //! except a load of a read-only typed constant object. //! -//! **Containment** of an arena access is on unless the profile's containment is `UnsafeOff` (no -//! robustness feature covers arenas): with `inb` the normative check against the arena's exact byte +//! **A kernel's arena of `float` words** (`memory::arena::TgWords`, on `Device::from_queries`' +//! profile, whose `ThreadgroupMemory` is `Native`): where every access of a kernel's threadgroup +//! arena is a whole, aligned `float` word ([`Leaf::float_words`]), with no atomic, memory +//! intrinsic or pointer cell in it, and its simdgroups are not emulated, the arena is a `float` +//! array of its own words ([`choose_words`]). An access is one `OpLoad` or `OpStore` of a `float` +//! per lane, at the word index `off / 4` and the words after it: no branch, no select and no +//! bitcast. Every other kernel's arena keeps its `u32` words. +//! +//! **Containment** of an arena access is on unless the profile's containment is `UnsafeOff`, or +//! the arena is threadgroup memory on a profile whose `ThreadgroupMemory` is `Native` +//! ([`contained`]): there no threadgroup access is contained, an arena's, its atomics', memory +//! intrinsics', pointer cells' and imageblock's alike, nor a typed threadgroup object's index, and +//! one past the memory is undefined, as in Metal (no robustness feature covers arenas). Contained, +//! with `inb` the normative check against the arena's exact byte //! size, a load reads at `select(inb, off, 0)` and yields `select(inb, v, 0)`, and a store sits in //! a builder-closed `if_(inb)`. A dereference of a null private pointer (undefined in Metal) reads //! or writes the kept first word, or an object's bytes at a field's offset: inside the arena @@ -42,8 +54,9 @@ //! **contained** under //! `GuestIsolation::On` (`memory::alloca`), so the access never leaves its object: a thread's own //! object's (an alloca's) are checked against their levels' lengths, a load past a level reading -//! zero and a store past one sitting in a builder-closed `if_` that drops it; a threadgroup or -//! constant object's are each clamped to the level's last element. A constant index is in range by +//! zero and a store past one sitting in a builder-closed `if_` that drops it; a threadgroup +//! object's, where threadgroup memory is contained ([`contained`]), and a constant object's are +//! each clamped to the level's last element. A constant index is in range by //! construction. Each dynamic index is the defining `getelementptr`'s own operand where the GEP's //! dynamic indices line up one to one with the path's dynamic levels (`lined_up`), and is //! recovered from the pointer's offset otherwise. @@ -90,12 +103,12 @@ use crate::air::ir::{ IntPredicate, Type, TypeId, Value, ValueId, }; use crate::budget::{tree_bytes, Meter, PRIVATE_ARENA_BYTES}; -use crate::device::profile::{Containment, GuestIsolation}; +use crate::device::profile::{Containment, GuestIsolation, ThreadgroupMemory}; use crate::error::{Error, Feature, Limit, LowerFamily, Unsupported}; use crate::lower::emit::EmitCx; use crate::lower::select::{Plan, SelectCx}; use crate::memory::alloca::{self, Init, Shape, Step, Strides, TypedPath, TypedTy}; -use crate::memory::arena::{self, Arena, ArenaDecl, ArenaMem, TgDecl, TgShape}; +use crate::memory::arena::{self, Arena, ArenaDecl, ArenaMem, TgDecl, TgShape, TgWords}; use crate::memory::contain; use crate::memory::fragment; use crate::memory::leaf::{self, k32, Leaf, WordOps}; @@ -141,7 +154,7 @@ pub struct LocalAccess { /// The stored value (stores only). pub value: Option, pub leaf: Leaf, - /// The in-shader containment check (off only for `Containment::UnsafeOff`). + /// The in-shader containment check ([`contained`]). pub contained: bool, /// A volatile access: every word it loads or stores carries `Volatile`. pub volatile: bool, @@ -168,9 +181,9 @@ pub struct TypedAccess { /// where its dynamic indices line up one to one with the path's dynamic levels /// (`lined_up`); `None` recovers each from the pointer's offset. pub indices: Option>, - /// Each dynamic index is contained (`GuestIsolation::On`): checked against its level's length - /// where the access is [`checked`](Self::checked), clamped to its level's last element - /// otherwise. + /// Each dynamic index is contained (`GuestIsolation::On`, and for a typed threadgroup object + /// where threadgroup memory is, [`contained`]): checked against its level's length where the + /// access is [`checked`](Self::checked), clamped to its level's last element otherwise. pub clamped: bool, /// A volatile access: its load or store carries `Volatile`. pub volatile: bool, @@ -308,9 +321,11 @@ impl LocalStrategy { }) } - /// The census name (`access..`). - pub fn name(&self) -> &'static str { + /// The census name (`access..`), a threadgroup arena access's as `plan`'s arena + /// lowers it: one in an arena of `float` words is named so. + pub fn name(&self, plan: &LocalPlan) -> &'static str { use LocalStrategy as L; + let floats = plan.tg.as_ref().is_some_and(|t| t.words == TgWords::Floats); match self { L::Alloca { home, .. } => by_home( *home, @@ -353,6 +368,7 @@ impl LocalStrategy { ], ), L::Load(a) => match (a.arena, a.contained) { + (Arena::Threadgroup, false) if floats => "access.threadgroup.load.floats", (Arena::Threadgroup, true) => "access.threadgroup.load.checked", (Arena::Threadgroup, false) => "access.threadgroup.load", (Arena::Private, true) => "access.private.load.checked", @@ -361,6 +377,7 @@ impl LocalStrategy { (Arena::Payload, false) => "access.payload.load", }, L::Store(a) => match (a.arena, a.contained) { + (Arena::Threadgroup, false) if floats => "access.threadgroup.store.floats", (Arena::Threadgroup, true) => "access.threadgroup.store.checked", (Arena::Threadgroup, false) => "access.threadgroup.store", (Arena::Private, true) => "access.private.store.checked", @@ -659,6 +676,13 @@ pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error // pass keeps across its tile dispatches (`tile::wrap_entry`), and so are a fragment // function's. shape.tile = (fragment || super::tile::is_tile(cx)) && !shape.regions.is_empty(); + // Only a kernel's own workgroup arena may be of `float` words. + let floats = cx.stage == Stage::Kernel + && !super::tile::is_tile(cx) + && cx.profile.threadgroup_memory() == ThreadgroupMemory::Native; + if !floats { + shape.words = TgWords::Composed; + } for &(_, index) in &shape.regions { if shape.tile { cx.facts @@ -697,6 +721,28 @@ pub(super) fn use_arena(cx: &mut SelectCx<'_>, arena: Arena) -> Result<(), Error Ok(()) } +/// The threadgroup arena keeps its composed `u32` words: `arena`, used by an atomic, a memory +/// intrinsic, an imageblock, a pointer cell or another use that is not a whole `float` word access. +pub(super) fn composed(cx: &mut SelectCx<'_>, arena: Arena) { + if arena == Arena::Threadgroup { + if let Some(tg) = cx.families.access.local.tg.as_mut() { + tg.words = TgWords::Composed; + } + } +} + +/// The form of the threadgroup arena, once every instruction is selected under `tier`: of `float` +/// words where every access was a whole, aligned `float` word and the simdgroups are not emulated +/// (the module docs); else composed. +pub(crate) fn choose_words(cx: &mut SelectCx<'_>, tier: crate::device::subgroup::Tier) { + let Some(tg) = cx.families.access.local.tg.as_mut() else { + return; + }; + if tg.words != TgWords::Floats || tier == crate::device::subgroup::Tier::Emulated { + tg.words = TgWords::Composed; + } +} + /// The refusal of a store into `arena` the function may not write: a mesh function's payload is /// its object function's, which it reads only (`TaskPayloadWorkgroupEXT` is read-only in a /// `MeshEXT` entry; Metal's mesh function takes it `const`). @@ -1092,17 +1138,34 @@ pub(crate) fn access( let proven = cx.memory.proven_align(cx.entry, ptr); let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?; let ptr = access_ptr(cx, ptr, arena, u64::from(leaf.bytes))?; + if arena == Arena::Threadgroup { + if let Some(tg) = cx.families.access.local.tg.as_mut() { + tg.words = match (tg.words, leaf.float_words()) { + (TgWords::Unseen | TgWords::Floats, true) => TgWords::Floats, + _ => TgWords::Composed, + }; + } + } let value = stored_value(cx, value)?; Ok(LocalAccess { arena, ptr, value, leaf, - contained: cx.profile.fields().containment != Containment::UnsafeOff, + contained: contained(cx, arena), volatile: false, }) } +/// Whether an access of `arena` is contained (the module docs): unless the profile's containment +/// is `UnsafeOff`, or the arena is threadgroup memory on a profile that contains none +/// (`ThreadgroupMemory::Native`). +pub(crate) fn contained(cx: &SelectCx<'_>, arena: Arena) -> bool { + cx.profile.fields().containment != Containment::UnsafeOff + && !(arena == Arena::Threadgroup + && cx.profile.threadgroup_memory() == ThreadgroupMemory::Native) +} + /// A pointer's offset shape while reading its definitions: `Empty` is a join's identity. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Sh { @@ -1478,8 +1541,11 @@ fn typed_access( (path, fragment, None) } }; - let clamped = - path.dynamic().next().is_some() && cx.profile.fields().isolation == GuestIsolation::On; + // A typed threadgroup object's index is contained as the arena's accesses are ([`contained`]). + let shared = matches!(home, Home::Shared(_)) && !contained(cx, Arena::Threadgroup); + let clamped = path.dynamic().next().is_some() + && cx.profile.fields().isolation == GuestIsolation::On + && !shared; let indices = match reader { Some(at) => lined_up(cx, at, ptr, &path, (obj, count), m)?, None => None, @@ -1862,6 +1928,16 @@ pub(super) fn decl_of( Ok(decl) } +/// The threadgroup arena of a word atomic: never an arena of `float` words, which an atomic keeps +/// composed (`composed`). +pub(super) fn words_decl(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { + let decl = decl_of(cx, fb, Arena::Threadgroup)?; + if decl.floats { + return Err(cx.fail("a word atomic in an arena of float words")); + } + Ok(decl) +} + fn ptr_value(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, p: LocalPtr) -> BResult { match p { LocalPtr::Value(v) => cx.operand(fb, v), @@ -1905,6 +1981,9 @@ pub(super) fn emit_access_at( mem: ArenaMem(decl, ops), kept, }; + if decl.floats { + return float_words(cx, fb, (a, decl, ops), off, stored); + } if !a.contained { return match stored { None => leaf::load(fb, &mut mem, &leaf, off).map(Some), @@ -1946,6 +2025,54 @@ pub(super) fn emit_access_at( } } +/// Load or store (`stored`) `a`'s leaf, whole `float` words, at byte offset `off` of an arena of +/// `float` words (`ArenaDecl::floats`, the module docs): lane `j` of `lanes` at word +/// `off / 4 + j`, one typed access each, uncontained (`ThreadgroupMemory::Native`). +fn float_words( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + (a, decl, ops): (&LocalAccess, ArenaDecl, WordOps), + off: SValue, + stored: Option, +) -> BResult> { + let leaf = a.leaf; + let lanes = u32::from(leaf.form.lanes); + if !leaf.float_words() || a.contained { + return Err(cx.fail("an access of another shape, or contained, in an arena of float words")); + } + let two = k32(fb, 2)?; + let first = fb.binary(BinOp::ShiftRightLogical, off, two)?; + let base = fb.module().global_value(decl.global)?; + let access = ops.access(fb, MemAccess::default(), stored.is_some())?; + let mut loaded = Vec::with_capacity(lanes as usize); + for j in 0..lanes { + let at = match j { + 0 => first, + _ => { + let j = k32(fb, j)?; + fb.binary(BinOp::IAdd, first, j)? + } + }; + let p = fb.access_chain(base, &[at])?; + match stored { + None => loaded.push(fb.load(p, access)?), + Some(v) if lanes == 1 => fb.store(p, v, access)?, + Some(v) => { + let x = fb.composite_extract(v, &[j])?; + fb.store(p, x, access)?; + } + } + } + match (stored, loaded.as_slice()) { + (Some(_), _) => Ok(None), + (None, [x]) => Ok(Some(*x)), + (None, xs) => { + let ty = crate::lower::arith::ops::ty(fb, leaf.form)?; + fb.composite_construct(ty, xs).map(Some) + } + } +} + /// The access-chain indices of `a`'s path, and the check's condition where `a` is checked /// ([`TypedAccess::checked`]). Each dynamic index is the defining GEP's operand where they line up /// (`TypedAccess::indices`), or is recovered from the pointer's offset level by level (`(rem - diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 46391d30f..8bfd2df27 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -526,7 +526,7 @@ impl FamilyStrategy for AccessStrategy { AccessStrategy::Pointer(PtrOp::Select { .. }) => "access.pointer_select".into(), AccessStrategy::Load(a) => a.name("access.load", slots), AccessStrategy::Store(a) => a.name("access.store", slots), - AccessStrategy::Local(l) => l.name().into(), + AccessStrategy::Local(l) => l.name(&slots.local).into(), AccessStrategy::Atomic(a) => a.name(slots), AccessStrategy::Blob(b) => b.name().into(), AccessStrategy::Memory(m) => m.name(slots), diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index f316a51f0..0d4e8f6c3 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1759,6 +1759,8 @@ fn finish( } // A fragment function's group operations run full quads, as Metal runs its helpers. simd::full_quads(&mut cx)?; + // The threadgroup arena's words, now that every access and the tier are known. + access::local::choose_words(&mut cx, tier); let requirement = SubgroupRequirement { // A vertex function's subgroups its driver runs as Metal does without the stage listed: its // module needs that fact in place of the stage. diff --git a/crates/metal2vulkan/src/memory/arena.rs b/crates/metal2vulkan/src/memory/arena.rs index 0af86c54f..6e4b00df0 100644 --- a/crates/metal2vulkan/src/memory/arena.rs +++ b/crates/metal2vulkan/src/memory/arena.rs @@ -22,6 +22,14 @@ //! contained load, which reads at offset 0, stays inside the array; a 32768-byte threadgroup //! allocation is a 32768-byte array and fits `maxComputeSharedMemorySize = 32768`. //! +//! **A kernel's arena of `float` words** ([`TgWords::Floats`], on a profile whose +//! `ThreadgroupMemory` is `Native`, `Device::from_queries`'): where every access of a kernel's +//! arena is a whole, aligned `float` word, a scalar or a vector of them (`lower::access::local`), +//! the array is of `float`, `N` long, `N` the arena's whole words (at least [`FLOAT_LEAST`]), and +//! an access of `lanes` lanes reads or writes them at the words from `off / 4`. Nothing contains +//! it: an access past the arena is undefined, as in Metal. The array is the arena's own words, so +//! its threadgroup memory is Metal's static length and lengths, as for any arena. +//! //! A kernel's explicit imageblock is the arena's last region: `width · height` cells of //! `cell_bytes`, its extent the specialization constants `SpecKey::ImageblockWidth` and //! `SpecKey::ImageblockHeight` (`RuntimeFact::ImageblockSize`, declared through @@ -72,6 +80,25 @@ pub const MIN_ARENA_BYTES: u64 = 32; /// Metal aligns every `[[threadgroup(n)]]` region, and its length, to 16 bytes. pub const REGION_ALIGN: u64 = 16; +/// The least length of an arena of `float` words ([`TgWords::Floats`]): Metal's 16 bytes +/// ([`REGION_ALIGN`]), the grain of its threadgroup memory, so an arena whose lengths are 0 is +/// still an array. +pub const FLOAT_LEAST: u64 = REGION_ALIGN / 4; + +/// What the threadgroup accesses selection has seen say of the arena's words. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum TgWords { + /// No access yet, in a kernel on a profile that holds such an arena in `float`s. + #[default] + Unseen, + /// Every access so far a whole, aligned `float` word access; the arena is of `float`s once + /// selection keeps it so (`lower::access::local::choose_words`). + Floats, + /// The `u32` array of composed words: an access of another shape, an atomic, a memory + /// intrinsic, a pointer cell, or a stage, tier or profile that keeps the composed form. + Composed, +} + /// Which arena a pointer points into. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Arena { @@ -102,6 +129,8 @@ pub struct TgShape { /// that of the pixel of the `FragCoord` input, stage-IO object `fragment` (the module docs). /// `tile` holds too. pub fragment: Option, + /// Whether the arena's words are `float`s (the module docs). + pub words: TgWords, } impl TgShape { @@ -113,6 +142,7 @@ impl TgShape { imageblock: None, tile: false, fragment: None, + words: TgWords::Unseen, } } @@ -247,7 +277,8 @@ pub fn workgroup_limit(stage: Stage, limits: &Limits) -> WorkgroupLimit { } /// A declared arena: its `u32` array variable and its byte size, the containment domain (a -/// plain `u32` constant, or for a threadgroup arena with regions an `OpSpecConstantOp`). +/// plain `u32` constant, or for a threadgroup arena with regions an `OpSpecConstantOp`), or a +/// threadgroup arena's `float` array. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ArenaDecl { pub arena: Arena, @@ -258,6 +289,8 @@ pub struct ArenaDecl { /// the access, `lower::access::tile_memory::base`) is the arena's word 0. `None` for an /// arena that is its own array, and in the declaration, before a function computes it. pub tile_base: Option, + /// An arena of `float` words (the module docs): `global` is a `float` array. + pub floats: bool, } /// The declared threadgroup arena and the byte offset of each region: `(parameter, offset)` in @@ -311,6 +344,23 @@ fn array(mb: &mut ModuleBuilder, class: StorageClass, words: ConstId) -> BResult mb.plain_global(class, ty, None) } +/// The length of an arena of `float` words of `words` whole words: its words, and never under +/// [`FLOAT_LEAST`]. +pub fn float_len(words: u64) -> u64 { + words.max(FLOAT_LEAST) +} + +/// The `Workgroup` `float` array of `len` (a constant) words: an arena of `float` words. +fn float_array(mb: &mut ModuleBuilder, len: ConstId) -> BResult { + let elem = mb.ty(Type::Float { width: 32 })?; + let ty = mb.ty(Type::Array { + elem, + len, + stride: None, + })?; + mb.plain_global(StorageClass::Workgroup, ty, None) +} + /// Words of a static arena of `bytes`: whole words, at least [`MIN_ARENA_BYTES`]. fn static_words(bytes: u64) -> u64 { bytes.max(MIN_ARENA_BYTES).div_ceil(4) @@ -322,19 +372,27 @@ fn static_words(bytes: u64) -> u64 { /// `SpecKey::TgLength(n_i)` (default 0: the binder always specializes it). The imageblock is one /// more region after them, of length `width · height · cell_bytes` from its specialization /// constants (default 0 by 0). The size is the last region's end, and the array's length `max(size -/// / 4, MIN_ARENA_BYTES / 4)`, all `OpSpecConstantOp`s. +/// / 4, MIN_ARENA_BYTES / 4)`, all `OpSpecConstantOp`s. An arena of `float` words +/// ([`TgWords::Floats`]) is a `float` array of its whole words, at least [`FLOAT_LEAST`] +/// ([`float_len`]). pub fn declare_threadgroup(mb: &mut ModuleBuilder, shape: &TgShape) -> BResult { let u32_ = u32_ty(mb)?; if shape.regions.is_empty() && shape.imageblock.is_none() { let size = konst(mb, shape.static_size)?; - let words = konst(mb, static_words(shape.static_size))?; - let global = array(mb, StorageClass::Workgroup, words)?; + let (global, floats) = if shape.words == TgWords::Floats { + let len = konst(mb, float_len(shape.static_size.div_ceil(4)))?; + (float_array(mb, len)?, true) + } else { + let words = konst(mb, static_words(shape.static_size))?; + (array(mb, StorageClass::Workgroup, words)?, false) + }; return Ok(TgDecl { decl: ArenaDecl { arena: Arena::Threadgroup, global, size, tile_base: None, + floats, }, regions: Vec::new(), imageblock: None, @@ -381,18 +439,31 @@ pub fn declare_threadgroup(mb: &mut ModuleBuilder, shape: &TgShape) -> BResult BR global: view.global, size: tile_length(mb)?, tile_base: None, + floats: false, }, regions, imageblock: None, @@ -471,6 +543,7 @@ pub fn declare_payload(mb: &mut ModuleBuilder, size: u64, emulated: bool) -> BRe global, size: bytes, tile_base: None, + floats: false, }) } @@ -484,6 +557,7 @@ pub fn declare_private(mb: &mut ModuleBuilder, size: u64) -> BResult global, size: bytes, tile_base: None, + floats: false, }) } @@ -611,6 +685,7 @@ mod tests { imageblock: None, tile: false, fragment: None, + words: TgWords::Unseen, }; let check = |s: TgShape| s.check(workgroup_limit(Stage::Kernel, &limits)); assert_eq!(check(shape(32768, &[])), Ok(())); diff --git a/crates/metal2vulkan/src/memory/leaf.rs b/crates/metal2vulkan/src/memory/leaf.rs index ae0fa7304..4afa06c63 100644 --- a/crates/metal2vulkan/src/memory/leaf.rs +++ b/crates/metal2vulkan/src/memory/leaf.rs @@ -246,6 +246,16 @@ impl Leaf { self.bytes.div_ceil(4) } + /// Whether the leaf is whole, aligned `float` words: a `float` or a vector of 2 to 4 of them + /// at an offset its alignment makes a multiple of 4 (an arena of `float` words holds it as + /// they are, `memory::arena::TgWords`). + pub fn float_words(&self) -> bool { + self.form.held == Held::Float(FloatFmt::F32) + && (1..=4).contains(&self.form.lanes) + && self.bytes == 4 * u32::from(self.form.lanes) + && matches!(self.path, Path::Vec4 | Path::Vec2 | Path::Aligned) + } + /// Whether the value is a chunked vector. pub fn chunked(&self) -> bool { self.form.lanes > 4 diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index db517cebb..10ba7b9d4 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -1274,7 +1274,7 @@ fn the_old_render_descriptor_key_keeps_its_value() { let key = device("moltenvk-m3").render_descriptor_key(&d); let hex: String = key.digest().iter().map(|b| format!("{b:02x}")).collect(); assert_eq!( - hex, "16991cf7f184e94d810824b0672eba81c8fd390efc4abe2458c5f506f7ed7f3d", + hex, "0114017aa4ed61c141e16042ccbcc63491776b40acddbbe6bb6b07750a738b40", "the old runtime's key of the descriptor" ); } diff --git a/crates/metal2vulkan/src/spirv/interp/tests.rs b/crates/metal2vulkan/src/spirv/interp/tests.rs index d1130eac3..40b3f75e1 100644 --- a/crates/metal2vulkan/src/spirv/interp/tests.rs +++ b/crates/metal2vulkan/src/spirv/interp/tests.rs @@ -882,6 +882,7 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { imageblock: None, tile: false, fragment: None, + words: Default::default(), }; Ok(declare_threadgroup(mb, &shape)?.decl.global) }); @@ -906,6 +907,7 @@ fn a_small_specialized_threadgroup_arena_is_floored_at_eight_words() { imageblock: None, tile: false, fragment: None, + words: Default::default(), }; Ok(declare_threadgroup(mb, &shape)?.decl.global) }); diff --git a/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs new file mode 100644 index 000000000..cc7fe600e --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs @@ -0,0 +1,694 @@ +//! A kernel's threadgroup memory on `Device::from_queries`' profiles +//! (`ThreadgroupMemory::Native`), against `Device::new`'s (`Contained`). +//! +//! - Where every access of the arena is a whole, aligned `float` word (a scalar, a `float2` or a +//! `float4`), the arena is a `Workgroup` `float` array of its own words: one access chain and one +//! typed load or store per lane, with no check. A static arena and one of `[[threadgroup(n)]]` +//! regions both. Every answer is exact, in both scheduling orders. +//! - Through `Device::new` the same kernels keep their composed `u32` words and checks, with the +//! same answers. +//! - No threadgroup access is contained through `from_queries`: a composed arena's (an `int` +//! word's) and a typed threadgroup object's are not, where `Device::new` checks and clamps them. +//! - The array is Metal's allocation: a region filling `maxComputeSharedMemorySize` is planned +//! through `from_queries` as through `Device::new`, one byte more is refused by both, and a static +//! arena's array is its own words. An arena filling the limit answers every word. +//! +//! An access past threadgroup memory is undefined, in Metal as here; no test reads one. +//! +//! `llvm-as` assembles the kernels; without it the tests skip visibly. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::bind::{BindState, BoundBuffer, StageTable}; +use crate::budget::Budget; +use crate::device::profile::DeviceProfile; +use crate::device::{Device, DevicePolicy}; +use crate::error::{BindError, Feature}; +use crate::library::Library; +use crate::lower::select::Plan; +use crate::memory::arena::TgWords; +use crate::pipeline::interface::PushLoc; +use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; +use crate::pipeline::testing::{ + compile, description, link_and_validate, llvm_assemble, typed_module, AssembleError, +}; +use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; +use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize}; +use crate::spirv::ir::TypedModule; + +/// Profiles of four drivers. +const PROFILES: [&str; 4] = [ + "moltenvk-m3", + "lavapipe", + "amd-780m-radv", + "nvidia-rtx50-linux", +]; + +const HEADER: &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\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; + +/// `stem` through `Device::from_queries` under `policy`. +fn queried_with(stem: &str, policy: DevicePolicy) -> Device { + let desc = description(stem).expect("description"); + Device::from_queries(desc, policy).expect("device") +} + +fn queried(stem: &str) -> DeviceProfile { + queried_with(stem, DevicePolicy::default()) + .profile() + .clone() +} + +/// `stem` through `Device::new`. +fn through_new(stem: &str) -> Device { + Device::new( + description(stem).expect("description"), + DevicePolicy::default(), + ) + .expect("device") +} + +fn assemble(name: &str, body: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-tg-floats-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{body}"), + } +} + +/// The body over the 64 `float`s at `%base`, with 64 threads: +/// +/// - thread `t` stores `t` at word `t`, and the `float4` of words `4 k` to `4 k + 3`'s indices at +/// word `4 k`, `k = t & 15`: each word holds its index, whatever the order of the stores; +/// - after a barrier, `out[t]` is the word `63 - t`, `out[64 + t]` the sum of the `float4` at +/// `4 (t & 15)` and `out[128 + t]` the sum of the `float2` at `2 (t & 31)`. +const BODY: &str = r#" %w = and i32 %t, 63 + %fw = uitofp i32 %w to float + %pa = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %w + store float %fw, ptr addrspace(3) %pa, align 4 + %k = and i32 %t, 15 + %w4 = shl i32 %k, 2 + %f4 = uitofp i32 %w4 to float + %v0 = insertelement <4 x float> poison, float %f4, i32 0 + %f41 = fadd float %f4, 1.000000e+00 + %v1 = insertelement <4 x float> %v0, float %f41, i32 1 + %f42 = fadd float %f4, 2.000000e+00 + %v2 = insertelement <4 x float> %v1, float %f42, i32 2 + %f43 = fadd float %f4, 3.000000e+00 + %v3 = insertelement <4 x float> %v2, float %f43, i32 3 + %p4 = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %w4 + store <4 x float> %v3, ptr addrspace(3) %p4, align 16 + tail call void @air.wg.barrier(i32 2, i32 1) + %r = sub i32 63, %t + %q = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %r + %x = load float, ptr addrspace(3) %q, align 4 + %xo = fptoui float %x to i32 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t + store i32 %xo, ptr addrspace(1) %o, align 4 + %j = and i32 %t, 15 + %j4 = shl i32 %j, 2 + %q4 = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %j4 + %y = load <4 x float>, ptr addrspace(3) %q4, align 16 + %y0 = extractelement <4 x float> %y, i32 0 + %y1 = extractelement <4 x float> %y, i32 1 + %y2 = extractelement <4 x float> %y, i32 2 + %y3 = extractelement <4 x float> %y, i32 3 + %ya = fadd float %y0, %y1 + %yb = fadd float %y2, %y3 + %ys = fadd float %ya, %yb + %yo = fptoui float %ys to i32 + %t64 = add i32 %t, 64 + %o4 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t64 + store i32 %yo, ptr addrspace(1) %o4, align 4 + %h = and i32 %t, 31 + %h2 = shl i32 %h, 1 + %q2 = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %h2 + %z = load <2 x float>, ptr addrspace(3) %q2, align 8 + %z0 = extractelement <2 x float> %z, i32 0 + %z1 = extractelement <2 x float> %z, i32 1 + %zs = fadd float %z0, %z1 + %zo = fptoui float %zs to i32 + %t128 = add i32 %t, 128 + %o2 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t128 + store i32 %zo, ptr addrspace(1) %o2, align 4 + ret void +"#; + +const TAIL: &str = r#" +declare void @air.wg.barrier(i32, i32) + +!air.kernel = !{!0} +!air.version = !{!8} +!air.language_version = !{!9} +!8 = !{i32 2, i32 8, i32 0} +!9 = !{!"Metal", i32 4, i32 0, i32 0} +!0 = !{ptr @NAME, !1, !2} +!1 = !{} +"#; + +const OUT_MD: &str = r#"!{i32 IX, !"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", !"uint", !"air.arg_name", !"out"}"#; + +const TID_MD: &str = r#"!{i32 IX, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}"#; + +/// `BODY` over a static `[words x float]` global, whose `float4` and `float2` loads keep it in the +/// arena (they are not its element). +fn static_kernel(words: u32) -> String { + static_of(words, BODY) +} + +/// `body` over a static `[words x float]` global. +fn static_of(words: u32, body: &str) -> String { + format!( + "@g = internal addrspace(3) global [{words} x float] undef, align 16\n\n\ +define void @tg_static(ptr addrspace(1) %out, i32 %t) {{\n{}}}\n{}\ +!2 = !{{!3, !4}}\n!3 = {}\n!4 = {}\n", + body.replace("BASE", "@g"), + TAIL.replace("NAME", "tg_static"), + OUT_MD.replace("IX", "0"), + TID_MD.replace("IX", "1"), + ) +} + +/// `BODY` over a `[[threadgroup(0)]]` `float` region, the arena's only part. +fn region_kernel() -> String { + region_of(BODY) +} + +/// `body` over a `[[threadgroup(0)]]` `float` region, the arena's only part. +fn region_of(body: &str) -> String { + let region = r#"!{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"a"}"#; + format!( + "define void @tg_region(ptr addrspace(3) %a, ptr addrspace(1) %out, i32 %t) {{\n{}}}\n{}\ +!2 = !{{!3, !4, !5}}\n!3 = {region}\n!4 = {}\n!5 = {}\n", + body.replace("BASE", "%a"), + TAIL.replace("NAME", "tg_region"), + OUT_MD.replace("IX", "1"), + TID_MD.replace("IX", "2"), + ) +} + +fn out_slot() -> ResourceSlot { + ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 0, + } +} + +/// Every word of an arena of `WORDS` `float`s over the `float`s at `BASE`, with 64 threads: each +/// thread stores each of its words' indices; after a barrier, `out[k]` is word `WORDS - 1 - k` +/// and `out[WORDS + j]` the sum of the `float4` at word `4 j`, `16 j + 6`. +const FILL: &str = r#"entry: + br label %fill + +fill: + %i = phi i32 [ %t, %entry ], [ %i2, %fill ] + %f = uitofp i32 %i to float + %pa = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %i + store float %f, ptr addrspace(3) %pa, align 4 + %i2 = add i32 %i, 64 + %more = icmp ult i32 %i2, WORDS + br i1 %more, label %fill, label %sync + +sync: + tail call void @air.wg.barrier(i32 2, i32 1) + br label %back + +back: + %k = phi i32 [ %t, %sync ], [ %k2, %back ] + %r = sub i32 LAST, %k + %q = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %r + %x = load float, ptr addrspace(3) %q, align 4 + %xo = fptoui float %x to i32 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %k + store i32 %xo, ptr addrspace(1) %o, align 4 + %k2 = add i32 %k, 64 + %more2 = icmp ult i32 %k2, WORDS + br i1 %more2, label %back, label %vectors + +vectors: + %j = phi i32 [ %t, %back ], [ %j2, %vectors ] + %j4 = shl i32 %j, 2 + %q4 = getelementptr inbounds float, ptr addrspace(3) BASE, i32 %j4 + %y = load <4 x float>, ptr addrspace(3) %q4, align 16 + %y0 = extractelement <4 x float> %y, i32 0 + %y1 = extractelement <4 x float> %y, i32 1 + %y2 = extractelement <4 x float> %y, i32 2 + %y3 = extractelement <4 x float> %y, i32 3 + %ya = fadd float %y0, %y1 + %yb = fadd float %y2, %y3 + %ys = fadd float %ya, %yb + %yo = fptoui float %ys to i32 + %at = add i32 WORDS, %j + %o4 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %at + store i32 %yo, ptr addrspace(1) %o4, align 4 + %j2 = add i32 %j, 64 + %more3 = icmp ult i32 %j2, QUADS + br i1 %more3, label %vectors, label %done + +done: + ret void +"#; + +/// [`FILL`] over `words` words: a static `[words x float]` global, or (`region`) a +/// `[[threadgroup(0)]]` `float` region. +fn fill_kernel(words: u32, region: bool) -> String { + let body = FILL + .replace("WORDS", &words.to_string()) + .replace("LAST", &(words - 1).to_string()) + .replace("QUADS", &(words / 4).to_string()); + if region { + region_of(&body) + } else { + static_of(words, &body) + } +} + +/// Output buffer 0 of 192 zero words, 64 threads, and `spec` besides. +fn resources(plan: &Plan, spec: &[(SpecKey, u64)]) -> Resources { + resources_of(plan, spec, 192) +} + +/// Output buffer 0 of `out_words` zero words, 64 threads, and `spec` besides. +fn resources_of(plan: &Plan, spec: &[(SpecKey, u64)], out_words: usize) -> Resources { + let mut s = BTreeMap::new(); + s.insert(SpecKey::LocalSize(Axis::X), 64); + s.insert(SpecKey::LocalSize(Axis::Y), 1); + s.insert(SpecKey::LocalSize(Axis::Z), 1); + s.insert(SpecKey::FlatLocalSize, 64); + s.extend(spec.iter().copied()); + // Zero push bytes: the output is bound at its start, and the dispatch is one region at the + // grid's origin. + let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; + for f in &plan.push.fields { + assert!( + matches!( + (f.field, f.loc), + ( + PushField::SlotBindOffset(_) | PushField::DispatchRegion, + PushLoc::Push { .. } + ) + ), + "unexpected push field {f:?}" + ); + } + Resources { + buffers: vec![Buffer { + slot: Some(out_slot()), + address: None, + bytes: vec![0; out_words * 4], + }], + push, + spec: s, + } +} + +/// The output words, in both scheduling orders (which must agree). +fn run_both(m: &TypedModule, res: &Resources) -> Vec { + let mut outs = Vec::new(); + for order in [Order::Forward, Order::Reverse] { + let cfg = Config { + subgroup: SubgroupSize::W32, + order, + ..Config::default() + }; + let out = run(m, &cfg, res.clone()).expect("run"); + outs.push( + out.buffers[0] + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes(*c)) + .collect::>(), + ); + } + assert_eq!(outs[0], outs[1], "scheduling orders disagree"); + outs.swap_remove(0) +} + +/// The answers of `BODY` over its 64-word arena: each word its index. +fn want() -> Vec { + // The words an access of `lanes` lanes at word `b` reads. + let lanes = |b: u32, lanes: u32| -> u32 { (b..b + lanes).sum() }; + let mut out: Vec = (0..64u32).map(|t| lanes(63 - t, 1)).collect(); + out.extend((0..64u32).map(|t| lanes(4 * (t & 15), 4))); + out.extend((0..64u32).map(|t| lanes(2 * (t & 31), 2))); + out +} + +/// What the module's words say of its `Workgroup` variables and their accesses. +#[derive(Debug, Default)] +struct Shape { + /// Each `Workgroup` variable's element: `Some(32)` for a 32-bit `float` array, `None` for any + /// other. + float_arrays: Vec>, + /// The constant length of each `Workgroup` `float` array where it is an `OpConstant`. + lengths: Vec, + /// `OpAccessChain`s into a `Workgroup` `float` array. + chains: usize, + labels: usize, + merges: usize, + bitcasts: usize, +} + +fn shape(words: &[u32]) -> Shape { + const TYPE_FLOAT: u32 = 22; + const TYPE_ARRAY: u32 = 28; + const TYPE_POINTER: u32 = 32; + const CONSTANT: u32 = 43; + const VARIABLE: u32 = 59; + const ACCESS_CHAIN: u32 = 65; + const BITCAST: u32 = 124; + const SELECTION_MERGE: u32 = 247; + const LABEL: u32 = 248; + const WORKGROUP: u32 = 4; + let mut floats = BTreeMap::new(); + let mut arrays = BTreeMap::new(); + let mut pointers = BTreeMap::new(); + let mut constants = BTreeMap::new(); + let mut vars = Vec::new(); + let mut s = Shape::default(); + let mut chains = Vec::new(); + let mut i = 5; + while i < words.len() { + let (n, op) = ((words[i] >> 16) as usize, words[i] & 0xFFFF); + let w = &words[i..i + n.max(1)]; + match op { + TYPE_FLOAT => { + floats.insert(w[1], w[2]); + } + TYPE_ARRAY => { + arrays.insert(w[1], (w[2], w[3])); + } + TYPE_POINTER => { + pointers.insert(w[1], (w[2], w[3])); + } + CONSTANT if n == 4 => { + constants.insert(w[2], w[3]); + } + VARIABLE if w[3] == WORKGROUP => vars.push((w[1], w[2])), + ACCESS_CHAIN => chains.push(w[3]), + BITCAST => s.bitcasts += 1, + SELECTION_MERGE => s.merges += 1, + LABEL => s.labels += 1, + _ => {} + } + i += n.max(1); + } + let mut float_vars = Vec::new(); + for (ty, id) in vars { + let array = pointers.get(&ty).and_then(|(_, p)| arrays.get(p)); + let elem = array.and_then(|(e, _)| floats.get(e)).copied(); + s.float_arrays.push(elem); + if let (Some(32), Some((_, len))) = (elem, array) { + float_vars.push(id); + if let Some(len) = constants.get(len) { + s.lengths.push(*len); + } + } + } + s.chains = chains.iter().filter(|b| float_vars.contains(b)).count(); + s +} + +/// A kernel's bitcode, its entry, and the specialization of a 64-word arena. +type Case<'a> = (&'a [u8], &'a str, Spec<'a>); + +/// Specialization constants. +type Spec<'a> = &'a [(SpecKey, u64)]; + +/// Each kernel through `from_queries` is of `float` words: one `Workgroup` `float` array (of 64 +/// words for the static 64), 12 access chains into it (one a lane: 1 + 4 stored, 1 + 4 + 2 +/// loaded), the `.floats` census names, no threadgroup check, and the exact answers. Through +/// `Device::new` the same kernel keeps its `u32` words, more blocks and bitcasts, and its checks, +/// with the same answers. +#[test] +fn an_arena_of_float_accesses_is_a_float_array_through_from_queries() { + let Some(st) = assemble("tg_static", &static_kernel(64)) else { + return; + }; + let Some(rg) = assemble("tg_region", ®ion_kernel()) else { + return; + }; + // The kernel and the specialization of a 64-word arena. + let short = [(SpecKey::TgLength(0), 256)]; + let cases: [Case<'_>; 2] = [(&st, "tg_static", &[]), (&rg, "tg_region", &short)]; + for stem in PROFILES { + let prof = queried(stem); + let new = through_new(stem); + for (bc, entry, spec) in cases { + let what = format!("{entry} on {stem}"); + let a = compile(bc, entry, &prof).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + // Metal's static length. + let metal = if entry == "tg_static" { 256 } else { 0 }; + assert_eq!(a.kernel.static_threadgroup_bytes, metal, "{what}"); + let s = shape(&a.module.words); + assert_eq!(s.float_arrays, vec![Some(32)], "{what}: {s:?}"); + if entry == "tg_static" { + assert_eq!(s.lengths, vec![64], "{what}: {s:?}"); + } + assert_eq!(s.chains, 12, "{what}: {s:?}"); + let (plan, m) = typed_module(bc, entry, &prof).expect("module"); + let tg = plan.families.access.local.tg.as_ref().expect("an arena"); + assert_eq!(tg.words, TgWords::Floats, "{what}"); + let census = plan.census(); + for name in [ + "access.threadgroup.store.floats", + "access.threadgroup.load.floats", + ] { + assert!(census.contains_key(name), "{what}: {name} in {census:?}"); + } + assert!(!contains_threadgroup(&census), "{what}: {census:?}"); + assert_eq!(run_both(&m, &resources(&plan, spec)), want(), "{what}"); + + // Through `Device::new`: composed words and their checks. + let rp = new.profile(); + let c = compile(bc, entry, rp).unwrap_or_else(|e| panic!("{what}: rows: {e}")); + let cs = shape(&c.module.words); + assert_eq!(cs.float_arrays, vec![None], "{what}: rows: {cs:?}"); + assert!( + s.labels < cs.labels && s.merges < cs.merges && s.bitcasts < cs.bitcasts, + "{what}: floats {s:?} against composed {cs:?}" + ); + let (plan, m) = typed_module(bc, entry, rp).expect("module"); + let tg = plan.families.access.local.tg.as_ref().expect("an arena"); + assert_eq!(tg.words, TgWords::Composed, "{what}: rows"); + assert!(contains_threadgroup(&plan.census()), "{what}: rows"); + assert_eq!( + run_both(&m, &resources(&plan, spec)), + want(), + "{what}: rows" + ); + } + } +} + +/// Whether `census` names a contained threadgroup access: a checked arena access or atomic, or a +/// clamped typed threadgroup object's. +fn contains_threadgroup(census: &BTreeMap) -> bool { + census.keys().any(|k| { + k.starts_with("access.threadgroup") && (k.ends_with(".checked") || k.ends_with(".clamped")) + || k.starts_with("access.atomic.threadgroup") && k.ends_with(".checked") + }) +} + +/// Thread `t` of 64 stores `t` as an `int` at word `t` of a 64-word `[[threadgroup(0)]]` region +/// (the arena composed: an `int` is not a `float` word), adds 1 to word 0 by an atomic, and after +/// a barrier `out[t]` is word `63 - t`; and stores `t` at element `t` of a typed threadgroup +/// `[64 x half]` object, `out[64 + t]` its element `63 - t`. +const COMPOSED: &str = r#"@h = internal addrspace(3) global [64 x half] undef, align 2 + +define void @tg_composed(ptr addrspace(3) %a, ptr addrspace(1) %out, i32 %t) { + %w = and i32 %t, 63 + %pa = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %w + store i32 %w, ptr addrspace(3) %pa, align 4 + %fh = uitofp i32 %w to half + %ph = getelementptr inbounds [64 x half], ptr addrspace(3) @h, i32 0, i32 %w + store half %fh, ptr addrspace(3) %ph, align 2 + tail call void @air.wg.barrier(i32 2, i32 1) + %old = tail call i32 @air.atomic.local.add.u.i32(ptr addrspace(3) %a, i32 1, i32 0, i32 1, i1 true) + tail call void @air.wg.barrier(i32 2, i32 1) + %r = sub i32 63, %t + %q = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %r + %x = load i32, ptr addrspace(3) %q, align 4 + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t + store i32 %x, ptr addrspace(1) %o, align 4 + %qh = getelementptr inbounds [64 x half], ptr addrspace(3) @h, i32 0, i32 %r + %y = load half, ptr addrspace(3) %qh, align 2 + %yo = fptoui half %y to i32 + %t64 = add i32 %t, 64 + %o2 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t64 + store i32 %yo, ptr addrspace(1) %o2, align 4 + ret void +} + +declare void @air.wg.barrier(i32, i32) +declare i32 @air.atomic.local.add.u.i32(ptr addrspace(3), i32, i32, i32, i1) + +!air.kernel = !{!0} +!air.version = !{!8} +!air.language_version = !{!9} +!8 = !{i32 2, i32 8, i32 0} +!9 = !{!"Metal", i32 4, i32 0, i32 0} +!0 = !{ptr @tg_composed, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 3, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"int", !"air.arg_name", !"a"} +!4 = !{i32 1, !"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", !"uint", !"air.arg_name", !"out"} +!5 = !{i32 2, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} +"#; + +/// No threadgroup access is contained through `from_queries` ([`COMPOSED`]): its composed arena's +/// loads, stores and atomic, and its typed threadgroup object's accesses, carry no check, where +/// `Device::new`'s carry theirs; the answers are the same, word 0 the 64 threads' atomic adds. +#[test] +fn no_threadgroup_access_is_contained_through_from_queries() { + let Some(bc) = assemble("tg_composed", COMPOSED) else { + return; + }; + let mut want: Vec = (0..64u32).map(|t| 63 - t).collect(); + want[63] += 64; + want.extend((0..64u32).map(|t| 63 - t)); + let length = [(SpecKey::TgLength(0), 256)]; + for stem in PROFILES { + let new = through_new(stem); + for (prof, how) in [ + (queried(stem), "from_queries"), + (new.profile().clone(), "Device::new"), + ] { + let what = format!("tg_composed on {stem} through {how}"); + let a = compile(&bc, "tg_composed", &prof).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let (plan, m) = typed_module(&bc, "tg_composed", &prof).expect("module"); + let tg = plan.families.access.local.tg.as_ref().expect("an arena"); + assert_eq!(tg.words, TgWords::Composed, "{what}"); + let census = plan.census(); + let checked = contains_threadgroup(&census); + assert_eq!(checked, how == "Device::new", "{what}: {census:?}"); + assert_eq!( + run_both(&m, &resources_of(&plan, &length, 128)), + want, + "{what}" + ); + } + } +} + +/// The array is Metal's allocation: through `from_queries` as through `Device::new`, a region +/// filling `maxComputeSharedMemorySize` is planned and one 16 bytes longer is refused +/// (`ThreadgroupMemorySize`). A static arena two words short of the limit is an array of its own +/// words. +#[test] +fn the_float_array_is_metals_allocation() { + let Some(bc) = assemble("tg_region", ®ion_kernel()) else { + return; + }; + for stem in PROFILES { + for (dev, how) in [ + (queried_with(stem, DevicePolicy::default()), "from_queries"), + (through_new(stem), "Device::new"), + ] { + let what = format!("{stem} through {how}"); + let lib = Library::from_air(&bc).expect("library"); + let f = lib.function("tg_region").expect("function"); + let d = + ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); + let pipe = dev + .compile_compute_pipeline(&d, &Budget::standard()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!( + pipe.metal_info.static_threadgroup_memory_length, 0, + "{what}" + ); + let state = |len: u32| { + let mut t = StageTable::default(); + t.buffers.insert( + 0, + BoundBuffer::Buffer { + length: 192 * 4, + offset: 0, + gpu_address: 0, + device_address: None, + attribute_stride: None, + }, + ); + t.threadgroup_lengths.insert(0, len); + let mut s = BindState::default(); + s.stages.insert(Stage::Kernel, t); + s + }; + let max = dev.profile().fields().limits.max_compute_shared_memory_size; + assert!( + pipe.plan(&dev, &state(max).shape()).is_ok(), + "{what}: exactly full" + ); + match pipe.plan(&dev, &state(max + 16).shape()) { + Err(BindError::Unsupported(u)) => { + assert_eq!(u.feature, Feature::ThreadgroupMemorySize, "{what}"); + } + other => panic!("{what}: {other:?}"), + } + } + let prof = queried(stem); + let words = prof.fields().limits.max_compute_shared_memory_size / 4; + let what = format!("a static arena of {} words on {stem}", words - 2); + let Some(big) = assemble("tg_static", &static_kernel(words - 2)) else { + return; + }; + let a = compile(&big, "tg_static", &prof).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let s = shape(&a.module.words); + assert_eq!(s.float_arrays, vec![Some(32)], "{what}: {s:?}"); + assert_eq!(s.lengths, vec![words - 2], "{what}: {s:?}"); + } +} + +/// An arena filling the workgroup limit answers every word in range: a `[[threadgroup(0)]]` +/// region of the limit's bytes, and a static arena two words short of it, every word stored and +/// loaded back through `from_queries` ([`FILL`]), as a scalar and as a `float4`. +#[test] +fn an_arena_filling_the_limit_answers_every_word_in_range() { + for stem in PROFILES { + let prof = queried(stem); + let words = prof.fields().limits.max_compute_shared_memory_size / 4; + for (n, region) in [(words, true), (words - 2, false)] { + let entry = if region { "tg_region" } else { "tg_static" }; + let what = format!("{entry} of {n} words on {stem}"); + let Some(bc) = assemble(entry, &fill_kernel(n, region)) else { + return; + }; + let a = compile(&bc, entry, &prof).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let s = shape(&a.module.words); + assert_eq!(s.float_arrays, vec![Some(32)], "{what}: {s:?}"); + if !region { + assert_eq!(s.lengths, vec![n], "{what}: {s:?}"); + } + let (plan, m) = typed_module(&bc, entry, &prof).expect("module"); + let length = [(SpecKey::TgLength(0), u64::from(4 * n))]; + let spec: &[(SpecKey, u64)] = if region { &length } else { &[] }; + let want: Vec = (0..n) + .map(|k| n - 1 - k) + .chain((0..n / 4).map(|j| 16 * j + 6)) + .collect(); + let got = run_both(&m, &resources_of(&plan, spec, want.len())); + let first = got.iter().zip(&want).position(|(got, want)| got != want); + assert_eq!(first, None, "{what}: the first word that differs"); + } + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 085cb3c45..5527dda19 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -197,6 +197,7 @@ mod engine_texture_tail; mod engine_texture_ulong; mod engine_texture_unit_bit_test; mod engine_texture_unk; +mod engine_threadgroup_floats; mod engine_tile; mod engine_tiny_products; mod engine_typed_clamp; diff --git a/docs/API.md b/docs/API.md index 9d8717199..3005746ec 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1052,6 +1052,20 @@ through buffer arguments it reads at any index. stitched library itself. A module whose linkage signature has no reading (a linked-constants signature on a module that still declares function constants) refuses the pipeline at a call that survives specialization, `Unsupported` with `Feature::Linking`. +- **Threadgroup memory.** On `Device::from_queries`' profile no threadgroup memory access is + contained: a load or store, atomic, memory intrinsic, pointer cell or imageblock access of a + threadgroup arena, and a typed threadgroup object's index, run as the program states them, and + one past the memory is undefined, as in Metal. A kernel whose every threadgroup access is a + whole, aligned `float` (a scalar or a vector of two to four), with no atomic, memory intrinsic, + imageblock or pointer kept in it, and whose SIMD groups are not emulated, holds its threadgroup + memory as a `Workgroup` array of `float`: each access is one typed load or store a lane, with no + branch and no bitcast, at the word `offset / 4` and the words after it. The array is the + memory's own words (the static part and the specialized `[[threadgroup(n)]]` lengths), at least + four: the memory Metal allocates, so its threadgroup memory is Metal's static length and lengths, + and a length filling the limit runs. The strategy census names its accesses + `access.threadgroup.load.floats` and `access.threadgroup.store.floats`. Every other kernel, and + every kernel on `Device::new`'s profile, holds `u32` words; on `Device::new`'s profile each + access is contained, a load past the memory reading 0 and its store dropped. - **Binary functions, required threadgroup sizes, buffer mutability.** Whether a binary function was compiled to a binary (`LinkedFunction::precompiled`), required threadgroup sizes and buffer mutability change no translation and are in no compile key; the runtime checks them as Metal