diff --git a/crates/metal2vulkan-devtools/src/vector_word_phases.rs b/crates/metal2vulkan-devtools/src/vector_word_phases.rs index 9b8fadf7a..8baefebb2 100644 --- a/crates/metal2vulkan-devtools/src/vector_word_phases.rs +++ b/crates/metal2vulkan-devtools/src/vector_word_phases.rs @@ -1,17 +1,17 @@ //! The owned fixture `vector_word_phases`: `uint4` and `float4` accesses at each word phase past a //! 4-aligned bound base, and through a 16-aligned `float4` buffer ([`WORDS`], [`VEC16`]; the //! fixture's source says what each thread does). Its inputs ([`inputs`]), the bind offsets a run -//! takes ([`OFFSETS`], [`vec16_offsets`]), and the four buffers' bytes afterwards where every -//! access lands at its own address ([`answer`]), which is where Metal places it: the -//! conformance crate's `vector-word-phases-*` cases record Metal's answer on an Apple M3 Max and -//! hold it equal to [`answer`], the product's CPU-interpreter test and the runtime's device -//! test hold theirs equal to it too. +//! takes ([`OFFSETS`], [`vec16_offsets`], [`VEC16_AT_WORDS`]), and the four buffers' bytes +//! afterwards where every access lands at its own address ([`answer`], [`answer_at`]), which is +//! where Metal places it: the conformance crate's `vector-word-phases-*` cases record Metal's +//! answer on an Apple M3 Max and hold it equal to [`answer_at`], the product's CPU-interpreter +//! test and the runtime's device test hold theirs equal to it too. /// The fixture. pub const FIXTURE: &str = "vector_word_phases"; /// The kernel over two `uint` buffers bound at a multiple of 4. pub const WORDS: &str = "vwp_words"; -/// The kernel over two `float4` buffers bound at a multiple of 16. +/// The kernel over two `float4` buffers bound at a multiple of 16, or of 4 ([`VEC16_AT_WORDS`]). pub const VEC16: &str = "vwp_vec16"; /// Threads of each kernel's grid, in one threadgroup. pub const THREADS: u32 = 64; @@ -30,11 +30,18 @@ const SIGN: u32 = 0x8000_0000; const NOT_EXPONENT: u32 = 0x807f_ffff; /// The bind offsets of [`VEC16`]'s `a` and `b` in the run that binds [`WORDS`]'s at `offset`: -/// multiples of 16, as Metal binds a `float4` buffer, that differ from run to run. +/// multiples of 16, as Metal's API validation asks of a `float4` buffer, that differ from run to +/// run. pub fn vec16_offsets(offset: u64) -> (u64, u64) { (16 + 4 * offset, 64 - 4 * offset) } +/// Bind offsets of [`VEC16`]'s `a` and `b` 4 and 8 bytes past a multiple of 16: its `float4` +/// arguments (alignment 16) at multiples of 4 only. Metal's API validation refuses such a bind +/// ("must be a multiple of 16"); plain Metal runs it with every access at its own address, an +/// Apple M3 Max under macOS 27.0.1 (the conformance crate's `probes/misaligned_buffer_binds.m`). +pub const VEC16_AT_WORDS: (u64, u64) = (4, 8); + /// The four buffers' bytes: the inputs before a run, or what a run leaves. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Buffers { @@ -75,6 +82,11 @@ pub fn inputs() -> Buffers { /// `offset`, then [`VEC16`] with `a` and `b` bound at [`vec16_offsets`] of it, from [`inputs`], /// every access at its own address. pub fn answer(offset: u64) -> Buffers { + answer_at(offset, vec16_offsets(offset)) +} + +/// [`answer`] with [`VEC16`]'s `a` and `b` bound at `vec16`'s offsets, multiples of 4. +pub fn answer_at(offset: u64, vec16: (u64, u64)) -> Buffers { let mut out = inputs(); let base = usize::try_from(offset / 4).expect("an offset in a usize"); let src = words(&out.src); @@ -92,7 +104,7 @@ pub fn answer(offset: u64) -> Buffers { } } out.dst = bytes(&dst); - let (a_at, b_at) = vec16_offsets(offset); + let (a_at, b_at) = vec16; let (a_at, b_at) = ( usize::try_from(a_at / 4).expect("an offset in a usize"), usize::try_from(b_at / 4).expect("an offset in a usize"), diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index 173016d02..88168a4a4 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -666,7 +666,8 @@ pub fn select( } } else if through_root { // A wide pointer reaches every candidate through its root entry's device address, so a - // typed atomic needs no slot moved. + // typed atomic needs no slot moved; a 64-bit one may reach any slot's memory. + cx.families.access.wide_atomics64 |= wide; memory_model::note_device_scope(cx); AtomicMem::Wide { ptr: super::dynamic::plan_deref(cx, r.ptr)?, @@ -683,8 +684,8 @@ pub fn select( let slot = plan.slot; cx.push.insert(PushField::SlotBindOffset(slot)); super::note_variable(cx, slot, fixed, false); - // An atomic reaches its word. - super::note_reach(cx, t.slot, 4); + // An atomic reaches its word, a 64-bit one its two words at a multiple of 8. + super::note_reach(cx, t.slot, if wide { 8 } else { 4 }); if wide { // A typed atomic's slot is reached by device address (`finish_slots`). cx.families.access.typed_slots.insert(t.slot); diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index 445d3e74b..fb6e8c823 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -308,18 +308,18 @@ pub(super) fn prepare( let lowering = cx.plan.families.access.slots.get(t.slot).copied().flatten(); let ops = WordOps::of(crate::lower::sync::memory_model::coherence(cx.plan)); if let Some(SlotLowering::Psb { start }) = lowering { - // Under the identity domains a slot whose address the binder holds to its argument's - // alignment is reached from that address as it is (its biased word), a leaf at an offset - // proven a multiple of 8 or 16 accessed at that alignment; any other from the word below - // each access. - let aligned = cx.plan.families.access.aligned.contains(&t.slot); + // Under the identity domains a slot whose address the binder holds to an alignment is + // reached from that address as it is (its biased word), a leaf at an offset proven a + // multiple of 8 or 16 accessed at that alignment up to the address's; any other from the + // word below each access. + let aligned = cx.plan.families.access.aligned.get(&t.slot).copied(); let a = if cx.plan.families.access.identity { match aligned { - true => { + Some(held) => { let base = super::pointer::biased_slot_address(cx, fb, choice.slot)?; - psb::prepare_direct(base, m) + psb::prepare_direct(base, m, held) } - false => { + None => { let address = super::pointer::slot_address(cx, fb, choice.slot)?; psb::prepare_at(fb, address, m)? } diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index f9145daae..b6d00a329 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -753,20 +753,25 @@ pub struct AccessPlan { /// (`psb::PsbMem::read_only`), so the device may read them as read-only memory (on RADV a /// uniform read is a scalar load). pub unwritten: BTreeSet, - /// Memory-plan slots reached under the identity domains from their address as it is, which - /// the binder holds to a multiple of their argument's alignment ([`address_alignment`], - /// `RuntimeFact::AddressAlignment`), at least the granularity their accesses reach - /// ([`AccessPlan::reach`]): no access rounds the address (`psb::prepare_direct`), and a leaf - /// at an offset proven a multiple of 8 or 16 is accessed at that alignment (`memory::leaf`'s - /// whole words). Every other device-address slot is reached from the word below each access + /// Memory-plan slots reached under the identity domains from their address as it is, each + /// with the alignment the binder holds that address to ([`address_alignment`], + /// `RuntimeFact::AddressAlignment`): their argument's, or 4 (8 where a 64-bit atomic may reach + /// it) for a slot of `LoweringInputs::word_bound_buffers`, at least the granularity their + /// accesses reach ([`AccessPlan::reach`]). No access rounds the address + /// (`psb::prepare_direct`), and a leaf at an offset proven a multiple of 8 or 16 is accessed + /// at that alignment where the address is held to it (`memory::leaf`'s whole words), else at + /// the address's. Every other device-address slot is reached from the word below each access /// (`psb::prepare_at`). - pub aligned: BTreeSet, + pub aligned: BTreeMap, /// The granularity in bytes at which the static-root accesses of each memory-plan slot reach /// its memory, the widest over them ([`note_reach`]): an access whose leaf is one narrow unit - /// ([`leaf_reach`]) that unit's size, and any other 4, as it reaches words or wider units - /// from a 4-aligned base. A slot whose alignment is below 4 is reached from its address as - /// it is only where its alignment is at least this. + /// ([`leaf_reach`]) that unit's size, a 64-bit atomic 8, and any other 4, as it reaches words + /// or wider units from a 4-aligned base. A slot whose alignment is below 4 is reached from its + /// address as it is only where its alignment is at least this. pub reach: BTreeMap, + /// Some 64-bit atomic goes through a wide pointer ([`atomic`]), which may reach any slot's + /// memory: a slot of `LoweringInputs::word_bound_buffers` is held to 8 ([`AccessPlan::aligned`]). + pub wide_atomics64: bool, /// The units ([`Units`]) the static-root accesses of each slot read or write whole, by /// memory-plan slot index: narrow units whose storage access the profile has, and `uvec2` /// and `uvec4` units. The slot gets a view of each that its final view kind holds @@ -1360,17 +1365,24 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result { addressed_slot(cx, plan.slot); if let Some(align) = address_alignment(cx, plan) { + // A word memory's base is a multiple of 4; a slot each of whose accesses is + // one narrow unit needs only that unit's alignment. + let reach = cx.families.access.reach.get(&i).copied().unwrap_or(4); + // A slot bound at a multiple of 4 below its argument's alignment is held to + // what its accesses need: 4 for words, 8 where a 64-bit atomic may reach it. + let align = match cx.inputs.word_bound_buffers.contains(&plan.slot) { + true if cx.families.access.wide_atomics64 => align.min(8), + true => align.min(reach.max(4)), + false => align, + }; if align >= 2 { cx.facts.insert(RuntimeFact::AddressAlignment { slot: plan.slot, align, }); } - // A word memory's base is a multiple of 4; a slot each of whose accesses is - // one narrow unit needs only that unit's alignment. - let reach = cx.families.access.reach.get(&i).copied().unwrap_or(4); if align >= reach.min(4) { - cx.families.access.aligned.insert(i); + cx.families.access.aligned.insert(i, align); } } BufferForm::Psb @@ -1441,10 +1453,13 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result, plan: &SlotPlan) -> Option { if !identity(cx.profile) || plan.element.is_some() || plan.argument_buffer { return None; diff --git a/crates/metal2vulkan/src/lower/access/psb.rs b/crates/metal2vulkan/src/lower/access/psb.rs index e5d597825..41927edb8 100644 --- a/crates/metal2vulkan/src/lower/access/psb.rs +++ b/crates/metal2vulkan/src/lower/access/psb.rs @@ -38,7 +38,9 @@ //! its first word (`memory::leaf`'s whole words; [`PsbMem`]'s `whole_place`), not one per word: //! from the word below the access, that word; from a slot's own address, the slot's address plus //! the offset, which a leaf proven a multiple of 8 or 16 takes as it is, with that `Aligned` -//! operand, and any other rounds down to a multiple of 4. +//! operand up to the alignment the address is held to (4 for a slot bound at a multiple of 4 +//! below its argument's alignment, `LoweringInputs::word_bound_buffers`), and any other rounds +//! down to a multiple of 4. use super::SLOT_ADDRESS_BIAS; use crate::device::DeviceProfile; @@ -205,8 +207,9 @@ enum Reach { /// `c`'s bytes into the bias: `(x + c) * s + 2^31` is `x * s + (c * s + 2^31)` modulo 2^32. /// The bias is one 32-bit add, which a device fuses with the index's shift; the offset is /// zero-extended, which a device splits into a scalar base and a vector offset; no shift of - /// the offset in 64 bits and no pointer bitcast. - Direct, + /// the offset in 64 bits and no pointer bitcast. It holds the alignment the binder holds the + /// slot's address to (`RuntimeFact::AddressAlignment`). + Direct(u32), } /// Prepare an access of a static slot at the `u32` displacement `m` from its bind offset, read as @@ -234,16 +237,16 @@ pub fn prepare_at(fb: &mut FunctionBuilder<'_>, address: Value, m: Value) -> BRe /// Prepare an access of a static slot at the `u32` displacement `m` from its bind offset, under /// the identity domains, from `base` (a `u64`), the slot's own device address less -/// [`SLOT_ADDRESS_BIAS`], an address the binder holds to a multiple of the argument's alignment +/// [`SLOT_ADDRESS_BIAS`], an address the binder holds to a multiple of `held` /// (`RuntimeFact::AddressAlignment`): the access is the byte offset `m`, read as signed, from that /// address, as a descriptor view's is `m` from its base ([`Reach::Direct`]). Every byte of a /// buffer lies within 2^31 bytes of each bind address in it, the runtime making no buffer longer /// than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the offset is exact whatever the slot's /// window. Nothing is rounded. The check, where the access takes one, is `emit::prepare`'s. -pub fn prepare_direct(base: Value, m: Value) -> PsbAccess { +pub fn prepare_direct(base: Value, m: Value, held: u32) -> PsbAccess { PsbAccess { mem: PsbMem { - reach: Reach::Direct, + reach: Reach::Direct(held), ..PsbMem::at(base) }, off: m, @@ -390,7 +393,7 @@ impl PsbMem { let addr = fb.binary(BinOp::IAdd, self.base, d)?; self.place(fb, addr, ty, load) } - Reach::Direct => { + Reach::Direct(_) => { let shift = bytes.trailing_zeros(); let (x, c) = fb.sum_of(index).unwrap_or((index, 0)); let s = k32(fb, shift)?; @@ -453,14 +456,15 @@ impl PsbMem { /// The `PhysicalStorageBuffer` place of a `pointee` (at most 16 bytes) at byte `at` past the /// word holding byte `off` of the memory, to load from where `load`, and the `Aligned` operand - /// of an access through it: `align` where the memory's base is its Metal address and `off` - /// is proven a multiple of `align`, else 4. + /// of an access through it: `align` up to the alignment the address is held to where the + /// memory's base is its Metal address and `off` is proven a multiple of `align`, else 4. /// /// A memory based at the word below one access ([`Reach::Rounded`], [`Reach::Below`]) holds /// that access's byte offset in the word, below 4: its first word is the base. A slot's own - /// address ([`Reach::Direct`]) is held to its argument's alignment, so a proven multiple of 8 - /// or 16 is the address's own; any other offset is rounded down to a multiple of 4, as the - /// word path reads it. + /// address ([`Reach::Direct`]) is held to its argument's alignment, or to 4 where the dispatch + /// binds it at a multiple of 4 below that (`LoweringInputs::word_bound_buffers`), so a proven + /// multiple of 8 or 16 lies at the address plus that offset, aligned as both are; any other + /// offset is rounded down to a multiple of 4, as the word path reads it. fn whole_place( &self, fb: &mut FunctionBuilder<'_>, @@ -479,9 +483,9 @@ impl PsbMem { }; Ok((self.place(fb, addr, pointee, load)?, 4)) } - Reach::Direct => { + Reach::Direct(held) => { let (off, align) = match align { - 8 | 16 => (off, align), + 8 | 16 => (off, align.min(held)), _ => { let mask = k32(fb, !3)?; (u32_op(fb, BinOp::BitwiseAnd, off, mask)?, 4) diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 94471a949..1b9c1fed4 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -402,6 +402,7 @@ mod serde_round_trips { object_payload: Some(64), region_viewports: true, push_base: 24, + word_bound_buffers: BTreeSet::from([slot(Stage::Kernel, SlotClass::Buffer, 2)]), }); } diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 799e1d473..6e203a5d9 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -467,6 +467,12 @@ pub fn function_key( if inputs.push_base != 0 { h.bytes(b"push-base").u64(u64::from(inputs.push_base)); } + // Appended only when set, as `signed_color_attachments`: a function whose buffers are bound + // at their arguments' alignments keeps its key. + if !inputs.word_bound_buffers.is_empty() { + h.bytes(b"word-bound-buffers") + .bytes(format!("{:?}", inputs.word_bound_buffers).as_bytes()); + } // Appended only when present, so a stage that links nothing keeps its key: the tag's length // prefix keeps the encoding unambiguous. if !linked.is_empty() { diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 94938b252..160ad6277 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -698,7 +698,8 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", object_payload: None", "") .replace(", tessellation: None", "") .replace(", region_viewports: false", "") - .replace(", push_base: 0", ""), + .replace(", push_base: 0", "") + .replace(", word_bound_buffers: {}", ""), "{derived}" ); } diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index aa65734a3..be0a73f28 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -777,6 +777,16 @@ pub struct LoweringInputs { /// 0. #[cfg_attr(feature = "serde", serde(default))] pub push_base: u32, + /// Buffer slots bound where their address is a multiple of 4 and not of their argument's + /// alignment (`air.arg_type_align_size`, 8 or 16), which Metal's API validation refuses and + /// plain Metal runs, each element at its own address (`probes/misaligned_buffer_binds.m` in + /// the conformance crate). Under the identity domains each such device-address slot states + /// `RuntimeFact::AddressAlignment` as its argument's alignment up to what its accesses need, + /// 4, or 8 where a 64-bit atomic may reach it, and its accesses from its address claim no + /// more `Aligned` than that. A slot of alignment 4 or less, or that is no device-address slot + /// held to its alignment, is ignored. + #[cfg_attr(feature = "serde", serde(default))] + pub word_bound_buffers: BTreeSet, } /// One channel of the second output a fragment function writes for an attachment held with its diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index b22f7575a..4b9ae4dab 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -289,12 +289,22 @@ pub fn compile_kept( bitcode: &[u8], entry: &str, p: &DeviceProfile, +) -> Result<(Arc, Plan, TypedModule), Error> { + compile_kept_with(bitcode, entry, p, &LowerInputs::new()) +} + +/// [`compile_kept`] under lowering inputs `inputs`. +pub fn compile_kept_with( + bitcode: &[u8], + entry: &str, + p: &DeviceProfile, + inputs: &LowerInputs, ) -> Result<(Arc, Plan, TypedModule), Error> { compile_bitcode_kept( bitcode, EntryRef::Name(entry), p, - &LowerInputs::new(), + inputs, &mut meter(), SPIRV_WORDS, ) diff --git a/crates/metal2vulkan/src/tests/engine_access_offsets.rs b/crates/metal2vulkan/src/tests/engine_access_offsets.rs index 31d88d116..4314dcc6b 100644 --- a/crates/metal2vulkan/src/tests/engine_access_offsets.rs +++ b/crates/metal2vulkan/src/tests/engine_access_offsets.rs @@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use super::engine_word_phases::identity_profiles; use crate::pipeline::testing::{ - compile, engine_dir, link_and_validate, llvm_assemble, AssembleError, + compile, compile_with, engine_dir, link_and_validate, llvm_assemble, AssembleError, }; use crate::spirv_binary::{parse_bytes, Operand}; use crate::spv::Op; @@ -157,3 +157,96 @@ fn no_access_address_is_scaled_in_64_bits() { } } } + +/// A kernel over a `ulong` buffer `buf` and a `float4` buffer `vec` (argument alignments 8 and +/// 16): a 64-bit `atomic_max` on `buf`'s first word, or, where `wide`, on the word at the address +/// `buf`'s first word holds (a pointer made from an integer, which may reach either buffer), and +/// `vec[t] = -vec[t]`. +fn held_kernel(wide: bool) -> String { + let target = match wide { + true => { + " %w = load i64, ptr addrspace(1) %0, align 8\n %a = inttoptr i64 %w to ptr addrspace(1)\n" + } + false => " %a = getelementptr i8, ptr addrspace(1) %0, i32 0\n", + }; + format!( + "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_v28-apple-macosx26.0.0\"\n\n\ +define void @held(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, i32 noundef %t) {{\n\ +entry:\n\ +{target}\ + %v = zext i32 %t to i64\n\ + call void @air.atomic.global.max.u.i64(ptr addrspace(1) %a, i64 %v, i32 0, i32 2, i1 true)\n\ + %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i32 %t\n\ + %x = load <4 x float>, ptr addrspace(1) %p, align 16\n\ + %y = fneg <4 x float> %x\n\ + store <4 x float> %y, ptr addrspace(1) %p, align 16\n\ + ret void\n\ +}}\n\n\ +declare void @air.atomic.global.max.u.i64(ptr addrspace(1), i64, i32, i32, i1)\n\n\ +!air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ +!9 = !{{ptr @held, !10, !11}}\n!10 = !{{}}\n!11 = !{{!12, !13, !14}}\n\ +!12 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"ulong\", !\"air.arg_name\", !\"buf\"}}\n\ +!13 = !{{i32 1, !\"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\", !\"vec\"}}\n\ +!14 = !{{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"t\"}}\n\ +!17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" + ) +} + +/// The alignment each buffer slot states its address is held to (`RuntimeFact::AddressAlignment`) +/// is its argument's, 8 and 16, and stays so for a slot bound at its alignment. Under +/// `LoweringInputs::word_bound_buffers`, both slots bound at a multiple of 4 below their +/// alignment, it is what the slot's accesses need: the `float4` buffer's 4, which plain Metal +/// runs bound at any multiple of 4, and the `ulong` buffer's 8, where a 64-bit atomic reaches it, +/// as Vulkan's 64-bit atomic needs its natural alignment. Where the atomic goes through a pointer +/// made from an integer, which may reach any buffer, both state 8. Each module passes L3. +#[test] +fn a_word_bound_slot_is_held_to_what_its_accesses_need() { + use crate::lower::select::LowerInputs; + use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; + let mut bound = LowerInputs::new(); + bound.word_bound_buffers = (0..2) + .map(|index| SlotRef { + stage: Stage::Kernel, + class: SlotClass::Buffer, + index, + }) + .collect(); + let plain = LowerInputs::new(); + for (wide, inputs, want) in [ + (false, &plain, [(0, 8), (1, 16)]), + (true, &plain, [(0, 8), (1, 16)]), + (false, &bound, [(0, 8), (1, 4)]), + (true, &bound, [(0, 8), (1, 8)]), + ] { + let Some(bc) = assemble_text("held", &held_kernel(wide)) else { + return; + }; + let bound = !inputs.word_bound_buffers.is_empty(); + let mut compiled = 0; + for (stem, p) in &identity_profiles() { + let what = format!("held (wide {wide}, word-bound {bound}) on {stem}"); + let a = match compile_with(&bc, "held", p, inputs) { + Ok(a) => a, + // A profile without 64-bit buffer atomics refuses the kernel. + Err(e) if e.to_string().contains("Int64") => continue, + Err(e) => panic!("{what}: {e}"), + }; + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let stated: Vec<(u32, u32)> = (a.facts.iter()) + .filter_map(|f| match f { + crate::pipeline::facts::RuntimeFact::AddressAlignment { slot, align } => { + Some((slot.index, *align)) + } + _ => None, + }) + .collect(); + assert_eq!(stated, want, "{what}: stated alignments"); + compiled += 1; + } + assert!( + compiled > 0, + "held (wide {wide}, word-bound {bound}): no profile compiled it" + ); + } +} diff --git a/crates/metal2vulkan/src/tests/engine_word_phases.rs b/crates/metal2vulkan/src/tests/engine_word_phases.rs index c7e5c9708..c8adbbe84 100644 --- a/crates/metal2vulkan/src/tests/engine_word_phases.rs +++ b/crates/metal2vulkan/src/tests/engine_word_phases.rs @@ -11,6 +11,11 @@ //! its `Aligned` operand does not divide, both kernels answer Metal's words with `vwp_words`'s //! buffers bound at offsets 0, 4, 8 and 12 (`metal2vulkan_devtools::vector_word_phases`). //! +//! Plain Metal also runs `vwp_vec16`'s `float4` buffers bound at a multiple of 4 that is not one +//! of 16, each element at its own address. The variant a dispatch so bound runs +//! (`LoweringInputs::word_bound_buffers`) claims and states 4 for those buffers, and answers +//! Metal's words on the interpreter there, where the plain module traps. +//! //! `llvm-as` assembles the fixture; without it the tests skip visibly. use std::collections::{BTreeMap, BTreeSet}; @@ -20,19 +25,21 @@ use crate::device::profile::{DeviceProfile, HandleDomain, PointerDomain}; use crate::device::{Device, DevicePolicy}; use crate::library::FunctionConstantValues; use crate::lower::dispatch::region_bytes; +use crate::lower::select::LowerInputs; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::PushField; +use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage}; use crate::pipeline::testing::{ - compile, compile_kept, description, engine_dir, link_and_validate, llvm_assemble, meter, - specialized_entry, AssembleError, + compile, compile_kept_with, compile_with, description, engine_dir, link_and_validate, + llvm_assemble, meter, specialized_entry, AssembleError, }; use crate::spirv::interp::{run, Buffer, Config, Resources}; use crate::spirv::testing::committed_profiles; use crate::spirv_binary::{parse_bytes, Operand}; use crate::spv::{Op, StorageClass}; use metal2vulkan_devtools::vector_word_phases::{ - answer, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, WORDS, + answer, answer_at, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, VEC16_AT_WORDS, + WORDS, }; /// `MemoryAccess`'s `Aligned` bit. @@ -228,7 +235,7 @@ fn vector_accesses_answer_metal_at_every_word_phase() { let (a_at, b_at) = vec16_offsets(offset); let [src, dst] = dispatch( &bc, - WORDS, + (WORDS, &LowerInputs::new()), p, [ (0x1_0000_0000, offset, before.src.clone()), @@ -238,7 +245,7 @@ fn vector_accesses_answer_metal_at_every_word_phase() { .unwrap_or_else(|e| panic!("{what}: {WORDS}: {e}")); let [a, b] = dispatch( &bc, - VEC16, + (VEC16, &LowerInputs::new()), p, [ (0x3_0000_2000, a_at, before.a.clone()), @@ -267,16 +274,108 @@ fn vector_accesses_answer_metal_at_every_word_phase() { } } -/// Kernel `name` run once over [`THREADS`] threads in one threadgroup on the interpreter, its -/// buffer `n` at device address `buffers[n].0` holding `buffers[n].2`, bound at offset -/// `buffers[n].1`: the buffers' bytes afterwards. +/// The inputs of a dispatch that binds both buffers of a kernel at a multiple of 4 below their +/// argument's alignment. +fn word_bound() -> LowerInputs { + let mut inputs = LowerInputs::new(); + inputs.word_bound_buffers = (0..2) + .map(|index| SlotRef { + stage: Stage::Kernel, + class: SlotClass::Buffer, + index, + }) + .collect(); + inputs +} + +/// Under [`word_bound`] inputs `vwp_vec16`'s every device-address load and store claims 4 and +/// both arguments state 4 (`RuntimeFact::AddressAlignment`), where its plain module claims and +/// states 16 ([`device_accesses_claim_at_most_the_proven_alignment`]); `vwp_words`, whose `uint` +/// arguments' alignment is 4 already, compiles to its plain module's words. Each module passes L3. +#[test] +fn a_word_bound_variant_claims_and_states_4() { + let Some(bc) = bitcode() else { + return; + }; + for (stem, p) in &identity_profiles() { + let what = format!("{VEC16} word-bound on {stem}"); + let a = + compile_with(&bc, VEC16, p, &word_bound()).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let claimed = device_alignments(&a.module.words); + assert!( + !claimed.is_empty() && claimed.iter().all(|&c| c == 4), + "{what}: claimed {claimed:?}" + ); + let stated: Vec = (a.facts.iter()) + .filter_map(|f| match f { + RuntimeFact::AddressAlignment { align, .. } => Some(*align), + _ => None, + }) + .collect(); + assert_eq!(stated, [4; 2], "{what}: stated alignments"); + let plain = compile(&bc, WORDS, p).unwrap_or_else(|e| panic!("{WORDS} on {stem}: {e}")); + let bound = (compile_with(&bc, WORDS, p, &word_bound())) + .unwrap_or_else(|e| panic!("{WORDS} word-bound on {stem}: {e}")); + assert_eq!( + plain.module.words, bound.module.words, + "{WORDS} on {stem}: the word-bound module" + ); + } +} + +/// On the CPU interpreter, with `vwp_vec16`'s `float4` buffers bound 4 and 8 bytes past a +/// multiple of 16 ([`VEC16_AT_WORDS`]), every buffer above 4 GiB, the [`word_bound`] variant +/// leaves Metal's words in both buffers, every access at its own address as plain Metal places +/// it, and no access traps on its `Aligned` operand. The plain module, which claims the 16 its +/// offsets are proven to be from the buffer's address, traps there. +#[test] +fn vec16_answers_metal_bound_at_a_multiple_of_4() { + let Some(bc) = bitcode() else { + return; + }; + let before = inputs(); + let (a_at, b_at) = VEC16_AT_WORDS; + let want = answer_at(0, VEC16_AT_WORDS); + let buffers = || { + [ + (0x3_0000_2000, a_at, before.a.clone()), + (0x4_0000_3000, b_at, before.b.clone()), + ] + }; + for (stem, p) in identity_profiles() + .iter() + .filter(|(s, _)| s == "lavapipe" || s == "moltenvk-m3") + { + let what = format!("{stem}: {VEC16} at {a_at} and {b_at}"); + let plain = dispatch(&bc, (VEC16, &LowerInputs::new()), p, buffers()); + assert!(plain.is_err(), "{what}: the plain module ran"); + let [a, b] = dispatch(&bc, (VEC16, &word_bound()), p, buffers()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + for (buffer, got, want) in [("a", &a, &want.a), ("b", &b, &want.b)] { + let words = |b: &[u8]| b.as_chunks::<4>().0.to_vec(); + let first = words(got) + .iter() + .zip(&words(want)) + .position(|(x, y)| x != y); + assert!( + got.len() == want.len() && first.is_none(), + "{what}: {buffer} differs from Metal's words first at word {first:?}" + ); + } + } +} + +/// Kernel `name` under `inputs` run once over [`THREADS`] threads in one threadgroup on the +/// interpreter, its buffer `n` at device address `buffers[n].0` holding `buffers[n].2`, bound at +/// offset `buffers[n].1`: the buffers' bytes afterwards. fn dispatch( bc: &[u8], - name: &str, + (name, inputs): (&str, &LowerInputs), p: &DeviceProfile, buffers: [(u64, u64, Vec); 2], ) -> Result<[Vec; 2], String> { - let (a, plan, module) = compile_kept(bc, name, p).map_err(|e| e.to_string())?; + let (a, plan, module) = compile_kept_with(bc, name, p, inputs).map_err(|e| e.to_string())?; assert!(a.interface.descriptors.is_empty(), "{name}: a descriptor"); let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; let region = region_bytes([0; 3], [THREADS, 1, 1], [THREADS, 1, 1]).expect("packs"); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index bfb933454..7cc4f36cd 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2463,6 +2463,7 @@ field metal2vulkan::pipeline::LoweringInputs.unattached_colors pub unattached_co field metal2vulkan::pipeline::LoweringInputs.uniform_varyings pub uniform_varyings: BTreeSet field metal2vulkan::pipeline::LoweringInputs.vertex_fetch pub vertex_fetch: Option field metal2vulkan::pipeline::LoweringInputs.viewport_index_varying pub viewport_index_varying: bool +field metal2vulkan::pipeline::LoweringInputs.word_bound_buffers pub word_bound_buffers: BTreeSet field metal2vulkan::pipeline::LoweringInputs.word_colors pub word_colors: BTreeMap field metal2vulkan::pipeline::LoweringInputs.zeroed_colors pub zeroed_colors: BTreeMap field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_coverage pub alpha_to_coverage: bool