From b2bbc8633974a667be7a6e65b211a966ea50a692 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 1 Nov 2026 16:29:51 -0800 Subject: [PATCH] Answer linked binary functions as plain Metal does Measured on this M3 Max under macOS 27.0.1 (binary_function_linking.m, plain and with MTL_DEBUG_LAYER=1, source libraries and metallibs alike), the runtime now answers what plain Metal answers rather than what its validation layer stops: - One name in `functions` and `binary_functions`, or twice in `binary_functions`, one function or two: made, where the runtime refused `Invalid(DuplicateLinkedFunction)`. `duplicate_linked_name` keeps only a name `functions` repeats, which plain Metal's creation fails ("error: duplicated symbol", code 3). With the previous commit, a call calls the `functions` one and a table holds each. - A function only `binary_functions` holds that a stage calls directly: `Compile(NeedsInput(LinkedFunction))`, as Metal fails with code 3, where the runtime linked it (previous commit). - A function not compiled to a binary in a stage's `binary_functions`: plain Metal fails the creation once the stage links, code 2 ("Internal error during compute pipeline creation", "... tile pipeline creation", an empty description for render and mesh-fragment stages), after a reference it leaves unresolved (code 3 first). The runtime answered `Invalid(BinaryFunctions(NotPrecompiled))` before the compile; it now answers `Error::MetalError` with that problem, the M3 Max's domain and Metal's code and text, right after the compile (`additions::check_precompiled`). Added to a made state's stage: `MetalError` code 1 ("Failed to allocate a new pipeline"). Added to a stage the state lacks: taken, as plain Metal makes it (it was refused). - A mesh pipeline's object or mesh stage linking binary functions ends plain Metal's process ("Binary linked functions are not supported for object and mesh shaders"): `Invalid(BinaryFunctions(ObjectOrMeshStage))`, a new problem, where the runtime made the state. The module docs of `pipeline/additions.rs` record the measurements, the error and README docs follow, REFUSALS.md and the API signatures are regenerated. RUNTIME_VERSION 1713: creation answers change class. Verified on this Mac (MoltenVK, --cfg m2v_gpu, under maclock and memcap): runtime_lane::tests::a_kernel_runs_the_functions_its_descriptor_links and runtime_lane::function_tables::{binary_functions_link_as_plain_metal_links_them, binary_functions_and_required_threads_answer_as_metal_s_do, functions_added_to_a_stage_a_drawing_state_lacks_are_left_out} pass; each asserts an answer the previous runtime gave otherwise. The runtime unit test of `duplicate_linked_name` passes. (Carried to development from steelbrain/reims-graphics-kext 580daa4338.) --- crates/metal2vulkan-runtime/README.md | 8 +- crates/metal2vulkan-runtime/src/error.rs | 23 +- .../src/pipeline/additions.rs | 248 ++++++++++++++---- .../metal2vulkan-runtime/src/pipeline/mod.rs | 83 +++--- .../src/pipeline/render.rs | 13 +- .../src/tests/pipeline.rs | 36 +-- .../src/runtime_lane/function_tables.rs | 233 ++++++++++++++-- .../src/runtime_lane/tests.rs | 65 ++++- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/REFUSALS.md | 14 +- 11 files changed, 565 insertions(+), 161 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 456e1f7e8..444bfe422 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -102,7 +102,13 @@ the linked function of its name, `Function::name`: the 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. A function Metal's +(`Compile`, `LinkProblem::UnresolvedConstant`), as Metal fails its creation. A function in the +stage's `binary_functions` is one a visible-function table calls: no call by name resolves to it +(`Compile`, `NeedsInput(LinkedFunction)`, as Metal's creation fails), and beside a function of its +name in `functions` the call calls that one while a table holds both, each with its handle. A +function there that was not made with `FunctionOptions::COMPILE_TO_BINARY` fails the creation as +plain Metal's does (`MetalError`, code 2), and one added to a made state +(`*_with_additional_binary_functions`) fails that call (`MetalError`, code 1). A function Metal's stitcher made links the same way, privately or not, from the stitched library's bytes (`Device::new_library_with_data`); the runtime makes no stitched library itself (`newLibraryWithStitchedDescriptor:` is not built). diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 21e218bc7..4cdc55b71 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -436,7 +436,8 @@ impl Unproven { /// `NSLocalizedDescription` = `localized_description`, its only key where Metal's holds no /// other (every refusal the runtime answers so: [`Problem::IndirectCommandsDirectArgument`], /// [`Problem::UnrasterizedVertexReturn`], [`Problem::DepthWrittenWithoutAttachment`], -/// [`Problem::UnwrittenFragmentInputs`], [`Problem::RasterSampleCount`]). +/// [`Problem::UnwrittenFragmentInputs`], [`Problem::RasterSampleCount`], and +/// [`Problem::BinaryFunctions`] with [`BinaryFunctionProblem::NotPrecompiled`]). #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MetalError { @@ -781,14 +782,15 @@ pub enum Problem { /// The function's name. name: String, }, - /// `new_compute_pipeline_state`: the kernel's linked `functions`, or its `binary_functions`, - /// list this name twice, or both lists hold it for two different functions. Metal's API - /// validation stops every repeat ("All linked functions must have unique names"); plain - /// Metal's creation fails on a name `functions` repeats and takes one function listed in both - /// lists, as the runtime takes it (measured on an M3 Max and an M4). + /// `new_compute_pipeline_state`: the kernel's linked `functions` list this name twice, one + /// function twice or two functions of the name: plain Metal's creation fails ("error: + /// duplicated symbol: add_one", code 3), and its API validation stops it ("All linked + /// functions must have unique names"). A name `binary_functions` lists twice, or both + /// `functions` and `binary_functions` hold, is made, as plain Metal makes it where its API + /// validation stops it (`pipeline/additions.rs`). /// - /// Basis: metal-measured (an M3 Max and an M4: plain Metal's creation fails on a name the - /// linked functions repeat). + /// Basis: metal-measured (an M3 Max, macOS 27.0.1: plain Metal's creation fails with code 3, + /// `binary_function_linking.m`). DuplicateLinkedFunction { /// The function's name. name: String, @@ -904,8 +906,9 @@ pub enum Problem { /// /// Basis: delegated(RequiredThreadsProblem). RequiredThreads(RequiredThreadsProblem), - /// A pipeline's binary functions that Metal refuses: not precompiled, of another stage, or - /// added to a pipeline created without support for adding them. + /// A pipeline's binary functions that Metal refuses: not precompiled (plain Metal's error, + /// [`Error::MetalError`]), in a mesh pipeline's object or mesh stage, or added to a stage of a + /// state that cannot take them. /// /// Basis: delegated(BinaryFunctionProblem). BinaryFunctions(BinaryFunctionProblem), diff --git a/crates/metal2vulkan-runtime/src/pipeline/additions.rs b/crates/metal2vulkan-runtime/src/pipeline/additions.rs index ee635892f..827583ec5 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/additions.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/additions.rs @@ -11,24 +11,61 @@ //! dispatch, whose threadgroup differs on any axis; without it Metal runs the size given, and //! so does the runtime. An indirect command buffer's dispatch is not checked, and runs the size //! it was encoded with. -//! - **Binary functions.** A function in a stage's `binaryFunctions`, or among the functions added -//! to a made state, must be compiled to a binary (`MTLFunctionOptionCompileToBinary`): API -//! validation stops another, and creation fails without validation. Adding to a stage of a -//! state made without its support flag (`supportAddingBinaryFunctions`, or the vertex and -//! fragment forms) is an API validation stop; without validation Metal adds them. The added -//! state has the base state's handles and one for each added function; an addition the stage -//! already links keeps its handle, and adding nothing makes a state alike. +//! - **Binary functions, added.** Adding to a stage of a state made without its support flag +//! (`supportAddingBinaryFunctions`, or the vertex and fragment forms) is an API validation stop; +//! without validation Metal adds them. The added state has the base state's handles and one for +//! each added function; an addition the stage already links keeps its handle, and adding +//! nothing makes a state alike. +//! +//! Measured on an M3 Max under macOS 27.0.1 (`binary_function_linking.m`, of libraries compiled +//! from source and of metallibs alike, plain and with `MTL_DEBUG_LAYER=1`): +//! - **A binary function is a table's function alone.** No visible-function reference resolves to +//! a function only `binaryFunctions` lists: a direct call to it from a compute, vertex, fragment +//! or tile function, or from a function `functions` links, fails the creation, plain and under +//! validation (code 3, "error: unresolved visible function reference: add_one", then "Reason: +//! visible function not loaded"), which the runtime answers as any reference no linked function +//! resolves (`Compile`, `NeedsInput(LinkedFunction)`); through a visible-function table, or +//! with no call, the pipeline is made and its table calls it. +//! - **One name in two lists.** `functions` and `binaryFunctions` holding a function of one name +//! (one function in both, or two functions of two libraries) is made, plain; API validation +//! stops it ("All linked functions must have unique names. Function 'add_one' is a duplicate +//! symbol in binaryFunctions, symbol first found in functions."). A reference calls the one of +//! `functions`, and a table holds each, each handle calling its own function. Two functions of +//! one name in `binaryFunctions` are made alike (a table holds both), and a function added to a +//! made state beside a function of its name the stage links is added, with a handle of its own, +//! validation or not. `functions` holding one name twice fails the creation (code 3, "error: +//! duplicated symbol: add_one"), the runtime's `Invalid(DuplicateLinkedFunction)`. +//! - **Not compiled to a binary.** A function made without `MTLFunctionOptionCompileToBinary` in a +//! stage's `binaryFunctions` fails a plain creation once its stage links, whether a table or +//! nothing calls it, and when `functions` lists it too: code 2, "Internal error during compute +//! pipeline creation" (a tile pipeline's "tile pipeline", and an empty description for a render +//! pipeline's vertex or fragment stage and a mesh pipeline's fragment stage), after a reference +//! the stage leaves unresolved (code 3 first). Among the functions added to a made state, of its +//! kernel, vertex, fragment or tile stage, with or without its support flag: code 1, "Failed to +//! allocate a new pipeline". Added to a stage the state lacks (a drawing state's tile stage, or +//! the fragment stage it has no function of; a tile state's vertex stage), it is added, as such +//! functions are, with no handle. API validation stops each ("Function 'add_one' was found in +//! binaryFunctions array but is not precompiled.", "... in Vertex functions array ..."), and +//! the runtime answers plain Metal's error ([`Error::MetalError`]), after the compile (a +//! fragment stage a render pipeline without rasterization drops is not asked: Metal's answer +//! there was not measured). While a +//! function `newFunctionWithDescriptor:` made compiled to a binary lives, Metal's +//! `newFunctionWithName:` of the same library function answers that one object, compiled to a +//! binary (and the other way about), where the runtime's two functions stay two. +//! - **Mesh pipelines.** A binary function in a mesh pipeline's object or mesh stage ends plain +//! Metal's process at the creation ("Binary linked functions are not supported for object and +//! mesh shaders"); its fragment stage takes them as a render pipeline's does. +use super::indirect_arguments::DOMAIN; use super::render::{GraphicsState, Kind, RenderPipelineState, StateDescriptor}; use super::tile::TileState; use super::{ComputePipelineState, Kernel, PipelineOptions}; -use crate::error::{invalid, Error, Problem}; +use crate::error::{invalid, Error, MetalError, Problem}; use crate::library::Function; use crate::values::Size; use crate::Device; use metal2vulkan::pipeline::{ - FunctionDescriptor, LinkedFunction, LinkedFunctions, MeshPipelineDescriptor, - RenderPipelineDescriptor, Stage, StageSource, + LinkedFunction, MeshPipelineDescriptor, RenderPipelineDescriptor, Stage, StageSource, }; /// A `requiredThreadsPerThreadgroup` Metal stops at a pipeline's creation. @@ -117,17 +154,34 @@ pub enum BinaryFunctionProblem { /// The stage. stage: BinaryFunctionStage, }, - /// A function not compiled to a binary in a stage's `binary_functions` ("Function 'f' was - /// found in binaryFunctions array but is not precompiled.") or among the functions added - /// ("Function 'f' was found in Fragment functions array but is not precompiled."): Metal's - /// API validation stops it, and its creation fails without validation. + /// A function not compiled to a binary in a stage's `binary_functions` or among the functions + /// added to a stage of a made state, which plain Metal's creation fails over: the runtime + /// answers it as [`Error::MetalError`], code 2 for a stage's ("Internal error during compute + /// pipeline creation", "Internal error during tile pipeline creation", or an empty + /// description for a render or mesh pipeline's stage) once its stage compiled, and code 1 + /// ("Failed to allocate a new pipeline") for one added. Metal's API validation stops both + /// ("Function 'f' was found in binaryFunctions array but is not precompiled.", "Function 'f' + /// was found in Fragment functions array but is not precompiled."); a function added to a + /// stage the state lacks is taken, as plain Metal takes it (the module docs). /// - /// Basis: metal-documented (Metal's validation says "Function 'f' was found in binaryFunctions - /// array but is not precompiled.", and its creation fails without validation). + /// Basis: metal-measured (an M3 Max, macOS 27.0.1: plain Metal's creation fails with code 2, + /// an addition's with code 1, `binary_function_linking.m`). NotPrecompiled { /// The function's name. name: String, }, + /// Binary functions in a mesh render pipeline's object or mesh stage (the `binary_functions` + /// of its function's linked functions, Metal's `objectLinkedFunctions` and + /// `meshLinkedFunctions`): plain Metal's process ends at the creation, at its descriptor + /// validation ("Binary linked functions are not supported for object and mesh shaders"). Its + /// fragment stage takes them. + /// + /// Basis: metal-measured (an M3 Max, macOS 27.0.1: plain Metal's process ends at the creation, + /// `binary_function_linking.m`). + ObjectOrMeshStage { + /// The stage: `Object` or `Mesh`. + stage: Stage, + }, /// Functions added to a stage the compile layer already compiled (`StageSource::Compiled`), /// whose linked functions are fixed: Metal's stages are functions, so it has no such call. /// @@ -181,13 +235,12 @@ impl Kernel { } } -/// Check, before compiling, a compute or tile creation of `kernel` (whose function is `function`) -/// in `call` on `device`: its required threads per threadgroup against the device's limit and its -/// own maximum, and that its `binary_functions` are precompiled, as Metal does (the module docs). +/// Check, before compiling, a compute or tile creation of `kernel` in `call` on `device`: its +/// required threads per threadgroup against the device's limit and its own maximum, as Metal does +/// (the module docs). pub(super) fn check_kernel( device: &Device, kernel: &Kernel, - function: &FunctionDescriptor, call: &'static str, ) -> Result<(), Error> { let (required, max) = kernel.threadgroup_fields(); @@ -223,44 +276,124 @@ pub(super) fn check_kernel( _ => {} } } - check_precompiled(call, &function.linked) + Ok(()) } -/// Check, before compiling, that a render creation's stages link only precompiled -/// `binary_functions`, as a compute creation's must. -pub(super) fn check_render( - descriptor: &RenderPipelineDescriptor, +/// The kind of pipeline a creation makes, whose name Metal's error for a binary function not +/// compiled to a binary says. +#[derive(Clone, Copy, Debug)] +pub(super) enum Made { + Compute, + Tile, + /// A render pipeline's vertex or fragment stage, or a mesh pipeline's fragment stage. + Render, +} + +impl Made { + /// Metal's `localizedDescription` for such a function of a stage of the pipeline. + fn description(self) -> &'static str { + match self { + Made::Compute => "Internal error during compute pipeline creation", + Made::Tile => "Internal error during tile pipeline creation", + Made::Render => "", + } + } +} + +/// The code of Metal's error for a stage's binary function not compiled to a binary. +const NOT_PRECOMPILED: i64 = 2; + +/// The code and the `localizedDescription` of Metal's error for a function added to a made state +/// that is not compiled to a binary. +const ADDED_NOT_PRECOMPILED: (i64, &str) = (1, "Failed to allocate a new pipeline"); + +/// Metal's error in `call` for `f`, not compiled to a binary, of `code` and `description`. +fn not_precompiled( call: &'static str, + f: &LinkedFunction, + (code, description): (i64, &'static str), +) -> Error { + Error::MetalError(MetalError::new( + call, + Problem::BinaryFunctions(BinaryFunctionProblem::NotPrecompiled { + name: f.name().to_owned(), + }), + DOMAIN, + code, + description, + )) +} + +/// Refused in `call` once the stages compiled, as plain Metal fails a creation of kind `made` +/// whose stage links a binary function not compiled to a binary (the module docs): the first such +/// function of `stages`, in order. A compiled stage links none Metal names. +pub(super) fn check_precompiled<'a>( + call: &'static str, + made: Made, + stages: impl IntoIterator, ) -> Result<(), Error> { - for stage in std::iter::once(&descriptor.vertex).chain(&descriptor.fragment) { - if let StageSource::Function(function) = stage { - check_precompiled(call, &function.linked)?; + for stage in stages { + let StageSource::Function(function) = stage else { + continue; + }; + if let Some(f) = function + .linked + .binary_functions + .iter() + .find(|f| !f.precompiled) + { + return Err(not_precompiled( + call, + f, + (NOT_PRECOMPILED, made.description()), + )); } } Ok(()) } -/// The first of `linked`'s `binary_functions` that is not precompiled refuses `call`. -fn check_precompiled(call: &'static str, linked: &LinkedFunctions) -> Result<(), Error> { - match linked.binary_functions.iter().find(|f| !f.precompiled) { - Some(f) => Err(not_precompiled(call, f)), - None => Ok(()), +/// Refused in `call` before anything, as plain Metal's descriptor validation ends its process +/// there: a mesh pipeline's object or mesh stage that links binary functions (the module docs). +pub(super) fn check_mesh( + call: &'static str, + descriptor: &MeshPipelineDescriptor, +) -> Result<(), Error> { + let stages = descriptor + .object + .iter() + .map(|object| (Stage::Object, object)) + .chain([(Stage::Mesh, &descriptor.mesh)]); + for (stage, source) in stages { + if let StageSource::Function(function) = source { + if !function.linked.binary_functions.is_empty() { + return Err(invalid( + call, + Problem::BinaryFunctions(BinaryFunctionProblem::ObjectOrMeshStage { stage }), + )); + } + } } + Ok(()) } -fn not_precompiled(call: &'static str, f: &LinkedFunction) -> Error { - invalid( +/// [`check_precompiled`] of a render creation's vertex and fragment stages. +pub(super) fn check_render( + call: &'static str, + descriptor: &RenderPipelineDescriptor, +) -> Result<(), Error> { + check_precompiled( call, - Problem::BinaryFunctions(BinaryFunctionProblem::NotPrecompiled { - name: f.name().to_owned(), - }), + Made::Render, + std::iter::once(&descriptor.vertex).chain(&descriptor.fragment), ) } /// `stage` of a state, with `functions` added to its `binary_functions`, in `call` on `device`; -/// `supported` is the stage's support flag. Each function must be of `device` and precompiled; -/// one the stage's `functions` or `binary_functions` already link (the same name it links under, -/// library function, AIR, constant values and specialization) keeps its entry and handle. +/// `supported` is the stage's support flag. Each function must be of `device` and precompiled +/// (Metal's error otherwise, the module docs); one the stage's `functions` or `binary_functions` +/// already link (the same name it links under, library function, AIR, constant values and +/// specialization) keeps its entry and handle, and another of a name the stage links is added +/// beside it. fn added( device: &Device, call: &'static str, @@ -291,7 +424,7 @@ fn added( } let linked = function.linked_function(); if !linked.precompiled { - return Err(not_precompiled(call, &linked)); + return Err(not_precompiled(call, &linked, ADDED_NOT_PRECOMPILED)); } let same = |f: &LinkedFunction| { f.name() == linked.name() @@ -342,18 +475,14 @@ fn added_counting( } /// `functions` added in `call` to a stage a drawing or tile state lacks, which plain Metal makes -/// the state without, giving no handle of them, where its API validation stops them: refused -/// (`Invalid`) only as a stage's are, for a function of another device or one not compiled to a -/// binary. +/// the state without, giving no handle of them, where its API validation stops them, a function +/// not compiled to a binary among them (the module docs): refused (`Invalid`) only for a function +/// of another device. fn ignored(device: &Device, call: &'static str, functions: &[Function]) -> Result<(), Error> { for function in functions { if !function.device().same(device) { return Err(invalid(call, Problem::ForeignObject)); } - let linked = function.linked_function(); - if !linked.precompiled { - return Err(not_precompiled(call, &linked)); - } } Ok(()) } @@ -366,9 +495,10 @@ impl ComputePipelineState { /// makes a state alike. On a state made without `support_adding_binary_functions`, which /// Metal's API validation stops, an added function's handle calls the kernel's last other /// callable function, and none where it has none (an entry that reads null), as plain Metal's - /// does. Refused (`Invalid`), as Metal's API validation refuses it: a function not made - /// compiled to a binary (`FunctionOptions::COMPILE_TO_BINARY`), which Metal's creation also - /// fails on without validation (`BinaryFunctions`); and a function of another device + /// does. A function not made compiled to a binary (`FunctionOptions::COMPILE_TO_BINARY`) fails + /// it as plain Metal's call fails, with or without the support flag: [`Error::MetalError`] + /// with `BinaryFunctions(NotPrecompiled)`, code 1 ("Failed to allocate a new pipeline"), where + /// Metal's API validation stops it. Refused (`Invalid`): a function of another device /// (`ForeignObject`). Otherwise refused as the creation is. pub fn new_compute_pipeline_state_with_additional_binary_functions( &self, @@ -467,16 +597,18 @@ impl RenderPipelineState { /// one with the default options and this state's label. It has this state's function handles /// and one for each added function. Functions added to a stage the state lacks (a drawing /// state's tile stage or missing fragment stage, a tile state's vertex and fragment stages) are - /// left out, with no handle, as plain Metal leaves them where its API validation stops them; on + /// left out, with no handle, compiled to a binary or not, as plain Metal leaves them where its + /// API validation stops them; on /// a stage made without its support flag (`support_adding_vertex_binary_functions`, /// `support_adding_fragment_binary_functions`, a tile descriptor's /// `support_adding_binary_functions`), which its API validation also stops, an added function's /// handle calls the stage's last other callable function, and none where it has none (an entry - /// that reads null), as plain Metal's does. Refused (`Invalid`), as Metal's API validation - /// refuses it: functions added to a mesh state (`BinaryFunctions(NotSupported)`; plain Metal's - /// process ends there), and a function not made compiled to a binary - /// (`BinaryFunctions(NotPrecompiled)`); a function of another device (`ForeignObject`); and - /// functions added to a stage the compile layer already compiled + /// that reads null), as plain Metal's does. A function not made compiled to a binary added to + /// a stage the state has fails it as plain Metal's call fails: [`Error::MetalError`] with + /// `BinaryFunctions(NotPrecompiled)`, code 1 ("Failed to allocate a new pipeline"), where + /// Metal's API validation stops it. Refused (`Invalid`): functions added to a mesh state + /// (`BinaryFunctions(NotSupported)`; plain Metal's process ends there); a function of another + /// device (`ForeignObject`); and functions added to a stage the compile layer already compiled /// (`BinaryFunctions(CompiledStage)`). Otherwise refused as the creation is. pub fn new_render_pipeline_state_with_additional_binary_functions( &self, diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index c4f4d02d1..c44a0825d 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -543,10 +543,17 @@ impl Device { /// `MTLComputePipelineDescriptor.linkedFunctions`); every variant compiles under the /// descriptor's other fields. A kernel the compile layer already compiled /// (`StageSource::Compiled`) is refused (`Invalid(CompiledKernel)`): the state compiles its - /// kernel again for each variant a dispatch needs. So is a name `functions` or - /// `binary_functions` lists twice, or both lists hold for two different functions - /// (`Invalid(DuplicateLinkedFunction)`); one function listed in both is linked once, with one - /// handle, as plain Metal takes it where its API validation stops it. So is an archive of + /// kernel again for each variant a dispatch needs. So is a name `functions` lists twice + /// (`Invalid(DuplicateLinkedFunction)`), as plain Metal's creation fails. A name both + /// `functions` and `binary_functions` hold, or `binary_functions` holds twice, is made, as + /// plain Metal makes it where its API validation stops it: one function listed twice is linked + /// once, with one handle; two different functions are two, each with its handle, and a call + /// to the name calls the one of `functions`. No call to a visible function resolves to a + /// function `binary_functions` alone holds, which only a visible-function table calls + /// (`Compile`, `NeedsInput(LinkedFunction)`, as Metal's creation fails). A function in + /// `binary_functions` not made compiled to a binary fails the creation once the kernel + /// compiled, [`Error::MetalError`] with `BinaryFunctions(NotPrecompiled)` (code 2), as plain + /// Metal's does. So is an archive of /// another device (`Invalid(ForeignObject)`). Under `FAIL_ON_BINARY_ARCHIVE_MISS`, a pipeline /// no listed archive holds is `BinaryArchiveMiss`. What the compile refuses is `Compile` or /// `Unsupported`: constant values that do not fit the function's constants, and a call to a @@ -702,7 +709,7 @@ impl ComputePipelineState { kernel.stage(), &options.budget(), )?; - additions::check_kernel(device, &kernel, function, call)?; + additions::check_kernel(device, &kernel, call)?; // A tile pipeline's descriptor has no `supportIndirectCommandBuffers`, and no // `resourceIndex`. let indirect = match &kernel { @@ -736,6 +743,13 @@ impl ComputePipelineState { Variant::compiled(&sources, function, &kernel, key) }) .map_err(|error| compile_error(device, error))?; + // Metal fails the creation over a binary function not compiled to a binary once the + // stage links, after a reference it leaves unresolved (`additions.rs`). + let made = match &kernel { + Kernel::Compute(_) => additions::Made::Compute, + Kernel::Tile(_) => additions::Made::Tile, + }; + additions::check_precompiled(call, made, [kernel.stage()])?; // Metal answers nil with an `NSError` for a compute state that supports indirect command // buffers whose kernel uses a direct texture or sampler (`indirect_arguments.rs`). // Asked of the kernel the compile above produced, which answers from what that compile @@ -874,47 +888,26 @@ pub(crate) fn warm(device: &Device, pipeline: &crate::warm::Pipeline) -> Result< Ok(true) } -/// The first name `linked` repeats where Metal's pipeline creation fails or was not measured: a -/// name `functions` lists twice ("error: duplicated symbol", without validation too), or -/// `binary_functions` twice, and a name both lists hold for two different functions (another -/// AIR, library function or constant values), in that order. A function's name is the one it links -/// under ([`LinkedFunction::name`]): its specialized name where it has one, so one library -/// function linked under its own name and under a specialized one is no repeat, as Metal links -/// both (`linked_function_specialized_name.m`, an M3 Max under macOS 27.0.1). Metal's API validation stops every repeat ("All -/// linked functions must have unique names. Function 'add_one' is a duplicate symbol in -/// binaryFunctions, symbol first found in functions"), but plain Metal takes one function listed -/// in both lists, with one handle (a probe, an M3 and an M4), as the compile layer links it once. -/// Whether validation also counts `private_functions` and `groups` was not measured, so they are -/// left to it. +/// The first name `functions` repeats, where plain Metal's pipeline creation fails ("error: +/// duplicated symbol: add_one", code 3, one function listed twice or two of one name, an M3 Max +/// under macOS 27.0.1, `binary_function_linking.m`). A function's name is the one it links under +/// ([`LinkedFunction::name`]): its specialized name where it has one, so one library function +/// linked under its own name and under a specialized one is no repeat, as Metal links both +/// (`linked_function_specialized_name.m`, an M3 Max under macOS 27.0.1). Metal's API validation +/// stops every repeat across the lists too ("All linked functions must have unique names. +/// Function 'add_one' is a duplicate symbol in binaryFunctions, symbol first found in +/// functions"), but plain Metal makes a name both `functions` and `binary_functions` hold, or +/// `binary_functions` holds twice, whether one function or two, and so does the runtime (the +/// compile layer resolves a reference against `functions` alone of the two, and a table holds +/// each). Whether a repeat `private_functions` or `groups` holds fails was not measured, so they +/// are left to the compile layer. pub(super) fn duplicate_linked_name(linked: &LinkedFunctions) -> Option { - fn name(f: &LinkedFunction) -> &str { - f.name() - } - fn repeated(list: &[LinkedFunction]) -> Option<&str> { - let mut seen = HashSet::new(); - list.iter().map(name).find(|n| !seen.insert(*n)) - } - let same = |a: &LinkedFunction, b: &LinkedFunction| { - name(a) == name(b) - && a.function.info().name == b.function.info().name - && a.function.info().air_hash == b.function.info().air_hash - && a.constants == b.constants - && a.specialized == b.specialized - }; - repeated(&linked.functions) - .or_else(|| repeated(&linked.binary_functions)) - .or_else(|| { - linked - .binary_functions - .iter() - .find(|b| { - linked - .functions - .iter() - .any(|f| name(f) == name(b) && !same(f, b)) - }) - .map(name) - }) + let mut seen = HashSet::new(); + linked + .functions + .iter() + .map(LinkedFunction::name) + .find(|n| !seen.insert(*n)) .map(str::to_owned) } diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index caea8a5e4..e38fecae5 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -1320,7 +1320,6 @@ impl GraphicsState { Problem::IndirectScaledTessellation, )); } - super::additions::check_render(descriptor, "new_render_pipeline_state")?; // Metal answers nil with an `NSError` for a state with rasterization disabled whose vertex // function returns a value (`unrasterized.rs`), before it compiles anything. // Each answer below is the one a creation of a descriptor of the same key worked out, where @@ -1494,6 +1493,9 @@ impl GraphicsState { RenderVariant::compiled(&sources, descriptor, key, entries, descriptor_key) }) .map_err(|error| compile_error(device, error))?; + // Metal fails the creation over a binary function not compiled to a binary once the + // stages link, after a reference they leave unresolved (`additions.rs`). + super::additions::check_render("new_render_pipeline_state", descriptor)?; let sized_class = matches!( descriptor.input_primitive_topology, PrimitiveTopologyClass::Line | PrimitiveTopologyClass::Triangle @@ -1649,6 +1651,8 @@ impl GraphicsState { if let Some(fragment) = &descriptor.fragment { super::unspecialized::check(device, CALL, Stage::Fragment, fragment, &budget)?; } + // And for binary functions an object or mesh stage links (`additions.rs`). + super::additions::check_mesh(CALL, descriptor)?; // A state an indirect command buffer's commands may set takes its ID where the options // place it, as a render state's does. let placement = if descriptor.support_indirect_command_buffers { @@ -1703,6 +1707,13 @@ impl GraphicsState { compile.compile_mesh_variant(descriptor, key, &budget) }) .map_err(|error| compile_error(device, error))?; + // A fragment stage's binary function not compiled to a binary, as a render state's + // (`additions.rs`). + super::additions::check_precompiled( + CALL, + super::additions::Made::Render, + &descriptor.fragment, + )?; let stand_in = !key.storage_images.is_empty(); let base = RenderVariant::of( device, diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline.rs b/crates/metal2vulkan-runtime/src/tests/pipeline.rs index 7936bdda6..373f95bdf 100644 --- a/crates/metal2vulkan-runtime/src/tests/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/tests/pipeline.rs @@ -1,5 +1,6 @@ //! The checks a compute pipeline state's descriptor passes before its compile -//! (`pipeline::duplicate_linked_name`, by the name each linked function links under), 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`). @@ -32,10 +33,11 @@ fn linked(stem: &str) -> LinkedFunction { LinkedFunction::new(library.function(stem).expect("function")) } -/// A name `functions` lists twice, or `binary_functions` twice, or both lists hold for two -/// different functions, is a descriptor Metal's creation fails on or whose answer was not measured, -/// named as its first repeat; one function both lists hold is taken, as plain Metal takes it; a -/// name only `private_functions` or a group repeats is left to the compile, as is one listed once. +/// A name `functions` lists twice is a descriptor plain Metal's creation fails on ("duplicated +/// symbol"), named as its first repeat; a name `binary_functions` lists twice, or both lists hold, +/// one function or two different ones, is taken, as plain Metal makes it (an M3 Max under macOS +/// 27.0.1, `binary_function_linking.m`); a name only `private_functions` or a group repeats is left +/// to the compile, as is one listed once. #[test] fn a_name_the_numbered_lists_repeat_is_found() { let (first, second, third) = ( @@ -63,7 +65,7 @@ fn a_name_the_numbered_lists_repeat_is_found() { duplicate_linked_name(&twice), Some("ob3_index_buffer".to_owned()) ); - // One function in both lists: plain Metal takes it, with one handle. + // One function in both lists, and twice in `binary_functions`: plain Metal makes both. let mut both = once.clone(); both.binary_functions .push(first.clone().with_precompiled(true)); @@ -73,20 +75,20 @@ fn a_name_the_numbered_lists_repeat_is_found() { third.clone().with_precompiled(true), third.clone().with_precompiled(true), ]); - assert_eq!( - duplicate_linked_name(&binary_twice), - Some("ob3_texture_array".to_owned()) - ); - // Another function of the same name (its constant values differ) in the other list. + assert_eq!(duplicate_linked_name(&binary_twice), None); + // Another function of the same name (its constant values differ) in the other list, and in + // `binary_functions` beside the first: plain Metal makes both too. let mut other = first.clone().with_precompiled(true); other.constants = FunctionConstantValues::defaults() .with_index(0, FunctionConstantValue::new(DataType::Bool, [1u8])); - let mut different = once; - different.binary_functions.push(other); - assert_eq!( - duplicate_linked_name(&different), - Some("ob3_stage_input".to_owned()) - ); + let mut different = once.clone(); + different.binary_functions.push(other.clone()); + assert_eq!(duplicate_linked_name(&different), None); + let mut binary_different = once; + binary_different + .binary_functions + .extend([first.with_precompiled(true), other]); + assert_eq!(duplicate_linked_name(&binary_different), None); } /// The name a list repeats is the one each function links under, its specialized name where it diff --git a/crates/metal2vulkan-validation/src/runtime_lane/function_tables.rs b/crates/metal2vulkan-validation/src/runtime_lane/function_tables.rs index 1821eb265..f33746322 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/function_tables.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/function_tables.rs @@ -37,9 +37,9 @@ use metal2vulkan::pipeline::{ use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, ComputeCommandEncoder, ComputePipelineState, CpuCacheMode, Device, Error, - FunctionTableProblem, HazardTrackingMode, Invalid, Library, LoadAction, PipelineOptions, - Problem, PurgeableState, RenderPassDescriptor, RenderPipelineState, ResourceId, - ResourceOptions, RuntimeGap, Size, StorageMode, StoreAction, TextureDescriptor, + FunctionTableProblem, HazardTrackingMode, Invalid, Library, LoadAction, MetalError, + PipelineOptions, Problem, PurgeableState, RenderPassDescriptor, RenderPipelineState, + ResourceId, ResourceOptions, RuntimeGap, Size, StorageMode, StoreAction, TextureDescriptor, VisibleFunctionTable, VisibleFunctionTableDescriptor, }; @@ -1044,7 +1044,10 @@ fn without_the_array_s_features_a_table_past_the_storage_range_is_called_through /// What Metal answers for binary functions and required threadgroup sizes (the M3 Max and the M4 /// alike): -/// - A stage's `binary_functions` and a made state's additions must be compiled to a binary. +/// - A stage's `binary_functions` and a made state's additions must be compiled to a binary: plain +/// Metal's creation fails with code 2 ("Internal error during compute pipeline creation"), and +/// its addition with code 1 ("Failed to allocate a new pipeline"), on an M3 Max under macOS +/// 27.0.1 (`binary_function_linking.m`). /// - Without the state's support flag, an added function's handle calls the kernel's last other /// callable function. /// - The added state has a handle for each of the base state's functions and each added one, and @@ -1078,13 +1081,19 @@ fn binary_functions_and_required_threads_answer_as_metal_s_do() { }; const CREATE: &str = "new_compute_pipeline_state"; const ADD: &str = "new_compute_pipeline_state_with_additional_binary_functions"; - let binary_problem = |call, problem| invalid(call, Problem::BinaryFunctions(problem)); - let not_precompiled = |call, name: &str| { - binary_problem( + let not_precompiled = |call, name: &str, (code, description)| { + Error::MetalError(MetalError::new( call, - BinaryFunctionProblem::NotPrecompiled { name: name.into() }, - ) + Problem::BinaryFunctions(BinaryFunctionProblem::NotPrecompiled { + name: name.into(), + }), + "AGXMetalG15X_M1", + code, + description, + )) }; + const MADE: (i64, &str) = (2, "Internal error during compute pipeline creation"); + const ADDED: (i64, &str) = (1, "Failed to allocate a new pipeline"); // The options a function descriptor takes: every combination of the four bits, each // answered back verbatim, as plain Metal answers it over a descriptor that lists no @@ -1111,7 +1120,7 @@ fn binary_functions_and_required_threads_answer_as_metal_s_do() { linked.binary_functions = vec![plain("table_add").linked_function()]; assert_eq!( create(&descriptor(linked)).err(), - Some(not_precompiled(CREATE, "table_add")) + Some(not_precompiled(CREATE, "table_add", MADE)) ); // Functions added to a made state. Without the support flag, which Metal's validation @@ -1165,7 +1174,7 @@ fn binary_functions_and_required_threads_answer_as_metal_s_do() { plain("table_sub"), ]) .err(), - Some(not_precompiled(ADD, "table_sub")) + Some(not_precompiled(ADD, "table_sub", ADDED)) ); assert_eq!(state.function_handle(&compiled("table_add")).unwrap(), None); let added = state @@ -1401,7 +1410,9 @@ fn functions_added_to_a_vertex_stage_without_its_flag_call_its_last_function() { /// Functions added to a stage a drawing state lacks (the fragment stage of a state without a /// fragment function, and the tile stage) are left out, with no handle, as plain Metal makes the /// state where its validation stops it; the state's vertex function keeps its handle. A function -/// not compiled to a binary stays refused there, as it is for a stage the state has. +/// not compiled to a binary is left out there too, as plain Metal leaves it (an M3 Max under +/// macOS 27.0.1, `binary_function_linking.m`), where one added to a stage the state has fails +/// the call. #[test] fn functions_added_to_a_stage_a_drawing_state_lacks_are_left_out() { use metal2vulkan::metal::FunctionOptions; @@ -1443,17 +1454,209 @@ fn functions_added_to_a_stage_a_drawing_state_lacks_are_left_out() { .unwrap() .is_some()); added.tile_additional_binary_functions = vec![plain("table_sub")]; + added.fragment_additional_binary_functions = vec![plain("table_mul")]; + let made = state + .new_render_pipeline_state_with_additional_binary_functions(&added) + .unwrap(); + assert_eq!( + made.function_handle(&plain("table_sub"), RenderStages::TILE) + .unwrap(), + None + ); + let mut to_vertex = RenderPipelineFunctionsDescriptor::new(); + to_vertex.vertex_additional_binary_functions = vec![plain("table_sub")]; assert_eq!( state - .new_render_pipeline_state_with_additional_binary_functions(&added) + .new_render_pipeline_state_with_additional_binary_functions(&to_vertex) .unwrap_err(), - invalid( + Error::MetalError(MetalError::new( "new_render_pipeline_state_with_additional_binary_functions", Problem::BinaryFunctions(BinaryFunctionProblem::NotPrecompiled { name: "table_sub".into() - }) + }), + "AGXMetalG15X_M1", + 1, + "Failed to allocate a new pipeline", + )) + ); + }); +} + +/// Binary functions a stage links as plain Metal links them (an M3 Max under macOS 27.0.1, +/// `binary_function_linking.m`, where Metal's API validation stops the two-list shapes): +/// - a function `binary_functions` alone holds is called through the stage's table, a kernel's +/// and a vertex function's; +/// - beside a function of its name in `functions` (the owned `linked_other_functions`' +/// `table_add`, `a + b + 100`), each has a handle of its own and the table calls each; +/// - one not compiled to a binary fails the creation once the stage links, with plain Metal's +/// error: code 2, "Internal error during compute pipeline creation" for a kernel, an empty +/// description for a vertex function; +/// - a mesh pipeline's mesh or object stage linking any is refused, as plain Metal ends its +/// process there; its fragment stage takes them. +#[test] +fn binary_functions_link_as_plain_metal_links_them() { + use metal2vulkan::metal::FunctionOptions; + use metal2vulkan::pipeline::{MeshPipelineDescriptor, Stage}; + use metal2vulkan_runtime::{BinaryFunctionProblem, FunctionDescriptor}; + on_device(|device| { + let (caller, functions) = libraries(device); + let other = llvm_assemble(&engine_dir().join("linked_other_functions.ll")).unwrap(); + let other = device.new_library_with_air(&other).unwrap(); + let compiled = |library: &Library, name: &str| { + let mut descriptor = FunctionDescriptor::new(name); + descriptor.options = FunctionOptions::COMPILE_TO_BINARY; + library.new_function_with_descriptor(&descriptor).unwrap() + }; + let plain = |library: &Library, name: &str| library.new_function_with_name(name).unwrap(); + let binary = |listed: Option<&metal2vulkan_runtime::Function>, held| { + let mut linked = LinkedFunctions::new(); + if let Some(listed) = listed { + linked = linked.with_function(listed.linked_function()); + } + linked + .binary_functions + .push(metal2vulkan_runtime::Function::linked_function(held)); + linked + }; + let add = |tid: u32| tid + 3; + let other_add = |tid: u32| tid + 103; + // A kernel's table: the binary function alone, then beside another of its name. + let alone = compiled(&functions, "table_add"); + let state = state_of(&caller, "visible_table_dispatch", binary(None, &alone)); + let one = table(&state, 1); + one.set_function(state.function_handle(&alone).unwrap().as_ref(), 0) + .unwrap(); + let expect: Vec = (0..N).map(add).collect(); + assert_eq!(words_of(device, &state, Some(&one), || {}), expect); + let (own, others) = ( + plain(&functions, "table_add"), + compiled(&other, "table_add"), + ); + let state = state_of( + &caller, + "visible_table_dispatch", + binary(Some(&own), &others), + ); + let handles = [&own, &others].map(|f| state.function_handle(f).unwrap().unwrap()); + assert_ne!(handles[0], handles[1]); + let two = table(&state, 2); + two.set_functions(&[Some(&handles[0]), Some(&handles[1])], 0) + .unwrap(); + let alternate: Vec = (0..N) + .map(|tid| { + if tid % 2 == 0 { + add(tid) + } else { + other_add(tid) + } + }) + .collect(); + assert_eq!(words_of(device, &state, Some(&two), || {}), alternate); + // A vertex function's table, beside another of its name. + let state = vertex_state_linking(device, binary(Some(&own), &others)); + let handles = [&own, &others].map(|f| { + state + .function_handle(f, RenderStages::VERTEX) + .unwrap() + .unwrap() + }); + let two = state + .new_visible_function_table( + &VisibleFunctionTableDescriptor::new(2), + RenderStages::VERTEX, + ) + .unwrap(); + two.set_functions(&[Some(&handles[0]), Some(&handles[1])], 0) + .unwrap(); + assert_eq!( + vertex_words_of(device, &state, Some(&two), || {}), + alternate + ); + // Not compiled to a binary: plain Metal's error, a kernel's and a vertex function's. + let not_precompiled = |call, description| { + Err(Error::MetalError(MetalError::new( + call, + Problem::BinaryFunctions(BinaryFunctionProblem::NotPrecompiled { + name: "table_add".into(), + }), + "AGXMetalG15X_M1", + 2, + description, + ))) + }; + let kernel = caller + .new_function_with_name("visible_table_dispatch") + .unwrap(); + assert_eq!( + device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function( + kernel.function_descriptor().with_linked(binary(None, &own)), + )), + &PipelineOptions::default(), + ) + .map(drop), + not_precompiled( + "new_compute_pipeline_state", + "Internal error during compute pipeline creation" ) ); + let bitcode = llvm_assemble(&engine_dir().join("vft_vertex_caller.ll")).unwrap(); + let vertex_caller = device.new_library_with_air(&bitcode).unwrap(); + let vertex = vertex_caller + .new_function_with_name("vft_vertex_dispatch") + .unwrap(); + let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function( + vertex.function_descriptor().with_linked(binary(None, &own)), + )); + descriptor.rasterization_enabled = false; + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + assert_eq!( + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .map(drop), + not_precompiled("new_render_pipeline_state", "") + ); + // A mesh pipeline's mesh and object stages. + let ll = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/public/examples/icb_direct_arguments.ll"); + let mesh_library = device + .new_library_with_air(&llvm_assemble(&ll).unwrap()) + .unwrap(); + let stage = |name: &str, linked: LinkedFunctions| { + StageSource::Function( + mesh_library + .new_function_with_name(name) + .unwrap() + .function_descriptor() + .with_linked(linked), + ) + }; + for linked_stage in [Stage::Mesh, Stage::Object] { + let linked = |of: Stage| match of == linked_stage { + true => binary(None, &alone), + false => LinkedFunctions::new(), + }; + let mut descriptor = + MeshPipelineDescriptor::new(stage("plain_mesh", linked(Stage::Mesh))); + descriptor.object = Some(stage("plain_object", linked(Stage::Object))); + descriptor.fragment = Some(stage("plain_fragment", LinkedFunctions::new())); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + assert_eq!( + device + .new_mesh_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .map(drop), + Err(invalid( + "new_mesh_render_pipeline_state", + Problem::BinaryFunctions(BinaryFunctionProblem::ObjectOrMeshStage { + stage: linked_stage + }) + )), + "{linked_stage:?}" + ); + } }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/tests.rs b/crates/metal2vulkan-validation/src/runtime_lane/tests.rs index 3a99cf5c8..bdf911e92 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/tests.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/tests.rs @@ -507,6 +507,14 @@ fn an_indirect_stage_in_region_reads_as_the_direct_one() { /// call no linked function supplies; a name the linked `functions` repeat, and a kernel the compile /// layer already compiled, are refused typed, and one function in `functions` and /// `binary_functions` is linked once, as plain Metal takes it. +/// +/// A call never resolves to a function `binary_functions` alone holds, as plain Metal's creation +/// fails (code 3, "unresolved visible function reference", an M3 Max under macOS 27.0.1, +/// `binary_function_linking.m`), whether it is compiled to a binary or not: the call no linked +/// function supplies refuses the state, before the function not compiled to a binary does, in +/// Metal's order. Beside a `linked_scale` of `functions`, another (the owned +/// `linked_other_functions`', `x + 100`) in `binary_functions` is made, as plain Metal makes it, +/// and the call calls the one of `functions`, from either module. #[test] fn a_kernel_runs_the_functions_its_descriptor_links() { use metal2vulkan::error::{Error as CompileError, RuntimeInput}; @@ -518,13 +526,15 @@ fn a_kernel_runs_the_functions_its_descriptor_links() { use metal2vulkan_devtools::{engine_dir, llvm_assemble}; const N: u32 = 32; let fixture = |stem: &str| llvm_assemble(&engine_dir().join(format!("{stem}.ll"))).unwrap(); - let (caller, functions) = ( + let (caller, functions, other) = ( fixture("linked_visible_caller"), fixture("linked_visible_functions"), + fixture("linked_other_functions"), ); on_device(|device, _| { let caller = device.new_library_with_air(&caller).unwrap(); let functions = device.new_library_with_air(&functions).unwrap(); + let other = device.new_library_with_air(&other).unwrap(); let undeclared = FunctionConstantValues::defaults().with_index( 5, FunctionConstantValue::new(DataType::UInt, 1u32.to_le_bytes()), @@ -552,8 +562,9 @@ fn a_kernel_runs_the_functions_its_descriptor_links() { } let zeros = vec![0u8; N as usize * 4]; let queue = device.new_command_queue().unwrap(); - // The dispatch of `pipeline` computes what Metal's does. - let runs = |pipeline: &metal2vulkan_runtime::ComputePipelineState| { + // The dispatch of `pipeline` computes what Metal's does, `scaled` the words. + let runs_scaled = |pipeline: &metal2vulkan_runtime::ComputePipelineState, + scaled: &dyn Fn(u32) -> u32| { let (words, floats) = ( buffer_with(device, &zeros).unwrap(), buffer_with(device, &zeros).unwrap(), @@ -579,10 +590,7 @@ fn a_kernel_runs_the_functions_its_descriptor_links() { .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) .collect::>() }; - assert_eq!( - values(&words), - (0..N).map(|i| 3 * i + (i & 7)).collect::>() - ); + assert_eq!(values(&words), (0..N).map(scaled).collect::>()); assert_eq!( values(&floats), (0..N) @@ -590,6 +598,9 @@ fn a_kernel_runs_the_functions_its_descriptor_links() { .collect::>() ); }; + let runs = |pipeline: &metal2vulkan_runtime::ComputePipelineState| { + runs_scaled(pipeline, &|i| 3 * i + (i & 7)) + }; let pipeline = device .new_compute_pipeline_state( &descriptor( @@ -616,6 +627,46 @@ fn a_kernel_runs_the_functions_its_descriptor_links() { .new_compute_pipeline_state(&descriptor(across), &defaults) .unwrap(), ); + // A call to a function `binary_functions` alone holds: no linked function supplies it, + // compiled to a binary or not. + let compiled = |library: &metal2vulkan_runtime::Library, name: &str| { + let mut made = metal2vulkan_runtime::FunctionDescriptor::new(name); + made.options = metal2vulkan::metal::FunctionOptions::COMPILE_TO_BINARY; + made.constant_values = Some(undeclared.clone()); + library + .new_function_with_descriptor(&made) + .unwrap() + .linked_function() + }; + let rest = || { + LinkedFunctions::new() + .with_function(linked(&functions, "linked_blend")) + .with_private_function(linked(&caller, "linked_offset")) + }; + for scale in [ + compiled(&functions, "linked_scale"), + linked(&functions, "linked_scale"), + ] { + let mut alone = rest(); + alone.binary_functions.push(scale); + match device.new_compute_pipeline_state(&descriptor(alone), &defaults) { + Err(Error::Compile(CompileError::NeedsInput(RuntimeInput::LinkedFunction { + symbol, + }))) => assert_eq!(symbol.to_string(), "linked_scale"), + other => panic!("linked_scale in binary_functions alone: {other:?}"), + } + } + // Two functions of the name, one in each list: the call calls the one of `functions`. + let own: fn(u32) -> u32 = |i| 3 * i + (i & 7); + let others: fn(u32) -> u32 = |i| i + 100; + for (listed, binary, scaled) in [(&functions, &other, own), (&other, &functions, others)] { + let mut both = rest().with_function(linked(listed, "linked_scale")); + both.binary_functions.push(compiled(binary, "linked_scale")); + let pipeline = device + .new_compute_pipeline_state(&descriptor(both), &defaults) + .unwrap(); + runs_scaled(&pipeline, &scaled); + } // A name `functions` repeats: Metal's creation fails ("duplicated symbol"). let within = LinkedFunctions::new() .with_function(linked(&functions, "linked_scale")) diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9b86d5b11..8405bf61a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 480; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1712; +pub const RUNTIME_VERSION: u32 = 1713; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 00c94a321..248fe86da 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -11051,6 +11051,7 @@ variant metal2vulkan-runtime::BinaryArchiveError::Write Write { path: PathBuf, k variant metal2vulkan-runtime::BinaryFunctionProblem::CompiledStage CompiledStage { stage: BinaryFunctionStage } variant metal2vulkan-runtime::BinaryFunctionProblem::NotPrecompiled NotPrecompiled { name: String } variant metal2vulkan-runtime::BinaryFunctionProblem::NotSupported NotSupported { stage: BinaryFunctionStage } +variant metal2vulkan-runtime::BinaryFunctionProblem::ObjectOrMeshStage ObjectOrMeshStage { stage: Stage } variant metal2vulkan-runtime::BinaryFunctionStage::Fragment Fragment variant metal2vulkan-runtime::BinaryFunctionStage::Kernel Kernel variant metal2vulkan-runtime::BinaryFunctionStage::Tile Tile diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 3352a4b52..26eaae876 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -35,7 +35,7 @@ Columns: | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | | What a call did wrong | 65 | 65 | 0 | 0 | 0 | 0 | 0 | -| What a call did wrong, in detail | 164 | 149 | 0 | 0 | 0 | 0 | 0 | +| What a call did wrong, in detail | 165 | 150 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -49,7 +49,7 @@ Columns: | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | | What a call did wrong | 21 | 3 | 5 | 0 | 11 | 8 | 17 | 0 | -| What a call did wrong, in detail | 57 | 27 | 23 | 0 | 31 | 26 | 0 | 0 | +| What a call did wrong, in detail | 59 | 26 | 23 | 0 | 31 | 26 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -358,7 +358,7 @@ Columns: | `IndirectScaledTessellation` | `new_render_pipeline_state` | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal ends its process, the API validation layer off | 1: `crates/metal2vulkan-runtime/src/pipeline/render.rs (create_reflecting)` | `-` | | `CompiledKernel` | `new_compute_pipeline_state` | every device (a public call's own check of its arguments) | `ours`: this crate's already-compiled stage: Metal's descriptor takes a function | 1: `crates/metal2vulkan-runtime/src/pipeline/mod.rs (of_kernel)` | `-` | | `UnspecializedFunction` | `new_compute_pipeline_state`, `new_render_pipeline_state`, `new_tile_render_pipeline_state` and `new_mesh_render_pipeline_state` | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal ends its process at a compute, render, tile and mesh state of each stage, `MTL_DEBUG_LAYER` unset | 1: `crates/metal2vulkan-runtime/src/pipeline/unspecialized.rs (check)` | `-` | -| `DuplicateLinkedFunction` | `new_compute_pipeline_state` | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max and an M4: plain Metal's creation fails on a name the linked functions repeat | 1: `crates/metal2vulkan-runtime/src/pipeline/mod.rs (of_kernel)` | `-` | +| `DuplicateLinkedFunction` | `new_compute_pipeline_state` | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal's creation fails with code 3, `binary_function_linking.m` | 1: `crates/metal2vulkan-runtime/src/pipeline/mod.rs (of_kernel)` | `-` | | `RenderState` | A viewport, scissor rectangle or other render encoder state Metal stops at its setter | every device (a public call's own check of its arguments) | `delegated`: RenderStateProblem, section 9 | 3: `crates/metal2vulkan-runtime/src/render_state.rs (check_count)`, `crates/metal2vulkan-runtime/src/render_state.rs (set_scissors)` (+1) | `-` | | `Visibility` | A `set_visibility_result_mode` Metal stops | every device (a public call's own check of its arguments) | `delegated`: VisibilityProblem, section 9 | 1: `crates/metal2vulkan-runtime/src/visibility.rs (check_mode)` | `-` | | `Heap` | A heap, or a resource placed in one, Metal stops (`new_heap` and the heap's calls) | every device (a public call's own check of its arguments) | `delegated`: HeapProblem, section 9 | 13: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (buffer_over_host_memory)`, `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)` (+11) | `-` | @@ -373,7 +373,7 @@ Columns: | `Sparse` | A sparse heap's or texture's call Metal stops, or answers nil for | every device (a public call's own check of its arguments) | `delegated`: SparseProblem, section 9 | 5: `crates/metal2vulkan-runtime/src/sparse/encoder.rs (move_texture_mappings)`, `crates/metal2vulkan-runtime/src/sparse/encoder.rs (update_texture_mapping_indirect)` (+2) | `-` | | `WrappedBuffer` | A buffer the caller made that cannot be wrapped as a Metal buffer of the length and storage (`new_buffer_with_vk_buffer`) | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal wraps no Vulkan buffer | 1: `crates/metal2vulkan-runtime/src/wrapped_buffer.rs (new_buffer_with_vk_buffer)` | `-` | | `RequiredThreads` | A pipeline's `requiredThreadsPerThreadgroup` that Metal refuses at creation, or a dispatch whose threadgroup size is not it | every device (a public call's own check of its arguments) | `delegated`: RequiredThreadsProblem, section 9 | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_kernel)` | `-` | -| `BinaryFunctions` | A pipeline's binary functions that Metal refuses | every device (a public call's own check of its arguments) | `delegated`: BinaryFunctionProblem, section 9 | 4: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added, 2 sites)`, `crates/metal2vulkan-runtime/src/pipeline/additions.rs (new_compute_pipeline_state_with_additional_binary_functions)` (+1) | `-` | +| `BinaryFunctions` | A pipeline's binary functions that Metal refuses | every device (a public call's own check of its arguments) | `delegated`: BinaryFunctionProblem, section 9 | 5: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added, 2 sites)`, `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_mesh)` (+2) | `-` | | `DynamicLibraryFunction` | A function made by name from a dynamic library (`newFunctionWithName:` and its forms) | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max and an M4, plain and under API validation: Metal asserts "type is not a valid MTLFunctionType" | 1: `crates/metal2vulkan-runtime/src/library.rs (function)` | `-` | | `Rebind` | `rebind_bytes_no_copy` of a buffer or heap the runtime cannot rebind as asked (a runtime extension; `rebind.rs`) | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal rebinds no bytes under a buffer | 5: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`, `crates/metal2vulkan-runtime/src/detach.rs (detach_backing, 2 sites)` (+1) | `-` | | `IndirectCommandsDirectArgument` | `new_render_pipeline_state`, `new_mesh_render_pipeline_state` or `new_compute_pipeline_state` of a descriptor with `supportIndirectCommandBuffers`... | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max under macOS 26.7 and an M4 under 27.0.1: plain Metal answers nil with an NSError | 1: `crates/metal2vulkan-runtime/src/pipeline/indirect_arguments.rs (refusal)` | `-` | @@ -550,7 +550,8 @@ Columns: | `RequiredThreadsProblem::OverMaxTotal` | A size of more threads than the descriptor's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: Metal's creation fails "must be <= maxTotalThreadsPerThreadgroup (32)", with or without API validation | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_kernel)` | `-` | | `RequiredThreadsProblem::MaxTotalDiffers` | A descriptor's `maxTotalThreadsPerThreadgroup` above the size's threads | every device (a public call's own check of its arguments) | `metal-documented`: Metal's creation fails "Kernel specified max total threads per threadgroup (64) must match compute pipeline specified max total threads per threadgroup (256)", with or without API validation | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_kernel)` | `-` | | `BinaryFunctionProblem::NotSupported` | Functions added to any stage of a mesh state, whose descriptor has no support flag | every device (a public call's own check of its arguments) | `metal-measured`: an M4, macOS 27.0.1: plain Metal's process ends at the call for a mesh state — cases `mesh_frag_two`, `mesh_frag_one_add_two`, `mesh_vertex_add` and `mesh_tile_add` | 2: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added)`, `crates/metal2vulkan-runtime/src/pipeline/additions.rs (new_compute_pipeline_state_with_additional_binary_functions)` | `-` | -| `BinaryFunctionProblem::NotPrecompiled` | A function not compiled to a binary in a stage's `binary_functions` ("Function 'f' was found in binaryFunctions array but is not precompiled.") or... | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation says "Function 'f' was found in binaryFunctions array but is not precompiled.", and its creation fails without validation | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (not_precompiled)` | `-` | +| `BinaryFunctionProblem::NotPrecompiled` | A function not compiled to a binary in a stage's `binary_functions` or among the functions added to a stage of a made state, which plain Metal's... | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal's creation fails with code 2, an addition's with code 1, `binary_function_linking.m` | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (not_precompiled)` | `-` | +| `BinaryFunctionProblem::ObjectOrMeshStage` | Binary functions in a mesh render pipeline's object or mesh stage (the `binary_functions` of its function's linked functions, Metal's... | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal's process ends at the creation, `binary_function_linking.m` | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_mesh)` | `-` | | `BinaryFunctionProblem::CompiledStage` | Functions added to a stage the compile layer already compiled (`StageSource::Compiled`), whose linked functions are fixed | every device (a public call's own check of its arguments) | `ours`: this crate's already-compiled stage: Metal's descriptor takes a function, so it has no such call | 1: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added)` | `-` | | `RebindProblem::NotHostMemory` | The buffer is not a no-copy buffer of its own (a buffer of the runtime's memory, one over the caller's `VkBuffer`, or a heap's buffer, whose heap... | every device (a public call's own check of its arguments) | `ours`: from `Problem::Rebind` | 4: `crates/metal2vulkan-runtime/src/detach.rs (detach_backing, 2 sites)`, `crates/metal2vulkan-runtime/src/rebind.rs (rebind_bytes_no_copy, 2 sites)` | `-` | | `RebindProblem::EncodedUses` | A command buffer that is not yet committed has encoded a use of the buffer or heap, or of a resource placed in it, or has an encoder open that... | every device (a public call's own check of its arguments) | `ours`: from `Problem::Rebind` | 1: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)` | `-` | @@ -842,7 +843,7 @@ Each refusal's sites, with the function that builds it. - `invalid::Sparse`: `crates/metal2vulkan-runtime/src/sparse/encoder.rs (move_texture_mappings)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (update_texture_mapping_indirect)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (update_texture_mappings)`; `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture, 2 sites)` - `invalid::WrappedBuffer`: `crates/metal2vulkan-runtime/src/wrapped_buffer.rs (new_buffer_with_vk_buffer)` - `invalid::RequiredThreads`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_kernel)` -- `invalid::BinaryFunctions`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added, 2 sites)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (new_compute_pipeline_state_with_additional_binary_functions)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (not_precompiled)` +- `invalid::BinaryFunctions`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added, 2 sites)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_mesh)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (new_compute_pipeline_state_with_additional_binary_functions)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (not_precompiled)` - `invalid::DynamicLibraryFunction`: `crates/metal2vulkan-runtime/src/library.rs (function)` - `invalid::Rebind`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/detach.rs (detach_backing, 2 sites)`; `crates/metal2vulkan-runtime/src/rebind.rs (rebind_bytes_no_copy, 2 sites)` - `invalid::IndirectCommandsDirectArgument`: `crates/metal2vulkan-runtime/src/pipeline/indirect_arguments.rs (refusal)` @@ -1000,6 +1001,7 @@ Each refusal's sites, with the function that builds it. - `subproblem::RequiredThreadsProblem::MaxTotalDiffers`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_kernel)` - `subproblem::BinaryFunctionProblem::NotSupported`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (new_compute_pipeline_state_with_additional_binary_functions)` - `subproblem::BinaryFunctionProblem::NotPrecompiled`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (not_precompiled)` +- `subproblem::BinaryFunctionProblem::ObjectOrMeshStage`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (check_mesh)` - `subproblem::BinaryFunctionProblem::CompiledStage`: `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added)` - `subproblem::RebindProblem::NotHostMemory`: `crates/metal2vulkan-runtime/src/detach.rs (detach_backing, 2 sites)`; `crates/metal2vulkan-runtime/src/rebind.rs (rebind_bytes_no_copy, 2 sites)` - `subproblem::RebindProblem::EncodedUses`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`