diff --git a/crates/metal2vulkan-conformance/probes/linked_function_specialized_name.m b/crates/metal2vulkan-conformance/probes/linked_function_specialized_name.m index c754fddd4..c7c9502d4 100644 --- a/crates/metal2vulkan-conformance/probes/linked_function_specialized_name.m +++ b/crates/metal2vulkan-conformance/probes/linked_function_specialized_name.m @@ -1,21 +1,60 @@ // Which name a visible-function reference resolves against when the pipeline links a function made -// by `newFunctionWithDescriptor:` with a `specializedName`: the function's own name, or the -// specialized one. +// by `newFunctionWithDescriptor:` with a `specializedName` (the function's own name, or the +// specialized one), and what a linked function does with a function constant of its module that +// it was given no value for, by the way it was made. // -// Measured on an Apple M3 Max under macOS 27.0.1, `MTL_DEBUG_LAYER` out of the environment, one -// case a process. +// Measured on an Apple M3 Max under macOS 27.0.1 (26A434), `MTL_DEBUG_LAYER` out of the +// environment, one case a process; the compile layer's `tests::engine_specialized_name` and the +// runtime lane's `runtime_lane::linked_functions` hold the answers. // // Build (no cargo target needed): // clang -fobjc-arc -O1 -fmodules -o linked_function_specialized_name \ // linked_function_specialized_name.m -framework Foundation -framework Metal // -// Kernel `k` calls the visible function `custom_fn`, which its library declares and does not -// define; the second library defines the visible function `base_fn`, which returns its argument -// times the function constant `scale` (index 0) plus 1. Cases: `specialized` (`base_fn` made with -// `specializedName` `custom_fn` and `scale` 3), `plain` (`base_fn` by name), `both` (the -// specialized function and the plain one, linked together), `other` (`specializedName` -// `another_fn`). Each prints the linked function's `name`, the pipeline's creation or its error, -// and the word the kernel stores (the call with 5). +// The caller library declares the visible functions `custom_fn`, `base_fn`, `guarded_fn` and +// `plain_fn` and defines none; kernel `k` stores `custom_fn(5)`, and `kb`, `kg` and `kp` store +// `base_fn(5)`, `guarded_fn(5)` and `plain_fn(5)`. The callee library declares the float function +// constant `scale` (index 0) and the program-scope `twice = scale * 2`, which its compiler computes +// in the static initializer, and defines `base_fn(x) = x * scale + 1`, `derived_fn(x) = x * twice`, +// `guarded_fn(x) = is_function_constant_defined(scale) ? x * scale : x - 1` and +// `plain_fn(x) = x + 2`. Each case prints the linked functions' `name`, the pipeline's creation or +// its error, and the word the kernel stores (the buffer is filled with 0xAB first, which reads as +// the float -1.21979e-12). +// +// WHAT IT MEASURED. Through `k`, each function made by `newFunctionWithDescriptor:` with +// `specializedName` `custom_fn` unless the case says otherwise: +// +// specialized base_fn, scale 3 name custom_fn; ran, stored 16 +// plain base_fn, scale 3, no name given name base_fn; failed: "unresolved visible +// function reference: custom_fn" +// both specialized and plain together names custom_fn, base_fn; ran, stored 16 +// other base_fn, scale 3, `another_fn` name another_fn; failed as plain +// unvalued base_fn, constantValues nil ran, stored nothing (the fill) +// unvalued-empty base_fn, empty values ran, stored nothing (the fill) +// guarded guarded_fn, constantValues nil ran, stored 4 +// guarded-empty guarded_fn, empty values ran, stored 4 +// guarded-valued guarded_fn, scale 3 ran, stored 15 +// derived derived_fn, scale 3 ran, stored 30 +// derived-empty derived_fn, empty values ran, stored nothing (the fill) +// constant-free plain_fn, constantValues nil ran, stored 7 +// +// Through `kb`, `kg` and `kp`, each function linked under its own name: +// +// byname base_fn, newFunctionWithName: failed: "cannot lower module with +// unresolved function constants" +// byname-empty base_fn, ...constantValues: empty ran, stored nothing (the fill) +// byname-valued base_fn, ...constantValues: 3 ran, stored 16 +// descriptor-nil base_fn, descriptor, values nil ran, stored nothing (the fill) +// descriptor-empty base_fn, descriptor, empty values ran, stored nothing (the fill) +// guarded-byname guarded_fn, newFunctionWithName: failed as byname +// constant-free-byname plain_fn, newFunctionWithName: ran, stored 7 +// +// So a reference resolves by the linked function's `name`, its specialized name where it has one, +// and the function's body is its own name's. A function made specialized +// (`newFunctionWithName:constantValues:` or `newFunctionWithDescriptor:`, with values or without) +// reads a constant it has no value for as undefined (a store of such a value did not land) and +// `is_function_constant_defined` false; one made by `newFunctionWithName:` fails the pipeline where +// it reaches a constant, guarded or not, and links where it reaches none. #import #import #include diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 94d55738b..38bdceb76 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -89,6 +89,16 @@ command_buffer.wait_until_completed()?; Creating a pipeline state translates its functions, each under the 20-second translation budget. A function the device cannot run exactly is refused there, typed, naming what is missing. +A `[[visible]]` function a stage calls but does not define comes from the functions it links: +`Function::linked_function` of each, in the stage's `LinkedFunctions` +(`function.function_descriptor().with_linked(linked)`, `MTLLinkedFunctions`). A call resolves to +the linked function of its name, `Function::name`: the specialized name +`Library::new_function_with_descriptor` made it with (`FunctionDescriptor::specialized_name`, +Metal's `specializedName`), else its own. A linked function computes with the constant values it +was made with, and a constant it was given no value for reads as undefined, as Metal's does; one +made by `new_function_with_name` that reaches a constant of its module refuses the pipeline state +(`Compile`, `LinkProblem::UnresolvedConstant`), as Metal fails its creation. + Creating a render pipeline state also makes the `VkPipeline` its first draw is predicted to take, before it returns, where Metal compiles. The prediction comes from the descriptor and the device alone: the pass of its attachments, its input primitive class, each vertex-descriptor layout's diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline.rs b/crates/metal2vulkan-runtime/src/tests/pipeline.rs index 4e79de4ff..7936bdda6 100644 --- a/crates/metal2vulkan-runtime/src/tests/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/tests/pipeline.rs @@ -1,5 +1,5 @@ //! The checks a compute pipeline state's descriptor passes before its compile -//! (`pipeline::duplicate_linked_name`), the imageblock length it answers +//! (`pipeline::duplicate_linked_name`, by the name each linked function links under), the imageblock length it answers //! (`pipeline::imageblock_memory_length`), the specialization values a failed draw's //! pipeline names (`pipeline::specialization_values`), and which form of a key a driver's facts //! choose (`pipeline::views_read_at_bind`). @@ -89,6 +89,34 @@ fn a_name_the_numbered_lists_repeat_is_found() { ); } +/// The name a list repeats is the one each function links under, its specialized name where it +/// has one: one library function linked under a specialized name and under its own is no repeat, +/// as plain Metal links both (`linked_function_specialized_name.m`'s `both`, an M3 Max under macOS +/// 27.0.1), and two functions under one specialized name are. +#[test] +fn a_repeated_name_is_the_name_a_function_links_under() { + let (first, second) = (linked("ob3_stage_input"), linked("ob3_index_buffer")); + let both = LinkedFunctions::new() + .with_function(first.clone().with_specialized_name("custom_fn")) + .with_function(first.clone()); + assert_eq!(duplicate_linked_name(&both), None); + let one_name = LinkedFunctions::new() + .with_function(first.clone().with_specialized_name("custom_fn")) + .with_function(second.with_specialized_name("custom_fn")); + assert_eq!( + duplicate_linked_name(&one_name), + Some("custom_fn".to_owned()) + ); + // Under its own name as a specialized name, a function's name is its own. + let own = LinkedFunctions::new() + .with_function(first.clone().with_specialized_name("ob3_stage_input")) + .with_function(first); + assert_eq!( + duplicate_linked_name(&own), + Some("ob3_stage_input".to_owned()) + ); +} + /// `imageblockMemoryLengthForDimensions:` rounds each side up to a power of two and ignores the /// depth, as Metal does on an M3 and an M4 (probe 6), and is none without an imageblock or a side. /// A cell rounds up to 8 bytes, as an M4's does (an M3's to 4), and the answer is raised to the diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index d2b618452..999d099ed 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -567,6 +567,8 @@ mod level_writes_by_usage; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod linear_attachments; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod linked_functions; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod logic_ops; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod made_at_creation; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/linked_functions.rs b/crates/metal2vulkan-validation/src/runtime_lane/linked_functions.rs new file mode 100644 index 000000000..0d3a5a91f --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/linked_functions.rs @@ -0,0 +1,233 @@ +//! Linked functions under a specialized name, and linked modules that declare function constants, +//! through the runtime on the device the cfg selects, under the validation layer, against what the +//! probe `linked_function_specialized_name.m` (the conformance crate's `probes/`) measured on an +//! Apple M3 Max under macOS 27.0.1. +//! +//! The libraries are the owned fixtures `linked_specialized_caller` (kernels calling `custom_fn`, +//! which no library defines, and `base_fn`, `guarded_fn` and `plain_fn` by their own names) and +//! `linked_specialized_functions` (those visible functions, in a module that declares the float +//! constant `scale` at index 0: `base_fn(x) = x * scale + 1`, `derived_fn(x) = x * twice` with +//! `twice = scale * 2` computed in the static initializer, `guarded_fn(x) = +//! is_function_constant_defined(scale) ? x * scale : x - 1`, `plain_fn(x) = x + 2`), the probe's +//! callee. Each kernel stores its callee's value at `tid + 5` to word `tid`, so word 0 is the +//! probe's word. + +use super::host_memory::{on_device, run}; +use super::read_buffer; +use crate::air_library::AirLibrary; +use metal2vulkan::error::RuntimeInput; +use metal2vulkan::error::{DescriptorError, DiagName, Error as CompileError, LinkProblem}; +use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; +use metal2vulkan::metal::DataType; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, LinkedFunctions, StageSource}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + ComputePipelineState, Device, Error, Function, FunctionDescriptor, Library, PipelineOptions, + ResourceOptions, Size, +}; + +/// Threads of each dispatch. +const N: u32 = 8; + +/// The caller's library and the functions' library. +fn libraries(device: &Device) -> (Library, Library) { + let fixture = |stem: &str| llvm_assemble(&engine_dir().join(format!("{stem}.ll"))).unwrap(); + ( + device + .new_library_with_air(&fixture("linked_specialized_caller")) + .unwrap(), + device + .new_library_with_air(&fixture("linked_specialized_functions")) + .unwrap(), + ) +} + +/// `scale` set to `v`. +fn scale(v: f32) -> FunctionConstantValues { + FunctionConstantValues::defaults().with_index( + 0, + FunctionConstantValue::new(DataType::Float, v.to_le_bytes()), + ) +} + +/// `newFunctionWithDescriptor:` of `name` with the specialized name and constant values given. +fn made( + library: &Library, + name: &str, + specialized: Option<&str>, + values: Option, +) -> Function { + let mut d = FunctionDescriptor::new(name); + d.specialized_name = specialized.map(str::to_owned); + d.constant_values = values; + library.new_function_with_descriptor(&d).unwrap() +} + +/// The state of `kernel` of `caller` linking `functions` in `MTLLinkedFunctions.functions`. +fn state( + caller: &Library, + kernel: &str, + functions: &[&Function], +) -> Result { + let linked = functions.iter().fold(LinkedFunctions::new(), |l, f| { + l.with_function(f.linked_function()) + }); + let kernel = caller.new_function_with_name(kernel).unwrap(); + caller.device().new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function( + kernel.function_descriptor().with_linked(linked), + )), + &PipelineOptions::default(), + ) +} + +/// The words `state` stores over `N` threads. +fn words(device: &Device, state: &ComputePipelineState) -> Vec { + let out = device + .new_buffer(u64::from(N) * 4, ResourceOptions::shared()) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&out), 0, 0).unwrap(); + encoder + .dispatch_threads(Size::new(N.into(), 1, 1), Size::new(N.into(), 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + read_buffer(&out, 0, out.length()) + .unwrap() + .as_chunks::<4>() + .0 + .iter() + .map(|w| f32::from_le_bytes(*w)) + .collect() +} + +/// `f(t + 5)` for each thread `t`. +fn expected(f: impl Fn(f32) -> f32) -> Vec { + (0..N).map(|t| f(t as f32 + 5.0)).collect() +} + +fn needs(symbol: &str) -> Error { + Error::Compile(CompileError::NeedsInput(RuntimeInput::LinkedFunction { + symbol: DiagName::new(symbol), + })) +} + +/// A function made with the specialized name `custom_fn` answers it and resolves the kernel's +/// `custom_fn`, storing the probe's 16 at word 0; made without one or with another it resolves +/// nothing, and the state needs `custom_fn`; linked beside a plain one it stores 16 as well. The +/// probe's `specialized`, `plain`, `other` and `both`. +#[test] +fn a_function_made_with_a_specialized_name_links_under_it() { + on_device(|device| { + let (caller, functions) = libraries(device); + let specialized = made(&functions, "base_fn", Some("custom_fn"), Some(scale(3.0))); + let plain = made(&functions, "base_fn", None, Some(scale(3.0))); + let other = made(&functions, "base_fn", Some("another_fn"), Some(scale(3.0))); + assert_eq!( + [specialized.name(), plain.name(), other.name()], + ["custom_fn", "base_fn", "another_fn"] + ); + let kernel = "linked_specialized_caller"; + let one = state(&caller, kernel, &[&specialized]).unwrap(); + let got = words(device, &one); + assert_eq!(got[0], 16.0); + assert_eq!(got, expected(|x| x * 3.0 + 1.0)); + assert_eq!( + state(&caller, kernel, &[&plain]).map(|_| ()), + Err(needs("custom_fn")) + ); + assert_eq!( + state(&caller, kernel, &[&other]).map(|_| ()), + Err(needs("custom_fn")) + ); + let both = state(&caller, kernel, &[&specialized, &plain]).unwrap(); + assert_eq!(words(device, &both)[0], 16.0); + }); +} + +/// A linked function computes with its own constant values, its module's static initializer +/// run over them, and reads one it was given no value for as undefined; made by +/// `newFunctionWithName:`, it refuses the state where it reaches a constant, guarded or not, and +/// links where it reaches none. The probe's `derived` (30), `guarded-valued` (15), `guarded` (4), +/// `constant-free` (7), `byname-valued` (16), `byname`, `guarded-byname`, `byname-empty`, +/// `descriptor-nil` and `constant-free-byname` (7). Metal's undefined read stored nothing; the +/// runtime's reads zero, so `base_fn` without a value stores 1. +#[test] +fn a_linked_function_s_constants_answer_as_metal_s_do() { + on_device(|device| { + let (caller, functions) = libraries(device); + let custom = |name: &str, values| made(&functions, name, Some("custom_fn"), values); + let custom_words = |f: &Function| { + words( + device, + &state(&caller, "linked_specialized_caller", &[f]).unwrap(), + ) + }; + assert_eq!( + custom_words(&custom("derived_fn", Some(scale(3.0)))), + expected(|x| x * 6.0) + ); + assert_eq!( + custom_words(&custom("guarded_fn", Some(scale(3.0)))), + expected(|x| x * 3.0) + ); + assert_eq!( + custom_words(&custom("guarded_fn", None)), + expected(|x| x - 1.0) + ); + assert_eq!( + custom_words(&custom("plain_fn", None)), + expected(|x| x + 2.0) + ); + assert_eq!(custom_words(&custom("base_fn", None)), expected(|_| 1.0)); + + let by_name = |name: &str| functions.new_function_with_name(name).unwrap(); + let unresolved = |name: &str| { + Err(Error::Compile(CompileError::InvalidDescriptor( + DescriptorError::LinkedFunction { + name: DiagName::new(name), + problem: LinkProblem::UnresolvedConstant { index: 0 }, + }, + ))) + }; + let base = "linked_specialized_base"; + assert_eq!( + state(&caller, base, &[&by_name("base_fn")]).map(|_| ()), + unresolved("base_fn") + ); + assert_eq!( + state( + &caller, + "linked_specialized_guarded", + &[&by_name("guarded_fn")] + ) + .map(|_| ()), + unresolved("guarded_fn") + ); + let free = state(&caller, "linked_specialized_free", &[&by_name("plain_fn")]).unwrap(); + assert_eq!(words(device, &free)[0], 7.0); + let valued = functions + .new_function_with_name_constant_values("base_fn", &scale(3.0)) + .unwrap(); + assert_eq!( + words(device, &state(&caller, base, &[&valued]).unwrap())[0], + 16.0 + ); + let empty = functions + .new_function_with_name_constant_values("base_fn", &FunctionConstantValues::defaults()) + .unwrap(); + assert_eq!( + words(device, &state(&caller, base, &[&empty]).unwrap()), + expected(|_| 1.0) + ); + let descriptor = made(&functions, "base_fn", None, None); + assert_eq!( + words(device, &state(&caller, base, &[&descriptor]).unwrap()), + expected(|_| 1.0) + ); + }); +} diff --git a/docs/API.md b/docs/API.md index ffd8f95ce..d58c1d763 100644 --- a/docs/API.md +++ b/docs/API.md @@ -496,6 +496,20 @@ layout stride of `None` is `MTLBufferLayoutStrideDynamic`: the stride comes from - **Visible functions and recursion.** Linked visible functions, function tables and intersection function tables compile; recursion through visible functions runs on a stack of frames sized by `max_call_stack_depth`. A call that finds the stack full returns zero. +- **Linked functions: names and constants.** A visible-function reference resolves to the linked + function whose `LinkedFunction::name` it names: its specialized name where it was made with one + (`with_specialized_name`, Metal's `MTLFunctionDescriptor.specializedName`), else its library + function's own; its body is still that library function's. A linked function whose module + declares function constants is specialized with its own values before it is linked, its + module's static initializer run over them. A function made specialized + (`LinkedFunction::specialized`: with constant values, or by `newFunctionWithDescriptor:` with or + without them) reads a constant it was given no value for as an entry's undefined constants read + (section 10, "Function constants"). One made unspecialized (`newFunctionWithName:`) that reaches + one of its module's constants refuses the pipeline at a call that survives specialization, + `DescriptorError::LinkedFunction` with `LinkProblem::UnresolvedConstant { index }`, guarded by + `is_function_constant_defined` or not, as Metal fails the creation ("cannot lower module with + unresolved function constants"); one that reaches none links. The specialized name and the + specialization are part of the compile key. - **Binary functions, required threadgroup sizes, buffer mutability.** These descriptor fields change no translation and are in no compile key; the runtime checks them as Metal does. - **Dynamic libraries.** `DynamicLibrary::new(library, &budget)` checks a dynamic metallib as @@ -3685,6 +3699,10 @@ each item named states the rule in full. it and an argument gated on it, negated or not, is absent. Metal makes the same pipeline, and its reads of the constant vary from read to read: on an M3 Max under macOS 27.0.1 it read `u + 3` as 0, `u * 7 + 1` as 1, `u == 0 ? 111 : 222` as 222 and `b ? 5 : 6` as 5. +- **A linked function's constant without a value reads as zero too**, where the function was made + specialized (section 3, "Linked functions: names and constants"). Metal makes that pipeline, + and its read is undefined: a kernel storing `x * scale + 1` of such a function stored nothing on + an M3 Max under macOS 27.0.1. **Kernels**